'<=' and '>=' operators do not work - ruby

To check if the the installer is installed, I did:
installer status |grep Version| cut -c12-13
The ouput [sic] says:
installer not found
But if it were installed, it would say 11 or 10 (any numeric). If the output is <=10 || >=11, then it would say not installed, and would proceed with the installation. In the library, it gives:
def get_installer_linux_version
begin
cmd = Mixlib::ShellOut.new('installer status |grep Version| cut -c12-13')
cmd.run_command
rescue Errno::ENOENT => e
return '0.0'
end
return 'Version 10' if cmd.stdout.include? '10'
return 'Version 11' if cmd.stdout.include? '11'
end
In the install recipe is:
if get_installer_linux_version.to_i <= 10 || get_installer_linux_version.to_i >= 11
log 'installer is installed'
else
log 'installer is not installed so procceding with the installation'

There are numerous things in your code that could be considered flawed, but for the sake of your question, I will focus on that.
get_installer_linux_version returns a few possible values. Either the string "version 10", "version 11", "0.0", or nil. You call this function, then call to to_i on it.
Maybe this will help illistrate it:
"version 10".to_i
#=> 0
I am going to guess that is not the intended behavior. No matter what happens in your get_installer_linux_version, the returned string will always be 0 after you call to_i on it. You then make condition that <= 10, which 0 is still less than 10, and it logs "installer is installed".
I would also venture to guess that using include? 'XX' is going to end up causing you problems when dealing with version numbers, but that is another question.
To further illustrate, let me write your code as it will always, always, always be as you have it written, and see if something looks off:
if 0 <= 10 || 0 >= 11
log 'installer is installed'
else
log 'installer is not installed so procceding with the installation'
What do you expect the result to be?? Although 0 is not ever going to be greater than 11, it will always be less than 10, so your result is always the same.
Just going to put this here, as it may be relevant the more I look at your sample.
>=
Checks if the value of left operand is greater than or equal to the
value of right operand, if yes then condition becomes true.
<=
Checks if the value of left operand is less than or equal to the value
of right operand, if yes then condition becomes true.

Related

Writing program for guessing a number in Small basic but the program won't run

this is the code I'm using
Sub btnguess_Click
randNum = Math.GetRandomNumber(10)
FCControls.GetText(txtCels)
If txtCels = randNum Then
lblanswer = "That's correct the Madame would like to hire you!"
ElseIf txtCels <1 or >10 Then
lblanswer = "Please enter number between 1 and 10"
Elseif txtCels <> randNum Then
lblanswer = "That's incorrect the Madame asks you to leave."
EndIf
endsub
error that I'm getting : 45,24:Expected a condition here.
I'm not sure what I'm missing here
The problem is at ElseIf txtCels <1 or >10 Then
When specifying a statement, you can't leave out a condition even if previously mentioned.
You'll have to re-write txtCels before the >10, i.e.
ElseIf txtCels <1 or txtCels >10 Then
Without this, you're essentially saying 'greater than 10' by itself, which makes no sense.

Can this Crystal benchmark code be improved significantly?

