jeudi 31 décembre 2020

Return Value inside if statement inside for loop inside function

My goal in the below code is to cycle through the IF statement and have the function return a True value if the IF statement holds true throughout all the iterations? If during any iteration the evaluation is false I want to immediately return False. Am I writing this correctly? I get confused with the order of operations within the IF statement. Is there a simpler more elegant way to write this?

function checkGroup($groupNum, $names, $namesNow, $$group, $groupSize, $i){
  for ($m=0; $m < count($$group); ++$m){
    //checks to make sure current person doesn't conflict with anyone else in current group
    if ($namesNow[$names[$i]][$$group[$m]] < $max ){
      continue;
    }
    else {
      return false;
      break;
    }
  }
  return true;
}

Trying to go back to a "Checkpoint" in ZSH script

Ok so, I'm making a program in ZSH and I've made all the client-sided scripts that are run with commands

I'm having two problems where I need to set "Checkpoints" just like in videogame.

First Problem:

A="LUNGOTEVEREMARZIO-UMBERTO (RM-CTR54)"
B="LUNGOTEVEREMARZIO-UMBERT1 (RM-CTR55)"
vared -p 'Which device would you like to access? ' -c tmp
X=$tmp
if [[ $tmp == 'A' ]]; then
    F=${A}
elif [[ $tmp == 'B' ]]; then
  F=${B}
else
  echo 'Error, CODE176, Variable not found. Please upload logStamp.txt to Ranieri#0001 on Discord'
  log start(./logstamp.txt)
sleep 2
echo Selected Option ${tmp}: ${F}

Here, I'd like for line 13 to proceed after the variables are set, however, after the variables are set the script just stops (I understand why it does that, I just need a way to stop it. Here, is problem 2:

vared -p 'Awaiting Commands >> ' -c response
if [[ $response == 'GG stop' ]]; then
  echo '${sTT}'
  STATUS='${stopResponse}'
  
elif [ $response == 'GG start' ]]; then
echo '${srTT}'
STATUS='${startResponse}'
./TrStart.js
    
fi

Here, I'd like to go back to line 1 (vared) so that the users can input more commands. I was thinking both of the problems are similar to "Checkpoints" in VGs as i'm basically trying to go back to a selected point and be able to rerun the script from there. I thought of just repasting the entire thing in the if statementes but I know there has to be a MUCH more efficient way. Any help is much appreciated Cheers, RCdS

Powershell AD Syntax - If Statement is duplicating a string

New scripter with hopefully an easy proofread.

I made an Powershell Active Directory script that processes people on Leave of Absence (LOA) within my organization from a daily CSV file I get.

In summary my problem segment should:

  • Check the $Line variable's currentStatus if that employee is "On Leave"
  • Disable that Active Directory account.
  • Grab that AD account's 'Description' field and look for the string part "LOA - " and add that ONLY if it is missing. Problem is that if that field already has "LOA - " in the description, it puts another one... and another, so on.

Example:

  • Description (Good): LOA - Chef
  • Description (Bad): LOA - LOA - Chef
  • Description (Please NO): LOA - LOA - LOA - Chef
  • Etc.

I'm fairly certain the problem is with this line here but I can't figure out how to fix it.

If ($null -ne ($newDescript | ? {$loaPhrases -notcontains $_}))

$loaPhrases = "LOA -|LOA-|LOA - |LOA- |LOA - LOA - "

ElseIf ($Line.currentStatus -eq "ON LEAVE") 
{
    #Add 'LOA - ' to description and disable AD
    Set-ADUser $User.samAccountName -Enabled 0
    'Disabled AD'

    $Description = Get-ADUser $User.samAccountName -Properties Description | Select-Object -ExpandProperty Description
    $newDescript = $Description.substring(0, $Description.IndexOf('-')+1)
    If ($null -ne ($newDescript | ? {$loaPhrases -notcontains $_}))
    {
        $Description = "LOA - " + "$Description"
        $Description = $Description.trim()
        Set-ADUser $user.samAccountName -Description $Description
    }  
}                                          

Conditional formatting in JTable if statement not executing

I have the following code below. I can make the first if statement work where they are coloured in red.

I cant make the second if statement work whereby it finds a row with the name "RATS-3" then that row would be coloured in black. Can someone advse?

The third else if statement is executed and colours all the remaining cells green

{
        JTable table = new JTable(array, columnHeaders)
      {
    @Override
            public Component prepareRenderer(TableCellRenderer renderer, int rowIndex,int columnIndex) 
            {
                JComponent component = (JComponent) super.prepareRenderer(renderer, rowIndex, columnIndex);  
    
                if(
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_FFES-2")||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_FFES-3")  || 
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_FFES-4")  ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_FOYE-2")  ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_DINO-2") ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_DINO-3") ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_DINO-4") ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_DINO-6")  ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_FOYE-1") ||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_CRUA-1") || 
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_CRUA-2")|| 
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_CRUA-3")||
                        getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_CRUA-4") 
                        
                        && columnIndex == 0) {
                    component.setBackground(Color.RED);
                    
                   if(getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_RATS-3") && columnIndex == 0){
                    component.setBackground(Color.black);  
                    
                    
                }}
                
                 else if(!getValueAt(rowIndex, 1).toString().equalsIgnoreCase("T_RATS-4") && columnIndex == 0){
                    component.setBackground(Color.GREEN);
                }
                
                
    
                return component;
            }

bash check if a given file exists in a directory is failing on wildcard [duplicate]

FILE=*.tf
if [ -f "$FILE" ]; then
> echo "$FILE exists."
> else
> echo "$FILE does not exist."
> fi
does not exist.

The directory Im running this in has a file myfile.tf in it.

Im wondering why this isnt finding the myfile.tf file - could it be because im using the * asterisk wildcard ? What am I doing wrong here?

Thanks

Why are my if, else if and else statement not working as they should be?

When I type in France or france, a country in the array, in the input field the block of code returns country not in our database. I'd expect the code to return France is a country located in Europe.

I've tried using the return keyword on each conditional statement but without success. I've also read up w3schools.com's documentation on if/else statement.

However, I'm still unable to solve that problem. Interestingly, the else if statement works. I mean when I leave the input field blank and then click the button the code does return field cannot be left blank. I know my question will probably sound pretty basic but I'm still a beginner.

const btn = document.getElementById("button");

