There is a website called Gild.com that has different coding puzzles/challenges for users to do. They can be completed in wide array of languages including Javascript. I am interested in solving these puzzles in Javascript, but I am unsure of the following:
How am I supposed to access the input file which is supposed to be passed as an argument?
How am I supposed to output the result?
My understanding of Javascript is that it is run from within an HTML page and that output really is only in the form of placing values in the HTML, modifying the DOM, etc. For that reason it is not clear to me how Javascript can be used for solving these types of problems. Can someone who has used Gild before or has some insights into my question suggest how to proceed?
An example of a problem would be: the given input file contains a positive integer, find the sum of all prime numbers smaller than that integer and output it.
EDIT: Some of the solutions below involve using external resources, but on Gild, I am supposed to put my solution in their editor and then submit it that way, like the following picture shows:
In other words, I don't think my solution can have access to Node.js or other external resources.
Edit: Here are some interesting articles that I have found that I think are the answer to my question:
http://www.phpied.com/installing-rhino-on-mac/
http://www.phpied.com/javascript-shell-scripting/
I haven't spent much time on Gild, but I do a lot of similar types of problems on Project Euler. I think the best way to go is probably Node.js.
If you're not familiar, Node is basically server-side JavaScript that runs in Google's V8 engine. Installing it on your own Mac/Windows machine takes about 2 minutes. It's also really fast (considering it's JavaScript).
And you'd use it like this:
var fs = require('fs'); // the filesystem module
var contents = fs.readFileSync('theFile.txt', 'utf-8');
// Do stuff with the file contents...
Everything after those first two lines can be done with the same JS you'd write in the browser, right down to calling console.log() to spit out the answer.
So, if you wrote your script in a file on your desktop called getprimes.js, you'd open up your terminal and enter node ~/Desktop/getprimes.js (assuming you're on a Mac)
If you're:
on a Mac,
planning to do a lot of these puzzles, and
willing to pay $10, then
I highly recommend CodeRunner. It encapsulates runtimes for a variety of languages — from C to JavaScript — and lets you quickly build and run any sort of one-off code. Just hack together your code, ⌘R, and the results are printed right there in the same window.
I haven't used any file-based JavaScript in CodeRunner, but I imagine kennis's suggestions would apply. To output your results:
console.log(...)
Easy as pie!
Related
So, I'm teaching myself various AI techniques, and I figured the best way to do so would be to create my own Python bot which can play the game Pokemon using an online open-source Pokemon simulator.
The issue is that this simulator has all its source code written in JavaScript, whereas my bot uses Python. At first, I solved the problem of grabbing the full list of valid Pokemon and such by simply downloading the server's .js files, which (handily) contained all valid Pokemon/moves as JSON objects that I could easily import into Python. This was all well and good when I just needed Pokemon names and such, but now that I'm building out the actual engine I've discovered that it uses these same JSON files for its actual gameplay code.
For example, here's the Pokemon "Ability" Aftermath. Pay attention to onAfterDamage:
"aftermath": {
desc: "If this Pokemon is knocked out with a contact move, that move's user loses 1/4 of its maximum HP, rounded down. If any active Pokemon has the Damp Ability, this effect is prevented.",
shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.",
id: "aftermath",
name: "Aftermath",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact'] && !target.hp) {
this.damage(source.maxhp / 4, source, target);
}
},
rating: 2.5,
num: 106,
}
As you can see, onAfterDamage is a JavaScript function, one that I can't easily call from Python (to my knowledge). So now I'm at a crossroads:
Stop grabbing the .js files from the server and write my own code entirely in Python, essentially "translating" the JavaScript code myself.
Rewrite my entire bot in JavaScript instead of Python, although I'm far less experienced and comfortable in JavaScript.
Find a way to run the JavaScript code I'm downloading from the server from within my Python bot, calling arbitrary functions from within the code and returning the results.
Option 1 has the issue of rapidly becoming out of date -- when new Pokemon mechanics are introduced or new Pokemon are created, I wouldn't get it "for free" -- I'd have to figure out what changed and implement the changes myself.
I'd like to avoid Option 2 just because I'm not very comfortable writing JavaScript -- it's something I've dabbled with in the past, but it's far from my favorite language and not something I want to deal with when it's not the primary focus of my project.
I realize that Option 3 is a pretty massive security risk -- while I'm reasonably sure that a man-in-the-middle attack won't happen to a bot that likely nobody will ever use but myself, I'm still just downloading random JavaScript from a server somewhere and trying to execute it.
I've seen things like PyExecJS, but they're no longer maintained, and I haven't really seen anyone recommending a good replacement for them. PyExecJS's functionality is exactly what I'm looking for (namely the function execjs.eval(js_code)), but I'm not sure I want to use something that's reached EOL. I've seen the answers here, but they don't recommend any replacements for PyExecJS; they only show that user that they're using it wrong.
I've also seen people suggest Selenium or running a headless browser, but I'm not sure if I want to deal with all that extra overhead. The very first programming project I ever did outside of school was very similar to this, and I wound up coding it in Java using Selenium. I wasn't happy with that experience, and I'm not looking forward to having to do it again, especially when I only need to execute JavaScript I already have downloaded locally.
Am I completely off-base here? Is there another approach I should take, or should I just get to work translating all this JS code to Python by hand?
Ideally you could run your .js-file from cli just like any other executable. With node -e you can execute your JavaScript code on cli.
Relating to this post https://stackoverflow.com/a/450329/6478277 you could similarly run your script with your local node.
node -e "function func(){console.log(123)};func();"
From a file
print subprocess.check_output(['node -e "require(\"./file.js\").test()"'])
Where file.js could be something like
module.exports = {
test: () => console.log(123),
}
I am using a WebRequest() function within the MetaTrader Terminal 4 codebase (MQL4) that allows one to download a HTML-response from a website.
Example site: http://www.forexfactory.com/docphoenix66#acct.57-tab.list
Here is an example how it is used in the MQL4 function call:
res = WebRequest( "GET",
"http://www.forexfactory.com/docphoenix66#acct.57-tab.list",
cookie,
NULL,
timeout,
post,
0,
result,
headers
);
and the documentation for the function WebRequest()
However, if I compare what is downloaded using a WebRequest() call with what you see when you right click and inspect element using Chrome or Safari, the bits I want available are missing!
In particular I want the trade information from below the following columns:
Instrument Price Open/Close Date Open/Close Lots Return
Profit Pips Chart Balance Swap Duration
And if you see below an example of what is missing from the htm file downloaded using the MQL4 function.
<td class="slidetable__cell slidetable__cell--fixed" style="width: 62px; min-width: 62px;"> <a id="snap_48205_trade_109309333" class="explorer__anchor explorer__anchor--trade"></a>
EUR/USD
</td>
If you download the HTML file, turn off your wifi and then open the file to see what was downloading, you see everything in the trade explorer still loading. Am I clear on what my problem is?
Short version: Yes, there is.
Long version: TL;DR;
Well, first, welcome to the Wild Worlds of MQL4
Given the intention is clear and given you were "promised" that there is "a possible way to read a HTML-page", I have to tell you it is not possible in all cases you will meet in real-world.
One may spend ages in MQL4-code domain to re-design html-sort-of Mark-Up syntax-(b)LOBs, suffering from all the restricted constraints the MQL4-code execution engine provided.
Nevertheless, the much faster, joyfull and a sure and future-proof ( read other posts on historically painfull creeping of the language syntax relief and crippled man*decades in API-integration code-base efforts ) approach exists .
Integrate MQL4-side via a professional fast & low-latency SIG/MSG-infrastructure with external, distributed processes, that can provide high-performance & robust services to MetaTrader Terminal ecosystem.
Using this approach we have prototyped and operate fast Mixed-Technical-and-Fundamental AI/ML-Inputs, including Web-page-feeds of Fundamental Data and News Announcements into the FX-trading realm 24/7/365 and it works blessingly well, independently of the limits the common MQL4 execution has.
If still in doubts, just try to read a page on rss.provider.com:6322/FED_actuals URL via a call to WebReqest() and you know, where is the dog burried.
While looking at how to make JavaScript source code more secure I came upon a lot of 'solutions'. but most people said the same thing; "It's not possible to make your source code 100% secure", "try obfuscation", "run your code server side", etc, etc. After reading a lot posts here on stackoverflow, and other sites I came to the conclusion that a combination of minifying and obfuscating would do the job (for me).
But here is the problem: we are currently using soma.js with dependency injection, and the way we set it up it does not work well with obfuscation. It's basically this:
var session = function(id, sessionModel){
this._sessionmodel = sessionModel;
}
mapping:
injector.mapClass("sessionModel", project.SessionModel, true);
Obfuscation will then rename the sessionModel in the function to for example 'A', but the mapping that was done on SessionModel by the injector still remains 'sessionModel' and not 'A', this then basically breaks the code.
I've read this post which is about the same subject Dependency Injection and Code Obfuscation, but it does not provide a real answer to my problem so I decided to write my own question.
Any tips/hint/suggestions are welcome.
Thanks in advance.
EDIT
It seems you can tell Yuicompressor to exclude certain identifiers by putting in 'hints' into the files like this: "identifier:nomunge, identifier2:nomunge".
var session = function(id, sessionModel){
"sessionModel:nomunge";
this._sessionmodel = sessionModel;
}
I tested this and it works but that means you'll have to put it in yourself which is a lot of work if you have to do that for every script, especially if you have a very big project..
Gonna look into it further, and update this post if anything new pops up
EDIT 2
It's been a while, I only work 1 day a week on this =S.
As said before you can get it working by telling it which identifiers to exclude.
For that I looked into regular expression to get the "mapped classes" programmatically, since doing it by hand is just insane.
What I basically did was instead of putting every hint in by hand, I made a identifier, for example "#nomunge"; and used a simple replaceregexp task to find it and replace it with a string containing all the identifiers. This string is build by loading the script and going through it with a tokenfilter.
<target name="build hints">
<loadfile property="hints" srcFile="${temp.loc}/all.js">
<filterchain>
<tokenfilter delimoutput=":nomunge,">
<ignoreblank/>
<containsregex pattern="${regexp}"/>
</tokenfilter>
</filterchain>
</loadfile>
<echo message="${hints}"/>
</target>
<replaceregexp file="${temp.loc}/all.js"
match="#nomunge"
flags = "g"
replace = "target:nomunge, dispatcher:nomunge, injector:nomunge,${hints}"
/>
This seems to do the job, for now...
I'm behind the soma.js framework, feel free to ask me questions on the google group, happy to help.
This might help a bit more:
https://groups.google.com/forum/#!topic/somajs/noOX2R4K58g
Romu
I'm looking for a way to do something that may or may not be possible.
On the site http://hitbox.tv/ there is a javascript function I believe that turns text into images.
For example, using:
emotify.emoticons("",{
"emote": ["http://example.com/emote.png", "channel"],
});
in a tampermonkey script or entering it directly into the chrome console would allow all occurrences of "emote" in the chat to be turned into that image.
If I type "emotify" into the chrome console, I'm given:
function (e,f){return f=f||function(h,j,g){return j=(j+", "+g).replace(/"/g,""").replace(/</g,"<"),'<img src="'+h+'" title="'+j+'" alt="" class="smiley"/>'},e.replace(b,function(j,g,m){var k=0,h=m,l=c[m];if(!l){for(;k<d.length&&!d[k].regexp.test(m);)k++;h=d[k].name,l=c[h]}return l?g+f(l[0],l[1],h,m):j})}
and if I type in "emotify.emoticons" I am given:
function (){var k,m,h,o,l=Array.prototype.slice.call(arguments),n="string"==typeof l[0]?l.shift():"",f="boolean"==typeof l[0]?l.shift():!1,g=l[0],j=[];if(g){f&&(c={},d=[]);for(k in g)c[k]=g[k],c[k][0]=n+c[k][0];for(k in c){if(c[k].length>2){for(m=c[k].slice(2).concat(k),h=m.length;h--;)m[h]=m[h].replace(/(\W)/g,"\\$1");o=m.join("|"),d.push({name:k,regexp:new RegExp("^"+o+"$")})}else o=k.replace(/(\W)/g,"\\$1");j.push(o)}b=new RegExp("(^|\\s)("+j.join("|")+")(?=(?:$|\\s))","g")}return c}
So what I'm wondering is, is there a way to use this code in a tampermonkey script somehow so that in the future, if the code is removed from the website, I could still use the emotify.emoticons function to create standalone emotes?
I really hope this makes sense. If you need any more information, fell free to ask. Any help is greatly appreciated!
-Tom
I might be wrong, but my inclination is that no, you can't - because the full behavior for this code is probably actually executed server-side, not in the web browser.
The images would have to get passed to the server to get circulated to the other people in the chatbox anyway
The function you list just returns a function, which does some (somewhat cryptic!) string operations, and little else, indicating the heavy lifting is done elsewhere.
The reason why you can run it using tampermonkey currently is because the function is defined on hitbox.tv. Defining it in tampermonkey probably won't help, because if hitbox removed it, they would also remove everything that uses it, rendering it useless.
You can do more investigation if you feel like it; http://www.hitbox.tv/dist/hitbox-ui.min.js is the link to their (minified) javascript file that runs the website. Running it through http://jsbeautifier.org/ yields a ~55,000 line long file, however, so unless you know what other variable words to search for, it's going to be impractical to comb through by hand.
I've been stuck with the unpleasant task of "unminifying" a minified JavaScript code file. Using JSBeautifier, the resulting file is about 6000 lines long.
Ordinarily, the variable and parameter names would be permanently lost, but in this case, I have an obsolete version of the original file that the minified JavaScript code file was generated from. This obsolete version of the original file contains most of the code comments and variable names, but absolutely cannot be used in place of the current version.
I would like to know if there is some way of renaming all instances of a particular parameter or variable in JavaScript. Since minification reduces the names to a single character, find-and-replace is impossible.
Is there some tool out there, which I can tell, in this file, the parameter a to function foo should be clientName and have it semantically rename all instances of that parameter to clientName?
Unfortunately, I work for a large organization with an approved list of software and I am stuck with Visual Studio 2010 for the forseeable future (no VS 2012).
Update: #Kos, we don't use Git, but we do use source control. The problem is that a developer who doesn't work for my organization anymore once made changes to the file, minified it, and only checked in the minified version to source control, so his changes to the original have been lost.
I'm a year late for this answer, but I had a similar problem to yours so I built this: https://github.com/zertosh/beautify-with-words. It unminifies code using UglifyJS2 but uses a phonetic word generator to rename variables. You get "long-ish" variable names so it's a breeze to do a find-and-replace. Hope this helps someone else!
You might have another way out.
Check out the last unminified version of the code. Compare to the minified version. Arguably most of it should be the same modulo consistent variable renaming. The differences you'll have to rename and remerge.
Diff won't do this kind of compare; you need tools that compare the programs as code, not text. Our SmartDifferencer tool will do this (by using language-specific full parsers to generate ASTs, and then comparing the ASTs); in effect, it compares the programs in spite of whitepspacing. SmartDifferencer also handles renaming; if two file are identical modulo a single renaming, that's what SmartDifferencer tell you.
I don't know how well this work work out; we haven't tried SmartDifferencer with 6000 lines of "consistently renamed" variables.
I found that a Visual Studio extension we've licensed here called "Telerik JustCode" has functionality to do what I want.