I'm deciding on a language to use for back-end use. I've looked at Go, Rust, C++, and I thought I'd look at Crystal because it did reasonably well in some benchmarks. Speed is not the ultimate requirement, however speed is important. The syntax is equally important, and I'm not averse to the Crystal syntax. The simple benchmark that I wrote is only a small part of the evaluation and it's also partly familiarisation. I'm using Windows, so I'm using Crystal 0.35.1 on Win10 2004-19041.329 with WSL2 and Ubuntu 20.04 LTS. I don't know if WSL2 has any impact on performance. The benchmark is primarily using integer arithmetic. Go, Rust, and C++ have almost equal performance to each other (on Win10). I've translated that code to Crystal, and it runs a fair bit slower than those three. Out of simple curiosity I also ran the code on Dart (on Win10), and it ran (very surprisingly) almost twice as fast as those three. I do understand that a simple benchmark does not say a lot. I notice from a recent post that Crystal is more efficient with floats than integers, however this was and is aimed at integers.
This is my first Crystal program, so I thought I should ask - is there any simple improvements I can make to the code for performance? I don't want to improve the algorithm other than to correct errors, because all are using this algorithm.
The code is as follows:
# ------ Prime-number counter. -----#
# Brian 25-Jun-2020 Program written - my first Crystal program.
# -------- METHOD TO CALCULATE APPROXIMATE SQRT ----------#
def fnCalcSqrt(iCurrVal) # Calculate approximate sqrt
iPrevDiv = 0.to_i64
iDiv = (iCurrVal // 10)
if iDiv < 2
iDiv = 2
end
while (true)
begin
iProd = (iDiv * iDiv)
rescue vError
puts "Error = #{vError}, iDiv = #{iDiv}, iCurrVal = #{iCurrVal}"
exit
end
if iPrevDiv < iDiv
iDiff = ((iDiv - iPrevDiv) // 2)
else
iDiff = ((iPrevDiv - iDiv) // 2)
end
iPrevDiv = iDiv
if iProd < iCurrVal # iDiv IS TOO LOW #
if iDiff < 1
iDiff = 1
end
iDiv += iDiff
else
if iDiff < 2
return iDiv
end
iDiv -= iDiff
end
end
end
# ---------- PROGRAM MAINLINE --------------#
print "\nCalculate Primes from 1 to selected number"
#iMills = uninitialized Int32 # CHANGED THIS BECAUSE IN --release DOES NOT WORK
iMills = 0.to_i32
while iMills < 1 || iMills > 100
print "\nEnter the ending number of millions (1 to 100) : "
sInput = gets
if sInput == ""
exit
end
iTemp = sInput.try &.to_i32?
if !iTemp
puts "Please enter a valid number"
puts "iMills = #{iTemp}"
elsif iTemp > 100 # > 100m
puts "Invalid - too big must be from 1 to 100 (million)"
elsif iTemp < 1
puts "Invalid - too small - must be from 1 to 100 (million)"
else
iMills = iTemp
end
end
#iCurrVal = 2 # THIS CAUSES ARITHMETIC OVERFLOW IN SQRT CALC.
iCurrVal = 2.to_i64
iEndVal = iMills * 1_000_000
iPrimeTot = 0
# ----- START OF PRIME NUMBER CALCULATION -----#
sEndVal = iEndVal.format(',', group: 3) # => eg. "10,000,000"
puts "Calculating number of prime numbers from 2 to #{sEndVal} ......"
vStartTime = Time.monotonic
while iCurrVal <= iEndVal
if iCurrVal % 2 != 0 || iCurrVal == 2
iSqrt = fnCalcSqrt(iCurrVal)
tfPrime = true # INIT
iDiv = 2
while iDiv <= iSqrt
if ((iCurrVal % iDiv) == 0)
tfPrime = (iDiv == iCurrVal);
break;
end
iDiv += 1
end
if (tfPrime)
iPrimeTot+=1;
end
end
iCurrVal += 1
end
puts "Elapsed time = #{Time.monotonic - vStartTime}"
puts "prime total = #{iPrimeTot}"
You need to compile with --release flag. By default, the Crystal compiler is focused on compilation speed, so you get a compiled program fast. This is particularly important during development. If you want a program that runs fast, you need to pass the --release flag which tells the compiler to take time for optimizations (that's handled by LLVM btw.).
You might also be able to shave off some time by using wrapping operators like &+ in location where it's guaranteed that the result can'd overflow. That skips some overflow checks.
A few other remarks:
Instead of 0.to_i64, you can just use a Int64 literal: 0_i64.
iMills = uninitialized Int32
Don't use uninitialized here. It's completely wrong. You want that variable to be initialized. There are some use cases for uninitialized in C bindings and some very specific, low-level implementations. It should never be used in most regular code.
I notice from a recent post that Crystal is more efficient with floats than integers
Where did you read that?
Adding type prefixes to identifiers doesn't seem to be very useful in Crystal. The compiler already keeps track of the types. You as the developer shouldn't have to do that, too. I've never seen that before.

For-loop in lua with löve2D, deleting variable

i'm a bit beginner about coding, and my english isn't great, i hope i'll be able to make my question clear:
So I have a for-loop in my code, and 2 if in it, in each if, I see if something is true or false, if it's true, I delete a portion of the loop. like that:
for n=#Test,1, -1 do
if Test[n].delete == true then
table.remove(Test, n )
end
if Test[n].y > 0 then
table.remove(Test, n )
end
end
kind of like that, and my problem is, if the first if make Test[n] being deleted, then the game crash at the next if because Test[n] Doesn't exist anymore. I solved the problem by making 2 for-loop, one for each if.
But I saw someone who did it without 2 for-loop, and it's not crashing, I tried to figure what was wrong but I can't find it.
If someone could find what is wrong with what I wrote, I would be thankful!
So here is the moment that makes problem in my code, on line 9, if the condition are met, i table.remove(ListeTirs, n ), then on line 17, when code try to find it again for test it, it bug :
for n=#ListeTirs,1, -1 do
if ListeTirs[n].Type == "Gentils"
then local nAliens
for nAliens=#ListeAliens,1,-1 do
if
Collide(ListeTirs[n], ListeAliens[nAliens]) == true
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n )
ListeAliens[nAliens].Supprime = true
table.remove(ListeAliens, nAliens)
end
end
end
if
ListeTirs[n].y < 0 - ListeTirs[n].HauteurMoitie or ListeTirs[n].y > Hauteur + ListeTirs[n].HauteurMoitie or ListeTirs[n].x > Largeur + ListeTirs[n].LargeurMoitie or ListeTirs[n].x < 0 - ListeTirs[n].LargeurMoitie
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n)
end
end
I hope it's clear, I could post the whole code but I don't feel it's necessary, if it is, I will add it.
Thank you :)
for n=#Test,1, -1 do
local should_be_removed
-- just mark for deletion
if Test[n].delete = true then
should_be_removed = true
end
-- just mark for deletion
if Test[n].y > 0 then
should_be_removed = true
end
-- actually delete (at the very end of the loop body)
if should_be_removed then
table.remove(Test, n )
end
end

IF, invalid syntax error

if volt.isalpha() or res.isalpha() or amp.isalpha():
What did I do wrong here? I get an INVALID SYNTAX, I am using this for a calculator program I am making. It calculates voltage, resistance, and amperage. But thats the easy part, I am just trying to make it fool proof. I have 3 variables in the code (volt, amp, res) that are inputted by the user. I just wanna make sure that they don't type in anything stupid. Like letters for e.g. ...
try:
float(volt) >= 0 and float(res) >= 0 and float(amp) >= 0
print("")
print("You put a value for everything. You don't need the calculator.")
allowed = 0
if volt.isalpha() or res.isalpha() or amp.isalpha():
print("You typed in characters for one of the values, this calculator doesn't use letters.")
allowed = 0
def find_voltage(a,b): # V = I * R
voltage = a * b
return(voltage)`
You don't have an except block after try - it is required. Do something like:
try:
float(volt) >= 0 and float(res) >= 0 and float(amp) >= 0
print("")
print("You put a value for everything. You don't need the calculator.")
allowed = 0
except ValueError:
print("Oops, you messed up.")
Additionally, the line
float(volt) >= 0 and float(res) >= 0 and float(amp) >= 0
doesn't do anything. You'll need to assign it to a variable, then check the results of the variable - if True, do one thing, if False, do something else.

Check if button is pressed or not

I have a Raspberry Pi with a Siri Proxy that is controlling my garage door, the garage door has only one command for open and close. To check if the garage door is opened to not I bought a magnet switch and I builded a flout point button. I already tried
doorstate = `gpio read 5`.chomp #gives value 1 or 0, 1 is opened, 0 is closed
print doorstate
if doorstate == "1"
print "The garage door is already opened.\n"
elsif doorstate == "0"
print "OK, I'll open it for you!\n"
else
print "Error, please open it manually.\n"
end
Can someone please tell me how I can check fi the returned value or string from doorstate = 'gpio read 5' is equal to a string?
I'm guessing here that the result of 'gpio read 5' contains a line ending.
Try chomping it off:
doorstate = `gpio read 5`.chomp
To verify the class of doorstate, insert p doorstate.class at line 2.
You need to change your single quotes (') to backticks (`, the little thing with the tilde on your keyboard). That will execute the command. The rest of your code is fine.

Resources