I'm trying to write a batch file that performs operations depending on the result of a modulus operation performed on a set variable. However, I can't seem to get it quite right.
To first of all test my syntax for the mathematical operation, I've been trying to get a simpler script to produce desired results.
:START
SETLOCAL
SET /P Input-Num="Input Number: "
SET /A Input-Num=%Input-Num% %% 2
ECHO %Input-Num%
ENDLOCAL
PAUSE
:END
If I input 5, the expected output is 1. However, instead I get a message saying Missing operator. and then it outputs 5.
What am I doing wrong here?
Using SET /P is your problem, as 5 is no longer treated as a numerical value. Your example as above works as expected
Related
I've written a prime-generating function generatePrimes (full code here) that takes input bound::Int64 and returns a Vector{Int64} of all primes up to bound. After the function definition, I have the following code:
println("Generating primes...")
println("Last prime: ", generatePrimes(10^7)[end])
println("Primes generated.")
which prints, unexpectedly,
Generating primes...
9999991
Primes generated.
This output misses the "Last prime: " segment of the second print statement. The output does work as expected for smaller inputs; any input at least up to 10^6, but somehow fails for 10^7. I've tried several workarounds for this (e.g. assigning the returned value or converting it to a string before calling it in a print statement, combining the print statements, et cetera) and discovered some other weird behaviour: if the "Last prime", is removed from the second print statement, for input 10^7, the last prime doesn't print at all and all I get is a blank line between the first and third print statements. These issues are probably related, and I can't seem to find anything online about why some print statements wouldn't work in Julia.
Thanks so much for any clarification!
Edit: Per DNF's suggestion, following are some reductions to this issue:
Removing the first and last print statements doesn't change anything -- a blank line is always printed in the case I outlined and each of the cases below.
println(generatePrimes(10^7)[end]) # output: empty line
Calling the function and storing the last index in a variable before calling println doesn't change anything either; the cases below work exactly the same either way.
lastPrime::Int = generatePrimes(10^7)[end]
println(lastPrime) # output: empty line
If I call the function in whatever form immediately before a println, an empty line is printed regardless of what's inside the println.
lastPrime::Int = generatePrimes(10^7)[end]
println("This doesn't print") # output: empty line
println("This does print") # output: This does print
If I call the function (or print the pre-generated-and-stored function result) inside a println, anything before the function call (that's also inside the println) isn't printed. The 9999991 and anything else there may be after the function call is printed only if there is something else inside the println before the function call.
# Example 1
println(generatePrimes(10^7)[end]) # output: empty line
# Example 2
println("This first part doesn't print", generatePrimes(10^7)[end]) # output: 9999991
# Example 3
println("This first part doesn't print", generatePrimes(10^7)[end], " prints") # output: 9999991 prints
# Example 4
println(generatePrimes(10^7)[end], "prime doesn't print") # output: prime doesn't print
I could probably list twenty different variations of this same thing, but that probably wouldn't make things any clearer. In every single case version of this issue I've seen so far, the issue only manifests if there's that function call somewhere; println prints large integers just fine. That said, please let me know if anyone feels like they need more info. Thanks so much!
Most likely you are running this code from Atom Juno which recently has some issues with buffering standard output (already reported by others and I also sometimes have this problem).
One thing you can try to do is to flush your standard output
flush(stdout)
Like with any unstable bug restarting Atom Juno also seems to help.
I had the same issue. For me, changing the terminal renderer (File -> Settings -> Packages -> julia-client -> Terminal Options) from webgl to canvas (see pic below) seems to solve the issue.
change terminal renderer
I've also encountered this problem many times. (First time, it was triggered after using the debugger. It is probably unrelated but I have been using Julia+Juno for 2 weeks prior to this issue.)
In my case, the code before the println statement needed to have multiple dictionary assignation (with new keys) in order to trigger the behavior.
I also confirmed that the same code ran in Command Prompt (with same Julia interpreter) prints fine. Any hints about how to further investigate this will be appreciated.
I temporarily solve this issue by printing to stderr, thinking that this stream has more stringent flush mechanism: println(stderr, "hello!")
So, I have some code which is supposed to check whether a pre-check sequence has completed before I begin patching a server. I'm doing this by using an until loop and as the condition, I have a flag set to true. When the flag is set to false that means that the pre-checks are done and I can now proceed out of the until loop.
The problem is I get stuck in an infinite loop and I get an error message saying [: true: integer expression expected
I continually call a URL to conduct my checks, and it returns a file which I save. An example extract from that file would be:
inProgress":true,"status":"IN_PROGRESS","preCheckMessages":[],"precheckResultItems":[]}
The part I need to extract from this is the value from the inProgress field (which could be 'true' or 'false'). I then use this value to compare to my flag. So I extract the value from the inProgress field.
The section of code causing me an issue is as follows:
inProgress="true"
until [ "$inProgress" -eq "false" ]
do
long_URL_goes_here > jobIdCheck.txt
inProgress=$(grep -o 'inProgress.*$' jobIdCheck.txt)
word="inProgress\":"
tempVar=${inProgress##${word}}
inProgress=${tempVar%%,*}
echo inProgress value = ${inProgress}
done
echo "Pre-checks complete. Ready to apply patch"
This is where I hit the infinite loop with the error message saying [: true: integer expression expected. (I never see the "Pre-checks complete message")
But I don't understand why it would be expecting an integer? Surely the string comparison should suffice?
Is the fact that the value true in the inProgress field ISN'T encapsulated in double quotes important?
Any help will be greatly received.
I am new to IDL and find the KEYWORD_SET difficult to grasp. I understand that it is a go no go switch. I think its the knocking on and off part that I am having difficulty with. I have written a small program to master this as such
Pro get_this_done, keyword1 = keyword1
WW=[3,6,8]
PRINT,'WW'
print,WW
y= WW*3
IF KEYWORD_Set(keyword1) Then BEGIN
print,'y'
print,y
ENDIF
Return
END
WW prints but print, y is restricted by the keyword. How do I knock off the keyword to allow y to print.
Silly little question, but if somebody can indulge me, it would be great.
After compiling the routine, type something like
get_this_done,KEYWORD1=1b
where the b after the one sets the numeric value to a BYTE type integer (also equivalent to TRUE). That should cause the y-variable to be printed to the screen.
The KEYWORD_SET function will return a TRUE for lots of different types of inputs that are basically either defined or not zero. The IF loop executes when the argument is TRUE.
Keywords are simply passed as arguments to the function:
get_this_done, KEYWORD1='whatever'
or also
get_this_done, /KEYWORD1
which will give KEYWORD1 the INT value of 1 inside the function. Inside the function KEYWORD_SET will return 1 (TRUE) when the keyword was passed any kind of value - no matter whether it makes sense or not.
Thus as a side note to the question: It often is advisable to NOT use KEYWORD_SET, but instead resort to a type query:
IF SIZE(variable, /TNAME) EQ 'UNDEFINED' THEN $
variable = 'default value'
It has the advantage that you can actually check for the correct type of the keyword and handle unexpected or even different variable types:
IF SIZE(variable, /TNAME) NE 'LONG' THEN BEGIN
IF SIZE(variable, /TNAME) EQ 'STRING' THEN $
PRINT, "We need a number here... sure that the cast to LONG works?"
variable = LONG(variable)
ENDIF
If I want to know, whether variable v exists in zsh, I can use ${+v}. Example:
u=xxx
v=
print ${+u} ${+v} ${+w}
outputs 1 1 0.
If I want to access the content of a variable, where I have the NAME of it stored in variable v, I can do it with ${(P)v}. Example:
a=xxx
b=a
print ${(P)b}
outputs xxx.
Now I would like to combine the two: Testing whether a variable exists, but the name of the variable is stored in another variable. How can I do this? Example:
r=XXX
p=r
q=s
Here is my approach which does NOT work:
print ${+${(P)p}} # Expect 1, because $p is r and r exists.
print ${+${(P)q}} # Expect 0, because $q is s and s does not exist
However, I get the error message zsh: bad substitution.
Is there a way I can achieve my goal without reverting to eval?
print ${(P)+p}
print ${(P)+q}
The opening parenthesis of of a Parameter Expansion Flag needs to follow immediately after the opening brace. Also, it is not necessary to explicitly substitute p or q as (P) takes care of that. Nevertheless, ${(P)+${p}} and ${(P)+${q}} would also work.
Problem
Is there a way to put a variable "to the power" of a number or other variable a batch file? Does a function exist for this? An example of this would be in Python where you can use ** for "to the power of".
EDIT
You can do maths in a batch file... http://en.wikipedia.org/wiki/Batch_file
The power to function is not available in batch scripting, as you may have already figured out from the answers.
One option is to use a loop. You can do the looping the way #Kirk Broadhurst did it last time he had to do the batch scripting, or you can use another way that has become available since then or otherwise may have gone unnoticed by Kirk:
:: calculate x^n
SET x=3
SET n=5
SET result=1
FOR /L %%i IN (1,1,%n%) DO SET /A result*=x
ECHO %result%
Another option is to use the approach described in this answer.
You don't have many maths functions / operators to work with, and you don't have proper loops either so you need to simulate these.
The basic algorithm for x^n
result = 1
for (i = 0 ; i < n; i++)
{
result = result * x;
}
In a batch file you'd need to use goto statements rather than a real loop.
set result=1
set i=1
:multiply
set /a result=result*x
set /a i=i+1
if %i% lss %n% goto multiply
This won't work for non-integer or negative / zero exponents, but you can work that out.
#echo off
:start
echo Set the value of the Base
set x=
set /p x=
echo set the power the Base is raised to
set n=
set /p n=
set y=%x%
If %n%==0 goto sol1
If %n%==1 goto solx
set /a n=%n%-1
set p=0
:eloop
set p=%P%
set /a p=%P%+1
set /a y=%y%*%x%
If %P%==%n% goto sol
goto :eloop
:sol1
set y=1
echo %y%
pause
goto :start
:solx
set y=%x%
echo %Y%
pause
goto start
:sol
set y=%y%
echo %y%
pause
goto start
This code works for all positive integers you select the base then the power the base is raised to it then loops the expression multiple times by adding 1 to a variable p until it matches a variable n multiplying x by itself each time then giving the solution it also gives a solution of %x% for n=1 and 1 for n=0.
I really like the answer by #Andriy, but I'd add one thing to make it a reusable function.
#echo off
CALL :pow 2 3 :: 8
CALL :pow 3 3 :: 27
CALL :pow 5 5 :: 3125
CALL :pow 256 3 :: 16777216
set /p=End of Script, press any key to exit...
GOTO :EOF
:: ----- Call Functions -----
:pow
SET pow=1
FOR /L %%i IN (1,1,%2) DO SET /A pow*=%1
ECHO %pow%
GOTO :EOF
P.S. You can also put the "functions" in files (for example "pow.bat", usage would be just "pow n n") and call them that way, which can be handy (especially if you start using the path variable). I've always found creating reusable functions in Batch to be the coolest but least known "feature" of the scripting language. Additionally, you'd be able to use the variable %pow% in your script (or assign it to another variable) until overwritten by calling the function again.
One last point I'd like to make is that while this is a fun exercise, there is a precision limitation to Batch.. I've found that batch fails to compute properly numbers greater than 2**31 (32 bit limitation).
Best!