dimanche 31 mai 2020

How to compare the variable which can be existed or null in MYSQL? [duplicate]

I am encountering an issue which is how to do comparison in where clause with the variable can be existed or null. I know there is a operator <=> can do that. But any other method can achieve the same result as <=>. My sample sp is as below. You can imagine I have a model for storing the number of fruit in each store. But the store name can be null which stands for the warehouse. So, the a_store_name can be really a store name or null, simply use = will throw error where there is comparing with null.

Sp:

CREATE PROCEDURE `sp_check_fruit`(IN a_store_name varchar(20))
sp:BEGIN
select fruit number
into number
from fruit
where store_name = a_store_name;
END

Else after return from first part of an if statement

The implementation of library's BigInteger.gcd(...) method begins with these statements:

public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}

and

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

Python- Why does it say password denied even when I enter a password that should work?


userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):


    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

I’m trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don’t seem to be working properly and whenever I enter a password like “Py11”, it says password denied.

Dart if(A is B) condition not working properly

is condition image

As you can see from the picture, I got a variable called item which is an instance of BookFavorItem.

However, when I use condition if( item is BookFavorItem ) to control the flow, it did not work as expected behavior. (I thought this condition should be true, but it didn't)

What's wrong with me?

-> flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.17.1, on Microsoft Windows [Version 10.0.19041.264], locale zh-CN)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit visit
      https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions.
[!] Android Studio (version 3.6)
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
[√] VS Code (version 1.45.1)
[√] Connected device (1 available)

Why doesn't K keep its value?

I'm quite new to prolog, so any mercy for idiotic mistakes is most welcome! I have this assignment, and during its course I have to make this function work properly. The goal is to increment K each time all three connections occur (meaning 'con(H, Li)' for i=1, 2, 3 ; these are pre-existing arguments).

ismember([], L1, L2, L3, 0, K).

ismember([H|T], L1, L2, L3, E, K):-
    ismember(T, L1, L2, L3, E, K),
    ((con(H, L1), con(H, L2), con(H, L3)) -> K is E + 1 ); K is E.

Now I try to run the code, and the first iteration of con(x, y) works fine (all three connections exists, so when I use trace, K seems to take value 1). In the next iteration however, the first connection does not exists, which in my mind would mean that the code would skip the middle part and go straight to 'K is E'. This is not the case, when I trace it two memory slot values appear: "_8230 is _9204" instead of "K is E" (I put two random memory addresses for the sake of the example). Why does prolog do this? Have I got the idea of the if-argument in Prolog all wrong, or do you think it has something to do with the rest of the code?

Thanks!

Ifelse labeling

Working with chemical dataset and plotting the sample sites on map, colored by the chemical concentrations. I want to label the highest concentration points with their site name and am trying to use the geom_text(label = ifelse())) but am unsure about the NO aspect of the function.

    Jul_Data <- ggplot() +
    geom_sf(data) +
    geom_point(data = Jul_Data, aes(x = Easting, y = Northing, color = Concentration)) +
    geom_text(label = ifelse(Jul_Data$Concentration > 2000))

I understand that there is more needed for the ifelse but am really unsure about what it is supposed to be. I know there is a test, Yes, and NO aspect. All examples have been too specific for me to understand. Apologies if this is a novice question.

dataframe: ValueError: The truth value of a Series is ambiguous

I am not sure why I am getting this strange error for this simple if condition. I have added the function funt to check values in each row of column 'Owner', first I am checking if row in column 'Owner has any of these values [ 'hal','jula','huli'], if yes then it should return 'cont'. This returned value will be used to create new column(team) in dataframe df. Whenever I try to run below code I get this error.

def funt(row):
  if df['Owner'] in ['hal','jula','huli']:   # error line
     return 'cont'
  elif df['Owner'] == "assigned":
     return "unassigned"
  elif df['Owner'] == "Other":
     return "Other"
  else:
     return "Something else"

df['team'] = df.apply(lambda row: funt(row), axis=1)

Error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Conditional rendering for functions

In react I am trying to tell the program to run only if the type is "text" and onSubmit() is ran(This happens when the button is clicked).

type === "checkbox" ? 
setTodos(updatedCheckbox) 
: 
type === "text" && onSubmit() ? 
setTodos(updatedText) 
:  
console.log("!"); 

Error: The truth value of a DataFrame is ambiguous when splitting strings into two columns if two conditions are met

I am trying to make split the string in column['first'] if the following two conditions are met.

  1. column['first'] contains words 'floor' or 'floors'
  2. column['second'] is empty

However, I received an error message.

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Below is my code

#boolean series for condition 1: when values in column['second'] are empty

only_first_token = pd.isna(results_threshold_50_split_ownership['second']) 
print (len(only_first_token)) 
print (type(only_first_token))

#boolean series for condition 2: when values in column['first'] contain string floor or floors

first_token_contain_floor = results_threshold_50_split_ownership['first'].str.contains('floors|floor',case=False)
print (len(first_token_contain_floor))
print (type(only_first_token))

#if both conditions are met, the string in column['first'] will be split into column['first'] and['second']

if results_threshold_50_split_ownership[(only_first_token) & (first_token_contain_floor)]:
    results_threshold_50_split_ownership.first.str.split('Floors|Floor', expand=True)

print(results_threshold_50_split_ownership['first'])

I have read some answers here and have already changed the code a few times. I made sure the total number of boolean are the same at 1016. And I can successfully locate the rows that can fulfil the two conditions with the same code if I remove if. So I don't understand why it is ambiguous.

Any help would be much appreciated. Many thanks.

returning an "else" value at the end of a FOR loop

PYTHON: I got an "if" statement nested in a "for" loop. I need to return a defalut value if, at the end of the for loop, no one of the if statement was satisfied.

example: print the missing numbers in a given list or return the number next to the last element in list

list1 = [0, 1, 2, 3, 5, 7]

FOR i in range(list1[0], list1[-1]):

IF (i not in list1):
    print(i)  {#prints 4, 6}

ELSE (if 4, 6 were in list1 and so there were not missing numbers in the range):

print(list1[-1] + 1)   {#prints the number right after the last item of list}

i knew it's possible to do an else statement regarding a while loop, and i was wondering if the for loop has the same possibility

I get the current amount that the user has after buying a soldier. Do-while () keeps repeating, even if I enter 50

Hello, I would need help. In the console, I get the current amount that the user has after buying a soldier. Do-while () keeps repeating, even if I enter 50.

do {

do {

 System.out.println("Jaké si vybereš?");//What is your choice?
    System.out.println("Pešák-0(2)"); //Plebs
    System.out.println("Lučištník-1 (5)");//Archer
    System.out.println("Jezdectvo-2 (10)");//Cavalry
   System.out.println("Težká jednotka-3 (20)");//Special unit
   VyberVojaky =  Integer.parseInt(sc.nextLine());//ChooseSoldier

    System.out.println("A kolik jich chceš?");//How many soldiers do you want?
     PocetVojaku = Integer.parseInt(sc.nextLine());//numbofSoldiers
 for(int i=0;i < PocetVojaku;i++) {
     System.out.println(armadaHrace2[VyberVojaky]); //secondPlayersarmy[chooseSoldiers];

 }
    //total amount
    // limit for recruiting soldiers is 50,so if player will recruit more than 50 soldiers,The game should alert the player and select the soldiers again


   }

   celkovyPocet -=  PocetVojaku;//total amount -= numbofSoldiers

   System.out.println("Ještě můžete naverbovat: " +  celkovyPocet + " " + "vojáků");
                      //How many soldiers player can recruit

   Vojaci = armadaHrace2[VyberVojaky];

   Penize -= armadaHrace2[VyberVojaky].getCena();
   //money
   System.out.println("Vybral sis" + armadaHrace2[VyberVojaky]);//Your choice
System.out.println("Zůstalo ti:" + Penize + " " +"peněz");//Your residue

if(CelkovyPocet > 50) {

                 System.out.println("Naverboval jsi více jak 50 vojáků");//You recrutied more than 50 soldiers
                 kontrola = false;
             }
             if(CelkovyPocet < 50) {
                 kontrola = true;
             }
             CelkovyPocet = CelkovyPocet - PocetVojaku;

            }while(kontrola == true);


          //total amount

}while(kontrola == true);

}while(  celkovyPocet != 0  );

System.out.println(armadaHrace2[VyberVojaky]);//second Player's army

Not having successful login to my account

I'm trying to login to my account., but after entering the correct password, the server is echoing wrong password. I'm not sure if the error is near the if-else condition.

<?php
 session_start();
//Database Configuration File
include('database.php');
error_reporting(1);
if(isset($_POST['submit']))
  {
    // Getting username/ email and password
    $email=$_POST['email'];
    $password=$_POST['password'];
    // Fetch data from database on the basis of username/email and password
    $sql ="SELECT email FROM student WHERE (email=:email)";
    $query= $conn -> prepare($sql);
    $query-> bindParam(':email', $email, PDO::PARAM_STR);
    $query-> execute();
    $results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach ($results as $row) {
$passwordhash=$row->password;
}
//verifying Password
if (password_verify($password, $passwordhash)) {
$_SESSION['email']=$_POST['email'];
    echo "<script type='text/javascript'> document.location = 'studentdashboard.php'; </script>";
  } else {
echo "<script>alert('Wrong Password');</script>";
  }
}
//if username or email not found in database
else{
echo "<script>alert('User not registered with us');</script>";
  }
}
?>

Combining two "for" to integrate a progress bar while deleting line in a text file in Python?

