jeudi 30 avril 2020

if condition not met but still prints "if" in nested if statements with for loop

Why does this code never goes in to "else" and print accordingly when the condition in "if" is not satisfied?

j=0
for i in data:
  if j<10:

    if i['product']['id'] == p_id:
        if (i['stop_price']!='None'):
            print("Order Type:" +  str(i['stop_order_type']))
            print("Stop Price: " + str(i['stop_price']))

        else:
            print("Order Type: " + str(i['order_type']))



        print("Limit Price: " + str(i['limit_price']))
        print("Side: " + str(i['side']))
        print("Size: " + str(i['size']))
        print("Unfilled Size: " + str(i['unfilled_size']))

        print("\n\n")

    j+=1

It prints the below output:

Order Type:stop_loss_order
Stop Price: 405.0
Limit Price: 400.0
Side: buy
Size: 1
Unfilled Size: 1



Order Type:None
Stop Price: None
Limit Price: 280.0
Side: sell
Size: 1
Unfilled Size: 0



Order Type:None
Stop Price: None
Limit Price: 300.0
Side: sell
Size: 1
Unfilled Size: 1

But the correct Output should be:

Order Type:stop_loss_order
Stop Price: 405.0
Limit Price: 400.0
Side: buy
Size: 1
Unfilled Size: 1



Order Type:Limit
Limit Price: 280.0
Side: sell
Size: 1
Unfilled Size: 0



Order Type:Limit
Limit Price: 300.0
Side: sell
Size: 1
Unfilled Size: 1

How to use if em google spreadsheet in c#

I am working on a google spreadsheet in conjunction with C #, I was able to make the connection and read the data from the spreadsheet but I am facing problems when making a comparison for a decision making using if

 String Range = "D1!A1:A1";

        SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(SpreadSheetId, Range);
        var response = request.Execute();

         IList < IList < Object >> values = response.Values;

        if(values != null && values.Count > 0){    
           foreach (var row in values)
            {
                Console.WriteLine(row[0]);
                if (row[0] == "Test")
                {
                    Console.WriteLine("Has Test string in spreadSheet!");
                }
            }

        }else{
            Console.WriteLine("Nothing");

        }

EDIT: looks like using Equals this is work but not properly i need

I do not why it is not roatating?

I don know what am I doing wrong.

Write a function named rotateArt that takes two (2) parameters: imageArray and rotation. (a) imageArray is a 2D array of any dimension containing an ASCII art “image.” (b) rotation is a value that is one of the following values: 0, 90, 180, 270, 360, -90, -180, -270. A positive value indicates a rotation in the clockwise direction. A negative value indicates a rotation in the counter-clockwise direction. A value of 0 or 360 means that no rotation is to take place, but that the image is to be mirrored or flipped around the vertical axis

function rotateChar(char,rotation){
let rowLookup = ['^','v','>','<','|','-','|','\\','/','`','~','[','=','_'];
let colLookup = [-270,-180,-90,0,90,180,270];
let rotations = [
    ['>','v','<','^','>','v','<'],
    ['<','^','>','v','<','^','>'],
    ['v','<','^','>','v','<','^'],
    ['^','>','v','<','^','>','v'],
    ['-','|','-','|','-','|','-'],
    ['|','-','|','-','|','-','|'],
    ['_','|','_','|','_','|','_'],
    ['/','\\','/','\\','/','\\','/'],
    ['\\','/','\\','/','\\','/','\\'],
    ['~','`','~','`','~','`','~'],
    ['`','~','`','~','`','~','`'],
    ['=','[','=','[','=','[','='],
    ['[','=','[','=','[','=','['],
];
   if (rowLookup.indexOf(char)=== -1 || colLookup.indexOf(rotation)=== -1) {
       return char;
   } else {
       return rotations[rowLookup.indexOf(char)][colLookup.indexOf(rotation)];
   } 
   }

 function rotateArt(imageArray,rotation){
 rotation = parseInt(rotation);
 let newArray = [];
 let width = 0, height = 0;
 let cols =  [-270,-180,-90,0,90,180,270];
 let rowLookup = ['^','v','>','<','|','-','|','\\','/','`','~','[','=','_'];

switch (rotation){
 case 90:
    width = cols;
    height = rowLookup;
    for (let i =0; i < width; i++){
        let newRow = [];
        for (let j =0; j < height; j++){
        newRow.push('x');
     }
     newArray.push(newRow);
}

for (let i = 0; i < rowLookup; i++){
    for (let j =0; j < cols; j++){
        newArray[j][rowLookup - 1 - i] = rotateChar(imageArray[i][j],rotation);
    }
   }
    break;
default:
    break;
       } 
return newArray;
       }

C - Variable Declaration in If Condition Available in Else?

If I declare a variable in an if condition in C, is that variable also available to the else branch? For example:

if((int x = 0)){
  foo();
} else{
  x++;
  bar(x);
}

Couldn't find the answer, at least not the way that I worded it. Please help.

Sort function not working as expected after putting getElementById this way

I'm a begginer figuring out my own first project but I can't get info about this case.

The application is supossed to receive data about a product, it's name, price, stock, number of sales and then sort them from the most sold to the less sold.

Here's the thing, I was trying to shorten how verbose the code was by putting this chunk this other way

so I went from this

var balanceVenta = (ev) =>{
    ev.preventDefault();  

    diseños.sort((a,b) => { return (a.ammountSold < b.ammountSold) ? 1 : -1 });   

    document.getElementById("name1").innerHTML = diseños[0].designName;
    document.getElementById("stock1").innerHTML = diseños[0].currentStock;
    document.getElementById("price1").innerHTML =  "$" + diseños[0].priceEa;
    document.getElementById("sold1").innerHTML = diseños[0].ammountSold;
    document.getElementById("lastProduction1").innerHTML = diseños[0].productionAmmount;

    document.getElementById("name2").innerHTML = diseños[1].designName;
    document.getElementById("stock2").innerHTML = diseños[1].currentStock;
    document.getElementById("price2").innerHTML = "$" +  diseños[1].priceEa;
    document.getElementById("sold2").innerHTML = diseños[1].ammountSold;
    document.getElementById("lastProduction2").innerHTML = diseños[1].productionAmmount;

    document.getElementById("name3").innerHTML = diseños[2].designName;
    document.getElementById("stock3").innerHTML = diseños[2].currentStock;
    document.getElementById("price3").innerHTML =  "$" + diseños[2].priceEa;
    document.getElementById("sold3").innerHTML = diseños[2].ammountSold;
    document.getElementById("lastProduction3").innerHTML = diseños[2].productionAmmount;

}

to this

var index = 0;

var balanceVenta = (ev) =>{
    ev.preventDefault();
        
    diseños.sort((a,b) => { return (a.ammountSold > b.ammountSold) ? 1 : -1 }); 


    index ++ ;
    var prefixName= "name";
    var prefixStock= "stock";
    var prefixPrice = "price";
    var prefixSold = "sold";
    var prefixLastProd = "lastProduction";

        document.getElementById(prefixName + index).innerHTML = diseños[index - 1].designName;
        document.getElementById(prefixStock + index).innerHTML = diseños[index - 1].currentStock;
        document.getElementById(prefixPrice + index).innerHTML = diseños[index - 1].priceEa;
        document.getElementById(prefixSold+ index).innerHTML = diseños[index - 1].ammountSold;
        document.getElementById(prefixLastProd + index).innerHTML = diseños[index - 1].productionAmmount;
        
}

Everything works fine except for the sort function, which was working fine in the first version, but not working at all in the second one.

Pd: "diseños" is an Array which holds an object inside each index through this function

let diseños = [];
const addDesign = (ev)=>{
    ev.preventDefault();  
    let diseño = {  
        designName: document.getElementById("textBox1").value, 
        currentStock: document.getElementById("textBox2").value,
        productionAmmount: document.getElementById("textBox3").value, 
        priceEa: document.getElementById("textBox4").value, 
        ammountSold: document.getElementById("textBox5").value
    
    }
    diseños.push(diseño);
    document.forms[0].reset();

Can you guys help me out figure this one out? Thanks!

Why if (integer) being evaluated as True?

In this piece of code why would line 6 execute with the conditional statement "if f(3):" wouldn't that just be essentially asking "if 3" since f(x) just returns x?

Also why does "not y" return False if y in this case is equal to 3?

1   def f(x):
2       return x
3   
4   def g(x, y):
5       if x(y):
6           return not y
7       return y
8   
9   x = 3
10  x = g(f, x)
11  f = g(f, 0)

Scan and Check for Binary Numbers

I managed to complete the assignment, but then I realized one fatal flaw: I didn't enable the code to accept a string of binary numbers. I managed to get the code to loop like I wanted until a binary number (either a 0 or 1) was entered, but I can't figure out how to enable the code to accept a string of binary numbers (ie: 1010) without ruining the loop I've created.

I'll also include the instructions as well: 1) Request an individual to enter a binary number and 2) Manage to test the input for compliance with the binary number system (only 0 and 1 are allowed).

boolean b = false;

System.out.println("\nEnter a binary number:");
do
{
  Scanner scan1 = new Scanner(System.in);
  int binaryNumber = scan1.nextInt();

  if (binaryNumber > 1 || binaryNumber < 0)
  {
    System.out.println("\nInvalid input. Try again.");
  }
  else
  {
    System.out.println("\nThe binary number \"" + binaryNumber + "\" is valid.");
    break;
  }
} while (!b);
}

How would I go about editing the code to include a string of binary numbers, but still maintain the loop and other details above? Or will I have to completely change the code in order to include and accept the binary string?

Handling nested ladder python

I have some multiple condition with boolean in dictionary

d = { 
        "statement01" = True,
        "statement02" = True, 
        "statement03" = False, 
        "statement04" = False, 
        "statement05" = False
    }

And I use if elif

Method 1

if d["statement05"]:
        if d["statement01"]:
                func01()
                func05()
elif d["statement04"]:
        if d["statement01"]:
                func01()
                func04()
elif d["statement03"]:
        if d["statement01"]:
                func01()
                func03()
elif d["statement02"]:
        if d["statement01"]:
                func01()
                func02()
elif not d["statement01"]:
        if d["statement05"]:
                func05()
        elif d["statement04"]:
                func04()
        elif d["statement03"]:
                func03()
        elif d["statement02"]:
                func02()
        else:
                func01x()

Method 2

if d["statement01"]:
        func01()
        if d["statement02"]:
                func02()
        elif d["statement03"]:
                func03()
        elif d["statement04"]:
                func04()
        elif d["statement05"]:
                func05()
elif not d["statement01"]:
        if d["statement02"]:
                func02()
        elif d["statement03"]:
                func03()
        elif d["statement04"]:
                func04()
        elif d["statement05"]:
                func05()
        else:
                func01x()

With d condition I expect the result is do func01() and func02()

but if condition dictionary like

d2 = { 
        "statement01" = True,
        "statement02" = False, 
        "statement03" = False, 
        "statement04" = False, 
        "statement05" = False
    }

I expect only do func01() and if the dictionary like

d3 = { 
        "statement01" = False,
        "statement02" = True, 
        "statement03" = False, 
        "statement04" = False, 
        "statement05" = False
    }

Only do func02()

