This obviuosly works perfectly:<script>alert(5*8-4)</script>
but i need to solve whatever someone puts inside an input box.
Heres what I thought of doing: I would get the value of the input, into a variable. then I would use
document.write("<script>alert("+theinputvalue+")<script>");
or do this:
var string="<script>alert("+theinputvalue+")<script>";document.write(string);
but nothing works.
Is it even possible to do this? if not, tell my what simple other system I could use.
eventually, I will use it to graph lines like this:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d")
for(var x=-100; x<100; x=x+.2){
y = .1*(x*x)
ctx.fillRect(x+50, -1*y+50, 2, 2);
}
http://jsfiddle.net/KGgq4/
eval('5*8-4')
will result in 36
I'm not aware of any library that is doing that (this doesn't mean that there are no such it simply means I never actually needed that) but what you should end up doing is to build an automata that will parse input string and transform it to a proper graph with proper transformations. This is not very easy topic and if you want to go this route you should start reading on arithmetic expressions parsing algorithms (sorry I do not have any solution in place).
Or you can cheat and define types of equations that will be selected by user. Once user selects type of equation you should be able show user inputs where user will be able to select coefficients. You can read those coefficients into different variables and apply transformations in your draw procedure (For example if user will select type sin(x) you know that general equation has following formula: y = k*sin(a*x + b) + c. So once it is selected you can allow user to enter k, a, b, c and based on that input calculate appropriate locations of points for your graph.)
Well, third solution could involve "eval ", but usually you should avoid eval at any cost (B/c it is straight forward JavaScript injection which may be an OK for this case but may get you in trouble later in your life. ).
You can use math.js, which comes with an advanced expression parser. It supports definition of variables and functions.
// create an instance of math.js
var math = mathjs();
// evaluate an expression
math.eval('5*8-4'); // 36
// user defined function (returns a native JavaScript function)
var f = math.eval('f(x) = 2*x^2 + 6');
// use the function (for graphing or something)
f(2); // 14
Related
I'm making a bot for a gaming chatroom with some friends, but I've hit an impasse. Is there a reliable way to get numbers from inside a string of text that won't completely break an inexperienced script kiddy's brain? Here's the best I've been able to come up with so far, variables simplified slightly for illustration's sake:
var k = [0];
function dieRoll(m,n) {
for(i = 0; i < m; i++) {
k[i] = Math.floor(Math.random()*n)+1;
}
}
var m = text[5];
var n = text[7];
if (text === 'roll '+m+'d'+n) {
dieRoll(m,n)
console.log(k);
}
The biggest problem as-is is that it's limited to single-digit input.
EDIT: Looping through the text looking for integers is exactly the kind of thing I'm looking for. I don't have much experience with programming, so I probably tend to end up with overly complicated and confusing messes of spaghetti code that would embarrass anyone remotely professional. As for the format of the input I'm looking for, "roll [number of dice]d[highest number on the dice]". For anyone who doesn't know, it's the notation most tabletop rpgs use. For example, "roll 2d6" for two normal six-sided dice.
EDIT: It's not that I'm necessarily against regex, I just want to be able to understand what's going on, so that if and when I need to edit or reuse the code it I can do so without going completely insane.
EDIT: Thank you all very much! split() seems to be exactly what I was looking for! It'll probably take some trial and error, but I think I'll be able to get her working how she's supposed to this weekend (Yes I call my bots 'she').
Basically, you need to look at the format of the input you're using, and identify certain facts about it. Here are the assumptions I've taken based on your question.
1) The "roll" command comes first followed by a space, and
2) After the command, you are provided with dice information in the form xdy.
Here's something that should work given those constraints:
function getRollParameters(inputCommand) {
var inputWords = inputCommand.split(' '); //Split our input around the space, into an array containing the text before and after the space as two separate elements.
var diceInfo = inputWords[1]; //Store the second element as "diceInfo"
var diceDetails = diceInfo.split('d'); //Split this diceInfo into two sections, that before and after the "d" - ie, the number of dice, and the sides.
//assign each part of the dicedetails to an appropriate variable
var dice = diceDetails[0];
var sides = diceDetails[1];
//return our two pieces of information as a convenient object.
return {
"dice": dice,
"sides": sides
};
}
//a couple of demonstrations
console.log(getRollParameters("roll 5d8"));
console.log(getRollParameters("roll 126d2"));
Effectively, we're first splitting the string into the "command", and the "arguments" - the information we want. Then, we split our arguments up using the "d" as a midpoint. That gives us two numbers - the one before and the one after the d. Then we assign those values to variables, and can use them however we like.
This obviously won't deal with more creative or flexible inputs, and isn't tested beyond the examples shown but it should be a decent starting point.
Is there a way to inspect which variables (and lines of code) contribute to a value in Javascript? For example if I would inspect the parameter input in this code
let x=5;
let y=x+3;
function a(input) {
// analyzing input in this scope/context,
// i would like to see that it is a combination of
// x from line 1 and a constant '3' from line 2.
inspectDataFlow(input);
}
a(y);
I would like to get as output a data structure that would be something like this:
input (line 8)
y (line 2)
x (line 1)
"3" (line 2)
Purpose and goal
My goal for this would be to have a tool where you could see/change the value of a Javascript variable and it would automatically adjust the variables that the value originates from.
For example, you could have a function to draw shapes. And when you adjust visually the shapes that were drawn, the original variables for color, shape positions etc would update accordingly.
Something a bit like this but for editing arbitrary code, even after a user has modified the code lines:
http://yining1023.github.io/p5PlayGround/
Another idea I was thinking was to visualize how a variable has been composed: which lines it is a combination of and how they affect the result.
Potential approach
One approach for this I'm thinking about is to add instrumentation to the code with Esprima/Acorn that is then called on runtime. The instrumentation would keep track on which variables have been called on which lines (and scopes) and how they relate to each other, a bit like this:
http://alltom.com/pages/instrumenting-javascript/
I wonder if this would work and if there is a framework one could use for this? Or if one would have to do the instrumentation from scratch?
Related themes
This could be related to data flow analysis or use-define chains, but I'm not sure, since I don't know much about compilers.
https://en.wikipedia.org/wiki/Use-define_chain
My first idea was that this could be done using static analysis with something like Esprima/Acorn, but I'm not sure if that is the right way, or if this could be done with some custom Javascript interpreter instead.
http://tobyho.com/2013/12/02/fun-with-esprima/
I'm using ExtendScript to work on JavaScript for Adobe Illustrator 2015. Is there any way I could get RGB values from a coordinate in the code below?
// declares a document
var doc = app.activeDocument;
// sets x and y coordinates to get color from
var xPosition = 70.0;
var yPosition = 64.0;
This is what needs work:
// gets rgb values
double redValue = doc.getRGBColor(xPosition, yPosition).red;
double greenValue = doc.getRGBColor(xPosition, yPosition).red;
double blueValue = doc.getRGBColor(xPosition, yPosition).red;
I've googled quite a bit and found this.
It doesn't work, though, either because it was posted in 2009, or because it was meant to be in photoshop.
A solution to the problem or translation of that post would be greatly appreciated.
[EDIT: My apologies for giving essentially an AppleScript answer to your ExtendScript question. I was just looking over AS questions and forgot I went to a different section. I can only hope that you are on a Mac. If not, I guess I'll just eat my downvotes and weep.]
There is a workaround. The advantage of it (and part of the workaround nature of it) is that it works in all apps. The downside is that it requires python (which should be on your Mac anyway - fairly easy to install if not), and two pieces of third party software (both free), "checkModifierKeys" and "cliclick". I've been using a script that appears in my script menu for years.
The python part is described here: http://thechrisgreen.blogspot.com/2013/04/python-script-for-getting-pixel-color.html
This script can be saved, made executable and invoked using the AS do shell script command.
and the rest of it, for selecting a point on the screen and for waiting for the control key to be pressed (that's how mine works) is pretty simple.
The basic checkModifierKeys part (which waits until the Control key is pressed) is:
set controlIsDown to false
repeat until (controlIsDown)
set initialCheck to ((do shell script "/usr/local/bin/checkModifierKeys control"))
if initialCheck = "1" then set controlIsDown to true
end repeat
The cliclick part (which gets the coordinates) is:
set xyGrabbed to do shell script "/usr/local/bin/cliclick p"
It may seem like a long way to go for it, but it works great. My version converts the rgb value to hex with this handler, which is useful for my purposes:
to makeHex(theNumber) --was anInteger
--Converts an unsigned integer to a two-digit hexadecimal value
set theResult to ""
repeat with theIndex from 1 to 0 by -1
set theBase to (16 ^ theIndex) as integer
if theNumber is greater than or equal to theBase then
set theMultiplier to ((theNumber - (theNumber mod theBase)) / theBase) as integer
set theResult to theResult & item theMultiplier of ¬
{1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"}
set theNumber to (theNumber - theBase * theMultiplier)
else
set theResult to (theResult & "0")
end if
end repeat
theResult
end makeHex
Yes, this solution doesn't work, because in vector editors such as Illustrator, color is applied to vector item (path) on the whole not to separate pixels. Even if you work with pixel image in illistrator there are no scripting functions to get pixel color.
I think it could be achieved via the rather monstrous solution:
Rasterize the artrboard.
Create Object Mosaic (where one tile ~> one pixel).
Figure out which one of the tiles lies underneath the given coordinates and pick its color.
I've got a basic Space Invaders type game going, and I can't get it to recognise when the shot from the player hits the alien. (I'm only checking Alien2 atm, the one second from the left). Since they're both moving, I've decided the only way to check for collisions is with either a range-based if statement (with 2 top coordinates and one left coordinate), or directly comparing the positions along the Y axis with Jquery.
I'm using the range-based solution at the moment, but so far it hasn't worked (not sure why).
My code so far:
if (key == "87"/*&& document.getElementById('BarrelOne').id=='BarrelOne'*/){
var Invader2 = document.getElementById('Alien2');
var Shot1 = document.getElementById('ShortShot');
Shot1.style.webkitAnimationPlayState="running";
setTimeout(function(){
Shot1.style.webkitAnimationPlayState="paused";
}, 1200);
if(document.elementFromPoint(625.5, 265.5) == Shot1){
Invader2.style.visibility="hidden";
}
};
Jsfiddle:
http://jsfiddle.net/ZJxgT/2/
I did something similar, and i found that it was much easier to achieve using gameQuery.
to test for collisions:
var collided = $("#div1").collision("#div2");
you can see full working example here
EDIT
If you're having trouble check out the API. For example, to find out how to use collisions check this part of the API.
the collision works in the following way:
This method returns the list of elements collisioning with the selected one but only those that match with the filter given as parameter. It takes two optional arguments (their order is not important). The filter is a string filtering element used to detect collision, it should contain all the elements the function should search collision into. For example if you look for collision with element of the class ‘foo’ that may be contained in a group you will use the filter ".group,.foo".
So, write something like this:
$("#ShortShot").collision("#Alien2").hide();
// will return the alien if it collides with ShortShot
or, to hide them both:
if (($("#ShortShot").collision("#Alien2")).length) {
$("#ShortShot").remove();
$("#Alien2").remove();
}
Instead of losing hours reinventing the wheel, I would suggest to switch (if still possible, depending on your time deadline) to a real 2D game engine for Javascript, with easy collision detection.
Check as well: 2D Engines for Javascript
I'm making a dew point calculator using the "closer approximation" on wikipedia.
I want to be able to calculate the dew point if the user enters any two variables.
Is there an easy way to do this rather than having a lot of if-statements?
More specifically: What if I wanted to use the wet-bulb temperature instead of the relative humidity? Would I have to make a new function or use an if-statement to exclude a set of variables?
Currently I'm using the temperature and relative humidity:
$('#calculate').click(function(){
//Get Temp
var T = parseInt($('#val1').val());
//Get RH
var RH = parseInt($('#val2').val());
//Get es and ex
var es = 6.112*Math.exp(17.76*T/(T+243.5));
var ex = (RH*es)/100;
//Calculate Dew Point
var Tdp = (243.5*Math.log(ex/6.112))/(17.67-Math.log(ex/6.112));
$('#output').append("<p>Dew Point"+Tdp+"</p>");
});
FYI solving systems of nonlinear equations is generally a hard problem. Do whatever you can to avoid that.
My usual approach if multiple pairs of values can be used to calculate an answer is to use the pair of values I'm given to calculate a canonical pair of values, which then is used to do the real calculation. Furthermore since it gets messy to have to sort through input to figure out what you have been given so you can DWIM, it might make sense to have separate functions for each pair of inputs that I'll accept. (Or it might not depending on the flow of control in your program, you know that better than I do.)