I manage to make two python script to work independently. The first one is about looking for a string in a text file and deleting all lines with this string.

bad_words = ['first.com','second.org','third.io']

with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line) 

The process is quite long because the input as nearly 1 000 000 lines and the bad_words are close to 100 entries.

So I would like to show a progress bar in the terminal while proceeding. I found this, and it is working, incrementing the bar every 1/10 of a second.

import time

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total: 
        print()



# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
    # Do stuff...
    time.sleep(0.1)
    # Update Progress Bar
    printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

Instead of a time sleep, I want the progress bar to move forward while each word from bad_words is being processed.

So I came up with that :

def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):

    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total: 
        print()

items = ['first.com','second.org','third.io']
l = len(items)


printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
with open('A+B_net.txt') as oldfile, open('A+B_sub.txt', 'w') as newfile:
    for line in oldfile:
        if not any(items in line for item in items):
            newfile.write(line)
    for i, item in enumerate(items):
    # Update Progress Bar
        printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

It seems the imbrication of the "For If" aren't proper.

How to use dict to store and use if-statement [closed]

So I have been trying to figure out on how to store and how to see if a value is inside a dict.

What I'm trying to do is to save headers and cookies when doing a requests to save it and to re-use it.

What I have done is:

while True:

    dediProxies = random.randint(0,9)

    proxiesDict = {}

    try:

        if dediProxies in proxiesDict:
            scraper.headers = proxiesDict[dediProxies]['headers']
            scraper.cookies = proxiesDict[dediProxies]['cookies']

        response = requests.get('https://www.helloworld.com')

        if dediProxies not in proxiesDict:
            proxiesDict[dediProxies] = {
                'headers': response.headers,
                'cookies': response.cookies
            }

    except Exception as err:
        print(err)
        sys.exit()

However unfortunately my problem is that I am getting the error:

Traceback (most recent call last):
  File "C:/Users/test.py", line 10, in <module>
    if dediProxies in proxiesList:
TypeError: unhashable type: 'dict'

My question is, How can I have a dict storage where I can save the headers and cookies to re-use - if we have matched if statement, re-use the headers and cookies and then continue and IF there are not in the DICT then we add it after the requests is done?

Python - Convert a roman numeral to an integer

I've tried the following Python 3 code for Roman to Integer. Which is working fine at a glance. But there are certain problem happened when I input 'X', 'V' or related to 'X' and 'V' value. For example: Input: 'V' not working but Input: 'IV' showing correct value.

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

I've set the condition which is, if the input roman number is equal or less than "MMMCMXCIX", it will print the roman number; else it will print "Try again". But the problem is when I input 'X', 'V' or related to 'X' and 'V' value the output is showing "Try again".

Please help me to understand where I went wrong. Thank you.

Use of conditional function, condition in definition

I have such a stupid problem. I write a definition and I don't know how to introduce conditional functions.

I have a definition that works:

def function_1 (kot):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

It wokrs good

function_1 (False)

No:

or

function_1 (True)

Yes:

But I would like to have such a thing in my definition

def function_1 (kot = True):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

and it doesn't work anymore. Each hint will be rewarded!

How to compare two lists in Python using for loop?

I am doing an exercise that ask me the following tasks. I am stack in the third one:

  1. Create two variables called gandalf and saruman and assign them the spell power lists. Create a variable called spells to store the number of spells that the sorcerers cast.

    spells = 10
    gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
    saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
    
  2. Create two variables called gandalf_wins and saruman_wins. Set both of them to 0. You will use these variables to count the number of clashes each sorcerer wins.

    gandalf_wins=0
    saruman_wins=0
    
  3. Using the lists of spells of both sorcerers, update variables gandalf_wins and saruman_wins to count the number of times each sorcerer wins a clash.

My solution is that but is not comparing all the elements of the list, could you help me?

for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

Using regextract and importrange together make a "duplicate" formula

I have a spreadsheet where I look if the data (website) already exist on the master sheet.

=if(countif(importrange("Spreadsheet Key","Leads!N:N"),K2)>0,"COMPANY EXISTS!","")

But the above formula is not dynamic enough. If there are companies with co.uk and on the master sheet if it's registered under .com, it won't show "COMPANY EXISTS!"

So I changed to the formula to look for works after before and after "." on a website.

=ARRAYFORMULA(REGEXEXTRACT(UNIQUE(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.","")), "([0-9A-Za-z-]+)\."))

But it's not working if I try to incorporate with if and countif.

=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."))>0,"Company Exist!",""))

It shows 'Wrong number of arguments to IF. Expected between 2 and 3 arguments, but got 1 arguments'

Can anyone help me out on where I am making the mistake?

Spreadsheet link- https://docs.google.com/spreadsheets/d/1La3oOWiM5KpzRY0MLLEUQC25LzDuQlqTjgFp-VlS8Bo/edit#gid=0

Error while indexing an array in google sheet

Formula1 ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+"))

Formula2 if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1)

B2 contains range E1:G4

Formula1 & 2 are working perfectly fine but when we combine both as mentioned below there is an error: "Function INDEX parameter 2 value is -1. Valid values are between 0 and 150 inclusive."

index(ArrayFormula(regexextract(ArrayFormula(address(1,sequence(150,1,1,1),4)),"\D+")),if(and(5>=column(indirect(B2)),5<=columns(indirect(B2))+column(indirect(B2))-1),5,-1))

I have deliberately used -1 which is not a valued value for index parameter 2 so that it gives error when "If" condition is unfulfilled and I can omit whole result with iferror function, but when condition is fulfilled then it shouldn't give any error. Any work around will not help me because I need to use this formula component in another complex formula.

Google Sheet with function

Thanks in advance.

samedi 30 mai 2020

If sttement is not executing only else part is executing

This is a php program in which If part is not working. Else part is working everytime.

How to do pd.fillna() with condition

Am trying to do a fillna with if condition

Fimport pandas as pd
df = pd.DataFrame(data={'a':[1,None,3,None],'b':[4,None,None,None]})
print df

df[b].fillna(value=0, inplace=True) only if df[a] is None
print df


  a   b
0 1   4
1 NaN NaN
2 3   NaN
3 NaN NaN

##What i want to acheive

  a   b
0 1   4
1 NaN 0
2 3   NaN
3 NaN 0

Please help

Can you see what i'm doing wrong

Hey guys I'm running into an issue with my Python program. Here's what I would like the code to do, the sales price input can contain a dollar sign, but it must be numeric; the sales price must be at least $100, including dollars and cents. (if the user includes a dollar sign, how will you “ignore” it to determine if the input is numeric? The same applies to a decimal point.) if the input is not a numeric entry I would like it to prompt "price must be numeric" if the entry is less than $100 I would like it to prompt "Price must be at least $100"

This is what I have so far

salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])

Test IF file exist, del this local file

To Mofi, much thanks for answering my other question that provided some used code below. Asking another question to all, same vein:

Background: On occasion I choose to run "aGallery-dl.bat" in a given folder (just one in each of 100's of folders). It first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible. All is well.

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg

Problem: Restating, Gallery-dl.bat is in each of 100's of folders. On occasion, I run one of these from within it's local folder. Line 5, if the call to the Web site is successful, gallery-dl.exe creates zzzGDB.sqlite3 within the local folder.

In the previous code, when aGallery-dl.bat completed, it would just delete the Folder.jpg. This assumes the call to the Web page was successful. On rare occasion, the call to the Web page will fail for any number of reasons, though at close (due to that final "del .\Folder.jpg"), it will still delete Folder.jpg.

If zzzGDB.sqlite3 was not created/not present, I need the Folder.jpg (yellow !) to remain.

So, in the below code (line 6, now blank), I've lopped off the final "del .\Folder.jpg" and am trying to plug-in the provided code beginning at line 7, inserting a test for zzzGDB.sqlite. If found, "del .\Folder.jpg". If not found, no action is taken against Folder.jpg (it remains). (The "rem" statement at the very bottom is just acting as a placeholder for my own knowledge.)

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\zzzGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"

setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
    if exist "%%I\zzzGDB.sqlite3" (
        del "%%I\Folder.jpg"
    )
rem 
)
endlocal

Note: Currently, the modified code goes back thru every single folder within "U:\11Web\gallery-dl\deviantart*". This action should be reserved only to the local folder. I'm guessing the below is the issue.

for /D %%I in ("U:\11Web\gallery-dl\deviantart\*")

I don't know how to remove it and still implement everything after "do"???

do (
if exist ".\zzzGDB.sqlite3" (
    del ".\Folder.jpg"
)
rem 
)

Variable inside if statement in javaScript

I wonder why my first code doesn't work and the second does. I thought they're basically the same.... Looks like var inside if statement doesn't seem to be processed as expected. Could anyone please clarify why it doesn't work?

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var arrayLength = myFarm.length;


for (var j = 0; j < arrayLength; j++) {

    console.log(myFarm[j]);


    if (myFarm[j].charAt(0) === "c" || myFarm[j].charAt(0) === "o") {

        alert("Starts with a c or an o!");
    }

}

Is there a better way to check if a number is in range of two numbers

I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
        if number in range(0,5499):
            return 5000
        elif number in range( 5500, 9499 ):
            return 10000
        elif number in range( 9500 , 14499 ):
            return 15000
        elif number in range( 14500 , 19499 ):
            return 20000
        elif number in range( 19500,24499 ):
            return 25000
        elif number in range( 24500,29499 ):
            return 30000
        elif number in range( 29500,34499 ):
            return 35000
        elif number in range( 34500-39499 ):
            return 40000
        elif number in range( 39500,44499 ):
            return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