Is anyone can give other/best way to handle condition and expected result or maybe not in if else method?

Why is this a valid scanf statement to break out of a while loop?

Why is this a valid line of code to break out of an indefinite while loop.

if (scanf("%s", word) != 1) break;

Is there a way to create lists in r based on matching filenames in a for loop?

(I am very new to R so I've been thinking about problem solving in python terms then trying to translate it, but it hasn't been working-- I need R though, for their raster/GIS capabilities)

My goal is to take a list of filenames which I have generated from a folder (ending in either ***DTM.tif or ***DSM.tif), go through that list trying to traverse the strings in each element to find the filenames that match between the DSM and DTM files, then append the files to new lists which order the DSM files and DTM files respectively.

    filenames

    ##### initialize lists
    dsmlst <- list_along()
    dtmlst <- list_along()

    ##### for loop
    for (i in seq_along(filenames)) {
      n = nchar(i)
      if substr(i, n-7, n) == "DSM.tif" {
        list.append(dsmlst, i)
      } else if substr(i, n-7, n) == "DTM.tif" {
        list.append(dtmlst, i)
      }
    }
    dsmlst
    dtmlst

This is all I have so far, and I haven't been able to get it to work. Any advice?

How to redirect users to their specified page after logging in?

I've modified the login file to redirect user to their specified page. But my code simply redirect every user to the first option(rd). Users under pd department are directed to rd page. My code is as below. Note: Please ignore SQL injection comments if there's any vulnerability... My db table, aside from names, includes the columns access level (admin & user) department (rd & pd).

<?php
if(!isset($_SESSION)){
 session_start();
                     }
include_once("connections/connection.php");
$con = connection();

if(isset($_POST['login'])){

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users_table WHERE username = '$username' AND password = '$password'";

$user = $con->query($sql) or die ($con->error);
$row = $user->fetch_assoc();
$total =$user->num_rows;

if($total > 0 AND $department=rd){
$_SESSION['UserLogin'] = $row['username'];
$_SESSION['Access'] = $row['access'];
$_SESSION['Fname'] = $row['fname'];
$_SESSION['Lname'] = $row['lname'];
$_SESSION['Department'] = $row['department'];

echo $_SESSION['UserLogin'];
echo header("Location: index_rd.php");}

else  if($total > 0 AND $department=pd){
$_SESSION['UserLogin'] = $row['username'];
$_SESSION['Access'] = $row['access'];
$_SESSION['Fname'] = $row['fname'];
$_SESSION['Lname'] = $row['lname'];
$_SESSION['Department'] = $row['department'];

echo $_SESSION['UserLogin'];
echo header("Location: index_proc.php");}

else{
echo "No user found.";
}
}
?>

Given an imported dataset, how do I assign the value of 0 to a new column if a value of a previous column = 1? On R

I'm a beginner to R so please excuse me if this is an overly simple question.

With n-back data, I'm trying to calculate the bias of the one-back trials.

I imported a dataset from Excel to R successfully and everything works except for the line

if (df$one_back_aprime == 1) {
  df$one_back_bias <- 0
}

in the following code:

library(readxl)
nback_mornings_data <- read_excel("NFS4and5_mornings_R.xlsx", sheet = 1) #replace with file name
df <- data.frame(nback_mornings_data)

if (df$one_back_hit_rate > df$one_back_fa_rate) {
  df$one_back_aprime <- 0.5 + ((df$one_back_hit_rate - df$one_back_fa_rate) * (1 + df$one_back_hit_rate - df$one_back_fa_rate))/(4 * df$one_back_hit_rate * (1 - df$one_back_fa_rate))
  } else if (df$one_back_hit_rate < df$one_back_fa_rate) {
    df$one_back_aprime <- 0.5 + ((df$one_back_fa_rate - df$one_back_hit_rate) * (1 + df$one_back_fa_rate - df$one_back_hit_rate))/(4 * df$one_back_fa_rate * (1 - df$one_back_hit_rate))
  } 

if (df$one_back_aprime == 1) {
  df$one_back_bias <- 0
} else {
  df$one_back_bias <- (((1 - df$one_back_hit_rate) * (1 - df$one_back_fa_rate)) - (df$one_back_hit_rate * df$one_back_fa_rate)) / (((1 - df$one_back_hit_rate) * (1 - df$one_back_fa_rate)) + (df$one_back_hit_rate * df$one_back_fa_rate))
}

When I run the code, everything works, except when the one_back_aprime == 1 , it prints NaN (because that's what the equation at else churns out). However, I'm confused as to why this is because I already put that it should be assigned the value of 0. So clearly I'm doing that wrong.
Can anyone please help to change that portion of the code so that when one_back_aprime = 1, the new one_back_bias column will show the value of 0? Note: I've tried print("0") but that doesn't work either.

Any help would be much appreciated! I'm sure I'm missing something very basic, but again, I'm just a beginner.

Conditionnaly color barplots

I would like to conditionally color these mirrors barplots. I want to colour according to the disease and the hospital. I want the diseases that have the first two identical characters to have the same colour (i.e. D4001 and D4002 will have the same colour; D3000, D3001 and D3003 will have the same colour). I also want to stratify the color on the hospital so that the transparency or contrast of the barplot will be different from one hospital to another for the same disease (for example a disease D4 in hospital A will be red and a disease D4 in hospital B will be transparent red).

set.seed(0)
ID=1:20
Hospital<-sample(c(rep("A",10),rep("B",10)))
Disease<-c("D1000",rep("D2001",2),rep("D2000",3),rep("D3000",4),
rep("D3001",2),rep("D3003",4),rep("D4001",3),"D4002")

data$Disease<-as.factor(data$Disease)
data<-data.frame(ID,Hospital,Disease)
datacount<-data%>%group_by(Hospital,Disease)%>%count
datacount$n2<-ifelse(datacount$Hospital=="B",datacount$n,-datacount$n)

ggplot(datacount,aes(x=Disease,y=n2))+
  geom_col(aes(fill=Hospital))+coord_flip()

All I know how to do is either color by hospital or by disease individually.

enter image description here enter image description here

how to make two If condition in laravel

Two conditions I want to apply for a button that will show the application when applied and if the user has a login then the button will show and ask to login.

Blade

            @if (Auth::check())
            @if ($tuitionJob->checkApply())

            <form action="" method="POST">
              @csrf
                <input type="hidden" value="" name="tuitionid">
                <button type="submit" class="btn btn-primary login-apply-btn my-2 text-light pull-right">
                  Apply <i class="fa fa-send"></i>
                </button>
              </form>
                @else
              <a href="/login" class="btn btn-primary login-apply-btn my-2 text-light pull-right">
                <i class="fa fa-send"></i>
                Login For Apply
              </a>
            @else
              <a href="tuition/job" class="btn btn-primary login-apply-btn my-2 text-light pull-right">
                <i class="fa fa-send"></i>
                 Applied
              </a>

            @endif
            @endif

Model

public function checkApply(){
  return \DB::table('tuition_applies')->where('users_id', auth()->user()->id)
  ->where('tuition_post_id', $this->id)->exists();
}

Assign value in one column if character in other column is x in R

I am trying to assign a specific interger/number in a column if the character in another column is x. I have 5 characters which repeat down the column, and in a new column I need to assign a number to each repeating character. Basically each of the 5 characters has a specific number that needs to go in the new column. Please help!

Both my if and else get excecuted at the same time when I write a correct word

I tried making this "game" where I have to write English words that have 5 characters, if I write something gibberish it says that that word is incorrect.

However, when I write a word from the list, it shows the word, but it also shows the message saying its incorrect. It seems both my if and else are executing. Can someone help me understanding this behavior?

var emrat5 = [
    {emri:"about"},
    {emri:"added"},
    {emri:"again"},
    {emri:"ahead"},
    {emri:"above"},
    {emri:"adult"},
    {emri:"album"},
]

    function shfaq(){
        var inputi = document.getElementById("inputi").value;
        document.getElementById("thewrongdiv").innerHTML = ""
        for(var i=0;i<emrat5.length;i++){
        if(inputi == emrat5[i].emri){
            document.getElementById("thewrongdiv").style.display = "none"
            var result = document.createElement("h2");
            result.innerHTML = inputi;
            result.style.color = "blue";
            result.style.display = "block"
            document.getElementById("theOutputdiv").appendChild(result)
            document.getElementById("inputi").value= null
            

        }
        else{
            document.getElementById("thewrongdiv").innerHTML = ""
            var wrong = document.createElement("h2");
            wrong.innerHTML = "Incorrect Word";
            wrong.style.color = "red";
            document.getElementById("thewrongdiv").style.display = "block"
            document.getElementById("thewrongdiv").appendChild(wrong)
            inputi.value = ""

        }
        }
    }
    
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
    body{
        background: #d4d4d4;
    }
    *{
        font-family: monospace;
    }
    .verytop{
        background-color: #929292;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        height: 70px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .verytop > h1{
        color:white;
        font-size: 30px;

    }
    #thetutorial{
        display: flex;
        justify-content: center;
        padding: 20px 0px;
    }
    #thetutorial > h3{
        font-size: 20px;
    }
    #thewrongdiv{
        width: 200px;
        height: 200px;
    }
</style>
<title>Word Guesser</title>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-4"></div>
            <div class="col-lg-4">
                <div class="verytop">
                    <h1>The 5 letter word game</h1>
                </div>
            </div>
            <div class="col-lg-4"></div>
        </div>
        <div class="row">
            <div id="thetutorial" class="col-lg-12">
                <h3>see how many 5 letter words with that length can you guess in 1 minute</h3>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-4"></div>
            <div class="col-lg-4">
                <div style="margin-top: 40px;" id="theInputdiv">
                <input onsearch="shfaq()" id="inputi" class="form-control" type="search">

                </div>
                <div id="theOutputdiv">

                </div>
            </div>
            <div style="height:400px" class="col-lg-4 d-flex justify-content-center align-items-center">
                <div id="thewrongdiv">

                </div>
            </div>
        </div>
    </div>
    </body>
    </html>

Javascript, how to write a while loop inside a if-else loop

Can anyone tell me what is wrong with my code. It seems like the after continue; it still loop over the same block even I input the largest number (i.e.10) here it still want me to input larger number

// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)

// 2) Ask the user input (reference: prompt())

let userInput = prompt(`Give me a  number`)
const userInputInt = parseInt(userInput)
console.log(userInput) 
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))


if(isNaN(userInput)){
    prompt(`Give me a freaking number`)
}else{
    let x = 0;
    while (x < 4) {
        console.log('hi')
        console.log(userInputInt)
        console.log(RanNum)

        if (userInputInt == RanNum) {
            console.log(`win`)
            prompt('YOU GOT IT MAN')
            break;
        }
        else if (userInputInt < RanNum) {
            x = x+1 ;
            prompt('Larger please')
            continue;

        }
        else if (userInputInt > RanNum) {
            x= x+1
            prompt('Smaller please')
            continue;

        }

    }
    if(x > 3){alert('More than 3 times')}

}

However, this one work fine. Can someone point to me whats wrong???

// Guess the number

const randomNumber = Math.floor(Math.random() * 11);

let trials = 0;

