dimanche 31 janvier 2021

KeyError even though columns exist?

I'm trying to create an And statement in my for loop. There is a data frame that I have under "b". There are two columns of the data frame that I isolated into their respective lists (cdr3_length and heavy_percent).

I'm trying to create a for loop where the it parses through b and adds all data where the cdr3_length > 15 and heavy_percent < 88 to a new list "candidates".

cdr3_length=marv["heavy_cdr3_aa_length"]
cdr3_length.head()
heavy_percent=marv["heavy_percent_id"]
heavy_percent.head()

cnt_=0
candidates=[]
for i in range(0, len(b)):
    if (cdr3_length(b[i]) > 15) and (heavy_percent(b[i]) < 88):
        candidates.append(b[i])
    
        cnt+=1

Unfortunately, I'm receiving a KeyError:0 even though my columns exist and both .head() functions work. It says the error appears in the if statement line. I appreciate any help given, thank you!

Python GUI multiple comboboxes with condition

I have created multiple comboboxes but unable to create the condition.

My Aim : Two combobxes with values. Like source(dev,test,prod) and target(dev, test, prod). If i select the source = dev, and target = test then new button(copy) should create automatically.

Please help on this. I am very new to python.

Getting error with if else statement in python using input

When I run the code below I get a a syntax error. What's the issue and how can I rectify it? Thanks!

m = input("enter number between -5 and +5: ")
m = int(m)
if m < 0:
  print( m, " is less than 0")
  elif m > 0:
    print(m, " is greater than 0")
  else:
    print(m, " is equal to 0")

What is wrong with my if statement in this multiplication test generator?

This is a multiplication test generator. When I enter the correct answer, it still displays the message "No. Please try again."

import random

answer = 0

def generate_numbers():
    num1 = random.randrange(0,10)
    num2 = random.randrange(0,10)
    return(num1, num2)

def display_question(answer):
    num1, num2 = numbers
    answer = num1 * num2
    guess = int(input(f'What is {num1} times {num2}?'))
                
    while guess != answer:
        print("No. Please try again")
        display_question()

    print("Very good!")

Problems with if statement in Javascript

This code is ment to be a simple ToDo-List.

I want the function InputCheck() to check if there is a value in the input bar. In case the bar is empty i want the function to not execute the addTodo-function. With the code like this it doesnt execute the function even if the input has a value .I dont know what´s causing it and i dont receive any errors. Any Ideas ? Thanks in advance.

const listButton = document.getElementById("ListButton");
const myList = document.getElementById("MyList");
const deleteButton = document.getElementById("Delete");
const doneButton = document.getElementById("Done");

listButton.addEventListener("click", InputCheck);

function InputCheck() {
  var input = document.getElementById("textValue").value;
  if (input == "") {
  } else {
    addTodo;
  }
}