awk, if else conditional when record contains a value

I'm having trouble getting an awk if/else conditional to properly trigger when the record contains a value. Running this in zsh on Mac OS Catalina.

This script (issue is on second to last line)...

echo "abcdefgh" >  ./temp
echo "abc\"\(\"h" >> ./temp
echo "abcdefgh" >> ./temp
echo "abcde\(h" >> ./temp 

val='"\("'
key="NEW_NEW"
file="./temp"

echo $val
echo $key
echo $file

echo ""
echo "###############"
echo ""

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    ($0 ~ /old/){ s=index($0,old); print substr($0,1,s-1) new substr($0,s+len) }{ print $0 }
' $val $key $file

outputs:

"\("
NEW_NEW
./temp

###############

abcdefgh
abc"\("h
abcdefgh
abcde\(h

I want to fix the script so that it changes the "\(" to NEW_NEW but skips the parenthesis without the quotes...

"\("
NEW_NEW
./temp

###############

abcdefgh
abcNEW_NEWh
abcdefgh
abcde\(h

EDIT

This is an abbreviated version of the real script that I'm working on. The answer will need to include the variable expansions that the sample above has, in order for me to use the command in the larger script.

State machine with python

hi I am trying to create a state machine that change state with regards to the input of the user. if the user types "A" the state machine is on StateA else on StateB. this is what I did but I can't finish it.

from statemachine import StateMachine, State

value=''

class Chat(StateMachine):

    begin= State('begin', initial=True)
    StateA=State('A')
    StateB=State('B')

    go_to_A=begin.to(StateA)
    go_to_B=begin.to(StateB)


    def on_enter_begin(self):
        global value
        value = input("Please enter a string:\n")
        if value=="A":
            go_to_A() # I want to know how can I execute this transition 
        else :
            go_to_B() # else this transition 


chat=Chat()
chat.current_state
chat.go_to_A()
chat.current_state

Place default profile image based on gender in django

I need help on selecting a default profile picture depending on the gender of the user.. I have three default images in my media folder that i want to use as defaults, namely "00.png, 01.png, and 02.png".

models.py

GenderChoice = (
    ('others', 'Others'),
    ('male', 'Male'),
    ('female' :'Female')
) 

class User(AbstractBaseUser):
    gender = models.CharField(choice=GenderChoice)
    pro_pic = models.ImageField(upload_to ="", default ="00.png")

what I want is if a user selects gender="others" then 00.png should be saved as default and if they select male the 01.png should be selected as default..

Please help🙏🙏🙏

If-Else Statement in R with 3 conditions

I am trying to use an if-else statement to create a column in my data set. I want this if-else statement to create a column called "Surgical" in the df "option1" that displays the value of the column "Duration" subtracted by 20 ONLY IF the value in Duration is above 625, AND the factor "Single" is indicated in the column "Variability". I have tried the following code:

option1$Surgical <- ifelse(option1$Variability == "Single", option1$Duration - 20, option1$Duration)

Any insight into how to specify the "only if the value is greater than 625" portion is appreciated!!

Df "option 1" for reference.

dput(option1) structure(list(Stimulus = structure(c(36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 7L, 9L, 12L, 18L, 28L, 26L, 51L, 37L, 3L, 2L, 19L, 14L, 27L, 23L, 65L, 77L, 7L, 9L, 12L, 18L, 28L, 26L, 51L, 37L, 3L, 2L, 19L, 14L, 27L, 23L, 65L, 77L, 5L, 11L, 20L, 16L, 30L, 25L, 35L, 33L, 7L, 9L, 12L, 18L, 28L, 26L, 51L, 37L, 5L, 11L, 20L, 16L, 30L, 25L, 35L, 33L, 7L, 9L, 12L, 18L, 28L, 26L, 51L, 37L), .Label = c("t1_block2_hoed3.mp3", "t1_block2_whod3.mp3", "t1_block2_whod4.mp3", "t1_block2_whod5.mp3", "t1_block3_heed2.mp3", "t1_block3_heed5.mp3", "t1_block3_hoed1.mp3", "t1_block3_hoed2.mp3", "t1_block3_hoed4.mp3", "t1_block3_whod3.mp3", "t1_block4_heed5.mp3", "t2_block1_hoed3.mp3", "t2_block1_whod1.mp3", "t2_block1_whod2.mp3", "t2_block1_whod4.mp3", "t2_block2_heed3.mp3", "t2_block2_hoed5.mp3", "t2_block3_hoed1.mp3", "t2_block3_whod1.mp3", "t2_block4_heed2.mp3", "t2_block4_heed5.mp3", "t3_block1_heed1.mp3", "t3_block1_whod2.mp3", "t3_block1_whod5.mp3", "t3_block2_heed5.mp3", "t3_block2_hoed2.mp3", "t3_block2_whod5.mp3", "t3_block3_hoed1.mp3", "t3_block3_hoed4.mp3", "t3_block4_heed3.mp3", "t4_block1_heed1.mp3", "t4_block1_heed2.mp3", "t4_block1_heed3.mp3", "t4_block1_heed4.mp3", "t4_block1_heed5.mp3", "t4_block1_hoed1.mp3", "t4_block1_hoed2.mp3", "t4_block1_hoed3.mp3", "t4_block1_hoed4.mp3", "t4_block1_hoed5.mp3", "t4_block1_whod1.mp3", "t4_block1_whod2.mp3", "t4_block1_whod3.mp3", "t4_block1_whod4.mp3", "t4_block1_whod5.mp3", "t4_block2_heed1.mp3", "t4_block2_heed2.mp3", "t4_block2_heed4.mp3", "t4_block2_heed5.mp3", "t4_block2_hoed1.mp3", "t4_block2_hoed3.mp3", "t4_block2_hoed4.mp3", "t4_block2_hoed5.mp3", "t4_block2_whod2.mp3", "t4_block2_whod4.mp3", "t4_block2_whod5.mp3", "t4_block3_heed1.mp3", "t4_block3_heed4.mp3", "t4_block3_heed5.mp3", "t4_block3_hoed1.mp3", "t4_block3_hoed2.mp3", "t4_block3_hoed4.mp3", "t4_block3_hoed5.mp3", "t4_block3_whod1.mp3", "t4_block3_whod2.mp3", "t4_block3_whod3.mp3", "t4_block3_whod5.mp3", "t4_block4_heed1.mp3", "t4_block4_heed2.mp3", "t4_block4_heed3.mp3", "t4_block4_heed4.mp3", "t4_block4_heed5.mp3", "t4_block4_hoed1.mp3", "t4_block4_hoed2.mp3", "t4_block4_hoed3.mp3", "t4_block4_whod1.mp3", "t4_block4_whod2.mp3", "t4_block4_whod3.mp3", "t4_block4_whod5.mp3"), class = "factor"), Duration = c(497L, 517L, 580L, 563L, 569L, 486L, 506L, 536L, 545L, 554L, 516L, 600L, 607L, 577L, 537L, 583L, 544L, 566L, 567L, 616L, 652L, 564L, 517L, 612L, 564L, 632L, 662L, 565L, 594L, 622L, 552L, 542L, 539L, 554L, 600L, 607L, 577L, 497L, 517L, 580L, 563L, 569L, 594L, 563L, 623L, 602L, 516L, 600L, 607L, 577L, 531L, 642L, 624L, 566L, 567L, 616L, 652L, 654L, 576L, 556L, 608L, 632L, 662L, 565L, 497L, 517L, 580L, 563L, 569L, 486L, 506L, 536L, 545L, 554L, 516L, 600L, 607L, 577L, 537L, 583L, 544L, 566L, 567L, 616L, 652L, 564L, 517L, 612L, 564L, 632L, 662L, 565L, 594L, 622L, 552L, 542L, 539L, 554L, 600L, 607L, 577L, 497L, 517L, 580L, 563L, 569L, 594L, 563L, 623L, 602L, 516L, 600L, 607L, 577L, 531L, 642L, 624L, 566L, 567L, 616L, 652L, 654L, 576L, 556L, 608L, 632L, 662L, 565L, 452L, 547L, 510L, 663L, 470L, 503L, 600L, 517L, 491L, 505L, 641L, 581L, 520L, 485L, 517L, 622L, 452L, 547L, 510L, 663L, 470L, 503L, 600L, 517L, 491L, 505L, 641L, 581L, 520L, 485L, 517L, 622L, 510L, 458L, 558L, 638L, 483L, 538L, 577L, 600L, 452L, 547L, 510L, 663L, 470L, 503L, 600L, 517L, 510L, 458L, 558L, 638L, 483L, 538L, 577L, 600L, 452L, 547L, 510L, 663L, 470L, 503L, 600L, 517L), F0 = c(196L, 204L, 204L, 197L, 203L, 216L, 208L, 223L, 213L, 219L, 196L, 202L, 205L, 202L, 208L, 205L, 206L, 197L, 202L, 195L, 200L, 201L, 210L, 202L, 208L, 195L, 196L, 195L, 205L, 208L, 203L, 203L, 212L, 213L, 210L, 206L, 204L, 196L, 204L, 204L, 197L, 203L, 201L, 198L, 199L, 203L, 196L, 202L, 205L, 202L, 193L, 195L, 208L, 197L, 202L, 195L, 200L, 201L, 195L, 205L, 202L, 195L, 196L, 195L, 196L, 204L, 204L, 197L, 203L, 216L, 208L, 223L, 213L, 219L, 196L, 202L, 205L, 202L, 208L, 205L, 206L, 197L, 202L, 195L, 200L, 201L, 210L, 202L, 208L, 195L, 196L, 195L, 205L, 208L, 203L, 203L, 212L, 213L, 210L, 206L, 204L, 196L, 204L, 204L, 197L, 203L, 201L, 198L, 199L, 203L, 196L, 202L, 205L, 202L, 193L, 195L, 208L, 197L, 202L, 195L, 200L, 201L, 195L, 205L, 202L, 195L, 196L, 195L, 215L, 219L, 219L, 220L, 199L, 202L, 202L, 204L, 224L, 231L, 238L, 240L, 217L, 212L, 210L, 208L, 215L, 219L, 219L, 220L, 199L, 202L, 202L, 204L, 224L, 231L, 238L, 240L, 217L, 212L, 210L, 208L, 230L, 223L, 219L, 221L, 199L, 200L, 204L, 210L, 215L, 219L, 219L, 220L, 199L, 202L, 202L, 204L, 230L, 223L, 219L, 221L, 199L, 200L, 204L, 210L, 215L, 219L, 219L, 220L, 199L, 202L, 202L, 204L), F1 = c(576L, 553L, 579L, 586L, 601L, 398L, 390L, 398L, 389L, 404L, 587L, 560L, 562L, 553L, 393L, 397L, 382L, 553L, 592L, 556L, 571L, 387L, 392L, 398L, 400L, 580L, 580L, 554L, 403L, 391L, 388L, 393L, 382L, 375L, 384L, 392L, 388L, 576L, 553L, 579L, 586L, 601L, 387L, 393L, 402L, 406L, 587L, 560L, 562L, 553L, 388L, 391L, 412L, 553L, 592L, 556L, 571L, 410L, 404L, 401L, 420L, 580L, 580L, 554L, 576L, 553L, 579L, 586L, 601L, 398L, 390L, 398L, 389L, 404L, 587L, 560L, 562L, 553L, 393L, 397L, 382L, 553L, 592L, 556L, 571L, 387L, 392L, 398L, 400L, 580L, 580L, 554L, 403L, 391L, 388L, 393L, 382L, 375L, 384L, 392L, 388L, 576L, 553L, 579L, 586L, 601L, 387L, 393L, 402L, 406L, 587L, 560L, 562L, 553L, 388L, 391L, 412L, 553L, 592L, 556L, 571L, 410L, 404L, 401L, 420L, 580L, 580L, 554L, 620L, 630L, 602L, 605L, 571L, 573L, 560L, 553L, 434L, 417L, 306L, 319L, 414L, 419L, 392L, 391L, 620L, 630L, 602L, 605L, 571L, 573L, 560L, 553L, 434L, 417L, 306L, 319L, 414L, 419L, 392L, 391L, 448L, 441L, 293L, 291L, 420L, 420L, 388L, 384L, 620L, 630L, 602L, 605L, 571L, 573L, 560L, 553L, 448L, 441L, 293L, 291L, 420L, 420L, 388L, 384L, 620L, 630L, 602L, 605L, 571L, 573L, 560L, 553L ), F2 = c(1339L, 1381L, 1381L, 1347L, 1394L, 1484L, 1521L, 1539L, 1430L, 1454L, 1353L, 1378L, 1325L, 1357L, 1424L, 1563L, 1578L, 1350L, 1397L, 1273L, 1319L, 1548L, 1452L, 1499L, 1515L, 1358L, 1347L, 1248L, 1575L, 1438L, 1414L, 1548L, 3001L, 2916L, 2948L, 2973L, 2947L, 1339L, 1381L, 1381L, 1347L, 1394L, 2943L, 2913L, 2987L, 2940L, 1353L, 1378L, 1325L, 1357L, 3010L, 3008L, 2972L, 1350L, 1397L, 1273L, 1319L, 2963L, 2991L, 3007L, 2989L, 1358L, 1347L, 1248L, 1339L, 1381L, 1381L, 1347L, 1394L, 1484L, 1521L, 1539L, 1430L, 1454L, 1353L, 1378L, 1325L, 1357L, 1424L, 1563L, 1578L, 1350L, 1397L, 1273L, 1319L, 1548L, 1452L, 1499L, 1515L, 1358L, 1347L, 1248L, 1575L, 1438L, 1414L, 1548L, 3001L, 2916L, 2948L, 2973L, 2947L, 1339L, 1381L, 1381L, 1347L, 1394L, 2943L, 2913L, 2987L, 2940L, 1353L, 1378L, 1325L, 1357L, 3010L, 3008L, 2972L, 1350L, 1397L, 1273L, 1319L, 2963L, 2991L, 3007L, 2989L, 1358L, 1347L, 1248L, 1247L, 1244L, 1293L, 1264L, 1348L, 1354L, 1378L, 1381L, 1314L, 1233L, 1190L, 1208L, 1643L, 1659L, 1452L, 1438L, 1247L, 1244L, 1293L, 1264L, 1348L, 1354L, 1378L, 1381L, 1314L, 1233L, 1190L, 1208L, 1643L, 1659L, 1452L, 1438L, 2837L, 2816L, 2780L, 2776L, 2684L, 2718L, 2947L, 2948L, 1247L, 1244L, 1293L, 1264L, 1348L, 1354L, 1378L, 1381L, 2837L, 2816L, 2780L, 2776L, 2684L, 2718L, 2947L, 2948L, 1247L, 1244L, 1293L, 1264L, 1348L, 1354L, 1378L, 1381L), F3 = c(2831L, 2779L, 2915L, 2875L, 2712L, 2730L, 2793L, 2779L, 2772L, 2692L, 2718L, 2856L, 2674L, 2659L, 2717L, 2584L, 2829L, 2726L, 2685L, 2866L, 2793L, 2614L, 2636L, 2907L, 2822L, 2932L, 2882L, 2882L, 2650L, 2929L, 2809L, 2737L, 3623L, 3607L, 3584L, 3576L, 3680L, 2831L, 2779L, 2915L, 2875L, 2712L, 3641L, 3590L, 3556L, 3584L, 2718L, 2856L, 2674L, 2659L, 3640L, 3656L, 3686L, 2726L, 2685L, 2866L, 2793L, 3516L, 3552L, 3513L, 3579L, 2932L, 2882L, 2882L, 2831L, 2779L, 2915L, 2875L, 2712L, 2730L, 2793L, 2779L, 2772L, 2692L, 2718L, 2856L, 2674L, 2659L, 2717L, 2584L, 2829L, 2726L, 2685L, 2866L, 2793L, 2614L, 2636L, 2907L, 2822L, 2932L, 2882L, 2882L, 2650L, 2929L, 2809L, 2737L, 3623L, 3607L, 3584L, 3576L, 3680L, 2831L, 2779L, 2915L, 2875L, 2712L, 3641L, 3590L, 3556L, 3584L, 2718L, 2856L, 2674L, 2659L, 3640L, 3656L, 3686L, 2726L, 2685L, 2866L, 2793L, 3516L, 3552L, 3513L, 3579L, 2932L, 2882L, 2882L, 2711L, 3129L, 2786L, 2833L, 2754L, 2771L, 2856L, 2779L, 2909L, 2750L, 2866L, 2863L, 2804L, 2704L, 2636L, 2929L, 2711L, 3129L, 2786L, 2833L, 2754L, 2771L, 2856L, 2779L, 2909L, 2750L, 2866L, 2863L, 2804L, 2704L, 2636L, 2929L, 3226L, 3121L, 3867L, 3319L, 3426L, 3269L, 3680L, 3357L, 2711L, 3129L, 2786L, 2833L, 2754L, 2771L, 2856L, 2779L, 3226L, 3121L, 3867L, 3319L, 3426L, 3269L, 3680L, 3357L, 2711L, 3129L, 2786L, 2833L, 2754L, 2771L, 2856L, 2779L), Word = structure(c(2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("heed", "hoed", "hoed ", "whod" ), class = "factor"), Vowel = structure(c(2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("i", "o", "o ", "u"), class = "factor"), F1.Mean = c(564L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 394L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 398L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 394L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 564L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 564L, 564L, 564L, 394L, 394L, 394L, 394L, 398L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 564L, 564L, 564L, 564L, 398L, 398L, 398L, 398L, 564L, 564L, 564L, 627L, 627L, 614L, 614L, 614L, 614L, 566L, 566L, 432L, 432L, 327L, 327L, 415L, 415L, 393L, 393L, 627L, 627L, 614L, 614L, 614L, 614L, 566L, 566L, 432L, 432L, 327L, 327L, 415L, 415L, 393L, 393L, 397L, 397L, 292L, 292L, 417L, 417L, 398L, 398L, 627L, 627L, 614L, 614L, 614L, 614L, 566L, 566L, 397L, 397L, 292L, 292L, 417L, 417L, 398L, 398L, 627L, 627L, 614L, 614L, 614L, 614L, 566L, 566L), F2.Mean = c(1328L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 2969L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 1328L, 1328L, 1328L, 1496L, 1496L, 1496L, 1496L, 2969L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1328L, 2969L, 2969L, 2969L, 2969L, 1328L, 1328L, 1328L, 1250L, 1250L, 1247L, 1247L, 1247L, 1247L, 1357L, 1357L, 1292L, 1292L, 1157L, 1157L, 1746L, 1746L, 1455L, 1455L, 1250L, 1250L, 1247L, 1247L, 1247L, 1247L, 1357L, 1357L, 1292L, 1292L, 1157L, 1157L, 1746L, 1746L, 1455L, 1455L, 2828L, 2828L, 2763L, 2763L, 2721L, 2721L, 2969L, 2969L, 1250L, 1250L, 1247L, 1247L, 1247L, 1247L, 1357L, 1357L, 2828L, 2828L, 2763L, 2763L, 2721L, 2721L, 2969L, 2969L, 1250L, 1250L, 1247L, 1247L, 1247L, 1247L, 1357L, 1357L), Distance = c(16L, 54L, 55L, 29L, 76L, 13L, 25L, 43L, 66L, 43L, 34L, 50L, 4L, 31L, 72L, 67L, 83L, 25L, 74L, 56L, 11L, 52L, 44L, 5L, 20L, 34L, 25L, 81L, 80L, 58L, 82L, 52L, 36L, 58L, 25L, 7L, 24L, 16L, 54L, 55L, 29L, 76L, 28L, 56L, 18L, 30L, 34L, 50L, 4L, 31L, 42L, 40L, 14L, 25L, 74L, 56L, 11L, 13L, 23L, 38L, 30L, 34L, 25L, 81L, 16L, 54L, 55L, 29L, 76L, 13L, 25L, 43L, 66L, 43L, 34L, 50L, 4L, 31L, 72L, 67L, 83L, 25L, 74L, 56L, 11L, 52L, 44L, 5L, 20L, 34L, 25L, 81L, 80L, 58L, 82L, 52L, 36L, 58L, 25L, 7L, 24L, 16L, 54L, 55L, 29L, 76L, 28L, 56L, 18L, 30L, 34L, 50L, 4L, 31L, 42L, 40L, 14L, 25L, 74L, 56L, 11L, 13L, 23L, 38L, 30L, 34L, 25L, 81L, 8L, 7L, 48L, 19L, 110L, 115L, 22L, 27L, 22L, 61L, 39L, 52L, 103L, 87L, 3L, 17L, 8L, 7L, 48L, 19L, 110L, 115L, 22L, 27L, 22L, 61L, 39L, 52L, 103L, 87L, 3L, 17L, 52L, 46L, 17L, 13L, 37L, 4L, 24L, 25L, 8L, 7L, 48L, 19L, 110L, 115L, 22L, 27L, 52L, 46L, 17L, 13L, 37L, 4L, 24L, 25L, 8L, 7L, 48L, 19L, 110L, 115L, 22L, 27L), Included = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Yes", class = "factor"), Talker = structure(c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("T1 ", "T2", "T3", "T4"), class = "factor"), Ambiguity = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("High", "Low"), class = "factor"), Variability = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Mixed", "Single"), class = "factor"), Consistency = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Consistent", "Inconsistent"), class = "factor"), Fake = c(477, 497, 560, 543, 549, 466, 486, 516, 525, 534, 496, 580, 587, 557, 517, 563, 524, 546, 547, 596, 632, 544, 497, 592, 544, 612, 642, 545, 574, 602, 532, 522, 519, 534, 580, 587, 557, 477, 497, 560, 543, 549, 574, 543, 603, 582, 496, 580, 587, 557, 511, 622, 604, 546, 547, 596, 632, 634, 556, 536, 588, 612, 642, 545, 477, 497, 560, 543, 549, 466, 486, 516, 525, 534, 496, 580, 587, 557, 517, 563, 524, 546, 547, 596, 632, 544, 497, 592, 544, 612, 642, 545, 574, 602, 532, 522, 519, 534, 580, 587, 557, 477, 497, 560, 543, 549, 574, 543, 603, 582, 496, 580, 587, 557, 511, 622, 604, 546, 547, 596, 632, 634, 556, 536, 588, 612, 642, 545, 452, 547, 510, 663, 470, 503, 600, 517, 491, 505, 641, 581, 520, 485, 517, 622, 452, 547, 510, 663, 470, 503, 600, 517, 491, 505, 641, 581, 520, 485, 517, 622, 510, 458, 558, 638, 483, 538, 577, 600, 452, 547, 510, 663, 470, 503, 600, 517, 510, 458, 558, 638, 483, 538, 577, 600, 452, 547, 510, 663, 470, 503, 600, 517), Check = c(20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -192L), class = "data.frame")

IF Statement won't Execute With Date().getHours() [closed]

not sure why this isn't executing

function get_Date(){
    if (new Date().getHours() < 12) {
        document.getElementById("date") .innerHTML + "Have a nice day";
    }
}
<p id="date" onclick="get_Date()">click here.</p>

Does the order of the comparisons matter when using OR operators in IF statements?

I'm trying to get a better understanding of conditions within IF statements. When I change the order of the conditions I receive a TypeError of undefined.

I receive a TypeError: Cannot read property 'length' of undefined when the order is changed to:

if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
  }

Does the order of the comparisons matter when using OR operators in IF statements?

Working code base:

const maze = [
  [' ', ' ', ' ', '*', ' ', ' ', ' '],
  ['*', '*', ' ', '*', ' ', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', ' '],
  [' ', '*', '*', '*', '*', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', 'e'],
];

const solve = (maze, row = 0, col = 0, path = "") => {

  if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
  }

  // Base case
  if (maze[row][col] === "e") {
    return console.log(`Solved at (${row}, ${col})! Path to exit: ${path}`)

    // General case
  } else if (maze[row][col] === "*") {
    return
  }

  // Marker
  maze[row][col] = "*"

  // Right
  solve(maze, row, col + 1, path.concat("R"))

  // Down
  solve(maze, row + 1, col, path.concat("D"))

  // Left
  solve(maze, row, col - 1, path.concat("L"))

  // Up
  solve(maze, row - 1, col, path.concat("U"))

  // Remove marker
  maze[row][col] = " "
}

console.log(solve(maze));

Generating branch instructions from an AST for a conditional expression

I am trying to write a compiler for a domain-specific language, targeting a stack-machine based VM that is NOT a JVM.

I have already generated a parser for my language, and can readily produce an AST which I can easily walk. I also have had no problem converting many of the statements of my language into the appropriate instructions for this VM, but am facing an obstacle when it comes to the matter of handling the generation of appropriate branching instructions when complex conditionals are encountered, especially when they are combined with (possibly nested) 'and'-like or 'or' like operations which should use short-circuiting branching as applicable.

I am not asking anyone to write this for me. I know that I have not begun to describe my problem in sufficient detail for that. What I am asking for is pointers to useful material that can get me past this hurdle I am facing. As I said, I am already past the point of converting about 90% of the statements in my language into applicable instructions, but it is the handling of conditionals and generating the appropriate flow control instructions that has got me stumped. Much of the info that I have been able to find so far on generating code from an AST only seems to deal with the generation of code corresponding to simple imperative-like statements, but the handing of conditionals and flow control appears to be much more scarce.

Other than the short-circuiting/lazy-evaluation mechanism for 'and' and 'or' like constructs that I have described, I am not concerned with handling any other optimizations.

In Java, how to print divisor numbers?

I want to print the divisors of a user input value between 1 and 10000.

import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }


        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);      
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}

I have problem here with command System.out.println("loop);. I want to print all the divisors, like if a user inserted 10, then the output should show something like:

!

Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4

! !

But the current output is:

!

Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4

! !

so how to print loop only when the (Range % loop == 0) is true??

Simple censor function does not work in python

I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****. But it does not censor the word.

def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text

What's wrong with the code?

How to add if else statement in python along with function defination

Sorry to bother i m new to coding just learning python. i just created some code by myself in python no error shows. but why if else statement not executing. can someone help.

code:

def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")


person = name("Aditya", 17)
print(person)

guys , please tell what is the error in this program as it is not printing anything on screen as output

This code is for finding the missing number in array but after running this code no output is visible what is wrong in this code ?

#include<bits/stdc++.h>
using namespace std;
int main()
{
  long long int n , a[n] , sum ;
  cin>>n;
  for (int i = 0; i < n; ++i)
{
    cin >> a[i];

}

 sum = n*(n+1)/2;
// cout<<sum;
for(int i=0; i<n;i++)
{
  sum=sum-a[i];
}
cout << sum;
//return 0;
}

To find mean using rolling function only if window has more than x data available

I have a dataframe df having columns like date, company name, price_standalone, price_consolidated, etc.

I want to find the mean of price column for the past 10 years with one condition.

If price_consolidated has data(i.e. it is not NaN), for the past 10 years then price_consolidated column's data to be used else price_standalone's data to be used.

df["Price mean 10 years"] = df.groupby('Company Name')["price_consolidated"].shift().rolling(min_periods=1, window=3650).mean()

This is how I calculated the mean. Can someone help me with the condition part of the code? Also if possible another column next to it stating whether price_consolidated is used of price_standalone is used. Thx.

Syntax shorthand for comparison operator in python [duplicate]

I have an if statement that wants to check:

if c=="a" or c=="e" or c=="i" or c=="o" or c=="w":

Is there a way to write this more efficiently so that I don't have to repeat c=="x" so much. Something like if c=="a" or "e" or "i" or "o" or "w":

Why doesn't compiler raise an error in the if statement? [duplicate]

Code is attached here. I got this code somewhere from the internet, and just want to clarify a doubt about the if-statement. I expected it raised an error.

#include <stdio.h> 

int main() {

    int a=10, b=10; 
    if(b=5)
        a--; 
    printf("%d, %d", a, b--);
    return 0;
}

How to solve invalid syntax error in a simple if else statement in Python?

I'm in the middle of creating an autocorrelation code and just doesn't work. It is simple but I'm stuck and have no idea how to fix this code.

S1 = [1, 0, 1, 0, 0, 1]

func = 0;
for l in range(0,254):
  for i in range (0,254):
    if int(l+i) < 255:
      func = (1-2*S1[i])*(1-2*(S1[i+l])
    else :
      func = (1-2*S1[i])*(1-2*(S1[(i+l)%2])
  if func = 255 or 1 or -1
    print ("R(%s) = %s " %l, %func)

There's a problem with the else statement but I'm not sure exactly what I did wrong.

Can you help me out?

Please help me in the logic portion which will be highly appreciated [closed]

A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height. Two boys or two girls must not be adjacent to each other. You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.

Let's say there are boys n=3 and girls n=3, where the boys' heights are b = [5,3,8 ] and the girls' heights area = [2,4,6 ]. These students can be arranged in the order , which is [2, 3, 4, 5, 6, 8]. Because this is in order of non-decreasing height, and no two boys or two girls are adjacent to each other, this satisfies the conditions. Therefore, the answer is "YES".

Function (My code) :

    string arrangeStudents(vector<int> a, vector<int> b) {
 sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    int n = a.size();

    for(int i{};i<n;i++){
        if(a[i] == b[i] ){
            return "YES";

        }}
        return "NO";

    for(int i{};i<n;i++){        
        if(a[i] > b[i]){
            return "YES";

        }}
         return "NO";

    for(int i{};i<n;i++){
        if(a[i] == b[i] ){
            return "YES";
               }}
       return "NO";

            }

Test IF file exist, ELSE xcopy these two files

Morning all.

So I've been up hours trying to cobble together -a variety of replies to other posts- into my own code in order to see if I could get something usable. No-go. I'm sufficiently lost in the sauce that I've now got to ask for some help from you.

Background: OS: Windows 10 I use the program text2folders.exe to create 20-30 new folders on a secondary drive every night. Primarily, I have a base file "aGallery-dl.bat" that I populate each folder with using an xcopy batch file. Secondarily, from time to time I update the source file "aGallery-dl.bat" using the same xcopy and this overwrites the older target file, populating all folders with the newest "aGallery-dl.bat" (whether they need it or not). All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

I've recently decided I want to add two new files to each folder and have expanded my xcopy to include these. All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"

Folder.jpg a big red X

Folder2.jpg a big yellow ! mark

When I choose to run a "aGallery-dl.bat" in a given folder (again, one of 100's), it first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. All is well.

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg

If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible.

Problem: When I have to re-run my original xcopy command to update "aGallery-dl.bat" in ALL FOLDERS, the Folder.jpg and Folder2.jpg will be re-copied to all folders, defeating the purpose of deleting them once via "aGallery-dl.bat." I don't want to have to go back and re-run "aGallery-dl.bat" 100's of times intermittently across a number of folders, just to get rid of them again. I need some type of test, that if "aGallery-dl.bat" is already present in the target folder, DO NOT xcopy Folder.jpg and Folder2.jpg aka vague example, below.

*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /s /y /d ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /s /y /d ".\Folder2.jpg" "%%a\"
GOTO eof

:eof

I had found a hopeful candidate test statement in the below (copied in its original form from what/where I read in other post), but am looking for ideas/replacements as I HAVE NO IDEA how to modify/inject/implement the below to work in the above.

If exist \\%DIR%\%Folder%\123456789.wav xcopy \\%DIR%\%Folder%\123456789.wav D:\%New Folder%\ /y

Having XCopy copy a file and not overwrite the previous one if it exists (without prompting)

Moving this to the end of the xcopy command (after the above, rather than before) allows "aGallery-dl.bat" to be updated in all folders without mucking up the above command.

for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

Arduino C what is the correct use of logical operators in this if statement?

I'm fairly new to C, and im writing code for an Arduino project which is essentially an led roulette game. The below code is from a section for a button and the leds in the project. What I'm doing is holding down the button and cycling through the leds, and when I release the button I want it to take the led or port information from the while loop at the time of release and go through the proceeding code.

I'm stuck at the if statement below the while loop. It always goes to the first else if and I'm really struggling with trying to get it to work. I know that the logical operators in the if statement below the while loop are most likely incorrect but I don't know what else I could do.

I've tried assigning variables in the loop such as b=1, b=2, and so on and calling it in the if statement, but it didn't work and I also have a good feeling that it was probably a bad idea to do that.

Any help would be appreciated

if (a == 1) {
    if (BIT_IS_SET(PINC,1)) {
      a = 2;
    }
    while (BIT_IS_SET(PINC,1)) { 
    PORTD = 0b01000000;  
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00100000;   
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00010000;
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00001000; 
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00000100;
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00000010; 
    _delay_ms(DEBOUNCE_MS);
    PORTD = 0b00000001; 
    _delay_ms(DEBOUNCE_MS);
    } 

    if (~(BIT_IS_SET(PINC,1)) && (a == 2) && ((PORTD == 0b01000000) || (PORTD = 0b00100000) || (PORTD == 0b00010000) || (PORTD == 0b00001000) || (PORTD == 0b00000100) || (PORTD == 0b00000010) || (PORTD == 0b00000001))){
      a = 3;     
    }

if (a == 3) {
    if  (PORTD == 0b01000000) {
        _delay_ms(200);
        PORTD = 0b00100000;
        _delay_ms(400);
        PORTD = 0b00010000;
        _delay_ms(600);
        PORTD = 0b00001000;
        _delay_ms(800);
        PORTD = 0b00000100;
        _delay_ms(700);
        PORTD = 0b00000010;
        a = 4;
    } else if (PORTD == 0b00100000) {
        _delay_ms(200);
        PORTD = 0b00010000;
        _delay_ms(400);
        PORTD = 0b00001000;
        _delay_ms(600);
        PORTD = 0b00000100;
        _delay_ms(800);
        PORTD = 0b00000010;
        _delay_ms(800);
        PORTD = 0b00000001;
        a = 4;
    } else if (PORTD == 0b00010000) {
        _delay_ms(200);
        PORTD = 0b00001000;
        _delay_ms(400);
        PORTD = 0b00000100;
        _delay_ms(600);
        PORTD = 0b00000010;
        _delay_ms(800);
        PORTD = 0b00000001;
        _delay_ms(800);
        PORTD = 0b01000000;
        a = 4;
    } else if (PORTD == 0b00001000) {
        _delay_ms(200);
        PORTD = 0b00000100;
        _delay_ms(400);
        PORTD = 0b00000010;
        _delay_ms(600);
        PORTD = 0b00000001;
        _delay_ms(800);
        PORTD = 0b01000000;
        _delay_ms(800);
        PORTD = 0b00100000;
        a = 4;
    } else if (PORTD == 0b00000100) {
        _delay_ms(200);
        PORTD = 0b00000010;
        _delay_ms(400);
        PORTD = 0b00000001;
        _delay_ms(600);
        PORTD = 0b01000000;
        _delay_ms(800);
        PORTD = 0b00100000;
        _delay_ms(800);
        PORTD = 0b00010000;
        a = 4;
    } else if (PORTD == 0b00000010) {
        _delay_ms(200);
        PORTD = 0b00000001;
        _delay_ms(400);
        PORTD = 0b01000000;
        _delay_ms(600);
        PORTD = 0b00100000;
        _delay_ms(800);
        PORTD = 0b00010000;
        _delay_ms(800);
        PORTD = 0b00001000;
        a = 4;
    } else if (PORTD == 0b00000001) {
        _delay_ms(200);
        PORTD = 0b01000000;
        _delay_ms(400);
        PORTD = 0b00100000;
        _delay_ms(600);
        PORTD = 0b00010000;
        _delay_ms(800);
        PORTD = 0b00001000;
        _delay_ms(800);
        PORTD = 0b00000100;
        a = 4;
    }       
    }

vendredi 29 mai 2020

Nested COUNTIF within IF Statement based on 3 separate sheets

I have (3) separate sheets in (1) workbook that all need to be referenced in the following formula to either return True, False or Blank.

There is an Attendance Tracking sheet which has the students first and last name and Date of Birth, and then a column for each day that the student has taken an exam, marked by either True or False in the column.

The formula below is neither on the Attendance Tracking or Test Results.

=IF(COUNTIFS('Test Results'!$A:$A,$A2,'Test Results'!$B:$B,$B2,'Test Results'!$C:$C,$C2,'Test Results'!$D:$D,J$1)>0,"Y","N")

How can I reference the Attendance Tracking sheet to say if a student signed in on the day the exam was taken but we do not have the test results back yet, then neither True or False, just blank?enter image description here

enter image description here

enter image description here enter image description here

Convert if/else statement to ?: operator C#

I would like to reduce my code to something better. That's why I'm trying to convert if/else statement to operator ?:

My actual code looks like this :

if (resultat.CodeAlgo != null)
 {
    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString();
 }
else
 {
    worksheet.Cells[ligne, 7].Value = string.Empty;
}

I tried to convert to :

resultat.CodeAlgo != null
  ? worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString()
  : worksheet.Cells[ligne, 7].Value = string.Empty;

But it said :

Only assignment, call, increment, decrement, and new object statement can be used as a statement.

First time I'm using this operator and I don't understand why my simplification is wrong ?

How do I print the dict to the correct format?

I previously used course_rolls(records) to make the data to a dictionary below:

{'EMT001': {2286560}, 'FMKT01': {2547053}, 'CSC001': {2955520, 2656583}, 'MGM001': {2928707, 2606735}, 'MTH002': {2786372}, 'FCOM03': {2762453, 2955520, 2564885, 2606735}, 'FMCM02': {2955520, 2928707, 2656583}, 'ENG001': {2571096, 2564885}, 'MKT001': {2571096, 2656583},'AWA001': {2286560}, 'ACC002': {2762453}, 'FMTH01': {2571096}, 'EMT003': {2762453, 2656583}, 'MEA001': {2564885, 2606735}, 'FPHY01': {2564885}, 'FBIO01': {2547053}, 'MTH001': {2286560}, 'ECO002': {2928707, 2786372}, 'FCHM01': {2286560}, 'FCOM01': {2786372}, 'ENG002': {2762453}}

Records variable contains:

[(('EMT001', 'Engineering Mathematics 1'), (2286560, 'Dayton', 'Archambault')), (('FMKT01', 'Marketing'), (2547053, 'Vladimir', 'Zemanek')), (('CSC001', 'Computer Programming'), (2656583, 'Ronny', 'Ridley')), (('MGM001', 'Fundamentals of Management'), (2928707, 'Susanne', 'Eastland')), (('MTH002', 'Mathematics 2'), (2786372, 'Danella', 'Crabe')), (('FCOM03', 'Introduction to Computing'), (2564885, 'Hpone', 'Ganadry')), (('FCOM03', 'Introduction to Computing'), (2762453, 'Phelia', 'Pottle')), (('FMCM02', 'Mass Communication II (Film Studies)'), (2656583, 'Ronny', 'Ridley')), (('ENG001', 'Foundations of Engineering'), (2564885, 'Hpone', 'Ganadry')), (('MKT001', 'Principles of Marketing'), (2571096, 'Shoshanna', 'Shupe')), (('AWA001', 'Engineering Writing Skills'), (2286560, 'Dayton', 'Archambault')), (('FCOM03', 'Introduction to Computing'), (2606735, 'Aaren', 'Enns')), (('ACC002', 'Financial Accounting'), (2762453, 'Phelia', 'Pottle')), (('FMTH01', 'Advanced Mathematics I'), (2571096, 'Shoshanna', 'Shupe')), (('FCOM03', 'Introduction to Computing'), (2955520, 'Bjorn', 'Kakou')), (('EMT003', 'Mathematical Modelling and Computation'), (2762453, 'Phelia', 'Pottle')), (('MEA001', 'Mixed English Programme'), (2564885, 'Hpone', 'Ganadry')), (('MGM001', 'Fundamentals of Management'), (2606735, 'Aaren', 'Enns')), (('MEA001', 'Mixed English Programme'), (2606735, 'Aaren', 'Enns')), (('FPHY01', 'Physics'), (2564885, 'Hpone', 'Ganadry')), (('FBIO01', 'Introduction to Biology'), (2547053, 'Vladimir', 'Zemanek')), (('ENG001', 'Foundations of Engineering'), (2571096, 'Shoshanna', 'Shupe')), (('MKT001', 'Principles of Marketing'), (2656583, 'Ronny', 'Ridley')), (('MTH001', 'Mathematics 1'), (2286560, 'Dayton', 'Archambault')), (('ECO002', 'Introduction to Macroeconomics'), (2786372, 'Danella', 'Crabe')), (('FCHM01', 'Chemistry'), (2286560, 'Dayton', 'Archambault')), (('FCOM01', 'Communication Skills II'), (2786372, 'Danella', 'Crabe')), (('FMCM02', 'Mass Communication II (Film Studies)'), (2928707, 'Susanne', 'Eastland')), (('CSC001', 'Computer Programming'), (2955520, 'Bjorn', 'Kakou')), (('ENG002', 'Engineering Mechanics and Materials'), (2762453, 'Phelia', 'Pottle')), (('EMT003', 'Mathematical Modelling and Computation'), (2656583, 'Ronny', 'Ridley')), (('FMCM02', 'Mass Communication II (Film Studies)'), (2955520, 'Bjorn', 'Kakou')), (('ECO002', 'Introduction to Macroeconomics'), (2928707, 'Susanne', 'Eastland'))]

The program input is: clashes CSC001

Expected output (Command: clashes CSC001):

Clashes with CSC001:
In CSC001 and EMT003
  2656583: 

In CSC001 and FCOM03
  2955520: 

In CSC001 and FMCM02
  2656583: 
  2955520: 

In CSC001 and MKT001
  2656583: 

The result I get (Command: clashes CSC001):

Clashes with CSC001:
In CSC001 and FCOM03  
  2955520: 

In CSC001 and FMCM02  
  2955520: 

In CSC001 and EMT003  
  2656583: 

In CSC001 and FMCM02  
  2656583: 

In CSC001 and MKT001  
  2656583: 

Program code: (clashes function need to fix)

def parse_course_code(commands, records):
    if commands in course_rolls(records).keys():
        print('Clashes with {}:'.format(commands))
        return clashes(commands, records)
    else:
        print("Unknown course code")


def clashes(course_code, records):
    unformatted_course_rolls = course_rolls(records)
    for course, prior_student_number in sorted(unformatted_course_rolls.items()):
        for prior_student_number_single in list(prior_student_number):
            if course_code == course:
                for code, student_number in sorted(unformatted_course_rolls.items()):
                    for num in list(student_number):
                        if prior_student_number_single == num and course != code:
                            print("In {} and {}  ".format(course, code))
                            print("  {}: \n".format(num))

def main():
    while True:
        command = input('Command: ')
        if command == 'quit':
            print('Adios')
            break
        else:
            parse_course_code(commands, records)
main()

If number > value, change number to another value [closed]

I want if the value of number is more than 5, it will automatically change it's value to 0 again. I tried the following code, but it is not working! It continues to 5, 6, 7, 8 ......

& One more thing how to change src as 1 .png , 2 .png , 3 .png (With file extension)

Please help :( Thank you in advance!

var number = 0;
$(window).keydown(function(e) {

  //left arrow key//
  if (e.keyCode == 37) {
    number--;
  }

  //right arrow key//
  if (e.keyCode == 39) {
    number++;
  }

  //back to first//
  if (number > 5) {
    number == 0;
  }

  $("#keymap").attr('src', number);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<img id='keymap' src='1.png'>

Axios - Interceptors: prevent further handling by original caller

I have a succesful response interceptor for my Axios instance. Under certain circumstances I basicly want to prevent further execution of .then()'s and .catch()'s.

axiosExtended.interceptors.response.use(response => successHandler(response), error => errorHandler(error))

function successHandler(response) {
    const relativeRequestUrl = response.config.url;
    const relativeResponseUrl = trim(response.request.responseURL.replace(response.config.baseURL, ''), '/');

    if (relativeRequestUrl !== relativeResponseUrl) {
        // dont return anything to original caller. No then. No catch.
        router.push(relativeResponseUrl)
    }

    // get handled by original caller...
}

Fill new pandas df based off values in another df

I am new here, so please don't be to hard on me! :)

See picture below!

Print screen: df['Datan]

I am trying to create a new dataframe (df['New_df']) based on the values in df['Datan'] so that df['New_df'] is equal to df['Datan'] on the rows where the string #SRU appears. If the string is not in df['Datan'], I want df['New_df'] to "keep" the value of the row above (where the #SRU string was included).

See below df of what I am trying to do.

| Index | Datan | New_df |
| 95 | #SRU 1512 7251 | #SRU 1512 7251 |
| 96 | #KONTO 1513 "Kundfordringar - delad faktura" | #SRU 1512 7251 |
| 97 | #SRU 1513 7251 | #SRU 1513 7251 |
| 98 | #KONTO 1519 "Nedskrivning av kundfordringar" | #SRU 1513 7251 |
| 99 | #SRU 1519 7251 | #SRU 1519 7251 |

I have been trying around with for loops combined with if statements with the apply method in particular but haven't reached a solution as of yet. Not able to find this specific problem in any other threads here.

How to check an animator inside of an if statement

Hi I'm trying to check when my animator plays a certain animation to do the rest of the code and I'm super new to code and I don't understand the errorenter image description here

Ifelse statement in R: One value cannot equal another

I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user = high_user he cannot also be a small_user.

head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface 

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

Any help would be greatly appreciated.

How to check if date is a monday (PHP)

how can I check if my date is a monday ?

Thats the date I want to check: 2020-04-20 00:00:00

I tried this, but it doesn't work:

if(date('D', $datum) === "Mon")
{
  echo "yes!";
}

Can someone please help me there, or show me an other way to check it ?

Mysql AFTER UPDATE trigger with IF-THEN condition, but no data insertion

Hi There, I created the following AFTER UPDATE trigger on the table manage_transaction using IF-THEN condition in order to insert the specific data into the table manage_site_income_details BUT, neither a single row is inserted into manage_site_income_details nor any error encounters. However, I modified my IF-THEN condition many times, but no success. Please help me figure out the issue.

DROP TRIGGER IF EXISTS
        `upon_subscription_payment`;
CREATE DEFINER = `test-db-ru-admin`@`%` TRIGGER `upon_subscription_payment` 
AFTER UPDATE
    ON
        `manage_transaction` 
FOR EACH ROW 
    IF 
       OLD.about LIKE 'SUB' AND NEW.status = 'Completed' 
    THEN
    INSERT INTO 
                manage_site_income_details
    VALUES(
        NULL,
        OLD.t_id,
        OLD.txn_id,
        'SUB_Fee',
        OLD.fee,
        NOW());
    END IF

How to jump back to the top of the code after if statement C language

I'm trying to make my program to start again from the beginning after user has selected an option from a menu. When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do? and not to just restart just the if statement.

Should I add a for loop inside of the if statement to accomplish this? thanks for the help.

 printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

    if(menu_option==1)
    {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    }

jeudi 28 mai 2020

Is it better to loop through a 2D array of n pairings of values or have n if statements? - Java

I need to assess objects adjacent to my current object. There may be one above, below, left and right of my current position. If my current position is (x, y), then my adjacent objects are at positions: (x-1, y), (x+1, y), (x, y-1), (x, y+1).

Is it better to calculate these 4 positions and then store them in a 2D array, traversing them with a for... in loop:

int[][] adjacentObjects = {
          {x-1, y},
          {x+1, y},
          {x, y-1},
          {x, y+1} };

for (int[] adjacent : adjacentObjects) { ...
  if (adjacent[0] == ...) // x coordinate
  if (adjacent[1] == ...) // y coordinate

Or am I better off just having 4 near-identical if statements? Each would be 4 lines, where the x and y coordinates are the only difference.

My current mindset is that the for... in loop is cleaner, though not as readable, but I don't really know which is 'better.'

I've also thought about using another method where I'd pass the values of x and y but I also need access to another two 2D arrays in the current method, and it seems wasteful to send those as parameters to the new method as well.

I'm using Java, but I don't feel this is specific to any one language. Any help is greatly appreciated!

Python searching lists with lists, all and any

I am having trouble for some reason with a certain if statement. Let's say I have three lists:

list1 = [1,2,3,4,5]
list2 = [1,2,4,5]
list3 = [4,5,6,7,8]

I evaluate each. I want to flag it if the list has both 4 AND 5, but does not have either 2 OR 3. I thought this would work:

if all(q in [4,5] for q in the_list_name) and not any(q in [2,3] for q in the_list_name)

I would expect this to flag only list3. However it returns false on all of the lists. I wonder what I am doing wrong?

Trouble with nested ifelse statement in R

I'm trying to run a nested ifelse statement in R. Here's a look at the structure of my data using the glimpse() function from the tidyverse:

Rows: 22,104
Columns: 9
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...

I'm trying to get R to look at the Age column and if the value is within a certain range, for it to put the geological age name into a new column called AgeName. If the value is not within the range, I want it to move on to the next age range and so on and so forth. Here's my code so far:

pbdb_tidyish$AgeName <- ifelse(56>=pbdb_tidyish$Age&&47.8<pbdb_tidyish$Age,
                               "Ypresian",
                               ifelse(47.8>=pbdb_tidyish$Age&&41.2<pbdb_tidyish$Age,
                                      "Lutetian",
                                      ifelse(41.2>=pbdb_tidyish$Age&&37.8<pbdb_tidyish$Age,
                                             "Bartonian",
                                             ifelse(37.8>=pbdb_tidyish$Age&&33.9<=pbdb_tidyish$Age,
                                                    "Priabonian",NA))))

When I run this code, it creates the new column but fills the whole column with "Priabonian" so the dataset now looks like this:

Rows: 22,104
Columns: 10
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
$ AgeName                 <chr> "Priabonian", "Priabonian", "Priabonian", "Priabonia...

Does anyone have any idea where I'm going wrong? I think it's just looking at the first Age value, running the ifelse statement then filling the whole column with the result of that as opposed to moving on to the next row.

Thanks,

Carolina

Problem with if statement and match with specific categories [duplicate]

I have a problem with an if statement

I want to display a different button for elements that are assigned to a specific category (7) than for elements that do not belong to that category:

<?php
            $result=get_media($ref);
            if(empty($result))

                include ('button1.php');

            if (count($result)>0)
            {

                for ($n = 0; $n < count($result); $n++)
                {

                    if($result[$n]["ref"] == '7')
                    {
                        include ('button2.php');
                    }
                    else 
                        include ('button1.php');
                }
            }
            ?>

The if statement works if the element is assigned to category "7" only. But if it is assigned to other categories as well, the "else" command is not working and both buttons are shown.

I could of course add more category IDs to the if statement but this would be a lot of them.

Also an unequal command in the else statement does not work.

Nested Run Keywords Statement Robot Framework

I have to execute a nested run keyword Statement and I am following below code in a function:

${value}=  Run keyword And Return Status   Dictionary Should Contain Key  ${details}  edit
    Run Keyword If   '${value}'=='True' 
    ...  Run Keywords
        ...    Run Keyword If  '&{details}[edit]'=='Block1'  Log  Block1 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block2'  Log  Block2 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block3'  Log  Block3 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block4'
                    ...  Run Keywords
                            ...  Log  Block4 1 Call
                                ...    AND  Log  Block4 2 Call
                                ...    AND  Log  Block4 3 Call

When I am passing the value as Block2, It returns:

Block2 Call
Block4 2 Call
Block4 3 Call 

But I want my result to only return "Block2 Call". Does Run Keyword does not support the Nested Statements?

If is not executed unless System.out.println is used or while debugging [duplicate]

We are developing a Simulator with Students with Java and Swing. The Problem we have is that after a Button Click in the Simulator.java the variable for private static boolean startButton change too true. After this the "if" should start doing their job, but that is not the case.

I have this Code Block in my Brain.java:


public class Brain
{
    // ==========================================================

    /*
     * This is the Part of Port A
     */
    // Tris for Port A | ARRAY VALUE 0
    private static boolean[] port_A_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 1
    private static boolean[] port_A_Pins_Checkboxes = new boolean[5];

    /*
     * This is the Part of Port B
     */
    // Tris for Port B | ARRAY VALUE 2
    private static boolean[] port_B_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 3
    private static boolean[] port_B_Pins_Checkboxes = new boolean[8];

    // ==========================================================

    /*
     * This is the Part of the Watchdog
     */
    private static boolean watchdogCheckbox;

    // ==========================================================

    /*
     * This is the Part of the Reset Button
     */
    private static boolean resetButton;

    // ==========================================================

    /*
     * This is the Part of the Einzelschritt Button
     */
    private static boolean einzelschrittButton;

    // ==========================================================

    /*
     * This is the Part of the Start Button
     */
    private static boolean startButton = false;

    // ==========================================================

    /*
     * This is the Part of the Stop Button
     */
    private static boolean stopButton = false;

    // ==========================================================

    public static void main(String[] args)
    {
        // startet das GUI
        Simulator.main(args);
        while (true) {

            if ((startButton == true) && (stopButton == false)) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());

            } else if (getStart() && getStop()) {

                /*
                 * If program has already started and the stop button was pressed,
                 * stop the program
                 */
                setStart(false);
                setStop(false);

            } else if (getStop()) {

                // No reason to save stopping of program if it didn't even start yet
                setStop(false);

            } else if (getEinzelschritt()) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());
                setEinzelschritt(false);
            }
        }

    }

    // ==========================================================

    /**
     * 
     * @param index : Checkbox value, true if checkbox has been marked
     * @param whichArray : Value that say which ArrayIndex is checked in which
     *        Array
     * 
     *        Diese Methode wird die in der GUI aktivierten Checkboxen hier in
     *        der Programm Logik vermerken sodass diese dann für die weitere
     *        Abarbeitung nach User wunsch geschehen und mit berüchsichtigung der
     *        aktivierten Checkboxen des Users
     */
    public static void setChechboxesForTrisOrPinBoolean(int index,
            int whichArray)
    {
        switch (whichArray) {
        case 0: {
            port_A_Tris_Checkboxes[index] = !port_A_Tris_Checkboxes[index];
            break;
        }
        case 1: {
            port_A_Pins_Checkboxes[index] = !port_A_Pins_Checkboxes[index];
            break;
        }
        case 2: {
            port_B_Tris_Checkboxes[index] = !port_B_Tris_Checkboxes[index];
            break;
        }
        case 3: {
            port_B_Pins_Checkboxes[index] = !port_B_Pins_Checkboxes[index];
            break;
        }
        default:
            throw new IllegalArgumentException("Unexpected value: " + whichArray);
        }
    }

    // ==========================================================

    /**
     * Diese methode wird die Aktivierung der Watchog Checkbox berücksichtigen
     * und eben dann auch vermerken
     */
    public static void setCheckboxForWatchdog()
    {
        watchdogCheckbox = !watchdogCheckbox;
    }

    // ==========================================================

    /*
     * The Set Method for the Reset Button
     */
    public static void setReset(boolean value)
    {
        if (value == true) {
            resetButton = true;
        } else {
            resetButton = false;
        }
    }

    /*
     * Get Method for the Reset Button Value
     */
    public static boolean getReset()
    {
        return resetButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Einzelschritt Button
     */
    public static void setEinzelschritt(boolean value)
    {
        if (value == true) {
            einzelschrittButton = true;
        } else {
            einzelschrittButton = false;
        }
    }

    /*
     * Get Method for the Einzelschritt Button Value
     */
    public static boolean getEinzelschritt()
    {
        return einzelschrittButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Start Button
     */
    public static void setStart(boolean value)
    {
        if (value == true) {
            startButton = true;
        } else {
            startButton = false;
        }
    }

    /*
     * Get Method for the Start Button Value
     */
    public static boolean getStart()
    {
        return startButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Stop Button
     */
    public static void setStop(boolean value)
    {
        if (value == true) {
            stopButton = true;
        } else {
            stopButton = false;
        }
    }

    /*
     * Get Method for the Stop Button Value
     */
    public static boolean getStop()
    {
        return stopButton;
    }

    // ==========================================================
}

the other Part is my Simulator:

JButton btnStart = new JButton("START");
        btnStart.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                // TODO Auto-generated method stub
                System.out.println("Pressed");
                Brain.setStart(true);
            }
        });

The funny thing is that only if we add a System.out.println() or we Debug... it starts the if.