Saving Formula Patterns - javascript

Short: I need a way to save Formulas, so that I can execute them when I need it
Details: I am writing something for a eccommerce-system, so that the price of a product can be calculated by volume of the product. I want the backend-user (admin, seller of the product) to be able to set custom formulas for different ways of calculating the voluma. [e.g. (A x B - C x D) * E; A x B x (C - D);]. They differ in operations used (*,-,/,+) and in the amount of variables used in the formula.
I need a way to save this formulas (string is obviously a bad idea) in PHP, so that I can use them when I need them (set A,B,C,D,E to values and get the result) and also pass them by to Javascript and use them there too.
I appreciate any input on how this could be done.

Wow, nice problem! Here are some ideas.
a) Meta programming (is it the right word?)
In JS you can define a formula with a simple statement:
var f = new Function('a', 'alert(a)');
You can write a startup script which reads all the formula and load then dinamically (querying a webservice for example). This function could be called as expected:
f('Here I am');
There are many years since i learnt PHP but I think you could try dynamic includes. When user defines a formula you could generate a file on a special folder containing the PHP code representing it. If PHP allows function reference, the formulas could be accessed like:
$formulaBag['MyFormula']('Here I am')
Since you're allowing the user to insert code in your system, you should avoid "direct programming". Offer your user a small language for formula definition. When it is done, you trigger a process parse the formula-script and generate the corresponding JS and PHP code.
b) Dynamic parsing
It seems you have some performance concerns... if you define a simple language, parsing it in PHP would be not that difficult. Do you expect to run many formulas on a long-time-running process? If not, maybe this is a better option since you will not need to generate dynamic includes (security risk?). Calculating the formula would be something like this:
$res = ExecuteFormula($formula_name, $array_of_parameters)
[Added]
Parsing is not that difficult. You will need a Finity State Machine and a Stack to "reserve" temporary values when leading parentheses.
Well, I hope it helps.

Related

Find a random variable using a relation and given sufficient inputs in Javascript

Lets say I have a relation E = mgh. And I have four textboxes on my site. Given three values, I can compute the value of the fourth variable by rearranging the variables by hand. But how to do so programmatically, efficiently, without redundant code.
Now the worst way of doing (which I have painfully done in the past in a different language) is manually checking which of the four variables is not inputted in the textboxes and then use a precomputed relation like g = E/mh to get its value. But this is bad because as the formula becomes more and more complex with more variable or different powers, it is tiresome and impractical to do by hand.
So what I'm looking for, is a Proof of Concept for JavaScript which can take a certain no of values, and a relation relating those values to find out the value of the missing variable on its own. Also note: the relation may not be a simple relation it might be complex like E=(m^1/2)(g^1/3)(h^4)
An Example of this might be this site where I can plug in some values and it will auto-compute the missing value on its own. I don't know what underlying structure they might be using, as they might have all the relations precomputed by hand.
EDIT
For all those out there, who feel this question being like asking for a Library recommendation, it is not. I'm looking for a minimal example which can do the following:
Using Array's/ Objects transform a given relation into another. (Generally referred in mathematical terms as rearranging the terms)
Now Using the above relation compute without using eval()
I know what to do for the second, i.e take the new expression, find the variable and then put the value at the place of the variable in the string.
Then evaluate the expression. Like ("y=x+3*e") -> (y="3+3*30")
How do I make the first step possible?
(OR) Do you have a better approach for this problem.

How to access changing the order number in each opening PDF file?