while(trials < 4){
    const guess= parseInt(prompt("Give me a number(0-10)!"));
    if(isNaN(guess)){
        alert("You are not inputing a number");
        // Works for while-loop, for-loop, do-while loop
        continue;
    }
    trials++;
    if(guess === randomNumber){
        // Equal
        alert("You win!!");
        // If the player wins, terminate the game
        // Works for while-loop, for-loop, do-while loop
        break;
    }else{
        // Unequal
        if(guess > randomNumber){
            alert("Too large!");
        }else{
            alert("Too small");
        }
    }
}

if(trials > 3){
    alert("You loses");
}

array formula is not working in google sheet

What I want to do:

  • Check if 4 of my cells are blank or not
  • If all of them are not blank, then its okay, else display nothing ("")
  • I want it to be auto dragged down

What I have tried

=arrayformula(if(AND(not(A1:D=""),not(B1:B=""),not(C1:C=""),not(D1:D="")),"ok",""))

Result

  • Although the statements of AND is true, it displays nothing ""

What can be the issue in the formula?

If, Elif and Else Format

I'm new to Python and Programming, and would really appreciate your help as I would like to set up an If, Elif and Else statement for the below: An Employee wants to check if they're scheduled to work or if they're on holiday:

I've set it like the below but can't get the response I require, please help. Thanks.

rota = input('Please answer Yes or No - Are you working today? ')
if rota == 'Yes' or 'yes':
    print('Please start your shift, thank you')
elif rota == 'No' or 'no':
    hols = input('Are you on holiday? ')
    if hols == 'Yes' or 'yes':
        print('You do not have a shift as you are on holiday')
    if hols == 'No' or 'no':
        print('Please check your rota for your shift')
    else:
        print('Contact your manager if you require additional information.')

Problems with script that prints content of a file from a given line number to the next line number specified

#!/bin/sh

START=$1
END=$2
FILENAME=$3

ERROR="[PINCH ERROR]"
if [ $# -lt 3 ]; then
    echo "$ERROR Need three arguments: Filename Start-line End-line"
    exit 1
fi

if [ ! -f "$FILENAME" ]; then
    echo -e "$ERROR File does not exist. \n\t$FILENAME"
    exit 1
fi

if [ "$START" -gt "$END" ]; then
    echo -e "$END $START"
    exit 1
fi

if [ "$START" -lt 0 ]; then
    echo -e "$ERROR Start line is less than 0."
    exit 1
fi

if [ "$END" -lt 0 ]; then
    echo -e "$ERROR End line is less than 0."
    exit 1
fi

NUMOFLINES=$(wc -l < "$FILENAME")

ENDDIFF=$(( NUMOFLINES - END ))

if [ "$START" -lt "$ENDDIFF" ]; then
    < "$FILENAME" head -n $END | tail -n +$START
else
    < "$FILENAME" tail -n +$START | head -n $(( END-START+1 ))
fi

exit 0 

The Problem I have is that if start is greater than end (exemple ./file 10 7) I need to print the the lines from start arg back to end arg (so basically line 10 9 8 7). Don't know how to do that :

if [ "$START" -gt "$END" ]; then
    echo -e "$END $START"
    exit 1
fi

If NULL or meets condition then continue in R

I want to check if x is NULL/NA/NAN and if it is, then carry out the function. I also want to carry out the function if x is not between a min and a max number.

If I do:

#Checks if blank
isnothing <-  function(x) {
  any(is.null(x))  || any(is.na(x))  || any(is.nan(x)) 
}


x <- as.numeric(NULL)
min <- 25
max <- 45

#Actual function
if (isnothing(x) | !between(x,min,max)) {
    #Do something
}

I get the dreaded "argument is of length zero in if statement" error in R

I also tried:

x <- as.numeric(NULL)
min <- 25
max <- 45

if (isnothing(x) |(!isnothing(x) & !between(x,min,max))) {
    #Do something
}

This still doesn't work

Assigning many values to one variable

I am get phone numbers based on users choice

#the dict that contains the data I need
x={"contact": 
{
    "facility_message": "testing testing testing", 
    "facilitydigits":101,
    "name": "", 
    "urn": "tel:+1234567891011", 
    "uuid": "60409852-a2089-43d5-bd4c-4b89a6191793",
    "selection_anc_pnc":"C"
    }
}

#extracting data from the dict
facility_number=str(x['contact']['facilitydigits'])
group=(x['contact']['selection_anc_pnc']).upper()
facility_message=(x['contact']['facility_message'])

#checking user selection 
if group =='A':
    group="MIMBA"
elif group =='B':
    group='MAMA'    
elif group=='C':
    group='MAMA' and "MIMBA"

My df looks like so

phone       group   County  PNC/ANC Facility Name   Optedout    Facility Code
25470000040 MIMBA   Orange  PNC     Centre            FALSE      101
25470000030 MAMA    Orange  PNC     Centre            FALSE      101
25470000010 MIMBA   Orange  PNC     Centre            FALSE      101
25470000020 MAMA    Orange  PNC     Centre            FALSE      101
25470000050 MAMA    Orange  PNC     Main Centre       FALSE      112

extracting phone numbers from my df

phone_numbers =merged_df.loc[(merged_df['Facility Code'] ==facility_number) & (merged_df['group'] == group) & (merged_df['Opted out'] == optout)]['phone']
print(phone_numbers)

what is currently happening because of the if statement

[25470000010,25470000040]

desired output

[25470000040,25470000030,25470000010,25470000020]

How to apply 2 awks inside an IF condition?

I have a file with the following format:

name   3  4
name  -4  3
name  -5  4
name   2 -4 

I want to make this substruction $2-$3 and to add an extra column at the beginning of my file with the -/+ sign based on the second column to obtain the following format:

   - name  -1  3  4
   - name  -7 -4  3
   - name  -9 -5  4
   + name   6  2 -4 

I used this command

awk '{print $1,$2-$3,$2,$3}' FILE |if ($2 < 0 ) then awk '{print "-",$0}' ; else awk '{print "+",$0}'; fi 

Which giving:

   - name  -1  3  4
   - name  -7 -4  3
   - name  -9 -5  4
   - name   6  2 -4 

I tried to "play" with curly brackets but it seems my condition stops after the first awk. What did I make wrong on my command?

using If/Else statement in ReactJs to return a component

Here is courseButton.jsx:

import React from "react"
import styles from "./styles.module.scss"
import {MenuFoldOutlined, MenuUnfoldOutlined} from '@ant-design/icons'


export default (props) => {
    const {collapsed, onClick} = props

    return (
        <>
            {collapsed ? MenuUnfoldOutlined : MenuFoldOutlined}
        </>
    )
}

Both of my components have the same props. So I want to avoid coding like this:

import React from "react"
import styles from "./styles.module.scss"
import {MenuFoldOutlined, MenuUnfoldOutlined} from '@ant-design/icons'


export default (props) => {
    const {collapsed, onClick} = props

    return (
        <>
            {collapsed ? 
                <MenuUnfoldOutlined className={styles.trigger} onClick={onClick}/> : 
                <MenuFoldOutlined className={styles.trigger} onClick={onClick}/> }
        </>
    )
}

So how I can give the selected component the style in one line code.

I want something like this code.

If else loop over list with conditionals matching a character pattern R

I have a list with several dataframes. I want to write a loop iterating this list and modifying the dataframes based on their title. In general I want to: 1. add a column (trait, protein, metabolite) with their name. my.files is a string with all the names 2. add a column with the calculated standard deviation 3. add a column with the calculated degrees of freedom

for (i in 1:length(list.txt)){
if (i %in% 'Height.txt'){

  list.txt[[i]][,'trait'] <- 'complex' #add trait name
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'SE']*sqrt(list.txt[[i]][,'N'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'N']-2 #add df

} else if (i %in% 'Folkersen*') {

  nam <- paste(my.files[[i]])
  list.txt[[i]] <- assign(nam, list.txt[[i]])
  list.txt[[i]][,'protein'] <- my.files[[i]] #add trait name
  list.txt[[i]][,'N'] <- 3394 #add N
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'SE']*sqrt(list.txt[[i]][,'N'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'N']-2 #add df

}  else {

  nam1 <- paste(my.files[[i]])
  assign(nam1, list.txt[[i]])
  list.txt[[i]][,'metabolite'] <- my.files[[i]] #add trait name
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'se'] *sqrt(list.txt[[i]][,'n_samples'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'n_samples']-2 #add df

}
}

This code returns 'Error in [.data.table(list.txt[[i]], , "se") : column(s) not found: se' and also doesn't recognize 'n_samples'. When these commands are switched off the code returns no errors, but doesn't change anything in the list. I am not sure what i'm doing wrong here, but I assume it has something to do with the conditionals.

Can I write a loop such that it recognizes when a link exists or not?

I am writing a script that goes onto a website and goes through and checks if a specifi item name exists within the site's code.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
import clipboard
import requests
import bs4 as bs
from bs4 import SoupStrainer
from splinter import Browser
import helpers
from selenium.common.exceptions import ElementNotInteractableException
from config import INFO
#This looks for the product based on what the category is 
#Uses the dictionary INFO, which has product information
    def findProduct(self):

        try:
            category =  str(INFO['category'])
            source = requests.get("http://www.supremenewyork.com/shop/all/"+category).text
            soup = bs.BeautifulSoup(source, 'lxml')
            temp_link = []
            temp_tuple = []
            for link in soup.find_all('a', href=True):
                temp_tuple.append((link['href'], link.text))
            for i in temp_tuple:
                if  INFO['product'] in i[1] or INFO['color'] in i[1]: 
                    temp_link.append(i[0])
                    #print(temp_link)

            #This creates end of the final link
            self.final_link = list(
                set([x for x in temp_link if temp_link.count(x) == 2]))[0]


            #Concatenates the previous link w/ the website
            link = 'http://www.supremenewyork.com'+str(self.final_link)
            print(link,end='\n')
            print("Link Copied to Clipboard")
        except IndexError:
            print('Hasn\'t dropped yet...') 


    BOT = Bot(**INFO) #INFO is just a dictionary which has product information
    found_product = False
    counter = 1
    max_iter = 15
    while not found_product and counter < max_iter:
        found_product = BOT.findProduct()
        print("We tried ",counter," times.")
        counter +=1
        print(type(BOT.findProduct()))
        print('Hi')
        if isinstance(BOT.findProduct(), type(None)) == True:
            print('found it')
            break
        else: print('Could not find it')
        continue

I understand that my code will always default to "found it" because the type of the function is the NoneType, but I would like the loop to check whether or not the link that gets copied to the clipboard exists. If it does I want the code to break off.

I have tried

if (print(BOT.findProduct()) == None):
            print('found it')
            break
        else: print('Could not find it')
        continue

And while I understand why it doesn't work, I hope that whoever is reading this can see what I'm going for.

If anyone could help I would greatly appreciate it.

mercredi 29 avril 2020

Create a program using one of the mathematical material and one of the material from physics, but uses 3 basic concepts

is there any material from mathematics and physics that uses the concepts of arrays, if-else, and looping in 1 program from c++ (example), I just need reference material

If-else with print statement is skipping scanner

I have this code here but the if-else statement always skips over my second scanner. What am I doing wrong here? I got Login Debit in my console.

public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
    String returnStatement = "";
    System.out.println("Welcome to Hollow gas station! Please let me know whether you are using a debit card or a credit card:\n"
            + "(1) Debit card \n(2) Credit card\n> ");
    int cardType = keyboard.nextInt();
    System.out.println("Awesome! Please enter your card number here: ");

    String cardNum = keyboard.nextLine();
    keyboard.next();
    if(cardType == 1) {
        returnStatement = String.format("Login\t%s\t%s", "Debit", cardNum);
    }
    else if(cardType == 2) {
        returnStatement = String.format("Login\t%s\t%s", "Credit", cardNum);
    }
    else {
        returnStatement = "Error";
    }
    System.out.println(returnStatement);
}