function addTodo(event) {
  event.preventDefault();
  
  
  const toDoDiv = document.createElement("div");
  const newListItem = document.createElement("li");
  newListItem.innerHTML = document.getElementById("textValue").value;
  toDoDiv.appendChild(newListItem);
  toDoDiv.classList.add("ToDo-Div");

  

  const deleteButton = document.createElement("button1");
  deleteButton.classList.add("delete-btn");
  deleteButton.innerHTML =
    '<button id ="Delete" class="button">Delete</button>';
  toDoDiv.appendChild(deleteButton);

  
  const doneButton = document.createElement("button1");
  doneButton.classList.add("done-btn");
  doneButton.innerHTML = '<button id ="Done" class="button1">Done</button>';
  toDoDiv.appendChild(doneButton);

  myList.appendChild(toDoDiv);
}```

How can I turn a .png image into an array of rgb values? (Grayscale is fine as well)

I would like to create a program to play a game. To do this, I need to look at the screen and the only way I can think of is to turn a .png screenshot into an array of RGB values then analyze them. How can I do this? I am open to other ideas on how to look for certain pixle colors.

php checking if password is valid problem

I need to write a function in php that checks if a password is valid.

Function would return True if the following conditions are met:

  1. The password must be at least 6 characters and at most 20 characters.
  2. It must contain at least one lowercase letter, one uppercase letter and one number.
  3. Otherwise, it returns False.

So far, this is the code I have (not too sure how to incorporate the second condition into the code after &&)...

<?php
    function isValid($password){
        if((strlen($password)>= 6 && strlen($password)<= 20) && ){

        }
    }
?>

Could someone show me how to complete my code in 2 ways? One without using preg_match() and the other with preg_match()?

IF Else or Case Function for SQL select problem

Hi I would like to make a select expression using case or if/else which seems to be a simple solution from logic perspective but I can't seem to get it to work. Basically I am joining against two table here, the first table is customer record with date filter called delivery_date and then the second table for the model scoring table with BIN and update_date parameters.

There are two logics I want to display

  1. Picking the model score that was the month before delivery_date
  2. If model score month before delivery is greater than 50 (Bin > 50) then pick the model score for same month as delivery_date

My 1st logic code is below

with cust as (
    select 
    distinct cust_no, max(del_date) as del_date, min(del_date) as min_del_date, (EXTRACT(YEAR FROM min(del_date)) -1900)*12 + EXTRACT(MONTH FROM min(del_date))  AS upd_seq
    from customer.cust_history   
    group by 1
)
,model as (
    select party_id, model_id, update_date, upd_seq, bin, var_data8, var_data2
    from 
    (
        select 
        party_id, update_date, bin, var_data8, var_data2,
        (EXTRACT(YEAR FROM UPDATE_DATE) -1900)*12 + EXTRACT(MONTH FROM UPDATE_DATE) AS upd_seq,
        dense_Rank() over (partition by (EXTRACT(YEAR FROM UPDATE_DATE) -1900)*12 + EXTRACT(MONTH FROM UPDATE_DATE) order by update_date desc) as rank1
        from 
        (
            select party_id,update_date, bin, var_data8, var_data2
            from model.rpm_model
            group by party_id,update_date, bin, var_data8, var_data2
        ) model
    )model_final
    where rank1 = 1
)
-- Add model scores
-- 1st logic Picking the model score that was the month before delivery date
select *
from 
    (
        select cust.cust_no, cust.del_date, cust.min_del_date, model.upd_seq, model.bin
        from cust
        left join cust 
        on cust.cust_no = model.party_id
        and cust.upd_seq = model.upd_seq + 1
    )a

Now I am struggling in creating the 2nd logic in the same query?.. any assistance would be appreciated

python if else return confusion, leetcode 669

Leetcode 669. Input: root = [1,0,2], low = 1, high = 2.

This code got error:

'Nonetype' object has no attribute 'val'

if not root will return, so anything passes this should be not None, which has a val.

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    def dfs(root):
        if not root:
            return None
        if root.val < low:         
            root = dfs(root.right)
        if root.val > high:
            root = dfs(root.left)  
        if root.val >= low and root.val <= high:
            root.left = dfs(root.left)
            root.right = dfs(root.right)
        return root            
    return dfs(root)

But the following works:

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    def dfs(root):
        if not root:
            return None
        elif root.val < low:            # OR if root.val < low
            root = dfs(root.right)
        elif root.val > high:
            root = dfs(root.left)  
        else:
            root.left = dfs(root.left)
            root.right = dfs(root.right)
        return root            
    return dfs(root)

I am confused why the first doesn't work. I think the ifs are mutually exclusive, so it will reach the return in the first if or through any of the last three to the end.

Refactoring Nested If-Else Statements

could you help me give me some ideas how to refactor the following nested if-statement?

function priceCalculator(age, height) {

  if (age == "under 18") {
      if (height <= 1.5) {
          price = 6.18;
      } else if (height > 1.5 && height <= 1.8) {
          price = 5.59;
      } else if (height > 1.8) {
          price = 5.37;
      }
  } else if (age == "18-50") {
      if (height <= 1.5) {
          price = 7.38;
      } else if (height > 1.5 && height <= 1.8) {
          price = 6.19;
      } else if (height > 1.8) {
          price = 7.22;
      }
  } else if (age == "over 50") {
      if (height <= 1.5) {
          price = 8.48;
      } else if (height > 1.5 && height <= 1.8) {
          price = 8.53;
      } else if (height > 1.8) {
          price = 8.17;
      }
  }

  console.log(price);
}

It gets pretty ugly, once I introduce even more age and height categories. Is there a possibility to kind of shorten the code and make it prettier? Switch statements are problematic, because the second variable is an integer.

Why am I getting garbage values?

I'm trying to make some basic number incrementation but I'm getting some weird garbage values. (this works in C# but not in C). Could someone tell me why this is not working?

while (1)
{
      int command = 0;

      printf ("Action: ");
      scanf ("%d", &command);


      int countX, countY, countZ = 0;
      if (command == 1)
    {
      countX++;
    }
      if (command == 2)
    {
      countY++;
    }
      if (command == 3)
    {
      countZ++;
    }
      if (command == 0)
    {
      printf ("x: %d, y: %d, z: %d", countX, countY, countZ);
    }

}

I'm trying to reduce the cell value in the column by 1 with duplicate and if condition

I'm working on an inventory replenishment tool. If column E says PICK and the barcode in Column A is Duplicate then the cell value (Warehouse stock) should reduce by 1 from Column C, else the same WH stock value in Column C. Please find the attached Screen shot:

enter image description here

Formula i tried, IF(E3="PICK",IF(COUNTIF($A$3:$A$9,$A3)>1,C3-ROW(A1),C3))

How to reference another value that meets certain conditions which can then be used in a calculation

I have to two data frames:

Test

Group.1   x
   1     25.5
   2     51
   3     51.5
   4     50
   5     51.5
   6     60 
   ...
   53    35.5

Calendar

Week   Hours  HourSpent
  1     8.5
  1     8.5
  1      0
  2     8.5
  2     8.5
  2     8.5
  2     8.5
  2     8.5
  2     6.5
  2     8.5
  3     7.0
  3     7.0
  3     8.2
  ...

What I am trying to do is to populate the 'HourSpent' column in the Calendar df by doing the following calculation: (('Hours' / 'HourSpent') * 0.79)

I want to be able to go through each line in the Calendar df and divide that rows 'Hours' value with the matching 'HourSpent' value. The 'HoursSpent' value can be decided from the 'Test' df...so if the value in the 'Week' column from the Calendar df matches any value in 'Group.1' column of the 'Test' df then I want the corresponding value in the 'x' column of the 'Test' df to be the 'HourSpent' value.

E.g.

Row 1 in the Calendar df will be 8.5 / 25.5 * 0.79...which will apply to the top 3 rows as the week number is 1. Then when we get to row 4 the calculation would change to 8.5/ 51 * 0.79 and so on...etc

Desired Output - Calendar df

Week   Hours  HourSpent
  1     8.5     0.2633
  1     8.5     0.2633
  1      0        0
  2     8.5     0.1317
  2     8.5     0.1317
  2     8.5     0.1317
  2     8.5     0.1317
  2     8.5     0.1317
  2     6.5     0.1007
  2     8.5     0.1317
  3     7.0     0.1074
  ...

Code Tried

for (i in 1:nrow(Calendar)){

 Calendar$'HourSpent' <- ifelse(Calendar$Week == Test$Group.1, 
 (Calendar$Hours/Test$x)*0.79, 
 0)

}

The problem is this only seems to work for one row then everything else is 0...is there a better solution to this issue?

Many thanks

Chaining assignment in an if condition

Hi just wondering if you use a chained assigment in an if condition, would the leftmost variable be used to check the if condition

like a=b=c , its a thats ultimetly checked and not b or c

#include <stdio.h>

 int main()
 {
  int a, b, c =0;
 
  // does this reduce to a == 100 and the variables b or c are not checked if they are == to 100 but simply assigned the value of 100 ? 
  if( (a = b = c = 100) == 100)
     printf( "a is 100 \n");

   
 return 0;
}

Select from List of cards (strings) at random, but allow ignoring of previously chosen cards (strings) next time around?

I am trying to make a card game in android studio. I had it working completely fine before, any time I click a "roll" button in android studio it would loop through the list of cards and show them one by one. Only problem was it would repeat the output of cards

I felt making another list of selected cards via their "random" index would be the best way of doing this. However, now my code is very messy and does not handle the logic correctly.

    public String shuffleCards() {

        // Strings to return to the user
        String errorString = "ERROR: NO CARDS IN DECK" + '\n' + '\n' + "Go to 'EDIT CARDS' to add game cards to the current deck.";
        String completedString = "All cards in deck have been shown." + '\n' + '\n' + "Go back to the MAIN MENU to restart";


        List<String> allCards = this.getRandomCards();
        List<Integer> cardsDone = new ArrayList<>();

        int randIndex = new Random().nextInt(allCards.size());


        if (!allCards.isEmpty()) {
            //generate rand int [0, size]
            String randString = allCards.get(randIndex); //get random string
            //check for all cards that have been done.
            if (!cardsDone.contains(randIndex)) {
                cardsDone.add(randIndex);
                return randString;
            } else if (cardsDone.size() == allCards.size()) {
                return completedString;
                }
            else {
            }
            return randString;
        }
        return errorString;
    }
}

Can anyone help fix this code so it handles the logic correctly, as well as give me any tips to make this not as messy (I feel like it can be much simpler).

Thanks :)

Why If statement does not work with tkinter

I have created two py files, one holds login GUI, the other contains the whole bunch of functions and windows which I call terminal.

I'm trying to do the following: To make a login GUI window appear first and after inputting correct credentials to have open/running the terminal (second GUI window).

However no matter what I tried I do not get the second window open after credentials. I have tried using if statement however failed, the only thing on my mind is re-doing the whole code in one file and that doesnt seems like a good idea to have that much code in one file

Login GUI:

import tkinter as tk


# from tkinter_practice import *


def username(txt_username):
    if txt_username == "1":
        return True


def password(txt_password):
    if txt_password == "2":
        return True


def ok_button(gotten_username, gotten_password):
    if username(gotten_username) and password(gotten_password):
        print('login success')
        return True
    else:
        print('Incorrect Username or Password')
        return False


root2 = tk.Tk()
root2.title('Login window')
root2.geometry('400x200-550-400')
root2.columnconfigure(0, weight=1)
root2.columnconfigure(1, weight=1)
root2.columnconfigure(2, weight=1)
root2.rowconfigure(0, weight=1)
root2.rowconfigure(1, weight=1)
root2.rowconfigure(2, weight=1)

lbl_username = tk.Label(root2, text='Username')
lbl_username.grid(row=1, column=0)

ent_username = tk.Entry(root2)
ent_username.grid(row=1, column=1)

lbl_password = tk.Label(root2, text='Password')
lbl_password.grid(row=2, column=0, sticky='n')

ent_password = tk.Entry(root2)
ent_password.grid(row=2, column=1, sticky='n')


btn_ok = tk.Button(root2, text='LOGIN', command=lambda: ok_button(ent_username.get(), ent_password.get()), padx=10,
                   pady=5)
btn_ok.grid(row=3, column=1, sticky='nw', )

btn_cancel = tk.Button(root2, text='Cancel', command=quit, padx=10, pady=5)
btn_cancel.grid(row=3, column=1, sticky='n')

root2.mainloop()

and second part of code which contains second window/GUI which I would to open after first one's credentials are True:

import tkinter as tk
from tkinter import *
# from PIL import ImageTk, Image
import webbrowser
import pytz
import datetime
import login_GUI
# from tkinter import messagebox

# Main frame/window

if login_GUI.ok_button(login_GUI.ent_username.get, login_GUI.ent_password.get):

    root = tk.Tk()
    root.title("Main terminal")
    root.geometry("800x600-50-50")
    # Here I get the icon for the left corner of bar on top
    root.iconbitmap(icon)
    new = 1
    url = "https://www.youtube.com"

    root.columnconfigure(0, weight=1)
    root.columnconfigure(1, weight=1)
    root.columnconfigure(2, weight=1)




    root.mainloop()

How could I code if-statement after switch-statement in C++?

I am writing a code to calculate the toll fee literally for my class assignment in C++. The code is shown below. My problem is that I only want to perform the calculation, ie, toll = vRate * distance if it meets any of the cases. If the input is invalid, by default, it will show "Invalid input" only and no calculation is required. For instance:

if !(default), 
    toll = vRate * distance;
    cout << "RM" <<toll << endl; 

But, I understand this would not work. Hence, any ideas in amending the code to make it clear cut and straightforward? Thank you in advanced.

#include <iostream>
using namespace std;
int main()
{
    char vCode;
    double vRate; // Toll rate for the vehicle
    double toll, distance;
    
    cout << "Enter vehicle code: " << endl;
    cin >> vCode; // C-Car, B-Bus, T-Truck, M-Motorbike
    cout << "Enter the distance travelled by the vehicle (in km): " << endl;
    cin >> distance;
    
    switch(vCode)
    {
        case 'C' : cout << "vRate = 50%" << endl;
        vRate = 0.5;
        break;
        case 'B' : cout << "vRate = 85%" << endl;
        vRate = 0.85;
        break;
        case 'T' : cout << "vRate = 100%" << endl;
        vRate = 1.00;
        break;
        case 'M' : cout << "Free toll" << endl;
        vRate = 0.00;
        break;
        default  : cout << "Invalid Vehicle Code" << endl;
    }
    toll = vRate * distance;
    cout << "RM" <<toll << endl; 
    return 0;
}

How can I continue the if from where i last picked of

I've been working on chat bot lately which questions people about their name and age and describes their generation using if like this:

     if (age >= 57 && age <= 75) {
                System.out.println("Oh so you're a baby boomer)");
                String boomer = in.nextLine();

but when I try to continue the questions it cuts off.




 System.out.println("Hello my name is ADA what's your name? ");
        String Name = in.nextLine();
        System.out.println("What a delightful name, How old are you dear?");
        int age = in.nextInt();
   if (age<=18){
              System.out.println("Oh your younger than I excpected come back when you are older dear)  ");   
              
        if (age >= 57 && age <= 75) {
            System.out.println("Oh so your a baby boomer)");
            String baby = in.nextLine();
            
            if (age>=42 && age <=56){
                System.out.println("oh so your from Generation x");
            String x = in.nextLine();
            
            if (age>=21 && age <=41){
            System.out.println("Oh so your from Generation Y");
            String Y= in.nextLine();
           
    
            


           

I dont know what i did wrong so I did place a scanner so that it would go to the next question but it seems that it stays where it is.

calling enum statement to change state through if statement but state not changing

I am trying to change the state of a enum through bool using if statement. Then what it will do is make a switch statement work. There are three scripts 1. LoadEveryThing sript with the switch statement 2. shop script with the bool 3. SaveEverthing script where the enum exists, I made a variable of type of the enum and then changing its state according to the state of the bool. Then on the basis of the enum state the switch statement works. Here are the scripts.

shop script:

public class shop : MonoBehaviour
{
    
      public TMPro.TextMeshProUGUI scoreText;
      public GameObject Item1;
      public GameObject Item2;
      public GameObject Item3;
      public GameObject Item4;
      public TMPro.TextMeshProUGUI notenough;
      public TMPro.TextMeshProUGUI notenough1;
      public TMPro.TextMeshProUGUI notenough2;
      public TMPro.TextMeshProUGUI notenough3;
      public GameObject buyButton;
      public GameObject buyButton1;
      public GameObject buyButton2;
      public GameObject buyButton3;
      public GameObject equipButton;
      public GameObject equipButton1;
      public GameObject equipButton2;
      public GameObject equipButton3;
      public float sec = 14f;
      public static bool isSold;
      public static bool isSold1;
      public static bool isSold2;
      public static bool isSold3;
      public ButtonState state;
      public ButtonState1 state1;
      public ButtonState2 state2;
      public ButtonState3 state3;
 
      private Dictionary<GameObject, float> ItemPrices;
  
  
    void Start ()
    {
        scoreText.text = "Score : " + ((int)PlayerPrefs.GetFloat ("Highscore")).ToString();
  
      ItemPrices = new Dictionary<GameObject, float>()
      {
       { Item1, 50f },
       { Item2, 80f },
       {Item3, 3500f},
       { Item4, 5000f },
       };
       notenough.enabled = false;
       notenough1.enabled = false;
       notenough2.enabled = false;
       notenough3.enabled = false;
       
    }
  
    public void PurchaseItem(GameObject Item)
   {
       foreach(KeyValuePair<GameObject, float> item in ItemPrices)
       {
            if (item.Key == Item)
            {
              
             float price = item.Value;
             float val = PlayerPrefs.GetFloat ("Highscore"); 
             if(val >= price)
             {
             val -= item.Value;
              PlayerPrefs.SetFloat("Highscore", val);
              scoreText.text = "Score : " + ((int)PlayerPrefs.GetFloat ("Highscore")).ToString();
                  buyButton.SetActive(false);
                  equipButton.SetActive(true);
                  isSold = true;
                  state = ButtonState.Equip;
                 // Take away the cost of the item from the player's currency
                 //PlayerPrefs.GetFloat ("Highscore") -= item.Value;
             }
             else
             {
                 Debug.Log("not enough money");
                  notenough.enabled = true;
                  notenough1.enabled = true;
                  notenough2.enabled = true;
                  notenough3.enabled = true;
                 Invoke("noen", 2);
                 state = ButtonState.Buy;
             }
            }     
       }
   }

    public void noen()
  {
    notenough.enabled = false;
    notenough1.enabled = false;
    notenough2.enabled = false;
    notenough3.enabled = false;
   
  }

}
 

isSold is the bool here.

SaveEverything script:

using UnityEngine;
 using System.IO;
 
 public class SaveEverything : MonoBehaviour
 {
     // What script to save
     public LoadEveryThing MyButton;
     
 
     public void Save()
     {
         // What data to save
         string saveData = MyButton.state.ToString();
        
 
         // Where the data is stored
         string path = Application.persistentDataPath + "\\buttonstate.save";
 
         
          // Writes data to file
          if (File.Exists(path))
          {
             File.WriteAllText(path, saveData/*, saveData1, saveData2, saveData3, 5*/);
          }
          else
          {
             File.Create(path).Close();
             File.WriteAllText(path, saveData/*, saveData1, saveData2, saveData3, 5*/);
          }
    }   
 }
 
  public enum  ButtonState
 {
     Buy,
     Equip
 }

ButtonState is the enum.

LoadEveryThing script:

using UnityEngine;
 using UnityEngine.UI;
 using System.IO;
 using System;
 using TMPro;
 
 public class LoadEveryThing : MonoBehaviour
 {
     // Types of buttons
     public GameObject BuyButton;
    /* public GameObject BuyButton1;
     public GameObject BuyButton2;
     public GameObject BuyButton3;*/
    public GameObject EquipButton;
    /*public GameObject EquipButton1;
     public GameObject EquipButton2;
     public GameObject EquipButton3;*/
 
     public ButtonState state;
 
      void Start()
     {
         // What file to read save data from
         string path = Application.persistentDataPath + "\\buttonstate.save";
 
         // Get data and set state to that data
         if (File.Exists(path))
         {
             string data = File.ReadAllText(path);
             
             if (Enum.TryParse(data, out ButtonState State))
                 state = State;
         }
 
         // Copy button properties onto this button
         // depending on the state
         switch (state)
         {
             case ButtonState.Buy:
                 SetButton(BuyButton);
                 break;
             case ButtonState.Equip:
                 SetButton(EquipButton);
                 break;


         }

          
         if(shop.isSold == true)
         {
             state = ButtonState.Equip;
             Debug.Log("working");
         }
         else if(shop.isSold == false)
         {
             state = ButtonState.Buy;
             Debug.Log(" buy working");
         }

     }

     void Update()
     {
     }
 
     void SetButton(GameObject button)
     {
         // Set on-click method of button
         Button myButton = GetComponent<Button>();
         Button targetButton = button.GetComponent<Button>();
 
         myButton.onClick = targetButton.onClick;
 
         // Set text of button
         TMPro.TextMeshProUGUI myText = GetComponentInChildren<TMPro.TextMeshProUGUI>();
         TMPro.TextMeshProUGUI targetText = button.GetComponentInChildren<TMPro.TextMeshProUGUI>();
 
         myText.text = targetText.text;
     }

      /*public static void SetEquipButton()
     {
      
     }

     public static void SetBuyButton()
     {
         
     }*/
 }


So now I wrote a variable of type ButtonState named state. Then in a if statement I checked whether the isSold bool is true or false if it is true change the state = ButtonState.Equip else if it is false change the ButtonState to buy. After all this stuff the switch statement works according to it. If ButtonState is buy then change the button to buybutton else changes it to equipbutton. But the problem is the enum state is not changing and I think the problem can be in the if statement or I don't know. By the way I am doing this stuff in c# using Unity Game Engine, That's all. If anything is unclear let me know, pls help. Thanks,

What does fork() == 0 returns?

I have 2 programs

The first program would call fork() and assign it to p. When p == 0, it implies child process.

// The first program
p = fork();
if (p == 0)
{
    // child process
}
else
{
    // parent process or exception
}

But what if we just call fork() == 0? I would think fork() return non-zero from it's docs. Hence the condition is never executed.

// The second program
if (fork() == 0)
{
    // Would this ever be reached?
    printf("A\n");
}

printf("B\n");

Please don't downvote this, or at least explain why... I tried this code before asking, "A" is never printed and there's not enough documentation about how fork() works

I want to input a variable and print the numbers descending till this variable becomes 1 is there a python loop condition [closed]

Make a variable called num, which is an input that accepts a specific number from the person, make sure that the number is its type and that it is greater than 0, and if it is not greater than 0, print a message stating that after entering the number, print the number smaller than it directly, the smallest then the smallest until it reaches the number 1 must not Printing the number itself and not printing the number 0 If the numbers contain the number 6, do not print it from among the numbers After finishing the numbers, print a message stating that all numbers have been printed successfully with writing how many numbers have been printed

Optimise processing of for loop?

I have this basic dataframe:

     dur    type    src    dst
0     0     new     543     1
1     0     new     21      1
2     1     old     4828    2
3     0     new     321     1
...
(total 450000 rows)

My aim is to replace the values in src with either 0, 1 or 2 depending on the values. I created a for loop/if else below:

for i in df['src']:
    if i <= 1000:
        df['src'].replace(to_replace = [i], value = [1], inplace = True)
    elif i <= 2500:
        df['src'].replace(to_replace = [i], value = [2], inplace = True)
    elif i <= 5000:
        df['src'].replace(to_replace = [i], value = [3], inplace = True)
    else:
        print('End!')

The above works as intended, but it is awfully slow trying to replace the entire dataframe with 450000 rows (it is taking more than 30 minutes to do this!).

Is there a more Pythonic way to speed up this algorithm?

how to write conditions in R

I want to write a condition in R from : at first, I wrote this code for generating a random integer between 0 and 4: effort <-sample(0:4, 1000,replace= T) then I want to generate a conditional format : #(if effort=0 then return 4500,if effort=1 then return 4300, if effort=2 then return 3700, if effort=3 then return 4700, if effort=4 then return 5300)

so I wrote these code:

bso<- function(effort){
if(effort==0){return(4500)}
if(effort==1){return(4300)}
if(effort==2){return(3700)}
if(effort==3){return(4700)}
if(effort==4){return(5300)}}

#but it doesn't work! I don't know how can I fix it!

Why is my els estatment giving me a syntax error Python

The else statement before the exception keeps giving me a syntax error I have tried deleting all the spaces and making sure I am using the same number of tabs to get the indentation, am I missing something simple

from pymongo import MongoClient from bson.objectid import ObjectId

class AnimalShelter(object): """crud operations for Animal collection in MongoDB"""

def __init__(self, username, password):
    # Initializing the MongoCLient. this helps to 
    #acess the MongoDB databse and collections.
    self.client = MongoCLient('mongodb://%s:%s@localhost:27017' % (username, password))
    self.database = self.client['project']
    
    # Create method to implement C in CRUD
    def create(self, data):
        if data is not None:
            if data:
                self.database.animals.insert(data) # data should be dictionary
                return True
            else:
                return False
        else:
            raise Exception("Nothing to save, because data parameter is empty")
            
    # Create method to implement R in CRUD
    def read(self, search):
        if search is not None: # if search is not None it will return all the rows that match
            if search:
                searchResults = self.database.animals.find(search)
                return searchResults
        else:
            execption = "Nothing to search, because search parameter is empty"
            return exception

samedi 30 janvier 2021

Passing string from a function into another function

this program functioned as taking the average of each 3 test and categorize it to "low", "medium", "high". the "input" function is used to collect data from a user . "deter" function was to calculate the average and to categorize it. "display" function was to show all the results. In this program I can pass float type data but why I can't pass with string type data. Can someone help me pls?.

#include <stdio.h>
void input ( float*, float*, float* );
void deter (float , float ,float ,float*,char* cate);
void display (float, float, float, float, char);


int main ()
{
    float t1_in, t2_in, t3_in, average;
    char category[10];

    input (&t1_in,&t2_in,&t3_in);
    deter(t1_in,t2_in,t3_in,&average,&category);
    display(t1_in, t2_in, t3_in, average, category);
}

void input ( float* t1, float* t2, float* t3)
{
    printf ("Enter Test 1 >> ");
    scanf ("%f",t1);

    printf ("Enter Test 2 >> ");
    scanf ("%f",t2);

    printf ("Enter Test 3 >> ");
    scanf ("%f",t3);
}


void deter (float tt1_det, float tt2_det,float tt3_det,float* avg,char* cate)
{
    *avg = (tt1_det+tt2_det+tt3_det)/3.0;

    if(*avg<2.0)
    {
        *cate="slow";
    }
    else if(*avg>=2.0 && *avg<=4.0)
    {
        *cate="Medium";
    }
    else if( *avg>4.0)
    {
        *cate="High";
    }
}

void display (float tt1, float tt2,float tt3,float avrg,char ct)
{
    printf ("\nTest 1 is %.2f ",tt1);
    printf ("\nTest 2 is %.2f ",tt2);
    printf ("\nTest 3 is %.2f ",tt3);
    printf ("\nAverage >> %.2f",avrg);
    printf("\nCategory >> %10s",ct);
}

here is my out put

Enter Test 1 >> 1

Enter Test 2 >> 2

Enter Test 3 >> 3

Test 1 is 1.00

Test 2 is 2.00

Test 3 is 3.00

Average >> 2.00

Process returned -1073741819 (0xC0000005) execution time : 1.478 s

Press any key to continue.

how to combine multiple if statements in on line python3

Hi i'm new to python and programming, How would I go about combining these:

if "Web" in source:
    source = "WEB"
if ((source == "Blu-ray") and (other == "Remux") and (reso == "1080p")):
    reso = "BD Remux"
if "DVD" in name:
    reso = "DVD Remux"
if ((source == "Ultra HD Blu-ray") and (other == "Remux") and (reso == "2160p")):
    reso = "UHD Remux"
if source == "Ultra HD Blu-ray":
    source = "Blu-ray"

Nothing appears after reading user input on fortran

For some reason I don't have anything appearing after the user inputs the limits for the upper and lower limit of my table. What I want to do is make it so that if the user has an upper limit or lower limit that exceeds the bounds of -10,200 the user has to re-input the limits. If it does not exceed the limit, then it will reveal a table/matrix showing the numbers from the upper to lower limit in addition to two columns, one that converts it to Fahrenheit and another converting it to kelvin.

My do loop functions normally on its own, but after adding in the if statements nothing appears after the user inputs the upper and lower limits.. what am i doing wrong ?

program Lab03b
implicit none
integer::i,k,l
real, dimension(22)::matrix
Write (*,*) 'Please enter the upper and lower limit of your table in centigrade where the 
lower&
& and the upper limit is within -10 to 200. (separate with comma)'
Read (*,*) k,l
if (k>=abs(-10)) then
if (l<=abs(200)) then
    write (*,*) '  Centigrade', '       Farenheit', '        Kelvin'
    do i=k,l
            matrix(i)=i
            print*, i,32.0+1.8*i,i+273.15
    end do
    print*, 'your table has',k+1,'rows and 3 columns'
else 
print*, 'Your lower limit is less than -10 or your upper limit is greater than 200, please try again' 
end if
end if
  end program Lab03b

Java last IF is not being run at all [duplicate]

I'm trying to add jbuttons via some if statements. For some reason , the last ifs are not working . For all 3 of the last ifs ( RJ1214 , PS1212 and MP1213 ) they don't even enter the if statement . If i try moving RJ1214 up on the list it does show up but the last IF still does not work . Any help please?

        if(numePiesa=="MP")
    {
        if((scanFile("S:\\Files\\MP1009.txt"))>0)
        {
            this.setVisible(true);
            JButton MP1009=new JButton("10.02 ora 09:00");
            this.add(MP1009);
        }
        if((scanFile("S:\\Files\\MP1013.txt"))>0)
        {
            this.setVisible(true);
             JButton MP1013=new JButton("10.02 ora 13:00");
             this.add(MP1013);
        }
        
        if((scanFile("S:\\Files\\MP1109.txt"))>0)
        {
            this.setVisible(true);
            JButton MP1109=new JButton("11.02 ora 09:00");
            this.add(MP1109);
        }
        if((scanFile("S:\\Files\\MP1113.txt"))>0)
        {
            this.setVisible(true);
             JButton MP1113=new JButton("11.02 ora 13:00");
             this.add(MP1113);
        }       
        if((scanFile("S:\\Files\\MP1209.txt"))>0)
        {
            this.setVisible(true);
             JButton MP1209=new JButton("12.02 ora 09:00");
             this.add(MP1209);
        }
        if((scanFile("S:\\Files\\MP1213.txt"))>0)
        {
            this.setVisible(true);
            JButton MP1213=new JButton("12.02 ora 13:00");
            this.add(MP1213);
        }
        
        
        
        
    }
    else if(numePiesa=="PS")
    {
        if((scanFile("S:\\Files\\PS1010.txt"))>0)
        {
            this.setVisible(true);
            JButton PS1010=new JButton("10.02 ora 10:00");
            this.add(PS1010);
        }
        if((scanFile("S:\\Files\\PS1012.txt"))>0)
        {
            this.setVisible(true);
             JButton PS1012=new JButton("10.02 ora 12:00");
             this.add(PS1012);
            
        }
        if((scanFile("S:\\Files\\PS1110.txt"))>0)
        {
            this.setVisible(true);
             JButton PS1110=new JButton("11.02 ora 10:00");
             this.add(PS1110);
            
        }
        if((scanFile("S:\\Files\\PS1112.txt"))>0)
        {
            this.setVisible(true);
             JButton PS1112=new JButton("11.02 ora 12:00");
             this.add(PS1112);
            
        }
        if((scanFile("S:\\Files\\PS1210.txt"))>0)
        {
            this.setVisible(true);
             JButton PS1210=new JButton("12.02 ora 10:00");
             this.add(PS1210);
            
        }
        if((scanFile("S:\\Files\\PS1212.txt"))>0)
        {
            this.setVisible(true);
            JButton PS1212=new JButton("12.02 ora 12:00");
            this.add(PS1212);
            
        }
        
    }
    else if(numePiesa=="RJ")
    {
        if((scanFile("S:\\Files\\RJ1008.txt"))>0)
        {
            this.setVisible(true);
             JButton RJ1008=new JButton("10.02 ora 08:00");
             this.add(RJ1008);
            
        }
        if((scanFile("S:\\Files\\RJ1014.txt"))>0)
        {
            this.setVisible(true);
            JButton RJ1014=new JButton("10.02 ora 14:00");
            this.add(RJ1014);
            
        }
        if((scanFile("S:\\Files\\RJ1108.txt"))>0)
        {
            this.setVisible(true);
            JButton RJ1108=new JButton("11.02 ora 08:00");
            this.add(RJ1108);
            
        }
        if((scanFile("S:\\Files\\RJ1114.txt"))>0)
        {
            this.setVisible(true);
            JButton RJ1114=new JButton("11.02 ora 14:00");
            this.add(RJ1114);
            
        }
        if((scanFile("S:\\Files\\RJ1208.txt"))>0)
        {
            this.setVisible(true);
             JButton RJ1208=new JButton("12.02 ora 08:00");
             this.add(RJ1208);
            
        }
        if((scanFile("S:\\Files\\RJ1214.txt"))>0)
        {
            this.setVisible(true);
            JButton RJ1214=new JButton("12.02 ora 14:00");
            this.add(RJ1214);
        }
        
    }
     public static int scanFile(String fileName) throws FileNotFoundException {
    Scanner scanner = new Scanner(new File(fileName));
    int freeSeat=0;
    while(scanner.hasNextLine()) {
        String line=scanner.nextLine();
        int a = Integer.valueOf(line);
        if(a==0)
        {
            freeSeat+=1;
        }
        
    }
    return freeSeat;
    }

Sorry for the long code . For example : RJ1214 , PS1212 and MP1213 buttons are NOT added even if they are true . I know the code looks like trash and all that .

arrays and if statements and accessing each index position

I am not sure I understand if statements and how they access arrays as well as I would like. I have this array:

If I var_dump($count) I get:

array(1) { [0]=> object(stdClass)#2472 (1) { ["nmbr_tables"]=> string(1) "4" } } array(1) { [0]=> object(stdClass)#2445 (1) { ["nmbr_tables"]=> string(1) "0" } } array(1) { [0]=> object(stdClass)#2452 (1) { ["nmbr_tables"]=> string(1) "0" } }

So I write

if($count >= 1){echo "hello";} else {echo "no";}; 

my expected output would be:

hello
no
no

Since the first index position has the nmbr "4" and then the next two have the nmbr "0"

Instead what I am getting is:

hellohellohello

Seeming to indicate that it is only paying attention to the first index position.

So then I thought maybe:

   foreach($count  as $val){
   if($count >= 2){echo "hello";} else {echo "no";};
   };

No difference.

Why does RenderUI randomly kick an error from some selection of Selectinput?

I am trying to render some dynamic text in the ui.r based on a user selection from selectinput and it works for most names but there are one or two in the list that kick the error:

Warning: Error in FUN: argument is not a character vector
  99: lapply
  98: paste8
  97: HTML
  96: renderUI [/Users/spencepurnell/Documents/Shiny_apps/Ray_Lewis_Experiment/server.R#933]
  95: func
  82: origRenderFunc
  81: output$combine_compare_color
   1: runApp

Given that error message I suspect it has something to do with parse of the characters but again it works for other names in the list but two names specifically kick the error and it cascades.

Here is how I set up the ui:

tabItem("profile_tab",
                           fluidRow(
                             box(
                               selectInput("profile_player_selection", 
                                           "Select Player to Profile", 
                                           choices = as.list(ed_profile_names), 
                                           selected = "Anthony Nelson")
                             ),
                             box(
                               selectInput("player_profile_comparison",
                                           "Select Player to Compare",
                                           choices =  as.list(ed_profile_names_compare),
                                           selected = "Nick Bosa"))
                           ),
                           fluidRow(
                             box(title = uiOutput("combine_status_color"), 
                                 width = 6,
                                 collapsible = T,
                                 tableOutput("combine_page_table"),
                                 ),
                             box(title = uiOutput("combine_compare_color"),
                                 width = 6,
                                 collapsible = T,
                                 tableOutput("combine_page_comparison")
                                 )
                              )
                           ) 

And here is the server.r:

ed_color <- reactive({
      data_ed() %>% 
        dplyr::select(
          Name,
          "Height (in)",
          "Weight (lbs)",
          "40 Yard",
          "Bench Press",
          "Vert Leap (in)",
          "Broad Jump (in)",
          Shuttle,
          "Three Cone",
          "Edge Combine Score"
        ) %>%
        dplyr::filter(Name == input$profile_player_selection) 
        
      
    })
#> Error in reactive({: could not find function "reactive"
    
  output$combine_status_color <- renderUI({
    
    if(ed_color()[,"Edge Combine Score"] > 90 ) {
      a <- paste("<span style=color:#2DBF29>",  "ELITE Combine Score")
    } 
    else if(ed_color()[,"Edge Combine Score"] < 90 & ed_color()[,"Edge Combine Score"] > 80 ) {
      a <- paste("<span style=color:#1955CE>",  "GOOD Combine Score")
    } 
    else if(ed_color()[,"Edge Combine Score"] < 80 & ed_color()[,"Edge Combine Score"] > 70 ) {
      a <- paste("<span style=color:#FA8B05>",  "STANDARD Combine Score")
    } 
    else if(ed_color()[,"Edge Combine Score"] < 70 & ed_color()[,"Edge Combine Score"] > 60 ) {
      a <- paste("<span style=color:#FA8B05>", "AVERAGE Combine Score")
    }
    else if(ed_color()[,"Edge Combine Score"] < 60 & ed_color()[,"Edge Combine Score"] > 50 ) {
      a <- paste("<span style=color:#FA8B05>",  "POOR Combine Score")
    }
    else if(ed_color()[,"Edge Combine Score"] < 50 & ed_color()[,"Edge Combine Score"] > 40 ) {
      a <- paste("<span style=color:#FA8B05>", "WORST Combine Score")
    }
    
     HTML(a)
    
  })

You can (hopefully) see that I am trying to filter a large dataframe by the same set of variables but change on the userinput of name. The RenderUI and if statements are meant to read a certain score in the dataframe and deliver the corresponding text. Again, most names work but only a few kick the error.

Write a Java program to check date is true or false (3 integers: dd mm yy) [closed]

Write a program that takes three integers as input from the user: day, month and year. It's necessary to determine whether the date exists. The program takes into account leap days and considers the AD years to be correct.

Example: input - 35 13 2020 output - false

input - 29 2 2020 output - true

It is recommended to use switch/ else, else if

Input Logic Not Resolving As Anticipated

I'm trying to figure out my code isn't working.

I'm trying to input an age, and assign a color to it based on it like I've show below, but my input always comes out green if its above 12.

Console.WriteLine("input your age: ");
int age = int.Parse(Console.ReadLine());

if (age<= 12)
{
    Console.WriteLine("color: white");
}
else if (age>= 13)
{
    Console.WriteLine("color: green");
}
else if (age >= 19)
{
    Console.WriteLine("color: red");
}
else if (age >= 26)
{
    Console.WriteLine("color: blue");
}
else
{
    Console.WriteLine("invalid age");
}

Console.ReadLine();

creating a procedure in mysql to check if a record exist and update if it does exist

ITS GIVING ME THIS ERROR NEAR UPDATE QUERY I REALLY DONT KNOW WHY??? HELP

CREATE PROCEDURE insertandupdate()
BEGIN
    if exists (SELECT * from roleprivillges as rp WHERE (rp.roleID=1 AND rp.priviligesID=1) LIMIT 1) then
    BEGIN
       UPDATE `roleprivillges` SET `IsActive`=0 WHERE roleID=1 AND priviligesID=1;                                            
    END;
    else
    BEGIN
        INSERT INTO roleprivillges('roleID','priviligesID','IsActive') VALUES('1','1','1');
    END;    
    end if;
END 

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 5

stand-alone If statement in function being iterated twice

I'm currently writing a function for a music quiz, the quiz involves the user guessing the song name from the artist and the first letter of each word in the name. after 2 attempts, the users username and score are appended to a text file and the users score is outputted - the code in question is:

if x == attempts:
            print("You scored:  ", score)
            g.write(username)
            g.write(str(score))
            g.write(',')
            print(leaderboard)

The problem arises when i compile and run the code, as this if statement is executed 2 times before the program is finished, an example being:

You scored:   6
['kaylem3', 'kaylem3', 'b6', 'b6', 'c3', 'c3', 'e6', 'e6', '']
You scored:   6
['kaylem3', 'kaylem3', 'b6', 'b6', 'c3', 'c3', 'e6', 'e6', '']

I've tried changing it to a while loop and I've tried changing it to an elif branch but nothing seems to fix this minor issue.

the function in it's entirety at the moment is:

def userguess(song, attempts):
    global x
    while x < attempts:
        print(song.firstletters, song.artist)
        guess = str(input("Enter the songs name: "))
        if guess == song.name:
            global score
            score += 3
            x += 1
            print("You're correct")
            choose_song()
        elif guess != song.name:
            x += 1
            print("You're wrong")
            choose_song()
    while not x < attempts:
        print("You scored:  ", score)
        g.write(username)
        g.write(str(score))
        g.write(',')
        print(leaderboard)
        break

Thanks for any help!

Python: if not true function is not running as it should [duplicate]

If the user doesn't type in multiplication, addition, ect, then a string should be printed. However, if one of these words is typed it still prints this string. I've just started with python; sorry that it's such a basic question!

print ("Multiplication, Addition, Subtraction or Division?")
type = str(input("Your choice:"))
if type != "multiplication" or "addition" or "subtraction" or "division":
    print("YOU DID NOT ENTER ONE OF THE ABOVE OPTIONS.\nTRY AGAIN!")
num1 = int(input("Enter your 1st number:"))

Control flow syntax

if(result[3]<=0.05){
    print("result of t-test is significant")
    print("Noble price on it's way!")
}else{
    print("result of t-test is NOT significant")
    print("back to the Lab")
}

Please is this code correct? I receive error message each time I run it.

React: state's boolean flag doesn't update fast enough

I keep boolean flag named validationPassed in a state which I use in if statement. If it's true, I allow axios request to happen. Before that if statement I call doValidation() which has a lot of if statements. If one of them fail, I setState of that boolean flag to false. In setState() I put console.log callback and it seems boolean flag is successfuly set to false but not immediately because if(this.state.validationPassed) passes when it shouldn't. I'm aware that React state is asynchronous. Tried to use prevState argument to toggle boolean's value but it didn't work. How do I make this work? Maybe there's another way to do validation without boolean flags?

    this.state = {

        validationPassed: true
    }
}

   this.doValidation(usernameFromUser, passwordFromUser)

   if(this.state.validationPassed){

    // axios call
   }

}

doValidation = (username, password) => {

    if(username.trim().length === 0){

          this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(password.trim().length === 0){

          this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    } 

    if(username.trim().length < 8){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(username.trim().length > 20){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
    }

    if(password.trim().length < 8){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});
        } 

    if(new RegExp("^(?!(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,}))").test(password)){

        this.setState( {
            validationPassed: false }, () => {console.log(this.state.validationPassed)});  
    }
}

IFERROR with Index/Match excel formula not working in VBA

I am having an issue for excel formula index/match with IFERROR and it is working fine in excel when I am running it manually however after writing into Macro it is not working. this formula is created for doing matching and look-ups at multiple conditions and give the output result.

I am getting following error while running macro Run-time error'1004': Unable to set the FormulaArray property of the Range class

Can someone please help to suggest

Sub Indexmatch()
'
' Macro15 Macro
'

  '
  Selection.FormulaArray = _
    "=IFERROR(INDEX('[NAL for Macro.xlsb]Sheet1'!C13,MATCH(1,('[NAL for Macro.xlsb]Sheet1'!C8=RC[-8])*(LEFT('[NAL for Macro.xlsb]Sheet1'!C3,15)=LEFT(RC[-13],15)),0)),IFERROR(VLOOKUP(RC[-8],'[NAL for Macro.xlsb]Sheet1'!C8:C15,6,0),IFERROR(VLOOKUP(RC[-8],'[NAL for Macro.xlsb]Sheet1'!C9:C15,5,0),(VLOOKUP(LEFT(RC[-13],15)&""*"",'[NAL for Macro.xlsb]Sheet1'!C3:C15,11,0)))))"
 End Sub

How to check if you written same numbers for two times in int input?

import random

purpose = random.randint(1, 10)
attempts = []
guess = int(input("Try to guess number between 1 to 10: "))
guess2 = guess + guess

    
while purpose != guess:
    print ("Oh sorry your guess was wrong :( ")
    attempts.append (guess)
    guess = int(input("Try to guess again: "))

there I want to make that if you guessed same number for two times, for example guesses were [5, 4, 4, 7]- program writes "you have a short memory". I tried it with function but code just writes "<function short_memory at 0x7fa6d7e58430>" (short_memory was name of function)

if purpose == guess :
    print ("Your guess was right!! ")


print ("your attempts was: ", attempts)

Elegant way to change a variable according to several conditions?

I'm trying to change the variable "exposure" according to multiple conditions.

For example: If stimulus_content is "neg", and if condition is "neg", and if set is "A", then the content of the variable "exposure" should be changed to "long" for the lines in which stimulus_no is either X1, X2, ... or X5. The variable "exposure should be changed to "short" for the lines in which stimulus_no is either X6, X7, ... or X10. And so on...

I hope the code below makes the problem more clear.

First, this is the approximate dataset:

n <- 6
dataset <- data.frame(
participant = rep(1:n, each=40),
condition = rep(c("pos","neg"), each=40),
set = rep(c("A","B"), each=40),
stimulus_content = rep(c("pos","neg"), each=20),
stimulus_no = rep(c("X1","X10","X11","X12","X13","X14","X15","X16","X17","X18","X19","X2","X20","X3","X4","X5","X6","X7","X8","X9"), each=2),
exposure = NA)

The first thing we tried is via a loop. For the sake of simplicity, only one part of the loop is included. It doesn't return an error but it also doesn't do anything.

for (i in 1:length(longdat[,1])){
  if(longdat[i,"stimulus_content"] == "pos") { 
    if(longdat[i,"condition"] == "pos") {
      if(longdat[i,"set"] == "A") {     
        for(stimulus_no in c("X1","X2","X3","X4","X5")){longdat[i,"exposure"] == "long"}
        for(stimulus_no in c("X6","X7","X8","X9","X10")){longdat[i,"exposure"] == "short"}
        for(stimulus_no in c("X11","X12","X13","X14","X15","X16","X17","X18","X19","X20")){longdat[i,"exposure"] == "none"}
      } else { #for condition = pos and set != A            
        for(stimulus_no in c("X11","X12","X13","X14","X15")){longdat[i,"exposure"] == "long"}
        for(stimulus_no in c("X16","X17","X18","X19","X20")){longdat[i,"exposure"] == "short"}
        for(stimulus_no in c("X1","X2","X3","X4","X5","X6","X7","X8","X9","X10")){longdat[i,"exposure"] == "none"}
      }
    }
  }
}

Next, we tried via mutate and case_when. This code does exactly what it's supposed to but it's almost 100 lines long! Please find an excerpt below.

longdat2 <- longdat %>%
  mutate(exposure = case_when(
    # Condition pos, set A
    stimulus_no=="X1" & stimulus_content=="pos" & condition=="pos" & set=="A" ~ "long",
    stimulus_no=="X2" & stimulus_content=="pos" & condition=="pos" & set=="A" ~ "long",
    # ...
    stimulus_no=="X9" & stimulus_content=="pos" & condition=="pos" & set=="A" ~ "short",
    stimulus_no=="X10" & stimulus_content=="pos" & condition=="pos" & set=="A" ~ "short",
    stimulus_no=="X11" & stimulus_content=="pos" & condition=="pos" & set=="A" ~ "none",
    # ... accordingly for condition pos and set B, and for condition neg and set A
    # and eventually for condition neg and set B
    stimulus_no=="X18" & stimulus_content=="neg" & condition=="neg" & set=="B" ~ "short",
    stimulus_no=="X19" & stimulus_content=="neg" & condition=="neg" & set=="B" ~ "short",
    stimulus_no=="X20" & stimulus_content=="neg" & condition=="neg" & set=="B" ~ "short",
  )
)

If someone manages to spot the error in the loop or could tell me a more succinct version of the second (or first) option, I'd be very grateful!

Thanks a lot in advance!

Query with macro

I want to run a macro that does the following every time I open a salary sheet:

  1. If column N displays the code 2102, 2111, 2112, 2201, 2101, 2301, 2312 then copy the name displayed in column H and paste this to Column AL.and add the code 2102 after the name.
  2. If column N displays the code 2102, 2111, 2112, 2201, 2101, 2301, 2312 then copy the text displayed in column F to column AM.

However, I'm not sure what type of formula I should use If Statement, Vlookup?

vendredi 29 janvier 2021

show total based on quantity and display total,item name,Rate etc

This is the code for check the quantity value is empty else do the calculation

 ordernew.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    if (addordernew.getText().toString().equals("")) {
                        addordernew.requestFocus();
                        addordernew.setError("Quantity is not Entered");
    
                    } else {
    
                        if(getstock.getText().toString().equals("Stove Top Stuffing"))
                        {
                            ShowItem.setText("Stove Top Stuffing");
                            
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Campell's Soup"))
                        {
                            ShowItem.setText("Campell's Soup");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Tide"))
                        {
                            ShowItem.setText("Tide");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Pampers"))
                        {
                            ShowItem.setText("Pampers");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Pepsi Products"))
                        {
                            ShowItem.setText("Pepsi Products");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Tang"))
                        {
                            ShowItem.setText("Tang");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Top Ramen"))
                        {
                            ShowItem.setText("Top Ramen");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Knorr"))
                        {
                            ShowItem.setText("Knorr");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Palmolive"))
                        {
                            ShowItem.setText("Palmolive");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Scotch-Brite"))
                        {
                            ShowItem.setText("Scotch-Brite");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Bounty Paper Towls"))
                        {
                            ShowItem.setText("Bounty Paper Towls");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
    
    
                        if(getstock.getText().toString().equals("Oreo Cookies"))
                        {
                            ShowItem.setText("Oreo Cookies");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
    
                        if(getstock.getText().toString().equals("Quaker Oats"))
                        {
                            ShowItem.setText("Quaker Oats");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
                        if(getstock.getText().toString().equals("Lays Potato Chips"))
                        {
                            ShowItem.setText("Lays Potato Chips");
                            Showqty.setText(addordernew.getText().toString());
                            ShowRate.setText(rategiven.getText().toString());
                        }
    
    
                        //  ShowItem.setText("Stove Top Stuffing");
                        //Showqty.setText(addordernew.getText().toString());
                       // ShowRate.setText(rategiven.getText().toString());
                        Toast.makeText(getApplicationContext(), "Order Taken", Toast.LENGTH_SHORT).show();
                    }
                }
            });

this is the code for the tax rate and percentage calculation

  getstock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(AddOrder.this, ListItem.class);
              Intent intent = getIntent();
               Bundle bd = intent.getExtras();
                if (bd != null) {
                    String getname = (String) bd.get("position");
                    getstock.setText(getname);
                    System.out.println(getname);


                   if(getstock.getText().toString().equals("Stove Top Stuffing")) {
                       taxgiven.setText("12");
                        stockgiven.setText("250");
                        rategiven.setText("598.214");
                        MRPRate.setText("999");


                       //Showqty.setText(addorder.getText().toString());
                       // ShowRate.setText(TaxInclrate.getText().toString());

                        //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)Math.round(rateamount* taxamount) / 100);
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);

                                          }
                   else if(getstock.getText().toString().equals("Campell's Soup"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("100");
                       rategiven.setText("150");
                       MRPRate.setText("456");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Tide"))
                   {
                       taxgiven.setText("5");
                       String a=taxgiven.getText().toString();
                       stockgiven.setText("50");
                       rategiven.setText("200");
                       MRPRate.setText("1000");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Pampers"))
                   {
                         taxgiven.setText("5");
                       stockgiven.setText("25");
                       rategiven.setText("100");
                       MRPRate.setText("1234");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Pepsi Products"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("5");
                       rategiven.setText("140");
                       MRPRate.setText("500");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Tang"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("23");
                       rategiven.setText("340");
                       MRPRate.setText("450");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Top Ramen"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("34");
                       rategiven.setText("1230");
                       MRPRate.setText("345");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Knorr"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("40");
                       MRPRate.setText("876");



                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Palmolive"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("145");
                       MRPRate.setText("980");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Scotch-Brite"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("10");
                       MRPRate.setText("890");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Bounty Paper Towls"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("150");
                       MRPRate.setText("1120");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Oreo Cookies"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("100");
                       MRPRate.setText("789");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Quaker Oats"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("400");
                       MRPRate.setText("1245");

                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)Math.round(rateamount* taxamount) / 100);
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }
                   else if(getstock.getText().toString().equals("Lays Potato Chips"))
                   {
                       taxgiven.setText("5");
                       stockgiven.setText("250");
                       rategiven.setText("15");
                       MRPRate.setText("900");

                       //percentage calculation
                       double taxamount = Double.parseDouble(taxgiven.getText().toString());
                       double rateamount = Double.parseDouble(rategiven.getText().toString());
                       Double result = ((double)rateamount* taxamount) / 100;
                       Double finalamount=(result + rateamount);
                       TaxInclrate.setText(""+finalamount);
                   }

                }
                startActivity(i);
            }
        });

and based on quantity i want to show the total tax rate and percentage calculation everything is work smoothly until i get this problem what can i do to get the total based on Quantity

How to run commands inside bash script based on execution

I have a linux bash script which consists of multiple commands. The first time when it runs, it should execute all the commands, and the second time of the execution of the script, it should execute only 2 commands. Can I do this with an "if else" statement?

First time execution of the script: Should run all the commands inside that script Second time execution of the script: Should run only two commands inside that script

Sort objects with multiple dynamic else-if statements

Considering we have the following:

typealias Fruit = String
typealias Count = Int

struct Smoothie {
   let uuid: String
   let fruits: [Fruit: Count]
}

let smoothies: [Smoothie] = ...

Given a conditions array set by the user:

let conditions: [Fruit] = ...

The lowest the index in the conditions array, the most important we consider it is for sorting.

I would like to sort the smoothies array so that the smoothies that contain the highest number of fruits (Count) from the conditions array, appear first.

If a fruit doesn't appear in the fruits dictionary, we consider its count as 0.

For example:

let fruitsA = ["Apple": 3, "Mango": 4, "Pear": 8, "Cherry": 1, "Banana": 2]
let smoothieA = Smoothie(uuid: "smoothie_a", fruits: fruitsA)

let fruitsB = ["Apple": 10, "Mango": 9, "Grapes": 8, "Cherry": 9]
let smoothieB = Smoothie(uuid: "smoothie_b", fruits: fruitsB)

let fruitsC = ["Apple": 23, "Kiwi": 4, "Pear": 1, "Cherry": 17, "Banana": 8]
let smoothieC = Smoothie(uuid: "smoothie_c", fruits: fruitsC)

let fruitsD = ["Apple": 1, "Orange": 6, "Pear": 8]
let smoothieD = Smoothie(uuid: "smoothie_d", fruits: fruitsD)

let conditions: [Fruit] = ["Apple", "Banana", "Cherry"]

Should return the following:

let sortedSmoothies = [smoothieC, smoothieB, smoothieA, smoothieD]

Because we're first sorting by Apple, then by Banana, then by Cherry count.

If I knew it would always be about Apple, Banana & Cherry, I could do the following and it would just work:

let sortedSmoothies = smoothies.sorted {
     if $0.fruits["Apple"] != $1.fruits["Apple"] {
         return $0.fruits["Apple"] > $1.fruits["Apple"]
     } else if $0.fruits["Banana"] != $1.fruits["Banana"] {
         return $0.fruits["Banana"] > $1.fruits["Banana"]
     } else {
         return $0.fruits["Cherry"] > $1.fruits["Cherry"]
     }
}

But in my case I do not know what are the fruits (and how many of them) that the user is going to select for filtering in the conditions array.

Does anyone has an idea how to sort this out please?

Thank you!

Multiple Conditions for an if statement in javascript [duplicate]

I'm pulling information off of a generic html table for a basketball algorithm I'm working on. I am saving all the stats I need inside the for loop into variables. The if statement I am trying to run should return players with a 'fppd' (fantasy point per dollar) that is greater than .045 AND if they are not injured. If they are injured, the table will display "GTD" or "O" so setting the condition inj = '' should return non-injured players.

Everything was working fine until I attempted to add multiple conditions to the if statement. Now I am somehow getting an "Uncaught TypeError: Cannot read property 'innerText' of undefined" I believe the problem is coming from the if statement. If you could take the time to help me out, it would be greatly appreciated

<script type="text/javascript">
const rows = document.querySelectorAll('tbody tr')
const statTable = document.querySelectorAll('tbody tr td')
const numOfPlayers = rows.length
for (let i=0; i<numOfPlayers; i++){
    let name = statTable[(i*8)+9].innerText
    let pos = statTable[(i*8)+8].innerText
    let opp = statTable[(i*8)+13].innerText
    let fPPG = statTable[(i*8)+10].innerText
    let sal = statTable[(i*8)+12].innerText
    let gamesPlayed = statTable[(i*8)+11].innerText
    let inj = statTable[(i*8)+14].innerText
    let fppd = fPPG/sal
    if ((fppd > .005) && (inj = ''))
    {
    console.log(name, pos, sal, opp, fPPG, gamesPlayed, fppd)
    }
}
</script>

 

how to make a code for posterzing for RBG colors in between 0-255 using python language. Cimpl library?

Recall that a pixel's red, green and blue components have values between 0 and 255, inclusive. We divide this range into four equal-size quadrants: 0 to 63, 64 to 127, 128 to 191, and 192 to 255. For each pixel, we change the red component to the midpoint of the quadrant in which it lies. We do the same thing for the green and blue components Develop a filter named posterize that returns a posterized copy of an image. The posterize function must call the _adjust_component function to determine the quadrant in which a component lies and obtain the midpoint of that quadrant.

If condition in java is entering the if block even if expression is evaluating false

enter image description here UNEXPECTED BEHAVIOUR OF IF BLOCK IN JAVA

execution is entering inside the if block even it's clearly visible in the expression window that both conditions are false while debugging.

Am I missing something or is this a bug? Please see the image attached

Using IF statement with data validation in Excel

I am new to excel and trying to use the IF statement along with Data Validation to make a conditional list based on a previous answer.

For example: If I chose dogs in B3, id like only the breed go dogs to show up (breeds of dogs are listed in column on info sheet in same workbook), but if I choose cats, id like only the breed of cats to show up (breeds of cats are listed in the column next to breed of dogs on info sheet in same workbook)

This is the code I am using: IF(B3=Info!$A$2,Info!$A$3:A$6,IF(B3=Info!$B$2,Info!$B$3:$B$6,IF(B3=Info!$C$2,Info!$C$3:$C$9,IF(B3=Info!$D$2,Info!$D$3:$D$7,IF(B3=Info!$E$2,Info!$E$3:$E$6,IF(B3=Info!$F$2,Info!$F$3:$F$10,IF(B3=Info!$G$2,Info!$G$3:$G$6,IF(B3=Info!$H$2,Info!$H$3:$H$7,IF(B3=Info!$I$2,Info!$I$3:$I$7,IF(B3=Info!$J$2,Info!$J$3:$J$5))))))))))

In this code, B3 is the cell that with the original condition (ie dogs or cats) and Info!sheet is the worksheet that includes the breeds in specific columns. For example, "dogs" breeds would be Info!$A$2 and all the dog breeds listed would be Info!$A$3:A$6.

Thanks for your help!!! I really appreciate it.

Console.ReadLine as an integer [duplicate]

Very basic question, my first day of learning C#

I am doing a tutorial from codeacademy.
Its a basic "how old are you"
enter a number and it says back to you "you are X years old!"

The code is

using System;

namespace GettingInput
{
class Program
{
static void Main()
{
Console.WriteLine("How old are you?");
string input = Console.ReadLine();
Console.WriteLine($"You are {input} years old!");
}
}
}

I want the string as an int (no text just numbers)
and an IF statement to return "you are x years old" if X <= 140
and else would be "you arent that old" for X > 140.

I tried

int input = Console.ReadLine();

        bool x =< 120 true; 
       
        if (input > "120");
      {
           Console.WriteLine($"You are not {input} years old!!");<br>
        }
  else if  (input =<"120")
        {
            Console.WriteLine($"You are {input} years old!");

Check if array is empty in bash [closed]

I am trying to see if an array is empty in bash

key=[]
key1=["2014"]

I have tried following ways:

[[ -z "$key" ]] && echo "empty" || echo "not Empty" 
[[ -z "$key1" ]] && echo "empty" || echo "not Empty"

Both return 'not Empty'

[[ $key==[] ]] && echo "empty" || echo "not Empty"
[[ $key1==[] ]] && echo "empty" || echo "not Empty"

Both return 'empty'.

Why "Saturday" keep showing in the output?

import java.util.*;

//Compiler version JDK 11.0.2

public class Excercise {
public static void main(String[] args) {
        
    String []day = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    for (int i=0; i<day.length; i++) {
        if (i==5) {
    System.out.println("Free Time"); }
         
        if (i==6) {
    System.out.println("Family Time"); }
    
        else {
    System.out.println(day[i]); }
        

    }
  }
}

T-SQL unexpected behavior

I am collecting telemetry messages into a SQL trigger, which used to work fine for several weeks (about 5 millions events ingested correctly), and I am experiencing unexpected behavior since a couple days, even though I did not modify this particular function.

The function decodes a raw payload to extract GPS coordinates, and is as such:

ALTER FUNCTION [getLongitude](@Firmware varchar(30), @RawData varchar(24))
    RETURNS float
    AS
    BEGIN
        DECLARE @EventID varchar(1),
                @Longitude float;

        SET @EventID = SUBSTRING(@RawData, 1, 1);
        IF @Firmware = 'V1'
            BEGIN
                IF @EventID = '1'
                    BEGIN
                        IF CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) < 8388608
                            BEGIN
                                SET @Longitude = CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) * 215.0 / 10000000;
                            END
                        ELSE
                            BEGIN
                                SET @Longitude = -1 * (16777216 - CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int)) * 215.0 / 10000000;
                            END
                    END
                ELSE SET @Longitude = 100; -- other events do not include GPS information
            END
        ELSE
            BEGIN
                IF @Firmware = 'V2'
                    BEGIN
                        IF @EventID = '1' OR @EventID = '2'
                            BEGIN
                                IF CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) < 8388608
                                    BEGIN
                                        SET @Longitude = CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) * 215.0 / 10000000;
                                    END
                                ELSE
                                    BEGIN
                                        SET @Longitude = -1 * (16777216 - CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int)) * 215.0 / 10000000;
                                    END
                            END             
                        ELSE SET @Longitude = 100; -- other events do not include GPS information
                    END
                ELSE SET @Longitude = 100; -- other firmwares are unknown
            END
        RETURN @Longitude;
    END;

For a specific device which has firmware V1, the function returns 100 as a value for the longitude. I have included "SELECT" lines to make sure the conditions were correctly applied, and this is where I do not understand the output:

DECLARE 
                @RawData varchar(24),
                @Firmware varchar(30),
                @EventID varchar(1),
                @Longitude float;
        
        SET @RawData = '1a330000003437cd3bfe95a7';
        SET @Firmware = 'V1';
        SET @EventID = SUBSTRING(@RawData, 1, 1);
        IF @Firmware = 'V1'
            BEGIN
                SELECT 'Cond1'
                IF @EventID = '1'
                    BEGIN
                        SELECT 'Cond 1.1';
                        IF CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) < 8388608
                            BEGIN
                            select 'Cond 1.1.1';
                                SET @Longitude = CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) * 215.0 / 10000000;
                            END
                        ELSE
                            BEGIN
                            SELECT 'Cond 1.1.2';
                                SET @Longitude = -1 * (16777216 - CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int)) * 215.0 / 10000000;
                                SELECT @Longitude
                            END
                    END
                ELSE 
                    SELECT 'Cond 1.2'
                    SET @Longitude = 100;
            END
        ELSE
            BEGIN
            SELECT 'Cond 2'
                IF @Firmware = 'V2'
                    BEGIN
                        IF @EventID = '1' OR @EventID = '2'
                            BEGIN
                                IF CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) < 8388608
                                    BEGIN
                                        SET @Longitude = CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int) * 215.0 / 10000000;
                                    END
                                ELSE
                                    BEGIN
                                        SET @Longitude = -1 * (16777216 - CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 19, 6)) AS int)) * 215.0 / 10000000;
                                    END
                            END             
                        ELSE
                            SELECT 'Cond 2.1'
                            SET @Longitude = 100;
                    END
                ELSE
                    SELECT 'Cond 2.2'
                    SET @Longitude = 100;
            SELECT 'Here?'
            END
            SELECT @Longitude

My outputs are:

Cond 1
Cond 1.1
Cond 1.1.2
-1,9943615 -- the correct value that I expect as function output
100

How come the longitude is finally set to 100 while neither Cond 1.2, Cond 2.1 nor Cond 2.2 are displayed?

I forgot to mention that fct.hexstrtovarbin is function that changes an hexadecimal string to a varbinary:

CREATE FUNCTION fct.hexstrtovarbin(@input varchar(8000)) RETURNS varbinary(8000)
AS
BEGIN
DECLARE @Result AS varbinary(8000)

IF LEN(@input) % 2 <> 0 
    BEGIN 
        SET @Result = 0000000000;
    END 
ELSE
    BEGIN
        SET @Result = CONVERT(VARBINARY(8000), @input, 2);
    END
    RETURN @Result
END;

How to print specific output based on condition from name variable

I have a dataframe data like that :

data

ANd I would like an output like that :

  • name1

    sentences1

    sentences2

    sentences3

  • name2

    sentences4

  • name3

    sentences5

    sentences6

Here's what I did so far :

first = True

for i in range(0, data.shape[0]):
    if data['Name'][i+1] == data['Name'][i] :
        if first:
            first = False
            print(data['Name'][i])
            print()
            print(data['Sentences'][i])
        else:
            print()
            print(data['Sentences'][i])
           
    if data['Name'][i] != data['Name'][i+1] :
        print(data['Name'][i])
        print(data['Sentences'][i])
       
    else :
        print()

But that doesn't give me the right output, the name aren't print at the place I wanted. I think I misplace or forget something in my loop but what ?

Thanks

EDIT : I think I figured it out ! I would like to know if I'm right, that's what I change in my code :

first = True

for i in range(0, data.shape[0]):
    if data['Name'][i+1] == data['Name'][i] :
        if first:
            first = False
            print(data['Name'][i])
            print()
            print(data['Sentences'][i])
        else:
            print()
            print(data['Sentences'][i])
           
    if data['Name'][i] != data['Name'][i+1] :
        print(data['Name'][i+1]) #i+1 instead of i
        print(data['Sentences'][i+1])# i+1 instead of i
       
    else :
        print()

How can I get the int i value in the javaFX for loop into if else?

LocalDate rst = LocalDate.of(2003, 1, 1);

LocalDate bdDate = dtDogum.getValue();

    for (int i = 0; i < personal.size(); i++) { 
        if (bdDate.isAfter(rst)) {
            hatamesajı.setTitle("Error");
            hatamesajı.setHeaderText("Personnel to be registered are under the age of 18");
            hatamesajı.show();
            return;
        }       
    }

I am coding a personnel registration program. A user under 18 gives a warning when registered. However, even though the first registration is under the age of 18, it does not give any warning. I think it is because I cannot place the int i value inside the for loop in the if block. How can I place it?

Bash scripting | Linux | if else statement [closed]

I'm having a bash script and it includes few config commands.

For example,

Command1 Command2 Command3 Command4 and so on...

The first time when the script is run, all the commands (Suppose there are 10 commands in that script) in that script should get executed. But after the first time, when the script get executed, only one command should get executed (For example, command5 only). How can I do this? Can I use "if statement" here? And how?

What is faster: adding a key-value pair or checking for the existence of a key?

Imagine a CSV file with 3 columns: individual name, group name, group ID. Obviously column 1 is different for every line while column 2 and 3 can be the same as before (every group name has an individual ID though). This is not sorted in any way.

For reasons I'm creating a dict to save: group ID (key) --> group name (value). Now what is faster of the following variants?

  1. checking if that key already exists and only saving if not.

    if ID not in group_dict:
       group_dict[ID] = name 
    
  2. just saving it every time again (replacing the value, which is the same anyway).

    group_dict[ID] = name 
    

Multi-operator Calculator With C

I want to make a calculator which takes 3+4/4*6 kinda input and I need to write it in C programming. I take numbers and operations separately from user, then I put numbers and operators to separate arrays. Then I wanted to loop through arrays respectively to do operations -I know operator priority is not considered- but It is not giving me correct result at all. To determine opeators, first I used switch case then tried If statement but both of them gave wrong results. I am gonna share both of them. How I can re-arrange this code to get correct result ?

By correct result I mean e.g 3+4/1*8 = 56

CODE WITH IF STATEMENT

#include <stdio.h>
int main(void){
    printf("You will enter your operations in number - operator order.\n");
    printf("How many numbers do you have to calculate?");
    int how_many; //how many numbers the user has in his/her whole operation
    scanf("%d",&how_many);
    int number_entry = how_many; //for example 1+2*9/5 has 4 numbers
    int operator_entry = how_many - 1; //and 3 operators
    int *number_in; //for every number as 1, 2 ,9 ,5 according to example
    //int *last;
    char *operator_in; // and for every operator as +, * , / according to example
    int numbers[number_entry];
    int ops[operator_entry];
    int j;
    int result;
    //int k;
    printf("\n");
    for(j=0;j<operator_entry;j++){
        printf("Enter the number : ");
        scanf("%d",&number_in);
        numbers[j] = number_in;
        printf("Enter the operation as + for add, - for substract, * for multiply and / for division: ");
        scanf(" %c", &operator_in);
        ops[j] = operator_in;
    };
    printf("Enter the number : ");
    scanf("%d" , &number_in);   
    numbers[number_entry-1] = number_in;
        
    
    int loop;

//wrote these loops to see if arrays works correctly or not

    for(loop = 0; loop < number_entry; loop++)
        printf("%d ", numbers[loop]);
    
    for(loop = 0; loop < operator_entry; loop++)
        printf(" %c", ops[loop]);
        
    for(loop = 0; loop<number_entry;loop++){
        
        if(ops[loop] == "+"){
            
            result = numbers[2*loop] + numbers[(2*loop)-1];
            
        }else if(ops[loop] == "-"){
            
            result = numbers[2*loop] - numbers[(2*loop)-1];
            
        }else if(ops[loop] == "*"){
            
            result = numbers[2*loop] * numbers[(2*loop)-1];
        }
        else if(ops[loop] == "/"){
            
            result = numbers[2*loop] / numbers[(2*loop)-1];
        }
        
    };
    
    printf("\n");
    
    printf("Result: ");
    
    printf("%d", result);
    
    return 0;
}

WITH SWITCH CASE

#include <stdio.h>
int main(void){
    printf("You will enter your operations in number - operator order.\n");
    printf("How many numbers do you have to calculate?");
    int how_many; //how many numbers the user has in his/her whole operation
    scanf("%d",&how_many);
    int number_entry = how_many; //for example 1+2*9/5 has 4 numbers
    int operator_entry = how_many - 1; //and 3 operators
    int *number_in; //for every number as 1, 2 ,9 ,5 according to example
    //int *last;
    char *operator_in; // and for every operator as +, * , / according to example
    int numbers[number_entry];
    int ops[operator_entry];
    int j;
    int *result = 0;
    //int k;
    printf("\n");
    for(j=0;j<operator_entry;j++){
        printf("Enter the number : ");
        scanf("%d",&number_in);
        numbers[j] = number_in;
        printf("Enter the operation as + for add, - for substract, * for multiply and / for division: ");
        scanf(" %c", &operator_in);
        ops[j] = operator_in;
    };
    printf("Enter the number : ");
    scanf("%d" , &number_in);   
    numbers[number_entry-1] = number_in;
        
    
    int loop;

//wrote these loops to see if arrays works correctly or not

    for(loop = 0; loop < number_entry; loop++)
        printf("%d ", numbers[loop]);
    
    for(loop = 0; loop < operator_entry; loop++)
        printf(" %c", ops[loop]);
        
    for(loop = 0; loop<number_entry;loop++){
        switch(ops[loop]){
            case '+':
                result = numbers[2*loop] + numbers[(2*loop)-1];
                break;
            case '-':
                result = numbers[2*loop] - numbers[(2*loop)-1];
                break;
            case '*':
                result = numbers[2*loop] * numbers[(2*loop)-1];
                break;
            case '/':
                result = numbers[2*loop] / numbers[(2*loop)-1];
                break;      
        };

        resulu = result + result;
    };
    
    printf("\n");
    
    printf("Result: ");
    
    printf("%d", result);
    
    return 0;
}

Create new, grouped conditional variable in R

Im trying to create a new variable, which is grouped and has several conditions underlying it. E.g. using the iris dataset:

I want to add a new column, grouped by species and contains information about the size. The outcome is expected to be a factor variable with levels "small", "medium" and "large".

Here's an example:

data(iris)
data %>% 
  dplyr::group_by(Species) %>% 
  dplyr::mutate(Size =
                  if_else(Sepal.Length <= 5.1 ~ "small",
                          Sepal.Length <= 5.8 & > 5.1 ~ "medium",
                          Sepal.Length > 5.8 ~ "large")
                ) 

It doesn't work. Apparently there's

an unmatched closed bracket ")"

Now, I am aware of other solutions, e.g. using Base R's ifelse function, but I'm trying to find an elegant way to express myself using tidyverse-style code. Can anyone help? I would be happy about any solutions using tidyverse code. Doesn't matter what function it is.