Can I perform mathematics on a selection in Sublime Text? - sublimetext3

Short of writing my own plugin to do so, does there exist a mechanism with which I can add/subtract from multiple selected numbers?
I need to apply the same equation (in this case, subtract 5) to many values; and I'd rather not do it individually. Could this perhaps be a job for another program?

If you already use Emmet (which I highly suggest), use its Evaluate Math function. No need to install more plugins. Only issue is that it cuts the result at 2 decimal digits.

There's plugin called Sublime-Evaluate which allows you to evaluate bits of Python, and output it straight into your buffer. For example, [i for i in range(5)] evaluated turns itself into [0, 1, 2, 3, 4]. That can be used for arithmetic operations as well, just use those multiple selections and write +5 after each value, then select it all and evaluate. The plugin usually screws positions of your cursors, don't get confused by that.

Sublime Calculate evaluates selected text, and looks great for small calculations, especially paired with the replace option: https://github.com/colinta/SublimeCalculate
As stated before, Sublime Evaluate has python evaluation covered: https://github.com/jbrooksuk/Sublime-Evaluate

Saw this yesterday and thought I would take a shot at it. Basically does the same thing as the Sublime-Evaluate (to bad I didn't see that earlier, could have saved some time). Anyways, the benefit of mine is it allows you to predefine python snippets to run. It also does some variable substitution of the content selected by the cursor. It doesn't do any expansion so you will have to select the content to insert. I was thinking of creating a setting to modify the word separator for the plugin, but hadn't decided yet. If you have an opinion on it, let me know.
https://github.com/skuroda/EvalInsert

Related

Ansible: Any way to do a non-lexicographic sorting of strings containing integers?

I have multiple versions of scripts files within the same directory. I want ansible via the find: module, through some sort of sorting comparison to always choose the highest version file it can. The issue is that the integer sorting I desire won't work because the strings in question aren't a pure integer comparison, and the lexicographic sorting won't give me the proper expected version. These filenames have a naming "convention" but there is no exact hard-coded filename versioning to work with, the versions are random within each project, but if integer ordering could be used, I/we could determine which file to use for each task.
Example, lets say I have the following 3 strings:
script_v3.sh
script_v9.sh
script_v10.sh
The normal sorting methods/filters within ansible (such as the sort filter) will try to do a lexicographic comparison of these strings in order. This means the one with the "highest" value will be script_v9.sh which is bad as I/we expect it should be script_v10.sh this is no good, as it will try to use script_v9.sh and then cause the rest of that process/task to fail. I would love to turn them into integers to do an integer comparison/sort, but as there are other non-numerical characters in the string every attempt so far to do so has been a failure. Note that I/we also need to occasionally use the lowest version in some tasks as well, which also screws up utilizing our example if lexicographic sorting is used.
I would like to know if this is possible to accomplish through some convenient comparison method, or filter which I have overlooked, or if anyone has any better ideas? The only thing I could possibly come up with is to use a regex to strip out the integers, compare them by themselves as integers, and then finally match up the result to the filename which contains the highest 10 value and then have the task use that. However, I'm horrible at regular expressions, and I'm not even certain that's the most elegant way to approach this. Anyone who could help me out would be highly appreciated.

is there a way to calculate every possible order of operation for 1 operation in Python?

Let's say that I have a = '1+2*5/3', there's a specific order to which my machine will evaluate this statement (with eval(a))
I would like to know if there's a line of code (or a function? just an elegant way that could get the job done) that would calculate :
(1+2)*5/3
1+(2*5)/3
1+2*(5/3)
(1+2*5)/3
1+(2*5/3)
(1+2)*(5/3)
1+2*5/3
In this example, I used an operation with 4 factors, so I could just code 1 function for each possibility, but I need to do the same thing with 6 factors and that would just take way too much time and effort since the possibility of different operation order would increase exponentially
It would be also great that it returns everything in a dictionary in this form {operation:result} with the parentheses included, if not i'll find my way around it
edit: as requested, the main goal is to make a program that find the solution to the game " le compte est bon " brute force method, the rules can be found here : https://en.wikipedia.org/wiki/Des_chiffres_et_des_lettres#Le_compte_est_bon_.28.22the_total_is_right.22.29
This is going to be very hard. I recommend you follow these steps:
Create a list to check if the formula has already been calculated
Randomize the order (such as +-*/ and randomly place numbers
Check if rule number`s one is a valid formula. if not try number 1 again
Randomize the order (such as opening and closing parentheses and ^)
Check if the sentence above is a valid formula. if not try number 3 again.
Check the formula through the list and see if it has already been calculated. if it has been calculated then we don't use it and go back to number two. but...
If it is not in the list then we can use it.
Those are the basic steps for common known math symbols, but what about square root?
Another way to do this is by making python move the symbols over like you did with the parentheses, but for EVERYTHING (numbers and symbols(+-/*))
EDIT:
This was before the original question was changed.

What is the most efficient way to reach a spot on sight on VIM?

Suppose you are on line 640 and notice the following on line 671:
if (jumps_over(quick_fox[brown],the_lazy_dog)) the_lazy_dog.bark();
What would be the most key efficient way to navigate to "bark"?
This is a common misconception about Vim: Vim is not designed to be efficient.
Vim is designed to use small building blocks in repeatable, often complex combinations, to achieve your goal. It is not an inherently efficient process, but for a subset of complex tasks, it's useful. For example, [motion][macro], or [count][command], these are small building blocks combined together in chains. Clicking on the screen is the most efficient movement, but might not be useful in a subset of a large text manipulation task where you have to do it thousands of times.
Here are all the ways I normally use that I can remember, you can see none of these are efficient uses of movement nor my cognitive processing power. (IDEs do things efficiently by taking out all the work listed below).
Once on the line I would personally use f.l since a quick scan shows that's a unique character. Or T. if you're past it. If there ends up being more than one . I would use ; to repeat the find until I got to it. Or, mash w or W until I got close, since trying to guess where lowercase w will take you when punctuation is involved is basically impossible in Vim.
If you have :set relativenumber on you can see how many lines away it is, and type nj to go there, then type f. to jump next to it to it
If you have :set number on you can type (since you'd know the line number) 671G (or :671Enter) f.
If you had marked that line with, say ma you could jump to the line with 'a or the exact char with `a (but most keyboards make ` useless to reach :( You probably won't use this one if it's a random look-need-to-fix jump.
If you have EasyMotion installed you could type leaderleaderfbsubchar to jump right to it
You could search for it as #kev suggests and use nN to bounce around until you get it. If bark is common but the_lazy_dog is unique you could do /dog.b/eEnter (e places cursor at end of match) and pray to the Vim gods that your search was specific enough to only match that line. That's more of a fun guessing game.
Depending on where the line is on the screen, you could use (n offset)H, M or L (high middle low) to get closer to it and use jk once there.
Or if the line has empty lines above / below it you could type the super handy { or } to help you jump close.
Or you could use the mouse if you're on a laptop where the trackpad is nearby + in gvim . I'm serious about that, even though I'd probably never do it. if you've played enough first person shooters your trigger finger may be more accurate and fast than any keyboard shortcut ;)
Despite all of Vim'm crazy keyboard power, there is not always a direct nor good way to do something, like very specific jumps. You need to keep and continuously build a bag of tricks to help you move around and use the appropriate ones for the job. I use all of the above fairly evenly and often (I use relativenumber), depending on what I think would be fastest. EasyMotion is pretty handy except that 5 keystrokes to perform one command is really awkward and error prone to type.
So in my humble few years of Vim experience, I'd say there is no good way to do it, but there are a lot of mediocre ways, that you can combine into a decent way.
Press /barkEnter. (maybe n is required)
(It depends on the shape of text. Without the information, I cannot provide a best way.)
If you wanted to increase the likelihood of a hit (ie. reducing the likelihood of having to hit n) using #Kev's suggestion, perhaps change your regular expression to include more text and offset your cursor from there. eg:
/dog\.bark/e-3
Turn on relative line numbers and the 31j becomes a VERY natural motion; this gets you to the line you need to be on.
Then, look for a unique character to the line near where you want to be. In this case . is unique and just before bark. So, f.. Then l and you're good.
So in total: 31jf.l.
(This is not always how it will work. Sometimes it's just as quick to use /bark once you've jumped to the line. Sometimes it's quicker to use /bark initially and just n a number of times to the line. Vim give you the tools, your code will always differ.)
Kev's answer works assuming bark is an uncommon word. You could be hitting n quite a few times.
I'd go with
671G to jump to the line,
$ to jump to the end of the line, and
2b to drop the cursor on the b.
Edit: reading over Andy's answer, I really have to agree with this:
Despite all of VIM's crazy keyboard power, there is not always a direct nor good way to do something, like very specific jumps.
I would opt for navigating around in approximate steps, like 9j to go down 9 lines. When you do this on reflex, you can navigate much faster than it takes to read line numbers or character position. It might end up being more keystrokes, but I prefer the extra speed.
Actually, I don't want to say that I think the most efficient way is use your mouse,
another way use command line:
/.*dog\&.*bark
this will reduce the frequency compared to /bark(and many n maybe)
One way of jumping to char on the same line was not mentioned, yet.
Use
61|
61"pipe", to jump directly to [b]ark in control mode.
I didn't incorporate this into my regular jumping, because the number is usually a guess. with with fixed 80 chars per line you can get used to it and it will be very efficient. But the pipe key is inconvenient imo. I'm planning on using it more often because of its elegance and efficieny.

eval in template strings

I'm considering porting a rather unwieldy bash script to python but I'm stuck on how to handle the following aspect: The point of the script is to generate a png image depending on dynamically fetched data. The bash script grabs the data, and builds a very long invocation of the convert utility, with lots of options. It seemed like python's template strings would be a good solution (I would vastly prefer to stay within the standard library, since I'll be deploying to shared hosting), but I discovered that you can't evaluate expressions as you can in bash:
>>> from string import Template
>>> s = Template('The width times one is ${width}')
>>> s.substitute(width=45)
'The width times one is 45'
>>> t = Template('The width times two is ${width*2}')
>>> t.substitute(width=45)
# Raises ValueError
Since my bash script depends quite heavily on such arithmetic (otherwise the number of variables to keep track of would increase exponentially) I'd like to know if there's a way to emulate this behavior in python. I saw that this question, asking roughly the same, has a comment, reading:
This would be very unPythonic, because it's counterintuitive -- strings are just
strings, they shouldn't run code!
If this is the case, what would be a more idiomatic way to approach this problem?
The proposed answer to the question linked above is to use string formatting with either the % syntax or the format() function, but I don't think that would work well with the number of variables in my string (around 50).
Why not use built-in string formatting?
width = 45
"Width times one is {width}".format(width=width)
"Width times two is {width}".format(width=2*width)
results in
Width times one is 45
Width times two is 90
The Pythonic solution to this problem is to forget about string formatting and pass a list of arguments to one of the subprocess functions, e.g.
# I have no idea about convert's command line usage,
# so here's an example using echo.
subprocess.call(["echo", str(1 + 1), "bla"])
That way, there's no need to build a single string and no need to worry about quoting.
You probably need a better templating engine. Jinja2 supports this kind of stuff and a lot more. I don't think the standard library has anything equally powerful, but from what I figured, the library is pure Python, so you can integrate it into your application by just copying it along.
If Jinja doesn't fit you for some reason, have a look at the Python wiki, which has a section specifically for those kinds of libraries. Amongst them is the very lightweight Templite, which is only one class and seems to do exactly what you need.
The task is not that hard, why don't you just make some coding for fun? And here is the function almost does what you want.
import re
def TempEval(template,**kwargs):
mark = re.compile('\${(.*?)}')
for key in kwargs:
exec('%s=%s'%(key,kwargs[key]))
for item in mark.findall(template):
template=template.replace('${%s}'%item,str(eval(item)))
return template
print TempEval('The width times one is ${width}',width=5)
#The width times one is 5
print TempEval('The width times two is ${width*2}',width=5)
#The width times two is 10

Identifying frequent formulas in a codebase

My company maintains a domain-specific language that syntactically resembles the Excel formula language. We're considering adding new builtins to the language. One way to do this is to identify verbose commands that are repeatedly used in our codebase. For example, if we see people always write the same 100-character command to trim whitespace from the beginning and end of a string, that suggests we should add a trim function.
Seeing a list of frequent substrings in the codebase would be a good start (though sometimes the frequently used commands differ by a few characters because of different variable names used).
I know there are well-established algorithms for doing this, but first I want to see if I can avoid reinventing the wheel. For example, I know this concept is the basis of many compression algorithms, so is there a compression module that lets me retrieve the dictionary of frequent substrings? Any other ideas would be appreciated.
The string matching is just the low hanging fruit, the obvious cases. The harder cases are where you're doing similar things but in different order. For example suppose you have:
X+Y
Y+X
Your string matching approach won't realize that those are effectively the same. If you want to go a bit deeper I think you need to parse the formulas into an AST and actually compare the AST's. If you did that you could see that the tree's are actually the same since the binary operator '+' is commutative.
You could also apply reduction rules so you could evaluate complex functions into simpler ones, for example:
(X * A) + ( X * B)
X * ( A + B )
Those are also the same! String matching won't help you there.
Parse into AST
Reduce and Optimize the functions
Compare the resulting AST to other ASTs
If you find a match then replace them with a call to a shared function.
I would think you could use an existing full-text indexer like Lucene, and implement your own Analyzer and Tokenizer that is specific to your formula language.
You then would be able to run queries, and be able to see the most used formulas, which ones appear next to each other, etc.
Here's a quick article to get you started:
Lucene Analyzer, Tokenizer and TokenFilter
You might want to look into tag-cloud generators. I couldn't find any source in the minute that I spent looking, but here's an online one:
http://tagcloud.oclc.org/tagcloud/TagCloudDemo which probably won't work since it uses spaces as delimiters.

Resources