AngularFire: $add sets fbUID and custom UID, why? - javascript

Before there are any questions, I have a function that creates a custom UID because I don't "need" the long Firebase UID and wanted something shorter which is more easy to remember.
Anyway, in my create-function I'm not sure I'm adding it to the db correctly.
Here's a snippet and below that is how it looks in my database.
$scope.create = function(){
// Generate a shorter random uid (6 chars) that replaces the long regular Firebase uid
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
uid_length = 6;
generator = function(){
random = '';
for(var i = 0; i < uid_length; i++){
random += letters.charAt(Math.floor(Math.random() * letters.length));
}
return random;
}
generator();
var lists = new Firebase('https://url.firebaseio.com/lists/' + random);
firebaseLists = $firebaseArray(lists);
//lists.child(random).set(random);
firebaseLists.$add(random).then(function(lists){
})
This gives me, for example:
lists
0Knn8M <- custom UID
-KH6kSxPAaerjU: '0Knn8M'
As I want the things that are added to 0Knn8M displayed on my page, it also displays the FB UID. Of course I could do a CSS 'display:none;' on that child but shouldn't it be another way around it?

I think, that here is an error:
generator = function(){
random = '';
for(var i = 0; i < uid_length; i++){
random += letters.charAt(Math.floor(Math.random() * letters.length));
}
return random;
}
generator();
var lists = new Firebase('https://url.firebaseio.com/lists/' + random);
You are calling generator() but not assigning it result to any variable. In var lists = new Firebase('https://url.firebaseio.com/lists/' + random); the variable random is now undefined. So firebase generates it's own id I guess.
So you need to change just one thing var random = generator().

Related

I would like to know how I can make the "namePrinter" loop function work well?

I was trying to get javascript to print the result of the "generateName" function at least 10 times when I press a button in the html, so i tried a loop inside the function that generates the names and but it didn't work then I separated the loop and wrote it in the function "namePrinter" and create the global variable "names" to store the results of the function "generateName"
but I don't know what part of this whole process is wrong, I already reviewed other questions that were made in this forum but I didn't find an answer either
JS:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length + 2)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length +2)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
for (var i = 0; i < 10; i++) {
text[i].innerHTML(`${names}`)
}
return namePrinter;
}
innerHTML is not a function, it's a property. So, in the loop use text.innerHTML += name
However, if it's a <textarea> element, then you need to use value property instead:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
document.getElementById("elvenFemButton2").onclick = namePrinter2;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
var names2 = [];
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
text.value = ""; //clear previous result
for (var i = 0; i < 10; i++) {
text.value += names;
}
}
function namePrinter2(){
var text = document.getElementById("textArea");
names2.length = 0; //clear array
for (var i = 0; i < 10; i++) {
names2[names2.length] = generateName();
}
text.value = names2;
}
<textarea id="textArea"></textarea>
<button id="elvenFemButton">generate names</button>
<button id="elvenFemButton2">generate different names</button>
This however as you can see will print the same name 10 times, if you need generate 10 names and store them globally, than you'll need save them in the array instead.
P.S.
Unrelated, but elfLastName2[getRandomInt(0,elfLastName2.length +2)] is wrong, you can't get value from an index that is larger than length of the array (aka +2 is wrong)

Unable to choose a random element from an array on Jmeter and put it on .sendKeys