Multiple condition in pandas dataframe - np.where

I have the following dataframe

Year          M  
1991-1990     10
1992-1993      9

What I am trying to so is a if statement: =IF(M>9,LEFT(Year),RIGHT(C2,4))*1

So basically if M if 10 choose the left value of the column year else choose the second value

I tried using np.where but I have no idea how to choose between two values in the same column.

Help?

Return empty cell instead of 0 in Google Sheets when data being displayed is an array from another sheet

I have a Google Sheet workbook with multiple sheets being used to track COVID-19 cases in institutions across the country. The built-in Google Sheets geo chart works perfectly for the data visualization I need to accomplish, with one issue: It currently can't differentiate between actual 0 and "no data", which super skews how the

chart displays colors

(essentially you can choose what color to use on the map for high value, mid value, low value, and no value. Where it should be using the color for "no value", it uses the low value color instead which makes the visualization confusing.)

The reason it's doing that is the array it's using as its data source contains zeroes to represent "no data available".

The array is imported from a different sheet by using ={'State Totals'!N4:P54}. I found an explanation for how to generally use a formula to return empty cells, the example there being =if(B2-C2>0, B2-C2, " ").

I'm extremely noob when it comes to these formulas, and I cannot figure out if I can nest an IF condition in an array import, or vice versa, or... what or how.

Here's a link to the sheet in question, if that helps at all. Really I just need a formula that

  • Imports the array values
  • Returns empty cells in place of zeroes where they appear

I don't want to affect the origin sheet's zero handling, just the one that the chart's using. (I also am absolutely not being paid enough to try and rig up a better map with Google Data Queries instead of the in-built Google Sheets chart maker, so here's to hoping it's a simple matter of syntax.)

How to test a dynamic substring variable in a conditional in shellscript?

This code check if the last 4 characters of the variable $1 correspond to the string in variable $2 anticipated by a dot.

    if [ "${1: -4}" == ".$2" ]; then
        return 0
    else
        return 1
    fi

// true with $1 = example.doc and $2 = doc
// false with $1 = example.docx and $2 = doc