I would like to create order number (following) in header, which would create automatically for each different opening the file by customer. Can I achieve this by using some functions in JS? or another? In attached screen this number should generate in each opening file
I presume that you are using Acrobat Pro to create the PDF form.
The quick and easy way to do this is to auto generate an order number based on the current date and time. Create a text field in your form (I've called mine "ordernumber"), double click it and go to the calculate tab then insert the following two lines into the custom calculation script box:
f = this.getField("ordernumber");
f.value = util.printd("yyyy/ddmm/hhmmss", new Date());
This will give you a unique order code (unless someone creates two orders in the same second!). You can change around the year (yyyy), day (dd), etc to make something that you like as a format.
If the order number needs to conform to an existing format or align with other systems then you would need to get the PDF to access an external database or something like that which would be a bit more complicated and beyond my knowledge.
It depends on whether your order number has to be unique only, or whether order numbers have to be consecutive.
In the first case, #Chris' answer pretty much gives the solution; you may be fiddling around with the base data, but that's it.
If the number has to be consecutive, there is a possibility if the use of the form can be limited to one single computer. In this case, you would create a Persistent Global Variable (which is a variable that is written back to the system, and can be reused the next time you open the document). See Acrobat JavaScript documentation for code samples. When you open the document, you read in that number, increment it and feed it into your order number field, and write it back.
If the number has to be consecutive, and the order form is used by several users, you will have to maintain the order number externally (which means, on a server). In this case, it might be even better to have a server-side order management, where the user may enter some base data, and then gets the prefilled order form made available.

Options for dynamic code generation

I have a (hypothetical) question and I think the solution would be to dynamically generate code.
I want to quickly evaluate an arbitrary mathematical function that a user has entered, say to find the sum i=1 to N of i^3+2i^2+6i+1. N is arbitrary and i^3+2i^2+6i+1 is arbitrary too (it need not be a polynomial, and it might contain trigonometric functions and other functions too). Suppose N can be very large. I want to know how I can evaluate the answer quickly, assuming that I have already parsed the user input to some bytecode or something else my program can understand.
If possible, I would also like my code to be easily compiled and run on different operating systems (including mobile).
I have thought of a few ways:
1) Write an interpreter that interprets and executes each command in my bytecode. This makes me free to use any language, but it's slow.
2) Write in Java/C# and use the dynamic code generation (e.g. Is it possible to dynamically compile and execute C# code fragments?). This would execute as as fast as if I had written the function directly in my source code, with a only a slight slowdown as C#/Java are both JIT-compiled to machine code. The limitation is that Java isn't widely supported on mobile, and C# is Windows-only.
3) Embed an assembler/C++ compiler/compiler for whatever compiled language that I use. The limitation is that it won't work on mobile either - it won't let me execute a data file.
4) Write HTML/Javascript then embed it in a web browser control and put it in an application (I think this is the way some people use to make a universal app that would run anywhere). But it's slow too and writing real applications in Javascript is a pain.
Which option do you think is most suitable? Or perhaps I should go with a mix, maybe my application code will create and execute a generated Javascript function?
The fastest and simplest way to perform these calculations on large values of N are with raw maths instead of repeated summation.
Here's a formula to calculate each individual item in the expression, perform this for all items in the expression and you are done:
H[n] is the nth Harmonic number.
There are multiple approaches to calculating H[n]. Some calculate the largest required number and generate all up to that number, saving any other values required...
Alternately store every 10,000th item in the series in a file and calculate H[n] from the nearest entry.

Appropriate DB solution for browser-based interactive query tool

I am working on an interactive query application for data records that look like this in a CSV file:
w1 w2 ... , w3 w4 w5 ... , f1, f2, f3, f4
where the first and second field contain phrases comprised of 1-15 words, and the rest (n1, n2 ...) are simply floating point numbers ("features"). The data can contain as many as 2-5 million such records.
I want to build a browser-based, standalone interactive querying app where I can run queries such as:
find N records (10 < N < 100) where the first (second) field is of length 5 words or less
find N records where the first (second) field contains a specific string
find N records with the highest (lowest) values for feature f1 (or f2/f3/f4)
find N records where the first field is longer (shorter) than the second field
...
I would like to use jquery to build the interactive part of this tool and, therefore, I figure that I need to use something like MongoDB to store the (JSON-formatted) data which I can then query using javascript. However, I am not sure whether it is even possible to use entirely local, client-side databases with JavaScript inside a browser. I am also not sure whether MongoDB can deal with queries like this for the data sizes that I will be dealing with. I am a complete novice at stuff like this so it is entirely possible that I may have missed something that's much more appropriate to this situation.
Thanks in advance!
I would think many local client browsers would run out of memory at that scale. I'd use Ajax to pass the queries back to some more traditional server-side database technology.
If you are developing this for an in-house type of project, you could definitely look into HTML5 client-side storage.
See:
http://www.webkit.org/blog/126/webkit-does-html5-client-side-database-storage/
https://developer.mozilla.org/En/Storage

Javascript Textarea Monitoring / Ruby Delta Calculation

I am working on a system which needs to keep constant (and I mean constant) track of browser side changes to a textarea via AJAX requests to the server. Ideally, every character would be stored as a row in the database, along with the position it was inserted and a timestamp.
I am hoping that there is either a good Javascript library that I have somehow missed which will make it trivial to do this all in the browser, but I think that inconsistencies in the DOM prevents one from doing so in any way which will be resource-reasonable. I'm a jQuery user, if that makes a difference.
The documents being created can get very large, so it is inefficient to send the entire document back and perform a diff on the server, but I think that I can work out a way to only send back the lines which are affected by an edit. Unfortunately, I do need a way to get per-character as opposed to per-line diffs calculated once it reaches the server.
I would like to use Ruby, so if there is a Ruby library that can do that, awesome. If not, is there a generic algorithm to calculating actual deltas between two strings that someone can suggest?
Summary:
Javascript Library for very tightly monitored textarea OR
Ruby library for calculating deltas OR
Generic delta calculation algorithm
In that order. Thank you in advance.
I think you can try having Ruby to call diff via the command line, then return those diff back to user ;)

Categories