I have a JSON script which contain live matches. These changes every 5 minutes. The changes could for instance be the keys live_in or score. Beside this matches are also deleted and added to the JSON. I want to keep my html output updated at all time how can i do this the best possible way? So far i've set the updating speed to 5 seconds for testing purposes. I've tried so far to set the divs id to equal to the match_id and thereby update by
$('div#match-date-id-' + match['match_id']).html('test');
However does not seem to update. How can i do this the best possible way? i've created a plnkr which enable you to download it with a json snippet, which can be edited in order to check.
plnkr.co/edit/eQCShhW01OG5jU4VLx04?p=preview
My bad earlier on :-) Now I've done more thorough testing and updated the plunker code. What I found in the test: the filter was trying to use an undefined value (match.id), also the filter was trying to compare values from different datatypes (String vs. Integer); so it wasn't working as intended:
Original:
match = match.filter(
function(match) {
return match.id > lastId;
});
Corrected code:
match = match.filter(
function(match) {
return parseInt(match.match_id) > lastId;
});
Above match_id represents String datatype in your JSON file, so I had to convert it to Integer before comparison. More info about JSON data-types. Following the older filter functionality, no match passed the comparison test.
Also for testing purposes I commented out the following line:
if (match.match_id > lastLoadedMatch) {
//lastLoadedMatch = match.match_id
}
because in the second round of updates with the same testing data, no data passes that condition.
Also, I think you need to convert match_id to Integer as well; like following:
var matchId = parseInt(match.match_id)
if ( matchId > lastLoadedMatch) {
lastLoadedMatch = match.match_id
}
I hope you find it useful :-) + note I added a timestamp for those updates; so it's clearly visible that the updates take place now every 5 seconds.
Related
I am trying to cut down and make my code simpler since my original method is not very readable and I get a lot of hard to understand errors for which I have to scan all of the code word by word as it is all one long line.
Lets say the text input was for
In my original code, I wrote :
//Example : You want to know if any of your favorite games were licensed by Nintendo
var tsf = (The value of a textInput in string form)
tsf.toLowerCase()
//Lets say the textinput said "Name your favorite games"
if(tsf.contains('mario') || tsf.contains('pokemon') || tsf.contains('mortal kombat')||etc,etc) {
Alert.alert('At least one of these games was licensed by Nintendo')
}
This works but in the real code there are a lot more "games" and it requires each and every item in the list as it is related to a health project I'm working on.
My 2nd idea was to create an array with all the elements and see if the array contains tsf
nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris',etc]
if(nintendoGames.contains(tsf)){
Alert.alert('This game was licensed by Nintendo')
}
This also works but only if tsf is a single word. Incase
tsf = 'mario, zelda'
the array method would not work since the array only contains 'mario' and 'zelda' and not the string 'mario, zelda'
I want to be able to scan to see if any part of the string contains any one of the elements in the array and so far, only the first solution works for me. If there is a modification in the .contains() function that works or if there is a certain script I have to write, it would be very useful. I wasn't able to find much online about this.
I am working on React.js with expo to host the app.
First, we convert the string to an array using 'split'.
Since we separate the games in the string with ', ' your code should be like:
tsf.split(', '); // we receive: ['mario','zelda'].
Then we use 'some' method to check if some of the elements in the array we created are in the 'nintedoGames' array.
const tsf = 'mario, zelda';
const nintendoGames = ['mario', 'pokemon', 'mortal kombat', 'zelda', 'tetris'];
const result = tsf.split(', ').some(game => nintendoGames.includes(game.toLowerCase()));
console.log(result)
let nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris'];
let str = "This is a mario games where you can play the way you like.";
if(nintendoGames.some(n => str.toLowerCase().includes(n.toLowerCase())))
alert("This game was licensed by Nintendo");
I have this string made up for a TMS program... I later found out I want the program to NOT select these postalcodes, it's now matching the string. I want it to be able to select anything between 1000-10000\s*a-zA-Z except for this:
(8388|8389|8390|8391|8392|8393|8394|8395|8396|8397|8398|8400|8401|8403|8404|8405|8406|8407|8408|8409|8410|8411|8412|8413|8414|8415|8420|8421|8422|8423|8424|8425|8426|8427|8428|8430|8431|8432|8433|8434|8435|8440|8441|8442|8443|8444|8445|8446|8447|8448|8449|8451|8452|8453|8454|8455|8456|8457|8458|8459|8461|8462|8463|8464|8465|8466|8467|8468|8469|8470|8471|8472|8474|8475|8476|8477|8478|8479|8481|8482|8483|8484|8485|8486|8487|8488|8489|8490|8491|8493|8494|8495|8497|8500|8501|8502|8503|8505|8506|8507|8508|8511|8512|8513|8514|8515|8516|8517|8520|8521|8522|8523|8524|8525|8526|8527|8528|8529|8530|8531|8532|8534|8535|8536|8537|8538|8539|8541|8542|8550|8551|8552|8553|8554|8556|8560|8561|8563|8564|8565|8566|8567|8571|8572|8573|8574|8581|8582|8583|8584|8600|8601|8602|8603|8604|8605|8606|8607|8608|8611|8612|8613|8614|8615|8616|8617|8618|8620|8621|8622|8623|8624|8625|8626|8627|8628|8629|8631|8632|8633|8635|8636|8637|8641|8642|8644|8647|8650|8651|8658|8700|8701|8702|8710|8711|8713|8715|8721|8722|8723|8724|8730|8731|8732|8733|8734|8735|8736|8737|8741|8742|8743|8744|8745|8746|8747|8748|8749|8751|8752|8753|8754|8755|8756|8757|8758|8759|8761|8762|8763|8764|8765|8766|8771|8772|8773|8774|8775|8800|8801|8802|8804|8805|8806|8807|8808|8809|8811|8812|8813|8814|8816|8821|8822|8823|8830|8831|8832|8833|8834|8835|8841|8842|8843|8844|8845|8850|8851|8852|8853|8854|8855|8856|8857|8860|8861|8862|8871|8872|8880|8881|8882|8883|8884|8885|8890|8891|8892|8893|8894|8895|8896|8897|8899|8900|8901|8902|8903|8911|8912|8913|8914|8915|8916|8917|8918|8919|8921|8922|8923|8924|8925|8926|8927|8931|8932|8933|8934|8935|8936|8937|8938|8939|8941|9001|9003|9004|9005|9006|9007|9008|9009|9011|9012|9013|9014|9021|9022|9023|9024|9025|9026|9027|9031|9032|9033|9034|9035|9036|9037|9038|9040|9041|9043|9044|9045|9047|9050|9051|9053|9054|9055|9056|9057|9060|9061|9062|9063|9064|9067|9071|9072|9073|9074|9075|9076|9077|9078|9079|9081|9082|9083|9084|9086|9087|9088|9089|9091|9100|9101|9102|9103|9104|9105|9106|9107|9108|9109|9111|9112|9113|9114|9121|9122|9123|9124|9125|9131|9132|9133|9134|9135|9136|9137|9138|9141|9142|91439144|9145|9146|9147|9148|9150|9151|9152|9153|9154|9155|9156|9160|9161|9162|9163|9164|9166|9171|9172|9173|9174|9175|9176|9177|9178|9200|9201|9202|9203|9204|9205|9206|9207|9211|9212|9213|9214|9215|9216|9217|9218|9219|9221|9222|9223|9230|9231|9233|9240|9241|9243|9244|9245|9246|9247|9248|9249|9250|9251|9254|9255|9256|9257|9258|9260|9261|9262|9263|9264|9265|9269|9270|9271|9280|9281|9283|9284|9285|9286|9287|9288|9289|9290|9291|9292|9293|9294|9295|9296|9297|9298|9299|9851|9852|9853|9871|9872|9873|9950)\s*[a-zA-Z]{2}
I obviously tried the [^] function and the ?: function but I can't get it working properly.
Just break this string into a set(I think slice function can do that) then sort it and every time you get a value match if it exists in this set or not.
Lets make it easier, I am guessing you are getting numbers in string format of some sort with some form of separation in this case "|".
Step one create array by splinting string based on separator
Step two use filter function that will return a new array based on conditions you provide as shown in example.
Below example takes into consideration edge cases e.g. we are only comparing numbers alphabets are of lesser comparative value to us. What we have to make sure is any comparative value starts with number rest is is all gibberish. So extract number and run bit of magic on that.
Your sting was too long I have used a hypothetical scenario to give you what you want. Rest should be self explanatory in example.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/g);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)
to check on whats being extracted run following and update function as needed.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/);
console.log(extractedNumber);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)
I have a simple script to generate a doc and PDF upon form submission. It worked well on simple template (e.g. Only 1 sentence, First name, Last name and Company name).
However, when I use a template that's longer, having many fields, and formatting, the code runs but replace the text randomly.
I have tried to hardcode the fields of forms in ascending order as the doc template. However it still replace the text randomly
Can anybody points out what have I done wrong?
My code:
function myFunction(e) {
var response = e.response;
var timestamp = response.getTimestamp();
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
var file = DriveApp.getFileById('XXXXX');
var folder = DriveApp.getFolderById('XXXXX')
var copy = file.makeCopy(companyName + '_one pager', folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Company Name}}', companyName);
body.replaceText('{{Name}}', name1);
body.replaceText('{{Position}}', position1);
body.replaceText('{{Email}}', emailAdd1);
body.replaceText('{{Linkedin}}', linkedin1);
body.replaceText('{{Fun Fact}}', funFact1);
body.replaceText('{{Game Stage}}', gameStage);
body.replaceText('{{Game Story}}', gameStory);
doc.saveAndClose();
folder.createFile(doc.getAs("application/pdf"));}
My template -
Result -
Question - Does that mean the array declaration in line 3 was supposed to match the order of my form responses columns?
You can use Regular Expresion:
body.replace(/{{Company Name}}/g, companyName); // /g replace globaly all value like {{Company Name}}
Finally I found what have went wrong after so many trials and errors!
The reason is because I declared the array variables randomly without following the order of the form responses columns.
The issue is with the part -
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
It's actually pulling responses from the spreadsheet, and should be corrected in order. The wrongly mapped values was what causing the replacement of text went haywire. I corrected the order as per form responses and it is all good now.
Learning points:
If you swapped around the variables, what response.getItemResponses().map(function(f) {return f.getResponse()} does is that it will go through the form responses column by column in order, and it will map the content to the wrong variable. As a result, when you replace your text later using body.replaceText('{{Game Stage}}', gameStage), there might be possibility that whatever stored in gameStage might be name1. Hence the replaced text will be wrong. And you will scratch your head until it bleeds without knowing why.
I saw #Tanaike's comment after I found the answer, but totally spot on!
I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});
Update: A Solution below!
I'm fairly new to website development but I've been tasked with developing e2e (end-to-end) tests for a developing website that uses AngularJS. As a result I've been looking down the road of using AngularJS's karma-run ngScenario testing wrapper.
Anyway, just getting started I want to make sure that a simple hyperlink's text matches part of its href address. There isn't need to know the structure of this code snippet, but these are thumbnails for user profiles, and you can click the thumbnail object completely (the first 'a') or you can click a link displaying their name (the second 'a').
There dozens of these on a page.
Here is what a part of the page looks like loaded with a user "PurplePenguin".
<div class="thumbnail__section">
<a href="/profile/PurplePenguin">
<div class="thumbnail__bottom">
<div class="thumbnail__rating ng-binding"> </div>
<div class="thumbnail__info">
<div class="thumbnail__name">
<a class="ng-binding" href="/profile/PurplePenguin">PurplePenguin</a>
</div>
[...]
Essentially I want a test that will take the text of the second 'a' element and check it against the href attribute: "assert that href '/profile/PurplePenguin' equals '/profile/' + 'PurplePenguin'"
This is what I've made just wanting to test the first thumbnail's 'a', (in my time writing "PurplePengiun" is the first user every time so I could hard code it).
it('should have the performer\'s name match the link', function() {
// "eq(n)" gets the nth instance of the element;
// "> a:eq(0)" grabs its first child a
var nameElement = element('.thumbnail__name:eq(0) > a:eq(0)');
// These work and pass
expect(nameElement.text()).toBe('PurplePenguin');
expect(nameElement.attr('href')).toBe('/profile/PurplePenguin');
// This does not
var textString = nameElement.text(); // textString == "[object Object]"
expect(nameElement.attr('href')).toBe('/profile/' + textString);
This gets returned:
expect element '.thumbnail__name:eq(0) > a:eq(0)' get attr 'href' toEqual "/profile/[object Object]"
expected "/profile/[object Object]" but was "/profile/PurplePenguin"
So I've figured out how to find the particular element on the page I need, but trying to manipulate the text of a simple 'a' element only gives me [object Object].
Some things I've tried with my basic knowledge of JS:
nameElement.text().toString(), nameElement.text().value(), nameElement[0].text()
Trying things other than text()
nameElement.html() and nameElement.val()
They too return [object Object] when trying to use them as strings.
It seems that looking at the values and attributes of these elements only works when using the very specific API functions like .toBe or .toEqual, but I want to assert that a specifically formatted string is made.
Thank you for any help!
Solution
Thanks for that bit of insight Andyrooger, I had actually taken a stab at the query function before posting my question but gave up on it too quick. Your explanation gave me the idea to start looking deeper into the samples that have been posted in the official docs. I ended up taking a hint from a Adi Roiban's post to another Angular e2e writer's question talking about query, done() messages, and promises. This ended up leading me to my eventual solution.
So I've made myself a solution and in the spirit of cooperation made a set of examples for others to learn by. There are four examples, the first two are just getting the text and the href and comparing them against hard-coded values. The third one uses indexOf to do dirt-simple comparisons. The fourth one shows how you can make your own more specific pass/fail conditions (more than what Jasmine provides with its matchers).
Number 1: User name text vs hard coded value
it('should have the user\'s name be \'PurplePenguin\'', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text(); // Can finally access this guy!
// The first param null indicates a nominal execution, the second param is a return of sorts
done(null, text);
});
// Passes
expect(textPromise).toBe('PurplePenguin')
});
Number 2: Profile href value vs hard coded value
it('should have the user\'s link be \'/profile/PurplePenguin\'', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var href = nameElement.attr('href');
// The first param null indicates a nominal execution, the second param is a return of sorts
done(null, href);
});
// Passes
expect(textPromise).toBe('/profile/PurplePenguin')
});
Number 3: Simple string comparison
it('should have the user\'s name match the link', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text();
var href = nameElement.attr('href');
// The first param null indicates a clean pass, the second param is a return of sorts
done(null, href.indexOf(text)); // indexOf returns -1 if text is _not_ a sub-string of href
});
expect(textPromise).toBeGreaterThan(-1);
// In the case of failure reports this in the console (if using Karma):
// expect element .thumbnail__name:eq(0) > a:eq(0) custom query toBeGreaterThan -1
// expected -1 but was -1
// In the runner.html page for the test simply reports this useless/misleading log:
// expected -1 but was -1
});
Number 4: More detailed string comparison doing it your own way plus a better error message
it('should have the user\'s name match the link', function() {
var nameStringPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text();
var href = nameElement.attr('href');
var message;
if (href.indexOf(text) == -1)
message = 'Did not find "' + text + '" in "' + href + '"';
done(message, href.indexOf(text));
});
expect(nameStringPromise);
// An expect() with no Jasmine matcher means that it only uses the done message to determine
// a pass or fail for the test. So I wrote that if my conditions weren't met it would print
// an informative message in the case of failure
// Example failure output with a broken url generator:
// Did not find "PurplePenguin" in "/profile/"
});
I'm struggling to find references to back this up or explain a little more nicely, other than these docs which don't have much info. Therefore this answer is mainly from memory of reading the relevant code.
When you write a test in ngScenario, you are not writing a series of immediate actions as you would do in a unit test. What you are actually doing queuing up a list of commands to execute when the test starts.
Methods that looks like normal jQuery functions, such as text() or attr() are actually part of ngScenario's DSL and return future objects (meaning they will at some point execute and have the result of the call you wanted.)
expect() already knows this so waits for the result before comparing to your expected value. The code underneath, in your example, is reading directly and immediately so will see the future object.
If you do need to read the element in this way I suggest looking at the query function which should allow it. On the other hand if you need to just check the formatting of the string you can use toMatch which has been implemented in ngScenario too.