how can I replace the hardcoded 4 with the following variable $CHECKER_EXTENSION calculated like this?

    LENGTH_EXTENSION=${#2}
    CHECKER_EXTENSION=$(( LENGTH_EXTENSION + 1 ))

Thanks in advance

Google Sheet Script: For Loop with If condition

I have a table with a lot of data from which I want to extract specific data into a separate tab, basically an If formula with a VLOOKUP just in a script. Col 23 is called Decision Meeting with options "Offer" and "Reject", and I want to extract each case that receives an "Offer" into the other sheet. I've written the code below, but for some reason it copies all cases, regardless of the content in (i,23). I hope someone can help:

function Offers() {

  var app = SpreadsheetApp;
  var Active = app.getActiveSpreadsheet().getSheetByName("Active");
  var Test = app.getActiveSpreadsheet().getSheetByName("Test");

  for (var i = 2 ; i<15 ; i++) {

    var DecisionMeeting = Active.getRange(i, 23).getValue();

    if(DecisionMeeting = "Offer"){
      Active.getRange(i, 1).copyTo(Test.getRange(i+2,1));
    }
  }
};

Adding the ID or class into the exact match element

Hi there I am expanding on my previous post: Jquery matching values. I was wondering if anyone knows how to have this also filter the ID or Class as it is doing with the data value. I am trying to build a filter like this in the end and have repeating elements show how many times they are repeated. I use TWIG for the HTML from Advanced Custom Fields Wordpress plugin.

Eventually I want this to be a dropdown like: https://i.stack.imgur.com/I06cT.png you can refer to this post: Building a dropdown select filter. Let me know if you have any direction how i should proceed! Thank you!!

I am also trying to make this sort both alphabetically for the locations and sort by date for the date section. This is the format of the date: February 26, 2020.

HTML:

<div class="filter" name="course-location" id="course-location">
  <div class="upper-filter"><h3>Locations</h3><i class="fas fa-angle-down"></i></div>
  <div class="filter-dropdown">
  
  <div class="class-location type-filter"></div>
  </div>
</div>
<div class="filter" name="course-date" id="course-date">
  <div class="upper-filter"><h3>Start Date</h3><i class="fas fa-angle-down"></i></div>
  <div class="filter-dropdown">
  
  <div class="class-date type-filter"></div>
  </div>
</div>

JQUERY:

  //Location Filter
  // Extract the values to an array
  $("#course-location").each(function() {
    let locations = $('.course-location').map((i, e) => $(e).data('value')).toArray();

    let reducer = (a, c) => {
      // If the city doesn't exist 
      a[c] === undefined ?
        a[c] = 1 : // One occurrence, else
        a[c] = a[c] + 1;  // Increment count
      return a;
    }

    let location_count = locations.reduce(reducer, {});

    // Create HTML Elements
    for (var place in location_count) {
      $('.class-location').append(`<div class="inner-info"><h4>${place}</h4><span>${location_count[place]}</span></div>`)
    }
  });

  //Date Filter
  // Extract the values to an array
  $("#course-date").each(function() {
    let date = $('.course-date').map((i, e) => $(e).data('value')).toArray();

    let reducer = (a, c) => {
      // If the date doesn't exist 
      a[c] === undefined ?
        a[c] = 1 : // One occurrence, else
        a[c] = a[c] + 1;  // Increment count
      return a;
    }

    let date_count = date.reduce(reducer, {});

    // Create HTML Elements
    for (var dates in date_count) {
      $('.class-date').append(`<div class="inner-info"><h4>${dates}</h4><span>${date_count[dates]}</span></div>`)
    }
  });

How do I form conditional statements (if) a value of a variable > another variable's, then conduct an equation using those variables? On R

I'm a beginner to R. I'm using an Excel dataset (which I've already imported onto my Rstudio).

I have two main variables, which are the hit rate and false alarm rates from an n-back task. I've already put them as numerical variables on my imported Excel sheet exactly as one_back_hit_rate and one_back_fa_rate.

I need to figure out

  1. if one_back_hit_rate > one_back_fa_rate , then I'd apply this equation: 0.5 + ((one_back_hit_rate - one_back_fa_rate) * (1 + one_back_hit_rate - one_back_fa_rate))/(4 * one_back_hit_rate * (1 - one_back_fa_rate)) to create a new variable called one_back_aprime.
  2. But if one_back_hit_rate < one_back_fa_rate , then I'd apply this different equation: 0.5 + ((one_back_fa_rate - one_back_hit_rate) * (1 + one_back_fa_rate - one_back_hit_rate))/(4 * one_back_fa_rate * (1 - one_back_hit_rate)) to create the same new variable called one_back_aprime.
  3. And if one_back_hit_rate = one_back_fa_rate , then one_back_aprime = 0

So far the code that I have tried out but isn't working:

nback_mornings_data <- read_excel("New_nback_R_2.xlsx", sheet = 1)
df <- data.frame(nback_mornings_data)

df[,-1] <- round(df[,-1],2)

if(one_back_hit_rate > one_back_fa_rate) {
  df$one_back_aprime <- 0.5 + ((one_back_hit_rate - one_back_fa_rate) * (1 + one_back_hit_rate - one_back_fa_rate))/(4 * one_back_hit_rate * (1 - one_back_fa_rate))
  } else if (one_back_hit_rate < one_back_fa_rate) { 
    df$one_back_aprime <- 0.5 + ((one_back_fa_rate - one_back_hit_rate) * (1 + one_back_fa_rate - one_back_hit_rate))/(4 * one_back_fa_rate * (1 - one_back_hit_rate))
  } else if (one_back_hit_rate == one_back_fa_rate) {
    df$one_back_aprime <- 0.5
  }

Everything up to the if statements runs fine. I'm very sure I'm missing something crucial at the beginning (I'm a beginner again! Just trying to learn) I would REALLY appreciate some help on this!

Note: When I run the code, this error message comes up: Error in if (one_back_hit_rate > one_back_fa_rate) { : missing value where TRUE/FALSE needed I don't have any NA values in my entire dataset, and I'm not using a for loop, therefore I'm not sure how to get around this error. If you have any suggestions on this, I'd really appreciate it!

Are there any loopholes in the JS code below which prevents it fulfilling its statements? [closed]

function trueOrFalse(wasThatTrue) {
  // Only change code below this line
if(trueOrFalse==true){
  return "Yes, that was true";
}
else if(trueOrFalse==false){
  return "No, that was false";  
  }
  // Only change code above this line
}

It is from freeCodeCamp's JS 300 hour curriculum, and its requirements are: 1.trueOrFalse should be a function 2.trueOrFalse(true) should return a string 3.trueOrFalse(false) should return a string 4.trueOrFalse(true) should return "Yes, that was true" 5.trueOrFalse(false) should return "No, that was false"

Wrong IF statement Output

i looped through a list returned by an API and grabbed 1.longName 2. RegularPrice 3.MarketCap which i have done but i want the market cap to return 'billion dollars' if its greater or equals 10 figures also return million dollars if it is less than 10 figures.

import requests
import pprint
import json



url = "https://yahoo-finance15.p.rapidapi.com/api/yahoo/ga/topgainers"

querystring = {"start":"0"}

headers = {
    'x-rapidapi-host': "yahoo-finance15.p.rapidapi.com",
    'x-rapidapi-key': "9efd0f3e52mshd859f5daf34a429p11cb2ajsn2b0e421d681e"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json()

#print(response.text)


def new_stock(data):
    new_market = []

    for item in data ['quotes']:
        new_name = item.get ('longName')
        new_price = item.get ('regularMarketPrice')
        res_price = (f'{new_price} Dollars')
        cap =item.get('marketCap')
        cap2 = str(cap)
        for i in cap2:
            if i == 1000000000:
                return(f'{cap2} Billion Dollars')
            else:
                return(f'{cap2} million Dollars')
        return cap2



        new_market.append((new_name, res_price, cap2))

    return new_market

value = new_stock(data)
dict = {i: value[i] for i in range(0, len(value))}
print(dict)

so i want a dictionary like

{Wienerberger AG', '4.38 Dollars', '2607606784 Billion Dollars} or {EPR Properties', '31.62 Dollars', '246636006 million Dollars}

How to edit variable globally python

I am working on a python library. I have a function, moveTrack(fileorvar, track_code, x, y). Right now I have the track_code, x, and y arguments working. What fileorvar does is it decides if you are editing a variable or a file, in which case the function will have to open said file. I am doing this in this way:

def moveTrack(self, fov, track_code, x-coord, y-coord):
    print((lambda c,n,x,y,l:'#'.join([','.join([(lambda o:' '.join([(lambda m:(lambda p,v:'0'if p==0else(('-'if v else'')+''.join([n[((p//(32**q))%32)]for q in range(int(l.log(p,32))+1)][::-1])))(abs(m),(m<0)))(int(m,32)+x if(t!=2and j%2==0)or(t==2and j%2==1)else int(m,32)+y)if(t!=2or j!=0)else m for j,m in enumerate(o)if m!='']))(i.split(' '))for i in d])for t,d in enumerate(c)]))([a.split(',')for a in track_code.split('#')],list('0123456789abcdefghijklmnopqrstuv'),int(x-coord),int(y-coord),__import__('math')))

The self argument is necessary but not used at all by the user. I want to have an if/else statment inside of it like this:

def moveTrack(self, fov, track, x-coord, y-coord):

    if fov == 'f':
        track_code = open(track_code, 'r')
    else:
        track_code = str(track)

    print((lambda c,n,x,y,l:'#'.join([','.join([(lambda o:' '.join([(lambda m:(lambda p,v:'0'if p==0else(('-'if v else'')+''.join([n[((p//(32**q))%32)]for q in range(int(l.log(p,32))+1)][::-1])))(abs(m),(m<0)))(int(m,32)+x if(t!=2and j%2==0)or(t==2and j%2==1)else int(m,32)+y)if(t!=2or j!=0)else m for j,m in enumerate(o)if m!='']))(i.split(' '))for i in d])for t,d in enumerate(c)]))([a.split(',')for a in track_code.split('#')],list('0123456789abcdefghijklmnopqrstuv'),int(x-coord),int(y-coord),__import__('math')))

This will not work. this is because when I edit track_code, it only saves inside that function. I know I can fix this by putting the one-liner inside of each of the if/else statements. I would, however, like to avoid this to improve readability. Any help is greatly appreciated, thanks!

JAVA ~ if-else block doesnt work as expected [closed]

ok so this time i want to make a program that takes the data of some people (name, salary, sex etc) and shows them on the screen. there are two classes, a Person and its subclass MarriedPerson. Person goes like this:

public class Person
{
    //[...]
    private float salary;
    //[...]
    public static final int MALE=0;
    public static final int FEMALE=1;  
    private int sex;
    //[...]}

MP has a method named setSalary that takes a MarriedPerson variable and return void. the purpose of this is that, if the variable has the different sex from the object, then it returns the objects salary plus the variable's salary, but if the sexes are the same, then nothing happens. kinda home of phobic i know but whatever i just want to pass this class

after struggling with this my prof suggested i try this:

public void setSalary(MarriedPerson spouse)
        {        
          float x;
          if (getSex() != spouse.getSex()) 
          x=this.getSalary()+spouse.getSalary();
        }

however, when i run the program, no matter the sex of the variable, the salary returned is always the same! for example, for these three:

   MarriedPerson mp1 = new MarriedPerson(980.5f, Person.FEMALE);
   MarriedPerson mp2 = new MarriedPerson(2080f, Person.MALE); 
   MarriedPerson mp3 = new MarriedPerson(600f, Person.FEMALE);

   mp1.setSalary(mp2);
   mp1.printInfo();

   mp1.setSalary(mp3);
   mp1.printInfo();

im expecting two messages like:

mp1 has a salary of 3060.5 $ //980.5+2080
mp1 has a salary of 3060.5 $ //both female, so its the same as before

but instead i get this!

mp1 has a salary of 980.5 $ 
mp1 has a salary of 980.5 $

as if nothing happens! why!!

if statements in iteration over column in pandas dataframe

I want to iterate through the columnn df['Social Distancing Advisory'] and replace various elements by another, but nothing seems to work when I set it up like this.

df looks like this State Social Distancing Advisory Date (effective) status new order until details


import pandas as pd 

df = pd.read_excel('/Users/Arthur/Desktop/COVID-RA/state_data.xlsx')

for column in df['Social Distancing Advisory']:

  if df['Social Distancing Advisory'] == 'sah':
    df['Social Distancing Advisory'].replace('sah','1')

  if df['Social Distancing Advisory'] == 'sip':    
    df['Social Distancing Advisory'].replace('sip','0')
df

Laravel Factory Conditonal statement

I currently have the following code in my posts factory and would like to fill the user_id field with the id of users with the role of writers in my users table.

$factory->define(Post::class, function (Faker $faker) {
   return [
       'title'      => $faker->sentences(1, true),
       'body'       => $faker->sentences(3, true),
       'user_id'    => function() use ($faker) {
           if (User::count())
               return $faker->randomElement(User::pluck('id')->toArray());
           else return factory(User::class)->create()->id;
       },
   ];
});

any help on how to implement this will be appreciated.

How to create a group of constants and check if a variable is or isn't included in that group?

I want to create an if code to check if variable x is a member of a defined group of constant named a, for example a = { 1 , 2 , 3 , 4 }, then use something like if (x != a).

I only know to use it like this if ( ( x != 1 ) || ( x != 2 ) || ( x != 3 ) || ( x != 4 ) )

How do I write a script that writes scripts if a file has the .iso extention in linux?

So i'm trying to make executables for games with an .iso extention, so I can add them to steam directly, but I didn't feel like writing every individual one manually, so I wrote a script to do it for me:

    #!/bin/bash

for file in "$/media/dexterdy/d60690f8-0511-44bf-aa66-b8a211460113/samsung/gamecube/"; do
    if [ ${file: -4} == ".iso" ]
    then
        cat > ${file}.sh << EOF
        dolphin-emu --batch --exec="/media/dexterdy/d60690f8-0511-44bf-aa66-b8a211460113/samsung/gamecube/${file}"
EOF
    fi
done;

If I run it, I don't get any error messages, but it also doesn't generate any files. I think it has to do with the if statement ([ ${file: -4} == ".iso" ]), but I'm not sure. It could also be because the .iso files have spaces in their names.

P.S. Im new to writing scripts and coding in general. This is my second script I've ever written, so it would be appreciated if the explanations aren't too complicated.

Search if all string in .txt

I am trying to run a program to look at a .txt file and if, else depending on the content

I thought would be

Searhterms = [A, B]
with('output.txt') as f:

    if ('A' and 'B') in f.read():
        print('mix')
    eLif ('A') in f.read:
        if ('B') not in f.read:
            print('ONLY A')
    elif ('B') in f.read():
        if ('A') not in f.read:
            print('ONLY B') 
    else:
        if ('A' and 'B') not in f.read:
            print('NO AB)

But if A and B present it works, but if only one it skips to the else. I am getting more confused about the longer I look at this.

When I type the trigger string the if statement just closes the Command Prompt (batch)

I made this fake hacking console, and when I type help, the if statement doesn't work?

@echo off
title Hacking Console
color 0a
:start
cls
echo Hacking Console, Unpatched, 2020
echo Type help for Help
echo.
set /p cmd = C://User/user/Windows/portaccess/set/

if %cmd% = "help" {
    echo Help Menu
    echo access.database.19223 Accesses the database of the U.S. army
    echo access.files.19223 Accesses the files of the U.S. army
    echo ddos.19223 DDoS the U.S. army
    echo bank.get.usd Gets a amount of money up to 100.000.000 USD
    echo help Gets Help 
    pause
    goto start
}


echo UNKNOWN SYNTAX. TYPE help FOR HELP
timeout /t 3 /nobreak
goto start

pause

Strings from the same source, imported in the same way, not registering as the same string? [duplicate]

So I am making a "restaurant management tool" and one of the classes' function is to manually enter the amount of an ingredient you have. It imports a list of stored ingredients from a .txt file and puts them in a JComboBox. When the button is pressed, it goes through the same file again, finds the selected option and replaces its quantity with the one that is written in the JTextField by the user.

For some reason, it is not entering the if statement. I have no idea why the two Strings would be different, as they come from the same source and they are imported in the same way (except for one of them going through a JComboBox first).

Here's my code (I put an arrow next to the part in question, I just thought the problem might be coming from somewhere else):

import java.io.*;
import java.nio.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Toolkit;

public class EditStock implements ActionListener{
    private static JLabel header;
    private static JFrame f;
    private static JComboBox optList;
    public static boolean authorized;
    public static JButton subB;
    private static JTextField amT;
    private static Scanner sc3;
    private static String token1;
    private static int n;
    private static Scanner sc4;
     public static void EditStockfunc() throws IOException{
        File stock = new File("C:\\Users\\liker\\OneDrive\\New\\new new\\Computer Science\\IA\\stock.txt");
        Scanner sc = new Scanner (stock);
        Scanner sc2 = new Scanner (stock);
        sc3 = new Scanner(stock);
        sc4 = new Scanner(stock);
        token1 = "";

        JPanel p = new JPanel();
        f = new JFrame("RMT 1.0");
        f.setSize(250,200);
        f.setLocation(1080,530);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.add(p);

        header = new JLabel("Which quantity would you like to change?");
        header.setBounds(10,20,80,25);
        p.add(header);



        int x = 0; 
        while(sc.hasNext()){
            x+=1;
            token1 = sc.nextLine();
        }               
        String[] temp = {""};
        String[] options = new String[x];

        x = 0;
        while(sc2.hasNext()){         
           token1 = sc2.nextLine();                   
           temp = token1.split(",");
           System.out.println(temp[0]);
           options[x] = temp[0]; 
           x+=1;
         }     

        optList = new JComboBox(options);
        optList.setBounds(75,35,100,25);
        optList.setSelectedIndex(0);
        p.add(optList);                      

        JLabel tLabel = new JLabel("Correct amount:");
        tLabel.setBounds(10,20,80,25);
        p.add(tLabel);
        amT = new JTextField(20);
        amT.setBounds(100,20,165,25);
        p.add(amT);
        subB = new JButton("Submit");
        subB.setBounds(150,150,80,25);
        subB.addActionListener(new EditStock());
        p.add(subB);
     }
    @Override
    public void actionPerformed(ActionEvent e){
       File stock = new File("C:\\Users\\liker\\OneDrive\\New\\new new\\Computer Science\\IA\\stock.txt");
       int a = Integer.parseInt(amT.getText());
       String o = (String)optList.getSelectedItem();               
       int x = 0; 
       while(sc4.hasNext()){
            x+=1;
            token1 = sc4.nextLine();
        }               
       String[] temp = {""};
       String[] options = new String[x];
       x = 0;
       while(sc3.hasNext()){                   
           token1 = sc3.nextLine();                   
           temp = token1.split(",");           
           System.out.println(temp[1]);
           if (o == temp[0]){ <---------------------- This part
               temp[1] = Integer.toString(a);
           }           
           System.out.println(temp[1]+o+temp[0]+a);
           options[x] = temp[1]; 
           x+=1;

        }

    }
}

And here's my .txt file:

Tomato,15
Potato,23
Spagetti,8
Beef,10

if else condition not working as expected in python's scipy code

I'm defining a function for solving my differential equations in scipy's solve_ivp.

def conv(t,Z):
    global sw,von,X

    if sw==0 and X[1]>=von or sw==1 and X[0]>0:
            zdot=LA.inv(v1).dot(A1).dot(v1).dot(Z).reshape(4,1)+LA.inv(v1).dot(B1).dot(U)
            sw=1
            von=0.7
            X=v1.dot(Z)
    else:
            zdot= LA.inv(v0).dot(A0).dot(v0).dot(Z).reshape(4,1)+LA.inv(v0).dot(B0).dot(U)
            sw=0
            X=v0.dot(Z)
    return np.squeeze(np.asarray(zdot)) 

and solving my equation using

sw=0
e1,v1=LA.eig(A1)
Z= np.array([0, 0, 0, 0])
X=v1.dot(Z)
U = np.array([[vin], [vdon]])
Z0= np.array([0, 0, 0, 0])
V=v1
sol = solve_ivp(conv, tspan,Z0,method='Radau')

Initially as sw=0 and X =[0,0,0,0] , I expect the if condition to be satisfied and the if block to be implemented. But the program is executing the else block.I'm not able to understand the problem.

If else (set maximum to end at a set value)

How can I set a loop to run to a maximum value (Dend)? I just want to see how fast and deep it will grow but I want to set a maximum to say that it can't grow beyond Dend.

I get an error stating

  In if (D == Dend) { :
   the condition has length > 1 and only the first element will be used

Code

 D0 <- 0 
 Dend <- 4200

 r <- 5 growth rate

 days <- 1000 
 n_steps <- days*1 


 D <- rep(NA, n_steps+1)
 D <- D0

  for (time in seq_len(n_steps)){  
   if (D == Dend){
   break}  else
    D[time + 1] <- r + D[time] 
   }

   D

   plot(-D, las=1)

Python: Why is "else" statement not accepting a string?

I am trying to calculate average daily windspeed from a file with hourly windspeed. To do this I am using for loops to identify month&day combinations and then analyze the hourly wind data from each calendar day. The hourly data either has a positive value, or -999 if the data is missing. I wrote the following line of code, which successfully filters out any missing data during a 24 hour period and returns the average for the day:

Average_WindSpeed = sum(row[1] == m and row [2] == d and float(row[4]) if float(row[4]) > -999 else 0 for row in reader)/24

My issue is that the else condition of the code will only let me enter a number. If I enter something like else: 'Missing' I get a TypeError: unsupported operand type(s) for +: 'int' and 'str' message. I know that the TypeError means that there is some combination of numbers and sting that is incompatible, I just don't understand how its occurring in an else statement. I am trying to set up the if statement so that if all 24 hours in the day are -999, else will return "Missing". The code works with the else: 0 place holder that I have put in, however, the numerical value that I am having to pass is erroneous. This is the pertinent section of code within a larger project:

import csv

print("Month", "Day", "WindSpeed")
months = ['01']

for m in months:
    if m == '01' or m =='03' or m == '05' or m == '07' or m == '08' or m == '10' or m == '12':
         dates = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
         for d in dates:

             # Calculate average daily windspeed from hourly data
             with open('samplehourlydata.txt', 'r') as f:
                reader = csv.reader(f)
                next(reader)
                Average_WindSpeed = sum(row[1] == m and row [2] == d and float(row[4]) if float(row[4]) > -999 else 0 for row in reader)/2
                print(Average_WindSpeed)

If it helps, here's some sample data:

yyyy,mm,dd,hour,W Speed
1941,01,01,00,-999
1941,01,01,01,-999
1941,01,01,02,-999
1941,01,01,03,-999
1941,01,01,04,-999
1941,01,01,05,-999
1941,01,01,06,-999
1941,01,01,07,-999
1941,01,01,08,-999
1941,01,01,09,-999
1941,01,01,10,-999
1941,01,01,11,-999
1941,01,01,12,-999
1941,01,01,13,-999
1941,01,01,14,-999
1941,01,01,15,-999
1941,01,01,16,-999
1941,01,01,17,-999
1941,01,01,18,-999
1941,01,01,19,-999
1941,01,01,20,-999
1941,01,01,21,-999
1941,01,01,22,-999
1941,01,01,23,-999
1941,01,02,00, 9.2
1941,01,02,01,11.5
1941,01,02,02, 9.2
1941,01,02,03,11.5
1941,01,02,04,11.5
1941,01,02,05, 8.1
1941,01,02,06, 9.2
1941,01,02,07,11.5
1941,01,02,08, 9.2
1941,01,02,09,10.4
1941,01,02,10,12.7
1941,01,02,11,13.8
1941,01,02,12,11.5
1941,01,02,13,10.4
1941,01,02,14,11.5
1941,01,02,15,11.5
1941,01,02,16,10.4
1941,01,02,17, 6.9
1941,01,02,18, 5.8
1941,01,02,19, 9.2
1941,01,02,20,10.4
1941,01,02,21,11.5
1941,01,02,22, 4.6
1941,01,02,23, 9.2

Also, I know that there are other ways to do this such as possibly setting up a dictionary, or using numpy, however I'm really trying to understand this "else" situation. Thanks.

List function with if statement [duplicate]

book = Python Crash Course by Eric Matthes page no. 133 problem = Checking That a List Is Not Empty i don't understand how this work

➊ requested_toppings = [] ➋ if requested_toppings:

how if requested_toppings works for non empty list. please explain

mardi 28 avril 2020

How do I properly set these conditionals in Python?

I am VERY new to coding in general so this may come across as a stupid question.

Right now I am experimenting with conditional statements and trying to code a little decision based two-way path in the style of a text game, where the user is given two options and each option has a different outcome. Right now, the "if True" string is ALWAYS executed in the console, regardless of what the user types in. Why is this happening and how can I rewrite it to make the command happen correctly? Also, I thought I followed the instructions for pasting code here but it doesn't look quite right.

input ("Type 'left' if you want to go left and 'right' if you want to go right"

right = True 
left = False 

right = "right"
left = "left"

if True:
    print("You have been eaten by a monster. Game Over!") 
else:
    print("Congratulations you have made it to the castle!")
else:
    print("Error")```

cannot resolve method value?


public class week2 {
    public static int numbers(int x, int y) {
        int value = x - y;
        System.out.println("Value is " + value + ".");
        return value;
    }


    public static void main(String[] args) {
        numbers(20,10);
        if(value == 1)
        {
            System.out.println("yo");
        }
        else{
            System.out.println("whatsup");
        }

    }
}

Why does the line if(value == 1) show the error that value cannot be resolved? Didn't I mention that value = x-y in my method? edit: ahh thank you guys I did not know that you can't access value outside the method

My function is not invoked in another function

I'm trying to get my function to determine singular and plural errors. I wrote two functions in the global scope to be called in the main function called errorChecker but it refuses to execute. I'm wondering why? and what it is I am doing wrong. I am really new to coding so, please understand. below is the code. it does not run hence the errorChecker function does not detect the errors.

function errorChecker (num1, word1, num2, word2) {
  if (num1 === Number(num1) && word1 === String(word1) && num2 === Number(num2) && word2 === String(word2)) {
    console.log('all parameters are ok')
  } else {
    return false
  }
  if (wordChecker(word1) === true && (wordChecker(word2) === true)) {
    return true
  } else {
    console.log('invalid parameter')
  }
  if (singularChecker(num1, word1) === false && (pluralChecker(num2, word2) === false)) {
    console.log('correct singular and plurals')
  } else {
    return true
  }
}
// For checking function effectiveness
const num1 = 1
const word1 = 'minutes'
const num2 = 2
const word2 = 'minute'

console.log(errorChecker(num1, word1, num2, word2))
// function to set exact word parameters that can be used
function wordChecker (word) {
  switch (word) {
    case 'seconds':
    case 'second':
    case 'minutes':
    case 'minute':
    case 'hours':
    case 'hour':
    case 'days':
    case 'day':
      return true
    default:
      return false
  }
}

function pluralChecker (digit, letters) {
  switch (letters.toLowerCase()) {
    case 'seconds':
    case 'minutes':
    case 'hours':
    case 'days':
      if (digit !== 1) {
        return true
      } else {
        return false
      }
  }
}

function singularChecker (numz, wordz) {
  switch (wordz.lowerCase()) {
    case 'second':
    case 'minute':
    case 'hour':
    case 'day':
      if (numz === 1) {
        return true
      } else {
        return false
      }
  }
}

VBA Question: Running iterations using multiple for loops and exit once a certain condition has been made

I need help with my code, please.

I am running through a list defined in range M9:M53 using a VBA command button. I am Copying the first value in the list into a different cell in the same sheet, then I have formulas that generate calculations and output a value in cell K24.

This is a linear relationship, the more I go through the range the closer I get to exceed number 5. The idea is that I want the Loop to get as close to 5 before exceeding it. So a part of the missing component would be checking through the list, and copying the right number. So if M15 is the first cell value to be greater than 5, then I would want to copy the previous cell number M14 and leave it on the cell I6

The next part of the code that is missing would be a loop that must occur before I pass from each value in range M9 to M54.

Grab Value in Cell F5, and start subtracting 1. For example, it will the cell has input value 10, then it will check K24 if K24 is greater than 5, then it will subtract 1 again, and so on. if the K24 value is finally less than 5, then it will exit the LOOP completely and the program would have completed its function. ******

This number directly affects the result in K24 which checks for being less than 5. It should stop the closest that it can to generating a result that K24 than is less than 5, without exceeding it.

An Additional condition to step out of this loop and go onto the next value in list M9:M54 Range would be

Checking that the value in Cell A7 is greater than 13.5. Going lower would mean skipping to the next value in range M9:M54

One additional and final condition would be to check for Cell Value G5 being less than or equal to 120.

For example. If copying M15 yields and answer for K24 that is less than 5, but cell G5 still yields over 120, then it should still skip to next value in the M range, M16.

Below a portion of the loop which needs a lot of work.


Private Sub CommandButton1_Click()

Dim Cell As Range

For i = 9 To 53 Range("M" & i).Copy Range("I6")

If Range("K24").Value < 5 Then

Exit Sub

End If Next Application.CutCopyMode = False

End Sub

Loop with If-statement runs slow, too slow

I am new to JavaScript. I use it to write some scripts for Adobe Illustrator. In this script I take a selection of items, and sub-select them by some user definded values (xPointMin, xPointMax, etc.). The loop below is the main part of the function.

My problem is that this loop is terribly slow. It takes several sec. to run a selection of 50 items.

I already tried the following:

  1. run the loop without any if-condition inside. This is fast.
  2. run the loop with only one if-condition inside. This is as fast as with all if-conditions.

Does someone know why it is so slow or can some just make it faster.

// xArray... are extracted vales from the Selection (xSel)
// xPointMin, xPointmax, xLengthMin, xLengthMay, xAreaMin, and xAreaMax are user defined values

for (var i in xSel) { // xSel is a list of selected items
  var xTF = true; // xTF is temporary variable

  // points // this will check if the given value (xArrayPoint) is within the requirements
  if (xArrayPoint[i] <= xPointMin || xArrayPoint[i] >= xPointMax) {
    xTF = false; // if so it sets the temporary variable to false
  }

  //length // same as in the first check, however we are testing the length
  if (xArrayLength[i] <= xLengthMin || xArrayLength[i] >= xLengthMax) {
    xTF = false
  }
  //area // same as in the first check, however this time we are testing area
  if (xArrayArea[i] <= xAreaMin || xArrayArea[i] >= xAreaMax) {
    xTF = false
  }

  xSel[i].selected = xTF; // changes the original value
}
}

android :How to change color of text of counter app after ( 33,66,99,elc ) clicks?

How to change counter when is 33,66,99,elc ??

the project is here on githup https://github.com/hamza94max/Counter

any one can help me ?


public class MainActivity extends AppCompatActivity {
    TextView textView;
    private int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.countertext);
        reset=findViewById(R.id.reset);
        RelativeLayout relativeLayout=findViewById(R.id.reltivee);



        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter++;


                    textView.setText(Integer.toString(counter));
                    textView.setTextColor(Color.BLACK);


                }
        });


    }}

How to implement if loop inside switcher of python

I want to know how to use if loop or nested if loop inside a switch case or rather switcher case inside python.

comparing two variables in c++

learning c++ and I'm sure I'm overlooking something obvious but I'm not sure why I dont get a message that i == j even though after the 3rd iteration the numbers are the same ?

This is the output:

8 is not equal to 12

9 is not equal to 11

appreciate any hints!

#include<iostream>

int main(){

   int i=8;
   int j=12; 

   for (i,j; i!=j; ++i, --j)
   {    
   if (i == j) 
        {     
         std::cout << "i = j" << "\n";   // this part doesnt work
         break;
        }
   else 

        std::cout << i <<" is not equal to " << j <<"\n"; 

   }
}

Power Query: how to add one to a column when a specific values appear in an other column

I have an ID column and I am looking for ways to increment my IDs each time a specific item appears in my Geography column (ItalyZ, ItalyM, UKY or UKM) is found.

The ID of ItalyZ starts at 0 and ends at 4000.

The ID of ItalyB starts at 4000 and ends at 8000.

The ID of UKY starts at 0 and ends at 4000.

The ID of UKM starts at 4000 and ends at 8000.

However, I am refreshing my file, and I will thus have from time to time new arrivals of "geographies" without the origins or first IDs. These boundaries/ranges are only known beginning and ends.

Here is a sample of my data:

  |---------------------|------------------|    
  |       ID            |   Geography      |
  |---------------------|------------------|
  |    AB0000           |      ItalyZ      |
  |---------------------|------------------|
  |    AB4041           |      ItalyB      |
  |---------------------|------------------|
  |    BC0000           |      UKY         |
  |---------------------|------------------|
  |    BC4001           |      UKM         |
  |---------------------|------------------|
  |    NULL             |      ItalyZ      |
  |---------------------|------------------|
  |    NULL             |      ItalyZ      |
  |---------------------|------------------|
  |    NULL             |      UKY         |
  |---------------------|------------------|
  |    NULL             |      UKM         |
  |---------------------|------------------|  

Here is my expected output :

  |---------------------|------------------|    
  |       ID            |   Geography      |
  |---------------------|------------------|
  |    AB0000           |      ItalyZ      |
  |---------------------|------------------|
  |    AB4041           |      ItalyB      |
  |---------------------|------------------|
  |    BC0000           |      UKY         |
  |---------------------|------------------|
  |    BC4001           |      UKM         |
  |---------------------|------------------|
  |    AB0001           |      ItalyZ      |
  |---------------------|------------------|
  |    AB0001           |      ItalyZ      |
  |---------------------|------------------|
  |    AB4042           |      UKY         |
  |---------------------|------------------|
  |    BC0001           |      UKM         |
  |---------------------|------------------|  

I have been trying many various ways and trying to adapt running total solutions. I have also been trying to break apart my file in four different ones in order not to have an If function alternating between cases, and thus making it simpler, like this in my power query:

 #"Added Custom2" = Table.AddColumn(#"Reordered Columns", "Sum", each if [Geography] = "UKM" then [Number AB range below 4000] + 1 
else if [Geography] = "UKY" then [Number AB range above 4000] + 1 
else if [Geography] = "ItalyB" then [Number BC range above 5000]
else [Number BC range below 5000] + 1)

But absolutely nothing works. This maddening.

Populate a column in R [using if statements?] based on variable in another column

A seemingly simple task that I am struggling with:

I collected behavior data and have a column ("Behavior") in which I recorded what behavior is taking place. I would like to group these behaviors into categories and fill in a column ("BehaviorGroup") with the category name.

An example of how this might look:

Behavior      BehaviorGroup
bite          aggressive contact
ram           aggressive contact
avoid         avoid
fast-approach aggressive approach
flee          avoid
fast-approach aggressive approach

etc. 

So I would like to use the behaviors listed under the Behavior column (which I already have) to fill in the BehaviorGroup column (which is currently empty) based on the category.

For the example above: "bite" and "ram" are "aggressive contact" "avoid" and "flee" are "avoid" "fast-approach" is "aggressive approach"

I have MANY more but I'm hoping this is enough to get started on how to tackle the code to do this! I would greatly appreciate any and all help with this!

Here's code for what I would be working with, based on the example given:

Behavior <- c("bite", "ram", "avoid", "fast-approach", "flee", "fast-approach")
BehaviorGroup <- c("NA", "NA", "NA", "NA", "NA", "NA")
data.frame(Behavior,BehaviorGroup)

I'm just trying to fill in the BehaviorGroup column Thank you in advance!

Joptionpane and equalstoignorecase is giving me an invalid output

My JOption Pane show messagedialog keeps on giving me a weird output. My if else statement with equalstoignore also doesnt work. The JOptionPane is giving me a long pane with text such as Name:Javax.swing.JtextField[,0,18,294,19,invalid,layout.............. and its so long i. it doesnt output my desired output like i use on toString.


    public static void main(String[] args)
    {
        ArrayList<PreSchool> PSList = new ArrayList<PreSchool>();
        JTextField  field1 = new JTextField();
        JTextField  field2 = new JTextField();
        JTextField  field3 = new JTextField();

        Object[] fields = {
            "Please Enter Name:",field1,
            "Please Enter Race(Malay/Chinese/Indian):", field2,
            "Please Enter Age:", field3
        };

        for(int i = 0; i < 5;i++){
            JOptionPane.showConfirmDialog(null, fields,"Enter Information for Children " + i,JOptionPane.OK_CANCEL_OPTION );
            String name = field1.toString();
            String race = field2.toString();
            int age = Integer.parseInt(field3.getText());
            PSList.add(new PreSchool(name,race,age));
        }

        StringBuilder builder = new StringBuilder();
        builder.append("Index: 0\n");
        builder.append(PSList.get(0).toString());
        builder.append("Index: 1\n");
        builder.append(PSList.get(1).toString());
        builder.append("Index: 2\n");
        builder.append(PSList.get(2).toString());
        builder.append("Index: 3\n");
        builder.append(PSList.get(3).toString());
        builder.append("Index: 4\n");
        builder.append(PSList.get(4).toString());

        JOptionPane.showMessageDialog(null,builder);

        int malay =0;
        int chinese = 0;
        int indian = 0;
        for(int i = 0; i < 5; i++)
        {
            if(PSList.get(i).getRace().equalsIgnoreCase("Malay"))
            {
                malay++;
            }
            else 
            {
                if(PSList.get(i).getRace().equalsIgnoreCase("Chinese"))
                {
                    chinese++;
                }
                else
                {
                    indian++;
                }
            }

        }
        JOptionPane.showMessageDialog(null,"Number of Malay:" + malay + "\nNumber of Chinese:" + chinese + "\nNumber of Indian:" + indian);


    }


}

Here is my Object class

    String name;
    String race;
    int age;

    public PreSchool()
    {
        name = " ";
        race = " ";
        age = 0;
    }

    public PreSchool(String n, String r,int a)
    {
        name =n;
        race =r;
        age = a;
    }

    public String getName() {
        return name;
    }

    public String getRace() {
        return race;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Name:" + name + ", race:" + race + ", age:" + age + '\n';
    }


}

Tax calculator in javascript

How do I split the result for the income tax brackets to auto display the right tax due when the gross pay affected is in a particular tax bracket.

Income Tax Bands    Tax Rates     Tax Due
3,300.00 and Below         0%        0
3,300.01 – 4,100.00        25%       0
4,100.01 – 6,200.00        30%       0
6,200.00 and Above         37.5%     0

Undefined element of forEach inside if condition [closed]

I try to make next code:

if(parseInt(e.target.value) === 1){            
            e.target.nextSibling.childNodes.forEach(element => {
                element.classList.add('disable')
            });            
        }
        else if(parseInt(e.target.value) === 2){
            e.target.nextSibling.childNodes.forEach(element,index => {
                index === 0 ?
                element.classList.remove('disable')
                :element.classList.add('disable')
            });
        }

and in second condition it throw me error 'element' is not defined but in first it works fine. But I cant understand why if statment make my element is undefined?

Is it possible to have multiple conditions in a function which includes a for loop in Python?

I'm new to programming with Python. Currently, I'm working on a program/algorithm to determine maintenance (combined replacement of multiple items) based on these items their condition. To be precise, I want to replace these items when one item's condition is below a predetermined threshold (for example 10%). The problem I have with my code, see below, is when this threshold is met all items are replaced.

def maintenance_action(self):
    do_repair = False
    for i in item:
        if i.condition[-1] <= 10:
            do_repair = True     
            break

    if do_repair:
        for i in items:
            i.repair()

However, I want to include an additional threshold (let's say 50%) which excludes all items with a condition > 50% from the maintenance action. It is important that the first threshold is met (because this item must be replaced) before the second one 'kicks in' (the items I want to include). I hope someone can help me.

Thanks!

Is there any mistake in my condition statement? [closed]

These are my snipped code below. When i input 2, which is the feline type, it was supposed to either output Feline doesnt want to roam at all today if the feli is 0 or Roaming for total range of 0 in 12 minutes if the feli is not 0. But, in my output which i attached the picture below, it also prints the roaming for total range of 0 in 12 even if the feli is zero. Is there any mistake on my condition statement? Any help is appreciated. Thank you.

void take(){
        int choose;
        int roam;
        int roaming;
        int p = anm.nama.size();
        if(p==0){
            view();
        }
        else{
            view();

            do{
                System.out.print("Choose animal to take for a stroll [1 - " + p+ "]: ");
                choose = scan.nextInt();
            }while(choose<1||choose>p);

            do{
                System.out.print("Roaming time [0-50]: ");
                roam = scan.nextInt();
            }while(roam < 0 || roam > 50 );

            if(roam==0)roaming = 60;
            else roaming = roam;

            for(int i=0; i<anm.nama.size(); i++){
                if(fel.genuss.get(i).equals("feline")){
                    int batas = 2;
                    Random rand = new Random();
                    int feli = rand.nextInt(batas);

                    if(feli == 0){
                        System.out.println("Feline doesn't feel like roaming at all today..");
                        break;
                    }
                    else{
                        int duration = 0;
                        if(roaming == 30)
                            {
                            duration = 30;
                            System.out.println("Roaming for total range of " + anm.range() +" in " + duration +" minutes");
                            }
                        else System.out.println("Roaming for total range of " + anm.range() +" in " + duration +" minutes");
                        break;
                    }
                }


                else if(can.genuss.get(i).equals("canine")){
                    int duration = 0;
                    if(roaming==0)
                        {
                        duration = 60;
                        anm.range();
                        System.out.println("Roaming for total range of " + can.range() +" in " + duration +" minutes");
                        }
                    else duration = roaming;
                    anm.range();
                    System.out.println("Roaming for total range of " + can.range() +" in " + duration +" minutes");
                }
            }
        }


    }

This is my output

what's the difference on dealing char between where statement and if statement in SAS 9.4M6

Recently, I happen to find an interesting thing:

data test;
    set sashelp.class;
    if _N_ in (2 3 5 7) then name = '';
run;

data test;
    set ;
    where name;
run;

The result is: data Test has 15 observations.

I use SAS 9.4M6 for over a year and don't remember that where statment can deal with char type variable just like boolean type variable. I strightly change where to if and it leads the results: name is not a numeric variable and data Test has 0 observation.

So here is my two questions:
1. Is where name; another way of where name is not missing? if not, what happens when submitwhere name?
2. When did this kind of code(where <variable>;) start be allowed in SAS?

Thanks for any tips.

I am stuck in "If" & "Else" function one of my android app

I my app I am fetch some text data from the server and showing this text data in the TextView. Here is something works fine. I am add an little arrow ImageView right to the TextView and this TextView is expandable so when TextView is more then 2 lines and if anyone click this TextView it expand and again click to shrink and I am also add an little arrow image right to the TextView (so user understant that it is an expandable text), here is everything is fine all code are works perfectly but now I want to remove this litter arrow image when the TextView is under 2 lines and when TextView is more then 2 lines it show. I want to tell you one more thing that I am also add a rotation in the arrow image so when the user click the text the little arrow image rotate the 180 degree and also text is expand and when user click the text second time arrow image again rotate to his previous position and text is shrink in 2 lines.

I want to remove this little arrow when the text is under 2 lies I do not want to remove the arrow image when text line more then 2, I'm guessing you understand.

I am new to the Java Code and I am learning is language so now I want to learn how to do this implementation in my app, I have add my code below so that you can understand batter.

textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
my_title_layout_expand.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    if (isTextViewClicked) {
      //This will shrink textview to 2 lines if it is expanded.
      textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
      myTitleImageView.setRotation(imageView.getRotation() + 0);
      myTitleImageView.setVisibility(View.VISIBLE);
      textViewMyVideoTitle.setMaxLines(2);
      isTextViewClicked = false;
    } else {
      //This will expand the textview if it is of 2 lines
      textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title());
      myTitleImageView.setRotation(imageView.getRotation() - 180);
      myTitleImageView.setVisibility(View.VISIBLE);
      textViewMyVideoTitle.setMaxLines(Integer.MAX_VALUE);
      isTextViewClicked = true;
    }
  }
});

So anybody can help me to achieve this code

enter image description here enter image description here

To understand %*d and if (( scanf( "%d", &n ) != 1 ) || ( n <= 0 )) in c

I have to print this pattern in c

4 4 4 4 4 4 4

4 3 3 3 3 3 4

4 3 2 2 2 3 4

4 3 2 1 2 3 4

4 3 2 2 2 3 4

4 3 3 3 3 3 4

4 4 4 4 4 4 4

And I found this code associated with it

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int main()  
{ 
    while ( 1 ) 
    { 
        printf( "Enter a non-negative number (0 - exit): " ); 

        int n; 

        if ( ( scanf( "%d", &n ) != 1 ) || ( n <= 0 ) ) break; 

        if ( INT_MAX / 2 < n )  
        { 
            n = INT_MAX / 2; 
        } 

        int width = 1; 

        for ( int tmp = n; tmp /= 10; ) ++width; 

        putchar( '\n' ); 

        int m = 2 * n - 1; 

        for ( int i = 0; i < m; i++ ) 
        { 
            for ( int j = 0; j < m; j++ ) 
            {
                int value1 = abs( n - i - 1 ) + 1;
                int value2 = abs( n - j - 1 ) + 1;

                printf( "%*d ", width, value1 < value2 ? value2 : value1 );
            } 
            putchar( '\n' ); 
        } 

        putchar( '\n' ); 
    } 

    return 0; 
 }

I want to know why in this statementscanf( "%d", &n ) != 1 is used

if (( scanf( "%d", &n ) != 1 ) || ( n <= 0 ));

and also how single format specifier is accepting two values here

printf( "%*d ", width, value1 < value2 ? value2 : value1 );

Why % and * are used together"%*d"??

values in this csv are not being edited - Powershell

$users = Import-Csv -Path "C:\scripts\door-system\test\testChange.csv" -Encoding UTF8 $users | ft

$output = forEach ($user in $users) {

if ($user.GroupName -like "Normal")
{
    $output.GroupName = "edited"
}

}

$output | export-csv .\modified.csv -noTypeInformation

if condition is being executed even after inside condition function with parameter returns false

bool isCycle(vector <int> adj[],int v)
{
    vector <bool> visited(v, false);
    for (int u = 0;u < v;u++)
    {
        if (visited[u] == false)
        {
           if(bfs(u, adj, visited,v));
                return true;
        }
    }
    return false;
}

even after function inside if condition returned false. Why is it executing the if condition ???

if(bfs(u, adj, visited,v));
       return true;

lundi 27 avril 2020

my c code not counting properly word and sentences, but counting char

I am making a C program to count No. of Letters , Words & sentences. but if condition for counting words and Sentences doesn't checks for null character. can anyone help me what i am doing wrong? However if condition for counting no of char is checking for null character.

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

int main (void)
{
    string text = get_string("text: ");
    int p=0,q=0,r,j=0,k=0;
    {
        printf("Your Text is : %s\n", text);
    }
    for(p=0,r=strlen(text); p<r; p++)
    {
        // for counting Letters.
        if (text[p]!= ' ' && text[p]!= '\0' && text[p]!='-' && text[p]!='_' && text[p]!= '.')
        {
            q++;
        }
        // for counting Words.
        else if (text[p]==' ' || text[p]== '-' || text[p]== '\0'  || text[p]=='_')
        {
            j++;
        }
        // for counting Sentences.
        else if (text[p]== '.' || text[p]== '!' || text[p]== '\0')
        {
            k++;
        }
    }
        printf("no.of chars is %i\n",q);
        printf("no.of words is %i\n",j);
        printf("no.of sentences is %i\n",k);
}

included cs50 Library to get string input

IF..ELSE Logic in stored procedure

I have a stored procedure where I need to pull data from a table column based on an input parameter.

If the input parameter is 'Y' I need to pull only 'Y' values from the table column, if it is 'N', I need to pull all values irrespective of 'Y' or 'N' or NULL.

if else on node.textContent

I am trying to make a drag and drop quiz in javascript that is able to check the answers after they are dropped in and give feedback on the answer. So far I have made the drag and drop section but when trying to check answers I am running into problems. This is my code for the webpage:

<!DOCTYPE html>
<html>
<head>
<title>Drag n Drop DEMO</title>
</head>

<body>
<h3>Quiz!</h3>
<p>Possible Answers</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
 <li draggable="true" data-value="geolocation">Geolocation</li>
 <li draggable="true" data-value="canvas">Canvas</li>
 <li draggable="true" data-value="web-worker">Web Workers</li>
 <li draggable="true" data-value="appcache">AppCache</li>
 <li draggable="true" data-value="drag-and-drop">Drag and Drop</li>

</ol>

<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragStartHandler(event) {
    if (event.target instanceof HTMLLIElement) {
      // use the element's data-value="" attribute as the value to be moving:
      event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
      event.dataTransfer.effectAllowed = 'move'; // only allow moves
    } else {
      event.preventDefault(); // don't allow selection to be dragged
    }
  }
   function dragEndHandler(event) {
    if (event.dataTransfer.dropEffect == 'move') {
      // remove the dragged element
      event.target.parentNode.removeChild(event.target);
    }
  }
</script>

<p>Provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.</p>
<ul id="answer1" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
&nbsp;
</ul>

<p>Move (an image or highlighted text) to another part of the screen using a mouse or similar device.</p>
<ul id="answer2" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)" style="margin-top: 0px;">
&nbsp;
</ul>

<p>Allows a developer to specify which files the browser should cache and make available to offline users.</p>
<ul id="answer3" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
&nbsp;
</ul>

<p>Provides web applications with access to geographical location data about the user’s device.</p>
<ul id="answer4" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
&nbsp;
</ul>

<p>Allows JavaScript to execute scripts in the background.</p>
<ul id="answer5" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
&nbsp;
</ul>

<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragEnterHandler(event) {
    var items = event.dataTransfer.items;
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.kind == 'string' && item.type == internalDNDType) {
        event.preventDefault();
        return;
      }
    }
  }
  function dragOverHandler(event) {
    event.dataTransfer.dropEffect = 'move';
    event.preventDefault();
  }
  function dropHandler(event) {
    var li = document.createElement('li');
    var data = event.dataTransfer.getData(internalDNDType);
    if (data == 'canvas') {
      li.textContent = 'Canvas';
    } else if (data == 'drag-and-drop') {
      li.textContent = 'Drag and Drop';
    } else if (data == 'appcache') {
      li.textContent = 'AppCache';
    } else if (data == 'geolocation') {
      li.textContent = 'Geolocation';
    } else if (data == 'web-worker') {
      li.textContent = 'Web Workers';
    }else {
      li.textContent = 'Unknown Answer';
    }
    event.target.appendChild(li);
  }
</script>

<h4>Check Answers Here!</h4>
<button type="button" onclick="checkAns()">Check Answers</button>&nbsp;&nbsp;<button onClick="window.location.reload();">Reset</button>
<br>
<div id="div1"></div>
<script>
function checkAns() {
    var node1 = document.getElementById('answer1')
    htmlContent = node1.innerHTML
    textContent = node1.textContent;

    var node2 = document.getElementById('answer2')
    htmlContent = node2.innerHTML
    textContent = node2.textContent;

    var node3 = document.getElementById('answer3')
    htmlContent = node3.innerHTML
    textContent = node3.textContent;

    var node4 = document.getElementById('answer4')
    htmlContent = node4.innerHTML
    textContent = node4.textContent;

    var node5 = document.getElementById('answer5')
    htmlContent = node5.innerHTML
    textContent = node5.textContent;


    var displayAnswer1 = document.createElement("p")   
    if (node1.textContent === 'Canvas') {
        var textNode1 = document.createTextNode("Question 1 was correct.");
        displayAnswer1.appendChild(textNode1);
        var bindElement1 = document.getElementById("div1");
        bindElement1.appendChild(displayAnswer1);
    } 
      else {
      var textNode1 = document.createTextNode("Question 1 was incorrect.");
      displayAnswer1.appendChild(textNode1);
      var bindElement1 = document.getElementById("div1");
      bindElement1.appendChild(displayAnswer1);
    }
}
</script>
</body>
</html>

I am able to get the textContent from the drag and drop section and even when I type alert(node1.textContent); I get the correct answer from the drag and drop. But in my if else statement whenever I press the button the if statements condition is never met. The condition I have in there currently is if (node1.textContent === 'Canvas') which is what it comes out to when I sat it as an alert instead of an if else. Any help would be much appreciated!