btn.addEventListener("click", function(){
  fetch("https://restcountries.eu/rest/v2/all")
  .then(function(response){
    return response.json()
  })
  .then(function(data){
    var userInput = document.getElementById("userInput");
    var userInputValue = userInput.value;
    var region = document.getElementById("region");
    for(var i = 0; i < data.length; i++) {
      if(userInputValue.toLowerCase() === data[i].name.toLowerCase()) {
        region.innerHTML = `${data[i].name} is a country located in ${data[i].region}`
      } else if (userInputValue === "") {
        region.innerHTML = "field cannot be left blank";
      } else {
        region.innerHTML = "country not in our database";
      }
    }
  })
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>API Beginners</title>
  </head>
  <body>
    <label for="userInput">country's name</label>
    <input id="userInput" type="text" name="" value="" placeholder="enter a country"><br>
    <label for="button">clik here to submit</label>
    <button id="button" type="click" name="button">click me</button>
    <div id="region"></div>

  </body>
  <script src="index.js" type="text/javascript"></script>
</html>

Issue with IF statement not following condition

I am reading data from a .csv file with columns having values as "TRUE" or "FALSE". My code sample is as of below. The value reads out to be "FALSE" in the list index but when I run same in loop the failed condition result is printed. If I change the 1st value of each column being read from FALSE or TRUE to any other letter then the loop runs fine.

import pandas as  pd


df = pd.read_csv('File Link')


headers = df.columns # Getting Headers from File

print (df['Sushi'][0]) #prints "False"

if df['Sushi'][0] == str('False'):
    print ('yes')

else:
    print ('not working') #prints not working even though the value is False

mercredi 30 décembre 2020

How to correctly check for a value in react useContext and return a statement

Im currently using React.useContext to store an array with objects like this:

{
 enable: true,
 id: 1
}

I made a switch that update the value inside the array from true to false. I've done the hard work and there is a bunch of code that don't need to be explained, but I'm pretty much sure that its works because in the end, when trying to console log the result, the switcher does change the value from [true] to [false] and back to [true] with no errors.

What I'm trying to achieve is to simply return a div and change the div id from red to blue regarding if the value is [true] or [false].

The most simple way I though this could be done is:

const myComponent = () => {

     const [value, setValue] = React.useContext(ValueContext);
        
         const checkEnable = value.filter((item) => (item.id === 1)).map((Item) => (
            Item.enable
          ));

     return (
            <div id={checkEnable === true ? "red" : "bue"} > </div>
            (
    
};

I have also trying this method

const setId = (checkEnable) => {
    if (checkEnable === true) {
      return "red"
    } else {
      return "blue"
    };

  }

and returned

<div id={setId(checkEnable) >

Again, console logging the checkEnable actually does return [true] or [false] so I think there was no error with the work until this stage. But the ternary operator/statements result only [true] and the div id are not changing from red to blue. Is there something I have overseen in this code? Thanks for all suggestions.

Compare Columns and replace Values in R

I'm trying to compare different columns ("Test1" - "Test3") to one basic-column ("Criteria") and replace values depending on the result of the comparison.

Here is an example - Consider the following data:

Test.data <- data.frame(c("Yes", "Yes", "No", "Yes"))
Test.data$Test1 <- (c("No", "No", "Yes", "Yes"))
Test.data$Test2 <- (c("Yes", "No", "Yes", "No"))
Test.data$Test3 <- (c("Yes", "Yes", "Yes", "Yes"))
colnames(Test.data) <- c("Criteria", "Test1", "Test2", "Test3")


  Criteria Test1 Test2 Test3
1      Yes    No   Yes   Yes
2      Yes    No    No   Yes
3       No   Yes   Yes   Yes
4      Yes   Yes    No   Yes

Is there an efficient way to replace the values in "Test1" - "Test3" with 0, if the value in the specific column corresponds to the basic-column and with 1, if it does not? Maybe with an if-function?

A result should look like this:

  Criteria Test1 Test2 Test3
1      Yes    1      0     0
2      Yes    1      1     0
3       No    1      1     1
4      Yes    0      1     0

Thanks everyone for taking time! You guys are doing a great job!

Why aren't my if statements working? Not reading the input right

I have been struggling with this problem, when I make a few if and elif statements, and when I go to type the input, it does not register my input, it shows me the wrong output. Here is my code.

def startup():
    print("Hello! Thank you for playing my game!")
    time.sleep(1)
    print("If you want to start then type 'start'.")
    time.sleep(1)
    print("If you want to exit the game then type 'exit'.")
    time.sleep(1)
    print("If you want to see the about then type 'about'.")
    time.sleep(0.5)
    while True:
        choice = input("Type an option: ")
        if choice == "start" or "Start":
            print("Ok, starting...")
            time.sleep(1)
            break
        elif choice == "exit" or "Exit":
            exit_question = input("Are you sure? Type Y or n.")
            if exit_question == Y:
                print("Exiting...")
                break
            else:
                print("Ok sorry...")
        elif choice == "about" or "About":
            about = open("about.txt", "r")

Then when I run the code this is what I get.

Hello! Thank you for playing my game!

If you want to start then type 'start'.

If you want to exit the game then type 'exit'.

If you want to see the about then type 'about'.

Type an option: about   <--------- my input

Ok, starting...

If anyone is able to help then that would be great.

Thanks, Noah

python if statement not working correctly with gensim language model

If statement not working properly when else added. The else statement prints when the if statement should.

Doesnt work:

variable = 'programming'

for i, word in enumerate(wv.vocab):
    if word == variable:
        print("Is ready to be measured")
    else:
        print("text to clean")
        #do this
        break

The below works showing the term variable is in the model wv.vocab

variable = 'programming'

for i, word in enumerate(wv.vocab):
    if word == variable:
        print("Is ready to be measured")
    #else:
        #print("text to clean")
        #do this
        break

When the variable is changed to something not in the model it does not work.

variable = 'programmings'

for i, word in enumerate(wv.vocab):
    if word == variable:
        print("Is ready to be measured")
    #else:
        #print("text to clean")
        #do this
        break

Combination of for-loop and ifelse in R

I'm trying to decide between "Yes" and "No" in R, if a specific (and variable) value is exceeded. For each value tested a new column with the different decisions should be created.

Here is a manually created example:

Test.data <- data.frame(c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100))
colnames(Test.data) <- c("Test")

Test.data$Test1 <- ifelse(Test.data$Test > 10, "Yes", "No")
Test.data$Test2 <- ifelse(Test.data$Test > 20, "Yes", "No")
Test.data$Test3 <- ifelse(Test.data$Test > 30, "Yes", "No")

Test.data

This simple example gives the following output:

   Test Test1 Test2 Test3
1    10    No    No    No
2    20   Yes    No    No
3    30   Yes   Yes    No
4    40   Yes   Yes   Yes
5    50   Yes   Yes   Yes
6    60   Yes   Yes   Yes
7    70   Yes   Yes   Yes
8    80   Yes   Yes   Yes
9    90   Yes   Yes   Yes
10  100   Yes   Yes   Yes

Is there a way to do this with a for-loop? I already tried different stuff like the following code, but it seems to be nonsense, since it doesn't create new columns and so on:

n = c(seq(from=10, to=100, by=10))

for(i in n) {
ifelse(Test.data$Test > i, "Yes", "No")
}

Thanks everyone!

Powering the positive returns of a column in R depending on it's value between 0 and 100

I am trying to create a risk/return plot. The return is the mean daily values. It isn't in percentage. I want it kind-of in percentage. When a stock goes up 100%, it is equivalent to a stock falling 50%. If the stock goes up 400%, it is the same as a stock falling 87.5%.

I'm trying to multiply my positive Returns by the following, depending on the value each return has:

  • Returns between 0 and 49.99 multiply the return value by 2
  • Returns between 50 and 74.99 multiply the return value by 4
  • Returns between 75 and 87.49 multiply the return value by 8
  • Returns between 87.5 and 93.74 multiply the return value by 16
  • Returns between 93.75 and 93.74 multiply the return value by 32 ...

Below is the code of the if statement I can't make work:

if (( 0 <= Poi[,2]) & (Poi[,2] <= 49.99999999)){
  Poi[,2] <- Poi[,2]*MyReturn*2
} else if (( 50 <= Poi[,2]) & (Poi[,2] <= 74.99999999)){
  Poi[,2] <- Poi[,2]*MyReturn*4
} else if (( 75 <= Poi[,2]) & (Poi[,2] <= 87.49999999)){
  Poi[,2] <- Poi[,2]*MyReturn*8
} else if (( 87.5 <= Poi[,2]) & (Poi[,2] <= 93.74999999)){
  Poi[,2] <- Poi[,2]*MyReturn*16
} else if (( 93.75 <= Poi[,2]) & (Poi[,2] <= 96.87499999)){
  Poi[,2] <- Poi[,2]*MyReturn*32
} else if (( 96.875 <= Poi[,2]) & (Poi[,2] <= 98.43749999)){
  Poi[,2] <- Poi[,2]*MyReturn*64
} else if (( 98.4375 <= Poi[,2]) & (Poi[,2] <= 99.21874999)){
  Poi[,2] <- Poi[,2]*MyReturn*128
} else if (( 99.21875 <= Poi[,2]) & (Poi[,2] <= 99.60937499)){
  Poi[,2] <- Poi[,2]*MyReturn*256
} else if (( 99.609375 <= Poi[,2]) & (Poi[,2] <= 99.80468749)){
  Poi[,2] <- Poi[,2]*MyReturn*512
} else if (( 99.8046875 <= Poi[,2]) & (Poi[,2] <= 99.90234374)){
  Poi[,2] <- Poi[,2]*MyReturn*1024
} else if (( 99.90234375 <= Poi[,2]) & (Poi[,2] <= 99.951171865)){
  Poi[,2] <- Poi[,2]*MyReturn*2048
} else if ( 99.951171875 <= Poi[,2]){
  Poi[,2] <- Poi[,2]*MyReturn*4096
} else {
  Poi[,2] <- Poi[,2]*MyReturn
}

dput(Poi):

structure(list(targetRisk = c(93.969862047238, 76.9768091680639, 
63.5982003855003, 54.5228767287575, 46.0821549451386, 37.6476764384589, 
29.2248472581225, 20.8278052738397, 12.5085917276091, 4.66122739912144, 
1.70147647969736, 4.34078819570542, 7.31911601372062, 10.4618350712519, 
13.948425299842, 17.515722070763, 21.228074686994, 25.1663931325116, 
29.261108015602, 33.5927110975208, 38.2162769926765, 43.116215831914, 
48.2106070287435, 53.5716998572496), targetReturn = c(-42.7922615561753, 
-38.2096263740965, -33.6269911920178, -29.0443560099391, -24.4617208278605, 
-19.8790856457821, -15.2964504637031, -10.7138152816245, -6.13118009954602, 
-1.54854491746736, 3.03409026461127, 7.6167254466899, 12.1993606287685, 
16.7819958108472, 21.3646309929257, 25.9472661750043, 30.5299013570829, 
35.1125365391614, 39.6951717212402, 44.2778069033188, 48.8604420853973, 
53.443077267476, 58.0257124495546, 62.6083466986961)), row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
), class = "data.frame")

Need to use if nested function or choose

I have two columns with values. One has values and many Na! And the other has some Na! And I have another column where I am using the aggregate function to calculate using the column with less Na! Values. However my problem is that I want to write a formula where if there is an Na! in one column then it chooses the value from the other column. And then I can use that value for the aggregate function.

If statement not working for all objects in an array

I'm very new to Java programming and have encountered a problem which I assume has a very simple solution. However I feel like I have tunnel vision right now and can't seem to figure out what the issue really is. So I'm making a program supposed to simulate a shoe warehouse, where one of the actions possible should be to add a new shoe - this part is working just fine. There's a catch to it tho - before being able to add a new shoe, the product ID of the shoe should be entered, and if the entered product ID is equal to the product ID of an already existing shoe, the user should be notified about this and not be able to add a shoe with this same product ID. I am using a if and if-else statement (nested in a for-loop, if that's how you say it) supposed to run through an array with Shoe class-objects in it, but it seems as if the if statement only runs for the first object in the array, where it works as expected and notifies the user that a shoe with that same product ID already exists, however if you enter the product ID of the 2nd or 3rd object in the array, the program will allow that to pass through without "blocking" the user from adding it, despite the fact that a shoe with that product ID already exists in the array. So my question is what's gone wrong here - is it something with the formatting of my code, typo, or something like that?

Code for the specific situation:

    System.out.println("Check to see if the product already exists "
        + "through entering product ID ");
    shoeExists = scanObj.next();
    
    //shoeArr is the array for Shoe object
    for (Shoe shoe:shoeArr) { 
        if (shoe != null && (shoe.getProdukt().equalsIgnoreCase(shoeExists))) {
            System.out.println("A shoe with product ID "+shoeExists+" already exists");
            System.out.println(" ");
            break;  
        }
                
        else if (shoe != null && !shoe.getProdukt().equalsIgnoreCase(shoeExists)){
            produktID = shoeExists;
            System.out.println("Product-ID saved. Enter other details below \n");
            System.out.println(" ");
            System.out.println("Product-ID: "+produktID);   
            System.out.println("Brand: ");
            brand = scanObj.next();
            System.out.println("Name: ");
            name = scanObj.next();
            System.out.println("Model: ");
            model = scanObj.next();
            System.out.println("Shoe type: ");
            shoeT = scanObj.next();
            System.out.println("Shoe size: ");
            shoeSize = scanObj.nextInt();
            System.out.println("Price: ");
            price = scanObj.nextInt();
            System.out.println("Stock: ");
            stock = scanObj.nextInt();
            
            Shoe b_obj = new Sko(produktID, brand, name, model,
                    shoeT, shoeSize, price, stock);
        
            if (counter < 20) {
                shoeArr[counter] = b_obj;
                counter++;
                
                System.out.println("Shoe with product ID "+produktID+ " added");
                
                break;
            }
            else {
                counter = skoArr.length-1;
                System.out.println("There is no room to add shoe.");
                
            }
        }
    }
        
    break;

I probably haven't used the correct terminology and language in some places, still new to this and learning by the day... so as I mentioned above this solution works for the first object in my array (that is pre-added to the array), but not for the other two objects that are pre-added to the array, and not for the ones added through this case either. Also I'm sure this is not the ideal or most efficient way of solving something like this by any means, but it is the solution I came to through the learning material and lectures from my teacher, and got closest to working.

If any more information is required to see what is causing the problem is needed or if something is poorly explained (which I'm sure is the case lol) just let me know and I will do my best to improve that. I suspect it's something very basic that's gone wrong though.

Thanks!

HOW I CAN SLEEP BUT IF A CONDITION IS TRUE STOP THE SLEPPING AND CONTINUE IN DART?

this is an example of sleep in dart, but I want that with a boolean condition. If its true break the sleep. put an if before the sleep is not the solution because it will be alwys false before the sleep but while the sleep is working maybe the variable change the value. Anybody knows a possible solution. Thank you

 sleep(Duration(milliseconds: 2000));

Problems with std::cin and isdigit in c++

When I run the code and enters for instance 1 in the terminal it goes to the 'else' condition and breaks. But I'm providing it with a digit so I have trouble understanding why it behaves like that. Could someone help clarify?

int main() 
{
  vector<int> positions;
  int p;
  
  for(int i = 0; i <= 3; i++){
    
    cout << "Enter a number: ";
    cin >> p;
    
    if(isdigit(p)){
      positions.push_back(p);
    } else
    {
      cout << "Please provide numbers from 0 to 100!" <<"\n";
      break;
    }
    
  }
  return 0;
}

C++ Nested Statements [closed]

I have an example from my textbook that I want clarification on. See below. Let's say my input is 0.5 for the fuelGaugeReading. It's read, goes to the nested IF, noticed it's greater than 0.25, then it produces nothing since it did not meet the requirements of either IF.

My question is, why does it not meet the requirement of the first IF, and therefore outputs the statement from the ELSE?

int main()
{
    
    double fuelGaugeReading;
 
    cout << "Enter fuel gauge reading: ";
    cin >> fuelGaugeReading;
    cout << "First with braces:\n";
    if (fuelGaugeReading < 0.75)
    {
       if (fuelGaugeReading < 0.25)
           cout << "Fuel very low. Caution!\n";
    }
    else
    {
        cout << "Fuel over 3/4. Don't stop now!\n";
    }

    return 0;
}

If Next statement does not work after the second time loop in VB

I'm very confused why this if statement doesn't work after the second loop. I want to pick up the cell which starts "[" and extract the sentence between the "[]". Once extracted, the sentence should be put on the different sheet as a list.

This code works only first time when InStr(Cells(i, 1), "[") > 0. However, this test fails thereafter.

Where am I going wrong?

Public rowCount As Integer
    
Sub Copy()
    Dim startNum As Integer, endNum As Integer
    Dim str As String
    Dim e As Long
    Dim le As Long
    
    Worksheets("DataBase").Activate
    rowCount = Cells(Rows.Count, 1).End(xlUp).Row 
    Dim i As Long
    Dim ExtractionStrings As String
    Dim arr() As Variant
    
    For i = 4 To rowCount
        For e = 1 To rowCount
            If InStr(Cells(i, 1), "[") > 0 Then
            startNum = InStr(Cells(i, 1), "【")
            endNum = InStr(startNum + 1, Cells(i, 1), "]")
            If startNum <> 0 And endNum <> 0 Then
                startNum = startNum + 1
                ExtractionStrings = Mid(Cells(i, 1), startNum, endNum - startNum)
                str = ExtractionStrings
                
                Worksheets("Sheet1").Activate
                Cells(i, 1) = str
                Else: MsgBox ("Error")
                End If
            End If
        Next e
    Next i
End Sub

Value in an Output where it shouldn't be

I am trying to condition this output so that each string is printed and formatted equally with the exception of "sarah". I've got this to work with the wording of her output being unique as she has only 1 "favourite language". However, now her language "C" is also in Jen's favourite language list when it shouldn't be. I tried using an elif/else in place of the 2nd "if" and got an invalid syntax error. I don't know how this is happening, thanks.

favourite_languages = {
    "jen": ["python", "ruby"],
    "sarah": ["c"],
    "edward": ["ruby", "go"],
    "phil": ["python", "haskell"],
    }
    for name, languages in favourite_languages.items():
    if len(languages) != 1:
        print(f"\n{name.title()}'s favourite languages are:")
    for language in languages:
        print(f"\t{language.title()}")
    if len(languages) == 1:
        print(f"\n{name.title()}'s favourite language is:")
        print(f"\t{language.title()}")

output:

Jen's favourite languages are:
    Python
    Ruby
    C

Sarah's favourite language is:
    C

Edward's favourite languages are:
    Ruby
    Go

Phil's favourite languages are:
    Python
    Haskell

Logstash JSON file Check fields

I try to drop evets that "id" field is "empty-null OR not exist" in my json data. But it seems logstash doesn't work properly in if loop.

How can I achieve my purpose?

JSON File

{"id": "10","counter":"en","note":"note1"}
{"id": "10","counter":"en","note":"note1"}
{"counter":"en","note":"note1"}

Logstash Conf

input {
  file {
    type => "json"
    path => "/data.json"
  }
}

filter {
    if ![id] or [id] == 'null' {
        drop {}
    }
}
......

javascript syntax questioon

So lets say i have the following code:

 function c (f,i) {
        let x = i;
        if (f(x,i)){
            x--;
        }
        if (f(x,2)) {
            console.log(1);
        }
        else {
            console.log(2);
        }
    }

what exactly happens in the if statements, i dont understand the syntax behind it. f is no function, its a variable, so what happens here? does it equal to f * ( x * i) ? whats the operands behind this syntax. Thanks in advance

multiple conditions without using multiple if else in sql

I have to write a program in sql that has multiple conditions but i shouldn't write it with multiple if else(because of the cost that if has ) , I'm new in this field and i have no idea how else could i write it which would be better here is my sample code:

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME = 'Food_tbl')
            BEGIN
                IF NOT EXISTS (SELECT TOP 1 FID FROM dbo.Food_tbl)
                 BEGIN
                    INSERT INTO dbo.Food_tbl
                    SELECT *
                    FROM DataFoodView                       
                 END
                ELSE IF (SELECT COUNT(*) FROM dbo.Food_tbl)=20
                 BEGIN
                    PRINT N'Table Exists'
                    SELECT *
                    FROM Food_tbl
                 END
                ELSE IF (SELECT COUNT(*) FROM dbo.FoodSara_tbl)<>20
                 BEGIN
                    print N'there isnt 20'
                    INSERT INTO Food_tbl (Food_tbl.FID, Food_tbl.Fname, Food_tbl.Ftype, Food_tbl.Fcount, Food_tbl.Datetype, Food_tbl.Fdescription)
                    SELECT DataFoodView.*
                    FROM DataFoodView 
                    LEFT JOIN FoodSara_tbl ON Food_tbl.FID = DataFoodView.FID
                    WHERE Food_tbl.FID IS NULL;     
                 END
            END

PS: I have at first check if the table is exits and if it hasn't any record insert all the data, if it has 20 records show the table, if the table doesn't have 20 records find the missing data then insert that.

Parse and precompile IF statement from file in parser

I have problem with parsing file that contain if statements. Exactly i'm trying to create VM and it working: it compares, prints, declares functions and other. I need a compiler for my VM that will translate my language to vm's bytecode. Programmer will write this:

if(1 == 1){
   if(2 == 2){
      print(test);
   }
}
if(3 == 3){
print(lol);
}

And it will translate to that WITHOUT closing curly braces:

cmp_nequal(1,1):4;
cmp_nequal(2,2):3;
cmp_nequal(3,3):5;
print(test);

Cause we should to inverse our IF statement to simplify it to bytecode. So actually I can translate cmp_nequal (compare not equals) to something about FF SOH DLE bytes, but I need help with parsing language. Me and my colleague are working about if statements about four days and we don't understand how can we parse it. Compiler works as: text -> special parser text (if -> cmp, print -> PRNT) -> bytecode (cmp -> FF SOH, PRNt -> FF FF). How can we exactly parse and compile all if to cmp_nequals statements? (if(x == z) -> cmp_nequals(x,z), if(x > z) -> cmp_less(x,z), if(x < z) -> cmp_more(x,z), if(x != z) -> cmp_equals(x,z)) Can anyone help with parser? Thanks!

mardi 29 décembre 2020

AHK if statment with variables not working always true

Here is what i am trying to do,

step 1 get the color of the mouse location

step 2 enter the loop

step 3 get the second color of the new mouse location

step 4 compare the two colors

error = no matter what the output of color 1 or color 2 the script below is stating true.

!^b::
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%
sleep, 5000
loop
{
    MouseGetPos, MouseX, MouseY
    PixelGetColor, color2, %MouseX%, %MouseY%   
    if (%color%=%color2%)
    {
        MsgBox, it matchs %color% = %color2%
        sleep,5000
    }
    else
    {
        MsgBox, It dosnt match %color% != %color2%
        sleep, 5000
    }

}   

Python error unhashable type: 'list' with pandas iloc

I am still learning Python. I am trying to check if the peak value of any of the average temperatures is satisfied using the if statement below but I am getting TypeError: unhashable type: 'list'. Can someone help clarify the issue and correct it?

Thank you!

df['T1avg'] = df['T1'].rolling(11, center=True).mean().shift(50)
df['T2avg'] = df['T2'].rolling(11, center=True).mean().shift(50)
averages = ['T1avg','T2avg']

pctl = np.nanpercentile(df, 1, axis=0)  # calculation of 1% percentile
peak = df.iloc[-1] < pctl

for i in range(1, len(df)):
if (peak.loc(axis=0)[i, averages]).any():

Send Email with the Google Leave request form submitted by the user, using app script, google form, spreadsheet

I am working on developing a simple Leave management system where we use Google form, Google spreadsheet, and App scripts.

In Google form for leave request, we have the confirmation at the beginning like whether you are a Requester or Approver.

  1. Leave request First Confirmation Screenshot of the form
  2. Requester form
  3. Approver form

The goal is:

  • Whenever the requester submits the leave request form an email with the detail is sent to the approvers.
  • The approver receives the email from the requester along with the edit link.

With the edit link clicked by the approver, the approver is redirected to the same form and the approver has to select the Approver in the form and decide whether to approve or decline the request. When the response is filled and submitted, an email is sent to the requester by the approver regarding the response like, if her/his request is approved or decline.

Here is the code:

var EMAIL_TEMPLATE_DOC_URL = 'Template link of the doc for requester email';
var EMAIL_TEMPLATE_DOC_URL2 = 'Template link of the doc for approver email';
var EMAIL_SUBJECT = 'Leave Request';

function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}

function onFormSubmit(e) {
var responses = e.namedValues;
var status = '';

var email = 'Approver email Address';

if( e.range.columnStart != 3 || e.value == "Requester")
{
MailApp.sendEmail({
to: email,
subject: EMAIL_SUBJECT,
htmlBody: createEmailBody(responses)
});

status = 'sent';

var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = 18;

sheet.getRange(row, column).setValue(status);

Logger.log('status=' + status + '; responses=' + JSON.stringify(responses));



function createEmailBody(responses) {


var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
var emailBody = docToHtml(docId);

var form = FormApp.openById('edit form id');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
// Logger.log(formResponse.getEditResponseUrl());
}

var timestamp = responses['Timestamp'][0].trim();
var name = responses['Name'][0].trim();
var leavetype = responses['Leave Type'][0].trim();
var starttime = responses['Start Time'][0].trim();
var endtime = responses['End Time'][0].trim();
var halfday = responses['Half day include'][0].trim();
var addinfo = responses['Additional Information'][0].trim();
var emailadd = responses['Email address'][0].trim();
var editurl = formResponse.getEditResponseUrl();

emailBody = emailBody.replace(//g, timestamp);
emailBody = emailBody.replace(//g, name);
emailBody = emailBody.replace(//g, leavetype);
emailBody = emailBody.replace(//g, starttime);
emailBody = emailBody.replace(//g, endtime);
emailBody = emailBody.replace(//g, halfday);
emailBody = emailBody.replace(//g,addinfo);
emailBody = emailBody.replace(//g,emailadd);
emailBody = emailBody.replace(//g, editurl);


return emailBody;
}
}

else(  e.value == "Approver")
{
var email2= 'requester email address';

MailApp.sendEmail({

to: email2,
subject: EMAIL_SUBJECT,
htmlBody: createEmailBody(responses)
});

status = 'send 2';

// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = 19;
//var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);

Logger.log('status=' + status + '; responses=' + JSON.stringify(responses));



function createEmailBody(responses) {


var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL2).getId();
var emailBody = docToHtml(docId);

var dec = responses['Approval Decision'][0].trim();
var exp= responses['Explanation'][0].trim();


emailBody = emailBody.replace(//g, dec);
emailBody = emailBody.replace(//g, exp);

return emailBody;
}
}
}




function docToHtml(docId) {

var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' +
docId + '&exportFormat=html';
var param = {
method: 'get',
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}

Is there something wrong with my if-else condition? The problem am facing is that both the if and else condition runs at the same time and I get two emails send to the requester as well as the approver. I am new to app script and my knowledge is zero in terms of all these so I don't know what should I do with the code I have to make the system work properly.

Can anyone help me to filter the submitted request like approver and requester so that I can send an email to the actual person who needs to get it? Any tips on if-else condition?

How can i update an differential equation variable during the odeint operation using 'if" condition in python?

I have these differential equations:

a=5*2.17*(10**-6)*n1*nx 
b=4*2.17*(10**-6)*n1*ni
c=n1/(0.154*(10**-7))
h=((8*(10**-7))/(3.14*t))**0.5
dn1dt=((1.7565*(10**18))-(n1/10**-6)-a-(19*b)-(c*h))
dnxdt=b
dxdt=(4*2.17*(10**-6)*n1)

initially ni=0 but i want to update it at each step according to the x that is calculated during odeint. here is my code:

function that returns dz/dt

enter code here
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
def model(z,t):
    n1=z[0]
    nx=z[1]
    x=z[2]
    ni=0
    a=5*2.17*(10**-6)*n1*nx
    b=4*2.17*(10**-6)*n1*ni
    c=n1/(0.154*(10**-7))
    h=((8*(10**-7))/(3.14*t))**0.5
    dn1dt=((1.7565*(10**18))-(n1/10**-6)-a-(19*b)-(c*h))
    dnxdt=b
    dxdt=(4*2.17*(10**-6)*n1)
    if x>18:
        ni=0.5*n1*(x-18)
    elif x<=18:
        ni=0
    dzdt = [dn1dt,dnxdt,dxdt]

    return dzdt

# initial condition
z0 = [0,0,0]

# time points
t = np.linspace(0.001,5)

# solve ODE
z = odeint(model,z0,t)

# plot results
plt.plot(t,z[:,0],'b-')
plt.plot(t,z[:,1],'r--')
plt.ylabel('response')
plt.xlabel('time')
plt.show()

someone please help!!

What if if statement is not executed and does not recognize numerical data from the date format?

A user suppose to enter the date and based on the date entered the code determines which day of the week was at that specific date?

The code successfully recognize the day of the week and recognize that each month has 31 days, so if I enter February 31, it automatically recognizes as March 3 if the year is simple, and as March 2 if the year is leap! If I enter some gibberish let's say 2019-15-34 it returns as NaN!

I set up conditions for each month that if the month is January maximal number of days should not surpass 31, and if the month is February maximal number of days should not surpass 28 if the year is simple, and so on for each month. After that I set up alert to show the message "Your data is invalid! Please enter valid data!" and set up continue thereafter to return eventual user to reenter the data this time valid date. If date is valid (the month is not suppose to be greater than 12, and date suppose not to be greater than 31) it suppose to show up the message "OK!Your data is valid!" and the code to continue with execution and to get out of if statement!

However it's evident that even when I enter some date that does not make sense let's say 2019-15-15 the code does not return "Your data is invalid! Please enter valid data!", but no matter of what I enter it comes out "OK! Your date is valid!".

What's wrong and why if statement does not recognize date and month format and does not properly execute the code?

Here is the code:

var flag = false;
while(!flag){
    var anydate = prompt('Enter any date in format yyyy-mm-dd', anydate);
    anydate = new Date(anydate);
    var dd = anydate.getDate();
    var mm = (anydate.getMonth()+1);
    var yyyy = anydate.getFullYear();
    if(((mm<1)||(mm>12)||((mm===1)&&(dd>31))||((mm===2)&&(dd>28))||((mm===3)&&(dd>31))|| ((mm===4)&&(dd>30))||((mm===5)&&(dd>31))||((mm===6)&&(dd>30))||((mm===7)&&(dd>31))||((mm===8)&&(dd>31))||((mm===9)&&(dd>30))||((mm===10)&&(dd>31))||((mm===11)&&(mm>30))||((mm===12)&&(dd>31)))){
        alert('Your data is invalid! Enter valid date please!');
        continue;
        flag = false}else{
        alert('OK! You can continue with process!');
        break;
    };
};

var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

console.log(weekday[anydate.getDay()]);
console.log(anydate.getMonth()+1);
console.log(anydate.getDate());
console.log(anydate.getFullYear());
a = anydate
anydate = mm + '-' + dd + '-' + yyyy;
console.log(anydate);

IF-Statements: Making VBAs codes more efficient

I'm working on a code to compare two long (+40,000 logs) worksheets with info. I need to use VBA, sadly can't use python, SQL or any other language.

I'm going over the sheets with 2 for loops as I think is the most efficient way... (Do you perhaps have a more efficient suggestion?) And inside these loops, I'm using one IF-Statement with many criteria (multiple ANDs).

For making my code faster, would you recommend keeping this statement as it is or using multiple ones with one condition each?

If ID = N_ID_IN And Cells(j, DCol) > 0 And Cells(j, Int_DCol) > Min And IsInArray(Routes, Cells(j, DCol), Num_R - 1) And (ActiveWorkbook.Sheets(DSheetName).Cells(j, Int_DCol) * (ActiveWorkbook.Sheets(DSheetName).Cells(j, DCol) - ActiveWorkbook.Sheets(ISheetName).Cells(i, ICol)) / 100) >= Min_S Then

The "IsInArray()" is a function I created to simulate the df.isin() function of Python. Do you consider is best to use this function outside the IF-Statement and store its value in a variable?

Thanks!!

How can I combine the "paste" command with the "ifelse" command in a for loop with R?

For Loop in R including paste and ifelse

Dear Community,

I'm trying to combine a paste command in combination with an ifelse command in a for loop with R Studio - but I'm receiving the error message Error: Unexpected '}' in "}".

Download simplified Dataset:

I have created a simple dataset to illustrate my problem. You can download via the following link: https://www.dropbox.com/scl/fi/jxvcfvxnv7pf8e74tulzq/Data.xlsx?dl=0&rlkey=de7b3e2d0ge8ju6tsvz2bkzuv

Background:

I would like evaluate empirical data from a test. Therefore I need to create a new column (called Point.[i]) for every item (i = 1-4). If the value in the "Answer.[i]"-column corresponds to the value of the "Right.Answer.[i]"-column, I would like to give 1 point (otherwise 0 points) for that task.

My Code

This is easy for one column:

data1 <- mutate(data, Point.1 = ifelse(Answer.1 == Right.Answer.1, 1, 0)) 

Now I would like write a for loop doing this for all columns, but the following code is not working:


for (i in 1:4) {
  data[i] <- mutate(data, paste("Answer.",i) = ifelse(paste("Answer.",i) == paste("Answer.",i), 1, 0))
  print(data)
}

I would be very grateful for any advice. Thanks in advance!

Karla

Getting outputs from a "for" loop in r into a matrix or data frame

I am trying to perform the following loop:

  1. Compare each of the n rows of my matrix X with a X.prototype matrix.

  2. Find the closest row of X.prototype to each row of X.

  3. if the two rows have the same label (y and y.prototype), then bring the values close; otherwise, put them further.

My code:

for (i in (1:n)){ 
  
  closest.row <- which.min(colSums((t(X.prototype) - X[i,])^2))
  
  X.new.x1 <- ifelse(y.prototype[closest.row] == y[i],
                     X.prototype[closest.row,1]+(eta*(X[i,1]-X.prototype[closest.row,1])),
                     X.prototype[closest.row,1]-(eta*(X[i,1]-X.prototype[closest.row,1])))
  X.new.x2<- ifelse(y.prototype[closest.row] == y[i],
                    X.prototype[closest.row,2]+(eta*(X[i,2]-X.prototype[closest.row,2])),
                    X.prototype[closest.row,2]-(eta*(X[i,2]-X.prototype[closest.row,2])))
  X.new <- matrix(c(X.new.x1,X.new.x2),ncol=2) 

  plot(X.new.x2~X.new.x1)

 print(X.new)
  
}


----------


set.seed(123)                        # Set seed for reproducibility
n <- 100
X <- cbind(x1 = runif(n, -1.5, 1.5),
           x2 = runif(n, -1.5, 1.5)) # Generate random points
y <- as.integer(rowSums(X^2)<1)      # Determine whether inside the circle#
idx <- sample(100, 10)               # Mess up 10 class labels ...
y[idx] <- 1-y[idx]                   # ... by flipping the label

is <- c(sample(which(y==0),K), sample(which(y==1),K))
X.prototype <- X[is,]
y.prototype <- y[is]                 # Will be K times 0, followed by K times 1

K <- 10
eta <- 0.25
H <- 25

The problem is that the outcomes come out as single vectors, and I am unable to bring them together in a X.new matrix, to use for new predictions and to plot it.

this is a link to how my output looks

This is how I'd like them to look

Thank you S

Asking the user if they want to run a program again in C

I'm new to coding so please forgive me if this is a stupid question. I am trying to create a program in C where the user can input the number of a month and then they are told how many days are in that month. My code works in a console, until I try to implement a way where the user is asked to begin the program again.

This is what I have tried to use so far in order to get it to work, but I cannot wrap my head around why it isn't. Any help would be greatly appreciated.

#include <stdio.h>

char choice;
do
{
    void printDays(int D) 
    { 
        if (D == 2) { 
            printf("This month has 28 days"); 
        } 

        else if (D == 4 || D == 6 
                || D == 9 || D == 11) { 
            printf("This month has 30 days"); 
        } 

        else if (D == 1 || D == 3 || D == 5 
            || D == 7 || D == 8 || D == 10 
            || D == 12) { 
            printf("This month has 31 days"); 
        } 
  
        else { 
            printf("Invalid month"); 
        } 
    } 

    int main() 
    { 
        int D = ; 
    
        printDays(D); 
    } 
    printf("Run the program again? (Y/N) ?"); 
    scanf("%c",&choice);
    if(choice=='n' || choice=='N') 
        break;
}while(1); 

adjusting easy python code "adding small condition"

I was trying to adjust this code so it accepts if I wrote rock , paper or scissor in small or capital letter. and if it wasn't one of these three words then it should exit the program and print "WRITE IT CORRECTLY!")

import random
y = input("Enter rock, paper or scissor: ")
x = ["rock","paper","scissor"]
z = random.choice(x)
c = print("Computer: " + str(z) )


if (y=="rock" and z=="scissor"):
    print("YOU WON!")

elif  (y=="rock" and z=="paper"):
    print("COMPUTER WON!")

elif  (y=="rock" and z=="rock"):
    print("TRY AGAIN!")

elif  (y=="paper" and z=="rock"):
      print("YOU WON!")

elif (y=="paper" and z=="paper"):
    print("TRY AGAIN!")

elif (y=="paper" and z=="scissor"):
    print("COMPUTER WON!")

elif (y=="scissor" and z=="rock"):
    print("COMPUTER WON!")

FOR loop inside IF loop can't break out of IF after FOR loop if finished

I'm new at programming with Javascript & Jquery, and I'm creating a table of parent rows and child rows using DIVs, instead of a table. This is what the client wants. I need to find a way to exit the IF loop after one full iteration of the inner FOR loop with variable z. There are variabl number of instances where stringJSONArray.data[i].list > 1. The inner FOR loop creates a varying number of DIVs for each instance where stringJSONArray.data[i].list > 1. I need to exit the IF loop and return to the main FOR loop with variable i each time the FOR loop with variable z completes. Currently, the inner FOR loop with variable z is iterating through all instances in one go without breaking out of the IF loop and returning to the main FOR loop with variable i. This creates all the child rows below the table, instead of each group of child rows under its specific parent. Everything is working fine, except I can't break out of the IF loop each time the FOR loop iterates through the child row data. The condition needs to be determined when a row has a child, thus the IF loop. I can't find any other loop statement to use for this. Any help will be greatly appreciated.

var staticUrl = 'https://example.com/get-json-data'
jQuery.getJSON(staticUrl,function(result){
var jsonString = JSON.stringify(result)
const stringJSONArray = JSON.parse(jsonString);

var i;
for (i = 0; i < jsonString.length; i++) {

// Code to create parent rows


if (stringJSONArray.data[i].list > 1) {

var divElementSymbol = document.createTextNode(stringJSONArray.data[i].symbol);
var staticUrl3 = `https://example.com/get-json-child?symbol=${divElementSymbol.data}`;

jQuery.getJSON(staticUrl3,function(result3){
var jsonString3 = JSON.stringify(result3)
const stringJSONArray3 = JSON.parse(jsonString3);

let childCount = stringJSONArray.data[i].list;

var z;
for (z = 0; z < childCount; z++) {

let ChildElement1 = document.createElement('div');
let ChildElementText1 = document.createTextNode(stringJSONArray3[z].symbol);  
ChildElement1.appendChild(ChildElementText1);
let parentList1 = document.querySelector('#stock-id2');
parentList1.appendChild(ChildElement1);

}; //End (var z) Iterate Through All Child Rows

}); //End (STRINGIFY CHILD) Pull All Child Row Entries From get-json-child JSON Data Link

}; //End IF Loop To Second Find All Entries With Child Rows


}; // First loop i

}); //Close jQuery.getJSON function

Make if elif else to move onto next elif

Suppose there is this code

statement = input()

if "book" not in statement:
    if "what" in statement:
        print("something")
    # else: 
        # something here which will make the program to move onto the next elif
    
elif "bag" in statement:
    print("anything")
elif "book" in statement:
    print("everything")

now if we execute the code, and there's no "book" in statement but there is "bag" it won't print anything. I know I can add and in the first condition but my real code is more complicated. Please tell me a way so that it will move on to the next elif, if "what" is not in statement

How to add json attribute value depend on existing value using apache nifi

I have a json data format as foloowing,

{
    "sensordata":{
        "sensorId":20,
        "dataValue":525.0,
        "date":"2020:12:29"
    }
}

I want to add new attribute called exceeded depending on the dataValue attribute, If datavalue is greater than 30 I want to assign true for the exceeded attribute, else false

output look like this,

{
    "sensordata":{
        "sensorId":20,
        "dataValue":525.0,
        "date":"2020:12:29",
        "exceeded":"true"
    }
}

my current dataflow is as follow, enter image description here

How can I use an if statement to get the identifier of the table view cell [closed]

How can I use an if statement to check if the cell touched by the user has a identifier "test" and do something if not do nothing?

Note: This is in swift on Xcode, I am using a table view and table view cells

Is it possible to loop through several variables that have range values?

Super newb here. I'm doing a python challenge on 101computin.net and I can't figure out how to make my code shorter. I have tried placing these variables into a list, but then I can't check if density is in the range within the list because object can't be interpreted as an integer.

#Eureka! - Archimedes and King Hiero's Crown - www.101computing.net/eureka-and-king-hieros-crown/
mass = float(input("Input the mass of the crown in kg"))
volume = float(input("Input the volume of the crown in cubic meter"))

density = mass / volume

aluminum = range(2400, 2700)
bronze = range(8100, 8300)
silver = range(10400, 10600)
lead = range(11200, 11400)
gold = range(17100, 17500)
platinum = range(21000, 21500)

if density in Aluminum:
    print('Your crown is aluminum!')
elif density in bronze:
    print('B')
elif density in silver:
    print('S')
elif density in lead:
    print('L')
elif density in gold:
    print('G')
elif density in platinum:
    print('P')
else:
    print('Nope!')

Obviously all the if/elif statements will work, but is there an easier way to loop through the ranges and determine which metal the output is based on the density?

Detecting if an array includes and output number (JavaScript) [duplicate]

I made a code to detect if an array includes something and delte it...

var arr = ["hi", "bye"," oh no"] 

if (arr.includes("bye")) {
    //remove it from arr
} 

note that the place of bye can change so just imagine you don't know its place... What can I do?

If else with loop " for " to repeat until done

I want to edit this script to add ssl and try again if it fails until I finish adding the certificate and then finish the script and start virtual host >> Can this be used ?? To fulfill my purposes

            sitesAvailabledomainSSL=/etc/apache2/sites-available/$2-le-ssl.conf
          if [ ! -e "$sitesAvailabledomainSSL" ]; then
       echo 1 | certbot -d "$2"
       else
      echo 1 | certbot --expand -d "$4"
      fi

   virtualHostStart='### start virtual host'
   virtualHostStart="${virtualHostStart} ${1}"
  virtualHostEnd='### end virtual host'
   virtualHostEnd="${virtualHostEnd} ${1}"

    ### regular expression to remove wrong virtual host from the SSL file
sed -zE -i "s/<IfModule mod_ssl.c>(\r\n|\r|\n)<VirtualHost \*\:80>(\r\n|\r|\n)$virtualHostStart.*? 
  $virtualHostEnd(\r\n|\r|\n)<\/VirtualHost>(\r\n|\r|\n)<\/IfModule>//" /etc/apache2/sites-available/$3-le-ssl.conf
### restart Apache
/etc/init.d/apache2 reload

fi


any suggestions?

lundi 28 décembre 2020

I'm practicing my if, elif, else and for some reason it's not working? [closed]

Here is the code that is not working:

import random 

a = int (input ("请输入一或者二"))
d = a

b = random.randint(1,2)

if a != b:
    print ("你被狮子吃掉了")

c = random.randint(1,2)

elif d != c:
    print ("你被龙吃掉了")
    
else:
    print("你活下来了")

Using a class/struct member delared inside 'if' conditional outside

I am attempting to recreate some "R" scripts in C++, just for the fun of it. Have used C decades ago but not recently. Now what I have is a bit of code where I am reading data from a binary file and placing the data into a structure (or class) with an unknown number of array structures (for the file reading side). Not knowing exactly how many arrays are needed, I define the number after reading another binary file which contains that data. So, I have two options; one to enter new data (which saves that plus the number of arrays to two files); another to read saved data back in (which provides the number of needed array structures). Having done either option via 'IF' conditionals, I need the new or recovered data to perform math on outside those conditionals. This is where things go wrong. The data is not available. The simple example recreates the problem and I have not stumbled upon the solution yet. I am not familiar enough with C++ to find what is most likely something simple to fix. The 'closed' function's first line outside the 'if' conditionals does work as expected, but that's not the data I need, and I don't want that line in the program.

#include <iostream>
using namespace std;
void closed(void);
class traverse {
public:
    int sta;
};
int main()
{
    closed();
    return 0;
}
void closed(void)
{
    traverse stations[1]; // removes 'stations was not declared' error on line 35.
    cout << "Enter 1 or 2\nSelect: ";
    int selType;
    cin >> selType;
    if (selType == 2) {
        cout << selType << " selected\n";
        traverse stations[1];
        stations[0].sta = 2; //need this member value available outside conditional.
        cout << "Value is " << stations[0].sta << " inside." << endl;
    } else {
        cout << selType << " selected\n";
        traverse stations[1];
        stations[0].sta = 1; //need this member value available outside conditional.
        cout << "Value is " << stations[0].sta << " inside." << endl;
    }
    cout << "Value is " << stations[0].sta << " outside." << endl;
}

I originally used a 'struct' but decided to try a 'class' to discover the differences. But, the same problem persists with both, so I don't think it is anything with the definitions, but perhaps with different declarations. Any ideas would be greatly appreciated. Thanks.

Please use IF-ELSE / FOR LOOP while writing the program. Please Help me and use IF-ELSE / FOR LOOP

strong text1.Enter a string. Check whether the string is a palindrome. Print accordingly. (Palindrome is a string which is same from the starting as in the reverse also eg. madam, racecar

  1. Write a program to accept a string and display its content in the following pattern- W A T E R

How can i optimice this FOR sentence with lots of IF?

It takes too many time to run one for iteration because the quantity of if in it, if its a better solution for it and someone can help me i would be very greatfull. The function works a singular code with the items detailed in IF sentences time by time. With a list of 2000 3000 codes it takes too much time and ejecutions because the 6 min max time expires frecuently.

function CODIFICADOR() {
  
  var sheet0 = SpreadsheetApp.getActive().getSheetByName('HOJA');
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('PROGRAMA');
  var cantcod = sheet0.getRange("B1:B1500").getValues().filter(String).length;
  SpreadsheetApp.getActiveSpreadsheet().toast('POR FAVOR NO REALIZAR NINGUNA ACCION MIENTRAS EL PROGRAMA SE EJECUTA');

   for(var i = 2; i <= cantcod; i++){
    var codigo = sheet0.getRange(i, 2).getValue();
    var codigosig = sheet0.getRange(i+1, 2).getValue();
    sheet1.getRange(2, 8).setValue(codigo);
    sheet1.getRange(2,11).setValue(codigosig);
    var codcumple = sheet1.getRange(6, 8).getValue();
    var codidentico = sheet1.getRange(8, 8).getValue();
    
    if( codcumple == "OK" && codidentico == "NO"){
   
    var codfila = sheet1.getRange(4, 8).getValue();
   
    if(codfila == "-AP" ){
    sheet0.insertRowsAfter(i, 3);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 4, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-KP01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Bomba").setBackground("green");
            sheet0.getRange(i+2, 2).setValue(codigo+"-MK01").setBackground("green");
            sheet0.getRange(i+2, 6).setValue("Acoplamiento").setBackground("green");
              sheet0.getRange(i+3, 2).setValue(codigo+"--M01").setBackground("green");
              sheet0.getRange(i+3, 6).setValue("Motor eléctrico").setBackground("green");
                 var cantcod = cantcod+3;
                 i = i+3;
    }

    else if(codfila == "-AN" ){
    sheet0.insertRowsAfter(i, 2);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 3, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"--M01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Motor eléctrico").setBackground("green");
            sheet0.getRange(i+2, 2).setValue(codigo+"-KN01").setBackground("green");
            sheet0.getRange(i+2, 6).setValue("Ventilador").setBackground("green");
                 var cantcod = cantcod+2;
                 i = i+2;
    }

    else if(codfila == "-AA" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-KA01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Válvula").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }

    else if(codfila == "-AT" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-KT01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Filtro").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }

    else if(codfila == "-BR" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-MR01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Tubería").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }

    else if(codfila == "-CP" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-QP01").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }

    else if(codfila == "-CT" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-QP01").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }    

      else if(codfila == "-CG" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"--S01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Interruptor de final de carrera").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }

    else if(codfila == "-AC" ){
    sheet0.insertRowsAfter(i, 1);
      sheet0.getRange(i, 21).activate();
      sheet0.getActiveRange().autoFill(sheet0.getRange(i, 21, 2, 1), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
        sheet0.getRange(i+1, 2).setValue(codigo+"-QC01").setBackground("green");
        sheet0.getRange(i+1, 6).setValue("Intercambiador de calor").setBackground("green");
          var cantcod = cantcod+1;
          i = i+1;
    }   

  }
  //else { sheet0.getRange(i, 2).setFontColor("red");}

 }

if statement to check file size AND file extension

I've got a basic if statement to check a file input's size and extension. Both my statements work separately, but I can't get both of them to work together.

To validate the extension:

//check file extension

let filename = imgInput.value
let last_dot = filename.lastIndexOf('.')
let ext = filename.slice(last_dot + 1)


if(ext !== 'jpg' || ext !== 'png' ){
    imgClient.innerHTML = 'Please select 1 JPG or PNG file less than 5mb'
    e.preventDefault()
} else {
    imgClient.innerHTML = ''
}

To validate the size:

// validate file size

if(imgInput.files[0]){
    let imgSize = imgInput.files[0].size
    if(imgSize > 5087408 ){
        imgClient.innerHTML = 'Your file is too big, please select an image under 5mb'
        e.preventDefault()
    } else {
        imgClient.innerHTML = ''
    }
}

One works when I comment the other out, but when I try both of them, only the first one executes.

I'm sure this might be a simple fix, I'm just stuck trying to figure it out... thanks for looking!

How to speed up conditional statement in python

I am trying to generate a new column in a pandas dataframe by loop over >100,000 rows and setting the value of the row conditional on an already existing row.

My current code is:

# if charging set to 1, if discharging set to -1.
# if -1 < IT100 < 1 then set CD to previous cells value
# Charging is defined as IT100 > 1 and Discharge is defined as IT100 < -1
def CD(dataFrame):


    for x in range(0,len(dataFrame.index)):
        print(x)
        current = dataFrame.loc[x,"IT100"]

        if x == 0:
            if dataFrame.loc[x+5,"IT100"] > -1:
                dataFrame.loc[x,"CD"] = 1
            else:
                dataFrame.loc[x,"CD"] = -1
        else:
            if current > 1:
                dataFrame.loc[x,"CD"] = 1
            elif current < -1:
                dataFrame.loc[x,"CD"] = -1
            else:
                dataFrame.loc[x,"CD"] = dataFrame.loc[x-1,"CD"]

Using if/Else loops is extremely slow. I see that people have suggested to use np.select() or pd.apply(), but I do not know if this will work for my example. I need to be able to index the column because one of my conditions is to set the value of the new column to the value of the previous cell in the column of interest.

Thanks for any help!

what is wrong if convert to conditional operator

I want to convert an "if" to "conditional operator (:?)". I tried to write it but I get an error expected expression before "for".

The original code:

#include <stdio.h>
int main ()
{
    int n, i, k, a [10], new;
    printf ("n:");
    scanf ("% d", & n);
    printf ("Initial \ n");
    for (i = 0; i <n; i ++)
    {
        a [i] = i;
        printf ("% d. value:% d \ n", i, a [i]);
    }
    printf ("Enter the index value you want to change:");
    scanf ("% d", & k);
    if ((k> = 0) && (k <n))
    {
        for (i = 1; i <= n; i ++)
        {
            if (i == k)
            {
                printf ("What number will you replace with array index% d?:", a [i]);
                scanf ("% d", & new);
                a [i] = new;
            } // if (i == k) end
        } // end of for loop

                        printf ("Last state \ n");
            for (i = 0; i <n; i ++)
            {
                printf ("% d. value:% d \ n", i, a [i]);
            }
    } // end of if statement
    else
        printf ("You did not enter a value within the array boundaries. \ n");
    return 0;
}

I want to convert it to conditional form.

I tried this:

#include <stdio.h>
int main ()
{
    int n, i, k, a [10], new;
    printf ("n:");
    scanf ("% d", & n);
    printf ("Initial \ n");
    for (i = 0; i <n; i ++)
    {
        a [i] = i;
        printf ("% d. value:% d \ n", i, a [i]);
    }
    printf ("Enter the index value you want to change:");
    scanf ("% d", & k);
    if ((k> = 0) && (k <n))

        for (i = 1; i <= n; i ++)

        {
            (i == k)?printf("What number will you replace with array index% d?:", a [i]), scanf("% d", & new),(a [i] = new): for(i = 0; i < n; i ++), printf("Last state \ n"), printf("% d. value:% d \ n", i, a [i]), printf("You did not enter a value within the boundaries of the array. \ n" );
        }
    return 0;

}

I get an error: expected expression before "for". How can I write this?

How do you use a variable from a dictionary in a if statement?

So I was wondering how you could use a if statement to print out a word if you cannot find a variable listed in a dictionary. If you know please tell me.

ONclick button, two expressions to AJAX, getting errors in ELSE statement but works in if statement

In an onclick button I am passing two expressions separated by a comma. The buttons are part of a PHP IF ELSE statement. There is one button that appears in the IF part of the statement. It also passes two expressions. This button works well. Here is the HTML code for the first button:

<button id='Search' class='button btn' onclick='Search($tbl_id, $cid)'><i class='icon fas fa-globe'></i></button>" 

In the ELSE part of the statement I have another button that needs to also pass two expressions. However with this button I am getting a console error of "expected expression, got ','". This confuses me since the exact same HTML with two expressions works just fine in the IF part of the statement. I have narrowed down the error to being in the HTML by removing the AJAX and still getting the error here. Here is the HTML for the button in the ELSE portion of the statement.

<button id='largerSearch' class='button btn' onclick='largerSearch($tbl_id, $cid)'>Search for alternative <i class='seated-icon fas fa-globe'></i></button>" 

If I remove the comma and remove on expression, then it works fine.

Why does the exact same HTML work and successfully pass two expressions in the IF portion of the statement and fail in the ELSE portion of the statement?

Why is Java skipping an if clause if they contain similar comparisons?

So, I just started to get my hands dirty on Java this week and I found something rather odd. I'll add the code and then walk you through.

import java.util.Scanner;

public class kids
{
    public static void main(String[] args)
    {
        System.out.println("How old are you, doll?");
        
        Scanner scanner = new Scanner(System.in);
        int age = scanner.nextInt();

        System.out.println("Doggie lover or a cat person?");
        String animal = scanner.nextLine();
        
        if(age < 18 && animal.contains("dog")) // 1st comparison
        {
            System.out.println("Hello cutie, welcome");
        }
        else if(age < 18 && animal.contains("cat")) // 2nd comparison
        {
            System.out.println("Oh, hi"); // This statement gets skipped
        }
        else if(age < 18 && animal.contains("cat")); // 3rd comparison
        {
            System.out.println("Hiya, Doggie lover!");
        }
    }
}

I've attached my output here Output

So, I gave an input "dogcat" to the string animal. It is pretty clear or at least to me that the three comparisons should return TRUE but my output says otherwise. Seems like only the first and the third comparisons return TRUE but clearly if the third comparison returns TRUE since it contains the string "cat" so does the second comparison. Why is Java skipping my comparison here?

How to use for loop when I have different length in R? [duplicate]

I have two dataframes df1 and df2 and `df2':

df1 = structure(list(Day = c(19L, 20L, 20L, 20L, 20L, 21L, 21L, 21L, 
21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 22L, 22L, 22L, 22L), 
    Month = c(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 
    9, 9, 9, 9), Year = c(2004, 2004, 2004, 2004, 2004, 2004, 
    2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 2004, 
    2004, 2004, 2004, 2004), Date = structure(c(12680, 12681, 
    12681, 12681, 12681, 12682, 12682, 12682, 12682, 12682, 12682, 
    12682, 12683, 12683, 12683, 12683, 12683, 12683, 12683, 12683
    ), class = "Date")), row.names = c("text1", "text2", "text3", 
"text4", "text5", "text6", "text7", "text8", "text9", "text10", 
"text11", "text12", "text13", "text14", "text15", "text16", "text17", 
"text18", "text19", "text20"), class = "data.frame")

       Day Month Year       Date
text1   19     9 2004 2004-09-19
text2   20     9 2004 2004-09-20
text3   20     9 2004 2004-09-20
text4   20     9 2004 2004-09-20
text5   20     9 2004 2004-09-20
text6   21     9 2004 2004-09-21
text7   21     9 2004 2004-09-21
text8   21     9 2004 2004-09-21
text9   21     9 2004 2004-09-21
text10  21     9 2004 2004-09-21
text11  21     9 2004 2004-09-21
text12  21     9 2004 2004-09-21
text13  22     9 2004 2004-09-22
text14  22     9 2004 2004-09-22
text15  22     9 2004 2004-09-22
text16  22     9 2004 2004-09-22
text17  22     9 2004 2004-09-22
text18  22     9 2004 2004-09-22
text19  22     9 2004 2004-09-22
text20  22     9 2004 2004-09-22

df2 = structure(list(days = structure(c(12680, 12681, 12682, 12683, 
 12684, 12685, 12686, 12687, 12688, 12689, 12690, 12691, 12692, 
 12693, 12694), class = "Date"), week = c(3, 3, 3, 4, 4, 4, 4, 
 4, 4, 4, 4, 4, 1, 1, 1)), row.names = c(NA, -15L), class = 
 "data.frame")

         days week
1  2004-09-19    3
2  2004-09-20    3
3  2004-09-21    3
4  2004-09-22    4
5  2004-09-23    4
6  2004-09-24    4
7  2004-09-25    4
8  2004-09-26    4
9  2004-09-27    4
10 2004-09-28    4
11 2004-09-29    4
12 2004-09-30    4
13 2004-10-01    1
14 2004-10-02    1
15 2004-10-03    1

As you can see df1 is longer than df2 and contains all the "dates" in df2. What I would like to get is a code that says: if the date is df1 is the same as the date in df2, then give me the weeknumber. I manage to do it individually:

if (df1$Date[1] == df2$days[1]) df2$week[1]

if (df1$Date[2] == df2$days[2]) df2$week[2] 

if (df1$Date[3] == df2$days[2]) df2$week[2] # this is the issue: df1 is longer than df2 since it repeats dates more than ones

if (df1$Date[4] == df2$days[2]) df2$week[2] # same as above
...

The problem is that when I try to loop for every element in df1 and df2 I fail since the two have different length since df1 repeats the same date n times. So I would need a loop that takes care of the repetions of dates in df1. Yet I got stuck here:

for (i in length(# don't know how to handle the different length)) {
if (df1$Date[1] == df2$days[1]) df2$week[1]
}

Can anyone help me sort this out?

Thanks!

Python syntax for “if a and b or a and c” where a, b and c are words in a sentence

I have a python script, and I should check if two words are present in a sentence separated by dash

test_dash_sentence="wordtest-wordtest-word3-word4"

if ("word1" and "word2") or ("word1" and "word3") in test_dash_sentence:
    print("FOUND")
else:
    print("NOT FOUND")

The issue I have is that is return me "FOUND" even if word1 is not present, so it should return me "NOT FOUND"

I have tried different models (with simple quotation, without parentheses) and it seems to work if I only look for one word in the sentence, but when I look for two words, it doesn't work.

Python function return None. Can someone explain Why? [duplicate]

hello guys I wrote a function for this task:

Task

You've just moved into a perfectly straight street with exactly n identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street.

The street looks something like this:

Street
1|   |6
3|   |4
5|   |2
  • Evens increase on the right;
  • Odds decrease on the left. H
  • House numbers start at 1 and increase without gaps.
  • When n = 3, 1 is opposite 6, 3 opposite 4, and 5 opposite 2.

Example

Given your house number address and length of street n, give the house number on the opposite side of the street.

over_the_road(1, 3) = 6

My solution:

def over_the_road(address, n):
    even = list(range(n + 1))
    for number in even:
        if number % 2 == 0:
            even.remove(number)
    odds = list(range(n + 1))
    odds.pop(0)
    for number in odds:
        if not number % 2 == 0:
            odds.remove(number)
    odds.reverse()
    if address == even:
        return odds[even.index(address)]
    elif address == odds:
        return even[odds.index(address)]

Can someone please explain why is my function returning none?

Java - If-statement returns false

I've got a button "addspieler" and when I first press it, the second if statement returns true and view.addbox is executed (I want to add an JComboBox every time the button is pressed). But after the execution the if-statement returns always "false" and view.addbox is not going to be executed anymore. I don't know why. Thanks for advice!

public void actionPerformed(ActionEvent e) {

            if (e.getSource() == view.button1) {
                view.zeige_AuswahlNeuesSpiel(modell.getSpieler());

            }

            if (e.getSource() == view.button_addSpieler) {
                view.add_Box(modell.spieler_Anzahl_NeuesSpiel, modell.getSpieler());

            }

    }

view.addbox =


 public void add_Box(int anz_spieler, ArrayList<Spieler> spieler_Liste)
        {
            if(ct >= anz_spieler)
                return;



            jcombo_Liste = erstelle_Box(anz_spieler);

            GridBagConstraints gbc = new GridBagConstraints();
            GridBagLayout layout = new GridBagLayout();
            setLayout(layout);


            jcombo_Liste.get(ct).addItem(spieler_Liste.toArray());






            button_addSpieler = new Button("Spieler hinzufügen");
            button_addSpieler.addActionListener(darts_controller);

            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridx = 0;
            gbc.gridy = 0;
            f1.add(button_addSpieler,gbc);


            gbc.gridx = ct;
            gbc.gridy = 1;
            f1.add(jcombo_Liste.get(ct),gbc);

            ct = ct+1;
            f1.repaint();


        }

How do I add a command (tkinter) in an if statement?

I have created an if statement to check if the username and password and username entered is the same to the username and password in the textile. I have been able to display if the data inputted is correct or not. I now want to add a command into the if statement e.g. command = main_menu if the data inputted is correct (I am using tkinter)

This is the if code I have so far:

def validation(username1, password1):
    file = open("Accounts.txt", "r")
    for line in file:
        line = line.split("\n")
        line = line[0].split(" ")

        if username1 == line[0] and password1 == line[1]:
            valid = Label(root, text="Data: Found")
            valid.place(x=290, y=130)
        else:
            valid = Label(root, text="Data: Not found")
            valid.place(x=280, y=130)

    file.close()

Any ideas on how to do this?

Thanks xx

weird syntax Javascript [duplicate]

I saw this piece of code in a book :

let book = {
  subtitle : {
    title : "nothing",
    }
}
let len = undefined;

// the first one
if (book) { 
  if (book.subtitle) len = book.subtitle.length;
}

// the second one (which i have no idea what is)
len = book && book.subtitle && book.subtitle.length

can anyone explain how does the second done work?

IF always returns FALSE after comparing data of a database

I'm trying to create a website that has a login page. I had connected a database which contains everyone name and passwords (we are 10 people, so I put all data on a database). After the login it should redirect you to another page, but it always returns false; despite this, I inserted all data correctly. Here's the code of the "if", thanks in advance for the help.

session_start(); 
                  if ($ArrRow["NomeUtente"]==$_POST["NomeUtente"] and $ArrRow["Password"]==$_POST["Password"]) {
                  $_SESSION["login"]=true;
                  echo "Login corretto";
                  echo "<meta http-equiv=refresh content=2;url=https://tpvgruppo.altervista.org/turni-settimanali/>";
                } else {
                  $_SESSION["login"]=false;
                  echo "Login non corretto, riprova.";
                  echo "<meta http-equiv=refresh content=2;url=https://tpvgruppo.altervista.org/area-riservata/>";
             } 

Show values based on dropdown selection on the same page

Is there a way for me to show the values based on selection of dropdown using if statements in Django.

The pricing output value depend on the contract selected and if it is a half day or full day, if it is a half day I just take the outputted price and divide by 2. Below is my model and form, I have been told that I need to do this ideally in the model but cannot figure out the code for a method to work this out or if I need to do it in the template or view, keep hitting brick walls if you have any documents you recommend I should read please let me know.

The way I am looking at solving this is that the dropdown lets say 1-Year Weekly will take the day rate x the number of days until the end date based on:

   @property
   def day_rate_year1(self):
     return self.year1 / weeksinyear / 5

Ideally I would like to have the results of the dropdown shown on the same pages, as I plan to use another button to generate a PDF. I am guessing from my research that this would be done using AJAX

Model

    class AdminData(models.Model):
        year1 = models.IntegerField()
        year3 = models.IntegerField()
        year1_fortnight = models.IntegerField()
        year3_fortnight = models.IntegerField()

    @property
    def fortnight_dayrate_year1(self):
        return self.year1_fortnight / weeksinyear / 5

    @property
    def fortnight_dayrate_year3(self):
        return self.year3_fortnight / weeksinyear / 5

    @property
    def day_rate_year1(self):
        return self.year1 / weeksinyear / 5

    @property
    def day_rate_year3(self):
        return self.year3 / weeksinyear / 5


class Price(models.Model):
        year_choice = Choices('1-Year Weekly', '3-Year Weekly','1-Year Fortnightly', '3-Year 
        Fortnightly')
        day_choice = Choices('Full Day', 'Half Day')
        name = models.CharField(max_length=100)
        contract = StatusField(choices_name='year_choice')
        time_daily = StatusField(choices_name='day_choice')
        start_date = models.DateField(default=datetime.now)
        end_date = models.DateField(default=datetime(2021,3,31))
        epoch_year = date.today().year
        year_start = date(epoch_year, 1, 4)
        year_end = date(epoch_year, 3 , 31)


        def __str__(self):
            return self.name

Please let me know if you need further code.

Thanks for the help, sorry for the stupid question.

Why is my code returning two results instead of one

I am writing a simple code for a password controller which should return false if the string contains less than 8 characters and false if the string contains 8 or more characters. but i am getting two response one is either true or false, and the other result is <function password at 0x00000272BA8B7F70>.

Here is the code I have written:

def password(str):
    if len(str) >= 8:
        print("true")
    else:
        print("false")
    return password
print(password("gtbd"))

Problem on adding quantity in existing item in DataGridView - vb.net

I am creating a shopping system as my university mini project, where the user can enter the barcode of an item they wanted and the entered item will be added to the grid on the right and also as a new item to the grid on the left. Each item has a unique barcode and can have the same product code. When the user enters an item with the same product code then quantity will be added on the grid on the left. I am having a problem where when the second item quantity need to be added, the system is detecting it as a new item instead of adding the quantity

eg: Example of products and items

    Public Sub addRecordTo2ndDGV()
    Try
        dbconnection()
        sql = "SELECT * FROM items_database WHERE Item_Barcode = @ItemBarcode;"
        cmd = New MySqlCommand
        With cmd
            .Connection = conn
            .CommandText = sql
            .Parameters.Clear()
            .Parameters.AddWithValue("@ItemBarcode", formUser.barcodeTB.Text)
        End With
        da = New MySqlDataAdapter
        dt = New DataTable
        da.SelectCommand = cmd
        da.Fill(dt)
        If dt.Rows.Count > 0 Then
            Dim ItemProductCode, ItemBarcode As String
            Dim repeated As Boolean = False
            ItemProductCode = dt.Rows(0).Item(1)
            ItemBarcode = dt.Rows(0).Item(2)
            formUser.itemproductcodeTB.Text = ItemProductCode
            formUser.itembarcodetb.Text = ItemBarcode
            
            For Each row2 As DataGridViewRow In formUser.ItemBarcodeDGV.Rows
                If Convert.ToString(row2.Cells(1).Value) = formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) = formUser.itemproductcodeTB.Text Then
                    MsgBox("QUANTITY WILL MINUS")
                    minusQuantity()
                    formUser.ItemBarcodeDGV.Rows.Remove(row2)
                    MsgBox("QUANTITY HAS MINUS")
                    Exit For

                ElseIf Convert.ToString(row2.Cells(1).Value) <> formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) = formUser.itemproductcodeTB.Text Then
                    MsgBox("QUANTITY WILL ADD")
                    formUser.ItemBarcodeDGV.Rows.Add(New String() {formUser.itemproductcodeTB.Text, formUser.itembarcodetb.Text})
                    addQuantity()
                    MsgBox("QUANTITY HAS ADDED")
                    Exit For

                ElseIf Convert.ToString(row2.Cells(1).Value) <> formUser.itembarcodetb.Text AndAlso Convert.ToString(row2.Cells(0).Value) <> formUser.itemproductcodeTB.Text Then
                    MsgBox("NEW ITEM")
                    formUser.ItemBarcodeDGV.Rows.Add(New String() {formUser.itemproductcodeTB.Text, formUser.itembarcodetb.Text})
                    addRecord()
                    MsgBox("REGISTERED SUCCESSFULL")
                    Exit For
                End If
                Exit For
            Next
        Else
            MsgBox("Barcode not registered!")
            formUser.barcodeTB.Text = ""
            formUser.barcodeTB.Focus()
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        conn.Close()
        da.Dispose()
        formUser.barcodeTB.Text = ""
        clearUserForm()
        retrieveSubTotal()
    End Try
End Sub

Public Sub addRecord()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)
                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
                formUser.ProductAddToCartDGV.Rows.Add(New String() {formUser.productcodeTB.Text, formUser.itemdescriptionTB.Text, formUser.unitpriceTB.Text, formUser.unitQuantityTB.Text, formUser.unitpriceTB.Text})
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

Public Sub addQuantity()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)

                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(3).Value = Convert.ToString(Convert.ToInt16(row.Cells(3).Value + 1))
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

Public Sub minusQuantity()
    If formUser.itemproductcodeTB.Text = "" Then
        MsgBox("Scan a barcode")
    Else
        Try
            dbconnection()
            sql = "SELECT * FROM products_database WHERE Product_Code = @ProductCode;"
            cmd = New MySqlCommand
            With cmd
                .Connection = conn
                .CommandText = sql
                .Parameters.Clear()
                .Parameters.AddWithValue("@ProductCode", formUser.itemproductcodeTB.Text)
            End With
            da = New MySqlDataAdapter
            dt = New DataTable
            da.SelectCommand = cmd
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                Dim productcode, itemdescription, unitprice As String
                Dim repeated As Boolean = False
                productcode = dt.Rows(0).Item(1)
                itemdescription = dt.Rows(0).Item(3)
                unitprice = dt.Rows(0).Item(4)

                formUser.productcodeTB.Text = productcode
                formUser.itemdescriptionTB.Text = itemdescription
                formUser.unitpriceTB.Text = unitprice
                formUser.unitQuantityTB.Text = "1"

                For Each row As DataGridViewRow In formUser.ProductAddToCartDGV.Rows
                    If Convert.ToString(row.Cells(0).Value) = formUser.productcodeTB.Text AndAlso Convert.ToString(row.Cells(2).Value) = formUser.unitpriceTB.Text Then
                        row.Cells(3).Value = Convert.ToString(Convert.ToInt16(row.Cells(3).Value - 1))
                        row.Cells(4).Value = Convert.ToString(row.Cells(3).Value * row.Cells(2).Value)
                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            conn.Close()
            da.Dispose()
        End Try
    End If
End Sub

Here is the output image

How to filter a list based on multiple other lists in Python?

I have 3 lists:

minimal_values = ['0,32', '0,35', '0,45']
maximal_values = ['0,78', '0,85', '0,72']

my_list = [
    ['Morocco', 'Meat', '190,00', '0,15'], 
    ['Morocco', 'Meat', '189,90', '0,32'], 
    ['Morocco', 'Meat', '189,38', '0,44'],
    ['Morocco', 'Meat', '188,94', '0,60'],
    ['Morocco', 'Meat', '188,49', '0,78'],
    ['Morocco', 'Meat', '187,99', '0,101'],
    ['Spain', 'Meat', '190,76', '0,10'], 
    ['Spain', 'Meat', '190,16', '0,20'], 
    ['Spain', 'Meat', '189,56', '0,35'],
    ['Spain', 'Meat', '189,01', '0,40'],
    ['Spain', 'Meat', '188,13', '0,75'],
    ['Spain', 'Meat', '187,95', '0,85'],
    ['Italy', 'Meat', '190,20', '0,11'],
    ['Italy', 'Meat', '190,10', '0,31'], 
    ['Italy', 'Meat', '189,32', '0,45'],
    ['Italy', 'Meat', '188,61', '0,67'],
    ['Italy', 'Meat', '188,01', '0,72'],
    ['Italy', 'Meat', '187,36', '0,80']]

I want to filter my_list based on index [-1] and the values in minimal_values and maximal_values. So like this:

  1. For Morocco I only want the rows where index[-1] is between 0,32 and 0,78
  2. For Spain I only want the rows where index[-1] is between 0,35 and 0,85
  3. For Italy I only want the rows where index[-1] is between 0,45 and 0,72

I ultimately want my_list to look like this:

my_list = [
    ['Morocco', 'Meat', '189,90', '0,32'], 
    ['Morocco', 'Meat', '189,38', '0,44'],
    ['Morocco', 'Meat', '188,94', '0,60'],
    ['Morocco', 'Meat', '188,49', '0,78'],
    ['Spain', 'Meat', '189,56', '0,35'],
    ['Spain', 'Meat', '189,01', '0,40'],
    ['Spain', 'Meat', '188,13', '0,75'],
    ['Spain', 'Meat', '187,95', '0,85'],
    ['Italy', 'Meat', '189,32', '0,45'],
    ['Italy', 'Meat', '188,61', '0,67'],
    ['Italy', 'Meat', '188,01', '0,72']]

This is the code I tried:

for l in my_list:
    if l[-1] >= [x for x in minimal_values] and <= [x for x in maximal_values]:
        print(l)

I received the following output:

SyntaxError: invalid syntax

Code is not working, and is not doing directed task

The code is self explanatory, but I need help because, when I use it, it skips all the "If" cases and jumps to the next loop directly. The "scanf" works correctly; the variable "order" receives input correctly too. If you figure out how to fix it, Let me know! Have a great day!

#include <stdio.h>
#include <string.h>

int main(){
    int side [3]; // Fries(0), Fried Squid(1), Cheese Fries(2)
    int combo [3]; // Spicy Chicken(0), Whopper(1), Double Whopper(2)
    int drinks[3]; // Cola(0), Vanilla Shake(1), Lemonade(2)
    int amount;
    char order [20];
    int total = 0;

    for(int i = 0; i < 3; ++i){
        combo[i] = 20;
        total = total + 20;
    }
     for(int i = 0; i < 3; ++i){
        side[i] = 20;
        total = total + 20;
    }
    for(int i = 0; i < 3; ++i){
        drinks[i] = 20;
        total = total + 20;
    }

    while (total > 0){
        printf("Make your order here: \n");
        scanf("%s %d", order, &amount);
        printf("%s\n", order);
        if(order == "Fries"){
            printf("A\n");A
            if(side[0] < amount){
                printf("Your order is invalid, and you are stinky.\n");
            }
            else{
                printf("B\n");
                printf("your order is here: %s x %d", order, amount);
                total = total - amount;
            }
            printf("C\n");
        }
        printf("D\n");
    }
    return 0;
}



dimanche 27 décembre 2020

if & else conditios not working in javascript [closed]

<script>
    document.addEventListener('DOMContentLoaded', function() {

        // by default the submit button shd be disabled 

        document.querySelector('#submit').disabled = true;

        document.querySelector('#task').onkeyup = () => {
            if (document.qerySelector('#task').value.length > 0) {
                document.querySelector('#submit').disabled = false;
            } else {
                document.querySelector('#submit').disabled = true;
            }

        }