var randomroom = ["BA783", "AP03A", "BC078", "HAW90"];
implicitFind(pkg.By.xpath("//input[#type='search']")).sendKeys("BA783");
I am new to coding and do not know how to make one random room from array go into the sendKeys, each time I run a test. The rooms will be typed on a search bar. This test will be executed on JMeter.
We can use Math.Random to create a random number and then limit it to from 0 to randomRooms.length -1 ;
var randomRooms = ["BA783", "AP03A", "BC078", "HAW90"];
let randomRoom= randomRooms[Math.floor(Math.random() * (randomRooms .length))]
console.log(randomRoom)
function randomRooms(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
console.log(randomRooms(5));
This can be also used if you wanna try.

Script to refresh data with IMPORTHTML in Google Sheets

I'm trying to get the data about XAU prices from table here: https://www.investing.com/currencies/xau-pln-historical-data
I need to have the data in google sheets and the problem is that it doesn't refresh the data. When I clean cells manually and insert formula then data is refreshed, but when I do it using script it doesn't work. I have this script (based on https://support.geckoboard.com/hc/en-us/articles/206260188-Use-Google-Sheets-ImportHTML-function-to-display-data-in-Geckoboard):
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var cellFunction = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1),2,2)';
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
for (var j = 2; j <= 14; j++) {
var cellFunction2 = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1),' + j + ',2)';
sheetName.getRange(j,11).setValue(cellFunction2);
}
}
I set up a trigger which runs the script every minute but the data is still the same.
Do you have any ideas what should I do?
A much easier solution is to enable circular references with 1 iteration. For example put in cell A1 =A1+1 then append your url with "?"&A1
You have declared the queryString variable but you have never used it. The idea of having it is to append it to the URL, so that it gets recognized as a different URL (that could yield different results). That causes the formula's results to be refreshed.
You can use the code below which uses the queryString variable:
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
for (var j = 2; j <= 14; j++) {
var functionTemplate = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data?%s","table",1),%s,2)';
var cellFunction2 = Utilities.format(functionTemplate, queryString, j);
sheetName.getRange(j,11).setValue(cellFunction2);
}
}
Additionally, you may be interested in replacing the for-loop for this single formula:
=QUERY(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1), "SELECT Col2 LIMIT 13 OFFSET 1", 0)
Which could be used in your code as follows:
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
var functionTemplate = '=QUERY(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data?%s","table",1), "SELECT Col2 LIMIT 13 OFFSET 1", 0)';
var cellFunction2 = Utilities.format(functionTemplate, queryString);
sheetName.getRange(2, 11).setValue(cellFunction2);
}
You may also read more about the Utilities.formatString function in case you may need it here.

Apply for loop with variable

I am trying to condense my code because I have a lot of repetitive coding happening. I will need to apply this same example many times over. I want to create a for loop but my variable needs to increase as well. Right now I have my variable increasing but I am unable to implement my cell data into the variable. I think I am double assigning var h. I can't figure out how to get around this. Thank you for your help.
For Loop
for (var j = 2; j<15; j++){eval("var polebrea" +j);
var h = ("polebrea" +j)
}
h = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
Code Attempting To Implement
polebrea2 = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
polebrea3 = document.getElementById("part1Table").rows[10].cells[3].innerHTML;
polebrea4 = document.getElementById("part1Table").rows[10].cells[4].innerHTML;
polebrea5 = document.getElementById("part1Table").rows[10].cells[5].innerHTML;
(cont. to 15)
Inserting Variable
<script>document.write(polebrea2)</script>
Ignoring design dogma....use the string index form of property access to set your variables:
// window is a bad place for this....you should probably put it on another object e.g. var polbreas = {};
for (var i = 2; i<15; i++){
window["polbrea"+i] = document.getElementById("part1Table").rows[10].cells[i].innerHTML;
}
While not necessarily good practice to do what you are doing, you could try this:
var createVariable = function( index ){
var variableName = "polebrea" + index;
var objName = document.getElementById("part1Table").rows[10].cells[index].innerHTML;
return (variableName + " = " + objName + ";");
};
for (var j = 2; j<15; j++){
var objToWrite = createVariable(j);
console.log( objToWrite );
}

Getting same result from function every time

why is my function returning the same result?
I would like to input all the values from the “ping” function to an array and then output that array in html.
I run the function 3 times but all three times the result is the same. Can you tell me why?
(The domains are just an example by the way, cant put originals here)
var str = ' ';
var t=[];
var n= 2;
var arr = ["www.google.com","www.example.com","www.example2.com"];
var results = [];
var finalurl = '';
function fun1(){
for (var i=0; i < arr.length; i++){
str = "http://" + arr[i] + "/images/";
finalurl = str + "image-l.gif" + "?id=" + (new Date()).getTime();
ping(finalurl);
textt += results[i] + " ";
$(‘#ping’).html(textt);
}
}
var ping = function(finalurl) {
var l = 0;
t.push((new Date()).getTime());
if(t.length > n) {
p=t[2]-t[1];
results.push(p);
}
else {
var img = new Image;
$(img).load(function() {
ping();
}).attr('src', finalurl);
}
}
//small part of html:
<h2>run</h2>
<h1 id=“ping”> </h1>
This generates three urls (the length of arr) but only attempts to show two (the value of n). The urls are different each time, but you are limiting them in ping so the new ones are not used.
Try setting n to higher number, you will see it will load more images each click - as it currently stands it tries to load more in a single click (3) than it allows (2).
Note: even if those urls are different, the images may be the same, this happens if the server ignores the id parameter... which probably does as it requires additional configuration for the server to handle requests to a ".gif" resource (which is not a known servcer side scripting language) - by default the server will just return the resource image-l.gif.
By the way: At $(‘#ping’) those are the wrong quotes. Also textt is not defined - I did define it as var textt = ''; for my tests.

Categories

Resources