Javascript: Modify code to add elements to an array/list - javascript

Hey Guys,
Javascript newbie here. I'm trying to modify some existing to code to instead of returning the count of elements, to actually add each of the specified elements to an array/list
here is the original code from Selenium CSS counter
private int getCSSCount(String aCSSLocator){
String jsScript = "var cssMatches = eval_css(\"%s\", window.document);cssMatches.length;";
return Integer.parseInt(selenium.getEval(String.format(jsScript, aCSSLocator)));
}
I then have to convert the code to python, which I am far more familiar with
def count_css_matches(self, css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
cssMatches.length;''' % css_locator
return int(self.selenium.get_eval(java_script_code))
But changing the original code to return the array instead of an integer is where I get stuck.
Thanks for the help and the below is the error I get when I tried to run it in Python.
Traceback (most recent call last):
"D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 1218, in get_eval
return self.get_string("getEval", [script,])
File "D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 219, in get_string
result = self.do_command(verb, args)
File "D:\Temp\1TestingApps\Selenium\SeleniumRC\selenium-python-client-driver-1.0.1\selenium.py", line 215, in do_command
raise Exception, data
Exception: ERROR: Threw an exception: missing ) after argument list

I'm not sure how eval_css works, but if returns an array of strings into cssMatches, as you can get an string, and not a list, using get_eval, then you should JSONify the list in the JS scope, getting it as an string into python, and using simplejson, converting it to an python's native list.
Something like this, I guess:
import json
def count_css_matches(self, css_locator):
java_script_code = '''
var cssMatches = eval_css("%s", window.document);
JSON.stringify(cssMatches.length);''' % css_locator
return json.loads(self.selenium.get_eval(java_script_code)))
I don't know if you need a return, document.write, or something like that in the js code to get the string. Please add a comment if it's needed, and I'll add it to the code :-)
Good luck!

If you update your python bindings you will have it. pip install -U selenium

Related

Converting a .txt file into a JSON in Adobe Acrobat and how to reference it

I have a file attached to my PDF entitled JSONTEST.txt. I have successfully returned a string from that .txt, however, I am now trying to turn that string into a JSON so I can reference it as so (obj[key] returns key value). In reading, it seems like eval() is what I should be using, however, every time I do, it gives me this error:
SyntaxError: missing ; before statement
5:Document-Level:jsontest
This is the script I am using:
console.show(); console.clear();
var oFile = this.getDataObjectContents("JSONTEST.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
var obj = eval(cFile);
What am I doing wrong?
Once it is working, can I reference it as I have described above?
I think I figured it out, though I'm still trying to figure out the correct way to reference fields. My JSON text was within curly brackets ( {} ), but should've been within square brackets ( [] ). Simple as that, so I change it to:
var obj = eval('[' + cFile + ']');
It seems to work now.

Google App Script new editor - string property double underlined

Probably a nube question but I have a line of code:
var c = message.substring(i, i + 1);
It works but in the new Google App Script editor, the string property "substring" has a double-underline under it, which seems to suggest that it's wrong, but it actually works!
"Show Fixes" gives me only two options - to ignore the "error" or disable checking, neither of which seems like what I want to do. Any ideas?
I think it is due to how the variable "message" is defined. I did a quick test trying to replicate your scenario and this is what I got:
With warning:
var message = 0
message = '123456789'
var c = message.substr(1, 5);
Without warning:
var message = '0'
message = '123456789'
var c = message.substr(1, 5);
Both cases have the same result without errors. If you provide more code I can check why the warning is appearing.
edit:
As you have said in the comments, your variable is being defined from the range of a SpreadSheet using getValue(), this method returns an object with the value of the cell. If you want to obtain a string you should use getDisplayValue(). You can also use the built-in method toString() to make sure that any variable is converted into a string.
References:
getValue()
getDisplayValue()

JavaScript "Packed" Function in CSharp

I have an obfuscated (p,a,c,k,e,d) function from JavaScript.
string value = #"eval(function(p,a,c,k,e,d)
{while(c--)if(k[c])p=p.replace(new RegExp('\\b'+c.toString(a)+'\\b','g'),k[c]);
return p}
('3("3b").3a({39:\"5://1b.1a.19.8:18/38/v.37\",36:\"5://1b.1a.19.8:18/i/35/34/33.32\",31:\"\",30:\"2z\",2y:\"2x\",2w:2v,2u:\"7\",2t:\"2s\",2r:[],2q:{2p:\'#2o\',2n:22,2m:\"2l\",2k:0}});b f;b k=0;b 6=0;3().2j(2(x){a(6>0)k+=x.17-6;6=x.17;a(0!=0&&k>=0){6=-1;3().2i();3().2h(2g);$(\'#2f\').j();$(\'h.g\').j()}});3().2e(2(x){6=-1});3().2d(2(x){16(x)});3().2c(2(){$(\'h.g\').j()});2 16(x){$(\'h.g\').2b();a(f)2a;f=1;$.29(\'5://12.9/15-28/27.15?26=25&24=23&21=20-1z-1y-1x-1w\',2(14){$(\'#1v\').1u(14)})};3().1t(\'1s\',2(){b 13=3().1r();13.1q(\'1p\',2(){11.10(\'z-y\')[0].w[1].1o=\"5://12.9\";11.10(\'z-y\')[0].w[1].1n=\"<u>1m - 1l 1k 1j & 1i</u>\"});a($.c(\'4\')==\"d\"){t.s(\"5://r.q.p/o/7.n\",\"m 9 1h\",e,\"l\")}1g{t.s(\"5://r.q.p/o/d.n\",\"m 9 1f\",e,\"l\")}});2 e(){$.c(\'4\')==\'7\'?4=\'d\':4=\'7\';$.c(\'4\',4);1e.1d.1c()};',36,120,'||function|jwplayer|primaryCookie|http|p02887336|html5||to|if|var|cookie|flash|switchMode|vvplay|video_ad|div||show|tt2887336|button2|Switch|png|images|tv|flashx|static|addButton|this|center||childNodes||featured|jw|getElementsByClassName|document|streamin|container|data|cgi|doPlay|position|8777|213|211|95|reload|location|window|Flash|else|HTML5|Storage|Sharing|Video|Free|Streamin|innerHTML|href|contextmenu|addEventListener|getContainer|ready|on|html|fviews|fb98c55a544241de2464a88086a6b0c9|1486917733|186|182|2887336|hash||2ca0tpqawtre|file_code|view|op|index_dl|bin|get|return|hide|onComplete|onPlay|onSeek|play_limit_box|false|setFullscreen|stop|onTime|backgroundOpacity|Arial|fontFamily|fontSize|FFFFFF|color|captions|tracks|start|startparam|primary|326|height|580|width|2638|duration|skin|jpg|lhl2j9yhfp1s|00085|01|image|mp4|rwi7bsgc5huzcg3h5fpsfen3362uwfp4cyzyo2mavczsvbbx4tnesmwhdteq|file|setup|vplayer'.split('|')))"
I am trying to use jint to interpret and get the value of the above function but when I execute the statement in jint engine it throws an exception for jwplayer is not defined.
I know why the exception is thrown but I only want to get the value of p above. But jint runs the whole function and then ends up with an empty function which doesn't exist and when it tries to run it, an exception is thrown.
I only want it to return the value in a string and it should not run it any further. I have already tried to search it for an answer but so far found nothing.
I am using the code as following:
Jint.Engine jEngine = new Jint.Engine();
var linkString = jEngine.Execute(value).GetCompletionValue().ToString();
var arrayFile = linkString.Split(' ', '\n');
Is something I am missing here? If someone can shed some light on it. That will be much appreciated. Thanks
I think the problem was eval at the start of the packed function. It was running the code after getting the value. So I removed the eval part and now it works as expected.

SyntaxError: identifier starts immediately after numeric literal?

I have been working on my project where I had to do some updates on my data records. After I finished my update I got an error: SyntaxError: identifier starts immediately after numeric literal and this line of code was below that error in firebug : maxScores.ew-19a = ''
I looked up in my code and I found where is this output coming from, here is the code:
var maxScores = new Object;
<cfoutput query="getRec">maxScores.#LCase(tCode)# = '#maxScore#';</cfoutput>
In my update I had to put - symbol between letter and number, in old data I did not have that so I think that causing the problem here. I was wondering how I can prevent this or if there is any method that I have to put around my output to prevent this? If you know how this can be fixed pleas let me know. Thank you.
ColdFusion will attempt to subtract ew from 19a when you just dump it between to pound signs like that. You will need to use bracket/object notation here. Try this:
<cfoutput query="getRec">
maxScores.#LCase(getRec["tCode"][currentrow])# = '#getRec["maxScore"][currentrow]#';
</cfoutput>
If you want to Lower case something do it in the query. Outputing JS using CF is useful and solves many problems, but you want to keep it as clean as possible to keep your brain from fogging over. :)

JSON to JavaScript, SyntaxError: Unexpected token &

I know this question has been asked numerous times, but I really donĀ“t get it.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = #weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph. I googled around and concluded that I should put ' ' around #weightsAsJsonString, so I do that.
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
Edit: This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
It sounds like your issue is trying to inject content via Razor into JavaScript. By default # will HTML-encode your content, which doesn't work in the context of JavaScript.
#Html.Raw(weightsAsJsonString) will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse later on.
When you do var jsonStringToGraph = #weightsAsJsonString; you are actually defining a JSON object and not a JSON string.
Hence when you do JSON.parse(teststring); you are trying to parse an object instead of a string.
Either put apostrophes around the first declaration var jsonStringToGraph = '#weightsAsJsonString'; or simply do not try to parse it again.

Categories