I have a coroutine function written for Unity which is as below:
IEnumerator initialize_reference_att()
{
Quaternion zero = new Quaternion(0, 0, 0, 0);
while (Input.gyro.attitude == zero)
Debug.Log("This line is required otherwise exits while without looping");
yield return null;
reference_attitude = Input.gyro.attitude;
Debug.Log("Reference attitude set to " + reference_attitude);
yield return null;
}
In this way it works as expected however when I write the while loop as below:
while (Input.gyro.attitude == zero)
yield return null;
the execution of while loop ends although Input.gyro.attitude == zero condition is still true. Apparently it has something to do with returning from coroutine immediately after while loop without doing any other thing. Because when I add an debug log line(as in the first code snippet), it works as expected. Does anybody have any idea why it behaves in that way? My issue is solved but I only want to understand why it happens. Thanks everyone.
This is basically the good old missing curly braces story:
while (Input.gyro.attitude == zero)
Debug.Log("This line is required otherwise exits while without looping");
yield return null;
basically equals writing
while (Input.gyro.attitude == zero)
Debug.Log("This line is required otherwise exits while without looping");
yield return null;
=> without the { } for enclosing a scope the while only applies to the first following expression after it
what you want is
while (Input.gyro.attitude == zero)
{
Debug.Log("This line is required otherwise exits while without looping");
yield return null;
}
Because when I add an debug log line(as in the first code snippet), it works as expected.
Let me doubt that. Your first snippet is an endless loop that the way it is written should crash your entire app as soon as the condition is true once.
In contrary actually I would expect
while (Input.gyro.attitude == zero)
yield return null;
which basically equals
while (Input.gyro.attitude == zero)
{
yield return null;
}
or also simply
yield return new WaitWhile(() => Input.gyro.attitude == zero);
would allow to yield once a frame => continue in the next frame and check again. Except something happened we all waited for and Unity suddenly made the API multi-threading ready you would always get the same value for Input.gyro.attitude during the same frame
Related
I am making an application which rarely uses the terminal for output. So, I found that the logging library was a great way to help debug faulty code as supposed to the print statement.
But, for this code, specifically the .get() statement at the bottom...
def process_variables(self, argument):
data = pd.read_excel(self.url, sheet_name=self.sheet)
data = pd.concat([data.iloc[2:102], data.iloc[107:157]]).reset_index()
fb = data.loc[0:99, :].reset_index()
nfb = data.loc[100:155, :].reset_index()
return {'fb': data.loc[0:99, :].reset_index(),
'nfb': data.loc[100:155, :].reset_index(),
'bi': data.loc[np.where(data['Unnamed: 24'] != ' ')],
'uni': data.loc[np.where(data['Unnamed: 25'] != ' ')],
'fb_bi': fb.loc[np.where(fb['Unnamed: 24'] != ' ')],
'fb_uni': fb.loc[np.where(fb['Unnamed: 25'] != ' ')],
'nfb_bi': nfb.loc[np.where(nfb['Unnamed: 24'] != ' ')],
'nfb_uni': nfb.loc[np.where(nfb['Unnamed: 25'] != ' ')],
}.get(argument, f"{logging.warning(f'{argument} not found in specified variables')}")
...returns this...
output
The output returns the default argument even though the switch-case argument was successful, given that it did return the pandas Data frame.
So how can I make it so it only appears when it wasn't found, as it should if it were just a string and not a logging-string method.
Thank you for your help in advance :)
Python evaluates the arguments for the arguments to a function before it calls the function. That's why your logging function will get called regardless of the result of get(). Another thing is your f-string is probably going to evaluate to "None" every time since logging.warning() doesn't return anything, which doesn't seem like what you intended. You should just handle this with a regular if statement like
variables = {
'fb': data.loc[0:99, :].reset_index(),
...
}
if argument in variables:
return variables[argument]
else:
logging.warning(f'{argument} not found in specified variables')
I have a method which helps me to solve a knight's tour. I want my recursion to stop as soon as I have found a solution however It keeps going on and on.
At the end it returns nearly 20 different solutions. I have added my code below, Can Someone please point out what is wrong here?
def myRecursion(dimension: Int, solution: Solution) : Option[Solution] = {
if ( dimension * dimension == solution.size) {
println("Stop it now")
Some(solution)
} else {
val movesAvailable = possibleMoves(dimension, solution, solution.head)
val bestm = bestMoves(movesAvailable)
if ( bestm.isDefined ) {
myRecursion(dimension, bestm.get ::: solution)
} else {
movesAvailable.foreach{ x =>
if(myRecursion(dimension, x:: solution).isDefined){
x::solution;
}
}
None
}
}
}
movesAvailable.foreach{ x =>
if(myRecursion(dimension, x:: solution).isDefined){
x::solution;
}
}
None
Thats probably your issue. You're calling your function recursively in a loop, but you don't actually exit the loop if its successful. You could probably switch that around to a takeWhile that keeps going while myRecursions returns None.
Also, that chunk of code isn't doing anything right now - You've got an if statement that evaluates to something, but then you return None no matter what.
I am struggling to make form validation work and it looks like the main problem is placeOrder function (other function which sit inside this functions work just fine). The function behaves in a strange way (gives alert only if the first input field (message) does not confirm to the test conditions, while if I leave the others blank it does not show alert). I was trying to find the reason for that by putting each part of the main if statement (which are divided by AND operators) in this test:
if(validateLenghtData(5, 32, form["message"], form["message_help"])) {
console.log("validation passed");
} else {
console.log("validation failed");
}
This gave me nothing because it only returns false ("validation failed") to console, while it outputs nothing if I enter valid text to the input. Where can be the bug and how can I test each part of big if statement ( like validatedZipCode(form["zipcode"], form["zipcode_help"])) in order to find out which part gives me false.
function placeOrder(form) {
// first check whether all fields are filled with valid data
// form["message"] and other simular arguments are part of form object and are passed from submit form (look it)
if (validateLenghtData(5, 32, form["message"], form["message_help"]) &&
validatedZipCode(form["zipcode"], form["zipcode_help"]) &&
validateNonEmptyField(form["date"], form["date_help"]) &&
validateNonEmptyField(form["name"], form["name_help"]) &&
validateNonEmptyField(form["phone"], form["phone_help"]) &&
validateNonEmptyField(form["email"], form["email_help"])) {
// everything is ok, submit the order to the server
form.submit();
} else {
alert ("You need to feel all fields correctly");
}
if(validateLenghtData(5, 32, form["message"], form["message_help"])) {
console.log("validation passed");
} else {
console.log("validation failed");
}
}
Is there a way to create something like this in AutoHotKey?
bool isReady = false;
while (!isReady) {
// Do something here
isReady = true;
}
I tried to experiment with While loop, but it ended with just 1 loop regardless of the condition I give the program. I am currently using Version 1.0.47.06.
I read the documentation here: http://www.autohotkey.com/docs/commands/While.htm I tried to give the while loop a value of true. But it only executed once. (I was expecting it to loop forever, until I terminate the script).
condition := true
while (condition)
{
MsgBox, condition
}
while (true)
{
MsgBox, true
}
Your code is correct, but the While command requires version 1.0.48+.
You should update to the latest version of AHK here - http://ahkscript.org/download/
To create a infinite loop , you can use this syntax:
Loop
{
; Your other code goes here
}
I was looking though a fellow developers code when I saw this ..
for (;;){
....
....
....
}
I have never seen ";;" used in a loop. What does this do exactly?
It loops forever. ';;' equates to no start value, no stop condition and no increment condition.
It is equivalent to
while (true)
{
...
}
There would usually be a conditional break; statement somewhere in the body of the loop unless it is something like a system idle loop or message pump.
All 3 parts are optional. An empty loop initialization and update is a noop. An empty terminating condition is an implicit true. It's essentially the same as
while (true) {
//...
}
Note that you it doesn't have to be all-or-nothing; you can have some part and not others.
for (init; cond; ) {
//...
}
for (; cond; update) {
//...
}
for (init; ; update) {
//...
}
Just like in C, the for loop has three sections:
a pre-loop section, which executes before the loop starts.
a continuing condition section which, while true, will keep the loop going.
a post-iteration section which is executed after each iteration of the loop body.
For example:
for (i = 1, acc = 0; i <= 10; i++)
acc += i;
will add up the numbers from 1 to 10 inclusive (in C and, assuming you use Perl syntax like $i and braces, in Perl as well).
However, nothing requires that the sections actually contain anything and, if the condition is missing, it's assumed to be true.
So the for(;;) loop basically just means: don't do any loop setup, loop forever (breaks notwithstanding) and don't do any iteration-specific processing. In other words, it's an infinite loop.
Infinite loop. A lot of the time it will be used in a thread to do some work.
boolean exit = false;
for(;;) {
if(exit) {
break;
}
// do some work
}
Infinite Loop (until you break out of it).
It's often used in place of:
while(true) { // Do something }
It's the same as
while(true) {
...
}
It loops forever.
You don't need to specify all of the parts of a for loop. For example the following loop (which contains no body, or update token) will perform a linear search of myArray
for($index = -1; $myArray[++$index] != $target;);