mardi 30 avril 2019

How to fetch values from if else condition?

I am trying to get a code using if else condition.I wish to take values from if else condition .

Currently if condition works, not working for else condition.

mname=input("Enter  name: ")
    m=[]

        if mname=="CS1TFD22" or "cs1tfd22":
            mcode='CS122S003'
            if l1l2=="NULL":
                icode = 'CS122S003d13_mh_'
            elif l1l2!="NULL":
                icode = 'CS122S003d13_L1_mh_'

        else:
            for i in mname:
                m.append(i)

            mcode = 'CS1'+m[5]+m[6]+'S003'
            if l1l2=="NULL":
                icode='CS1'+m[5]+m[6]+'S003d113_mh_'
            elif l1l2 != "NULL":
                icode = CS1'+m[5]+m[6]+'S003d13_L1_mh_'

        print(mcode,icode)

Output I get is always mcode='CS122S003' and icode='CS122S003d13_L1_mh_', if mname is not 'CS1TFD22'. For example if I enter mname as CS1TFD23 , then icode should be 'CS123S003' and icode should be 'CS123S003d13_mh'

How to work for else condition also?

JavaFX GUI that uses If-statements to specify columns, is only showing one column at a time

I have created a GUI that uses checkboxes to pull columns from an SQL query. Depending on the checkboxes that the user has checked certain columns SHOULD show up within a text area. However, when I run my program only one column shows up within the text area at a time. I need to be able to display multiple columns preferably next to each other similar to a table.

I believe the problem stems from how my if-statements work with the Result Sets, but I am unsure how specifically this is causing the problem if it is. I believe this to be true because outside of the if-statements the query and Result Sets work like they are supposed to.

Here is the part that I believe is the offending code.

if (cbVin.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    vinAsc = rsetAsc.getString(1);
                                    displayArea.appendText("VIN: " + vinAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    vinDesc = rsetDesc.getString(1);
                                    displayArea.appendText("VIN: " + vinDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbMake.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    makeAsc = rsetAsc.getString(2);
                                    displayArea.appendText("Make: " + makeAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    makeDesc = rsetDesc.getString(2);
                                    displayArea.appendText("Make: " + makeDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbModel.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    modelAsc = rsetAsc.getString(3);
                                    displayArea.appendText("Model: " + modelAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    modelDesc = rsetDesc.getString(3);
                                    displayArea.appendText("Model: " + modelDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbYear.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    yearAsc = rsetAsc.getString(4);
                                    displayArea.appendText("Year: " + yearAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    yearDesc = rsetDesc.getString(4);
                                    displayArea.appendText("Year: " + yearDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbColor.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    colorAsc = rsetAsc.getString(5);
                                    displayArea.appendText("Color: " + colorAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    colorDesc = rsetDesc.getString(5);
                                    displayArea.appendText("Color: " + colorDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbPrice.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    priceAsc = rsetAsc.getString(6);
                                    displayArea.appendText("Price: " + priceAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    priceDesc = rsetDesc.getString(1);
                                    displayArea.appendText("Price: " + priceDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }

Also I will post the full code for reference.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ProductGUI extends Application {
    private String cssLayout = "-fx-border-color: black;\n" + "-fx-border-width: 1;\n";
    private int clickCount = 0;
    private Connection connection;
    private ResultSet rsetAsc;
    private ResultSet rsetDesc;
    private PreparedStatement preparedStatement;
    private String queryStringAsc;
    private String queryStringDesc;
    private String vinAsc;
    private String vinDesc;
    private String makeAsc;
    private String makeDesc;
    private String modelAsc;
    private String modelDesc;
    private String yearAsc;
    private String yearDesc;
    private String colorAsc;
    private String colorDesc;
    private String priceAsc;
    private String priceDesc;
    private TextArea displayArea = new TextArea();
    private TextField tfwhere = new TextField();

    @Override
    public void start(Stage primaryStage) {
        // The GUI is created here within a try catch block to catch exceptions.
        /*
         * This GUI will be placed within the BorderPane, this will contain a TableList
         * to output the parts of the product table that the user desires. This will be
         * regulated using CheckBoxes and if statements. The Query button will be used
         * to query the database with a lambda expression pointing to a custom method.
         */
        try {
            // Creating all the UI controls.
            // Placement controls.
            BorderPane root = new BorderPane();
            VBox vbox = new VBox();
            HBox hbox = new HBox();

            // Buttons
            Button btQuery = new Button("Query");
            Button btReset = new Button("Reset");

            // Labels
            Label lbChooseField = new Label("Choose Your Fields");
            Label lbOrdered = new Label("Order by Price");
            Label lbWhere = new Label("Specify a Where Statement");
            Label lbWarning = new Label("Please Reset before your next Query!");

            // CheckBoxes
            CheckBox cbVin = new CheckBox("VIN");
            CheckBox cbMake = new CheckBox("Make");
            CheckBox cbModel = new CheckBox("Model");
            CheckBox cbYear = new CheckBox("Year");
            CheckBox cbColor = new CheckBox("Color");
            CheckBox cbPrice = new CheckBox("Price");

            // RadioButtons
            RadioButton rbAscending = new RadioButton("Ascending");
            RadioButton rbDescending = new RadioButton("Descending");
            ToggleGroup tRadio = new ToggleGroup();

            // Placing the controls.
            root.setCenter(displayArea);
            displayArea.setEditable(false);
            displayArea.setMouseTransparent(true);
            displayArea.setFocusTraversable(false);
            root.setPadding(new Insets(12, 12, 12, 12));
            root.setBottom(hbox);
            hbox.setPadding(new Insets(12, 12, 12, 12));
            root.setRight(vbox);
            vbox.setPadding(new Insets(12, 12, 12, 12));
            vbox.setStyle(cssLayout);

            // Placing within HBox.
            hbox.getChildren().addAll(btQuery, btReset);

            // Placing within VBox.
            vbox.getChildren().addAll(lbChooseField, cbVin, cbMake, cbModel, cbYear, cbColor, cbPrice, lbOrdered,
                    rbAscending, rbDescending, lbWhere, tfwhere);
            rbAscending.setToggleGroup(tRadio);
            rbAscending.setSelected(true);
            rbDescending.setToggleGroup(tRadio);

            // Lambda expression for btQuery will create columns based on CheckBox
            // selections and fill with
            // appropriate data.
            btQuery.setOnAction(e -> {
                // The purpose of clickCount is to make sure that the button does not output
                // multiple repeat columns.
                if (clickCount < 1) {
                    // Initialize a connection to the example database.
                    initializeDB();

                    if (cbVin.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    vinAsc = rsetAsc.getString(1);
                                    displayArea.appendText("VIN: " + vinAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    vinDesc = rsetDesc.getString(1);
                                    displayArea.appendText("VIN: " + vinDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbMake.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    makeAsc = rsetAsc.getString(2);
                                    displayArea.appendText("Make: " + makeAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    makeDesc = rsetDesc.getString(2);
                                    displayArea.appendText("Make: " + makeDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbModel.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    modelAsc = rsetAsc.getString(3);
                                    displayArea.appendText("Model: " + modelAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    modelDesc = rsetDesc.getString(3);
                                    displayArea.appendText("Model: " + modelDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbYear.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    yearAsc = rsetAsc.getString(4);
                                    displayArea.appendText("Year: " + yearAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    yearDesc = rsetDesc.getString(4);
                                    displayArea.appendText("Year: " + yearDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbColor.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    colorAsc = rsetAsc.getString(5);
                                    displayArea.appendText("Color: " + colorAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    colorDesc = rsetDesc.getString(5);
                                    displayArea.appendText("Color: " + colorDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (cbPrice.isSelected()) {
                        try {
                            if (rbAscending.isSelected()) {
                                while (rsetAsc.next()) {
                                    priceAsc = rsetAsc.getString(6);
                                    displayArea.appendText("Price: " + priceAsc + "\n");
                                }
                            }
                            if (rbDescending.isSelected()) {
                                while (rsetDesc.next()) {
                                    priceDesc = rsetDesc.getString(1);
                                    displayArea.appendText("Price: " + priceDesc + "\n");
                                }
                            }
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    close();
                    clickCount++;

                } else {
                    // Part will tell the user that a reset of the GUI via btReset is required to
                    // use again.
                    root.setTop(lbWarning);
                }

            });

            // The Lambda for btReset which will bring the GUI to it's original state,
            // allowing for another query.
            btReset.setOnAction(e -> {
                clickCount = 0;

                if (cbVin.isSelected()) {
                    cbVin.setSelected(false);
                }
                if (cbMake.isSelected()) {
                    cbMake.setSelected(false);
                }
                if (cbModel.isSelected()) {
                    cbModel.setSelected(false);
                }
                if (cbYear.isSelected()) {
                    cbYear.setSelected(false);
                }
                if (cbColor.isSelected()) {
                    cbColor.setSelected(false);
                }
                if (cbPrice.isSelected()) {
                    cbPrice.setSelected(false);
                }
                displayArea.clear();
                tfwhere.clear();
                root.setTop(null);
                rbAscending.setSelected(true);
            });
            // Scene created by default Main method from JavaFX project.
            Scene scene = new Scene(root, 900, 700);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.setTitle("Product Table GUI");
            primaryStage.show();
        } catch (

        Exception e) {
            e.printStackTrace();
        }
    }

    // This method initializes the database and creates the connection. It is
    // located within a try catch block to catch exceptions.
    private void initializeDB() {
        try {
            // Load the JDBC driver.
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("Driver loaded");

            // Create the connection.
            connection = DriverManager.getConnection("jdbc:mysql://localhost/example", "scott", "tiger");
            System.out.println("Database Connected.");

            queryStringAsc = "select * from product " + tfwhere.getText().toLowerCase() + " order by price asc;";
            preparedStatement = connection.prepareStatement(queryStringAsc);
            rsetAsc = preparedStatement.executeQuery();

            queryStringDesc = "select * from product " + tfwhere.getText().toLowerCase() + " order by price desc;";
            preparedStatement = connection.prepareStatement(queryStringDesc);
            rsetDesc = preparedStatement.executeQuery();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void close() {
        try {
            if (rsetAsc != null) {
                rsetAsc.close();
            }
            if (rsetDesc != null) {
                rsetDesc.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

how to fix 'Cannot read property of undefined'?

I'm trying to determine which object in an array has the longest name and logging that object to the console.

I can't seem to access the length of the name property in my if statement.

  let longest;
  for (let i = 0; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.length) {
      longest = instructors[i];
    }
  }
  return longest;
};

console.log(instructorWithLongestName([
  {name: "Samuel", course: "iOS"},
  {name: "Jeremiah", course: "Web"},
  {name: "Ophilia", course: "Web"},
  {name: "Donald", course: "Web"}
]));
console.log(instructorWithLongestName([
  {name: "Matthew", course: "Web"},
  {name: "David", course: "iOS"},
  {name: "Domascus", course: "Web"}
]));

I expect the output of
{name: "Jeremiah", course: "Web"}
{name: "Domascus", course: "Web"}

but I get an error stating it cannot read property '.length'

No matter the input if statement continues on the first "exit"

Working on a text based rpg and im realy confussed why no matter the input it always gives me the same result.

cout << "Human" << endl;
cout << "Ghoul" << endl;
cout << "Super mutant" << endl;
cin >> rase;
cout << "Your input: " << rase << "." << endl;
if (rase == "Human" || "human")
{
    cout << "You are standing at the exit of Vault 101. \n" << endl;
    weapon = 25;
    health = 100;
    MAXhealth = 100;
    system("PAUSE");
}
else if (rase == "Ghoul" || "ghoul")
{
    cout << "You are standing at the Megaton bar selling some drinks. \n" << endl;
    weapon = 50;
    health = 125;
    MAXhealth = 125;
    system("PAUSE");
}
else if (rase == "Super mutant" || "super mutant" || "Super Mutant" || "supermutant")
{
    cout << "You are standing and wishing you had a new weapong to smash stuff with. \n" << endl;
    weapon = 100;
    health = 200;
    MAXhealth = 200;
    system("PAUSE");
}
else
{
    cout << "wrong input" << endl;
}

i have tried to make it with char how ever that has caused alot more errors, atleast while using string i compiles and take in input.

i would like to some how make the program to pick my "race" without just simple 1,2,3 pick for example.

statements and return within a lambda expression lambda

In C# I'm trying to verify if a buss full of passengers is ready to go by verifying the passengers payments:

bool busReadyToGo = true;
passengers.Any(p => p.paymentStatus == PaymentRegistryEnum.NotPaid ?  busReadyToGo = false; return busReadyToGo; : continue; );

So this should check all the passengers payment status, if it encounters one passenger that hasn't paid then it stops right there and returns busReadytoGo = false. otherwise it continues iterating/filtering passengers, which means it will later return true if a passenger hasn't paid.

Not sure if this is the right way to do this within the Linq/lambda expression, because I keep getting syntax errors.

How to assign a variable to equal any number

So I am a beginner in learning python. I have been reading “how to automate the boring stuff” and while reading I try writing code to learn better. I’m writing a simple code to multiply any number a user inputs by 10. And it is a while loop so thy can continue doing it if they choose to. I don’t know what to assign my variable “number” to equal any number that the user inputs. Here’s what the code looks like. I’m using my iPhone to do this so I’m using a free app that’s python 2 something I don’t even know lol.

print('What number you want me to multiply by         10?')
number=float(raw_input())
while number==????!!!
     print(number*10)
      number=float(raw_input('Enter new number: '))
else:
     print('Please enter a number next time')

how to fix an if function which returns only the else statement

I'm writing a function that should display a specific text in an area depending on the src of an image, this function runs when the mouse is over another image. Always the same text is displayed besides the src of the image.

I've tried if-else functions, onmouseover or addEventListener none of those work


<img id="avatar" src="avatar1.jpg" alt="avatar" class="avatar">
<img src="icon.jpg" class='icon' id='icon'>
<p id='description'> specifit text should appear in here <p>



/*this funcion changes the source of 'avatar' and it works fine*/

const faces = [ "avatar1.jpg", "avatar2.jpg" ];
const avatar = document.getElementById('avatar');

function changeFace() {
  const face = avatar.src.split('/').slice(-1)[0];
  const index = faces.indexOf( face );

  avatar.src = faces[ ( index + 1 ) % faces.length ];
  console.log( avatar.src );
}

var icon = document.getElementById('icon');
icon.addEventListener('click', changeFace);

/*clicking on the 'icon' changes the src of 'avatar' from 'avatar1.jpg' to 'avatar2.jpg' and viceversa.*/

/*this function display 'text' in p 'description', it works fine*/

function writeText(text) {
  document.getElementById("description").innerHTML=text
}

/*this is the funcion that doens't work*/

function changeText() {
if (avatar.src === "avatar1.jpg") {
writeText('text number 1');}
else { writeText('text number 2');}
}

icon.addEventListener('mouseover', changeText);


it returns 'text number 2' regardless the src of 'avatar'enter code here

Which value of num when initialized would give this nested loop a "true" output?

Had this question on an exam and am pretty sure there's some sort of trick to it.

"Suppose num was initialized to a certain value prior to this loop. Which value of num would give a "true" output?"

int result = 0; 
for (i = 0; i < num; i++)
     if (i % 3 == 1)
     result += i;

     if result == num 
          cout << "True" << endl;
     else
          cout << "False" << endl;

a) 4

b) 5

c) 6

d) 7

Am a newbie programmer. Can anyone interpret what's going on?

Sorting data into groups

I have a data set where participants had to choose 3 out of 20 people (e.g. W26 means the person they chose is a 26-year old woman.) This means, that if they chose W26, M20 and W30 these variables each have the code "1" in my data, and the other 17 people get the code "0". Now I have about 200 participants that each chose 3 people. Now I want to sort the list with the following structure so that it is easy to see who chose who and what gender and age they are. This is the sort of list I want:

                  person1_gender person1_age    person2_gender  person2_age        
  participant 1   female         26             male           20               
  participant 2   male           32             female         19
  participant 3   male           19             male           30

etc.

I have tried to do this with the if code ... which means that if the code = 1 then they should say "female" or "male" respectively, but I am actually not sure at all if I have to do other things before I use the if code.

 if (data$M18 > 0) 

   data$M18 = "male"

   print (data$M18)

The output does give me the following: "Warning message: In if (data$M18 > 0) data$M18 = "male" : the condition has length > 1 and only the first element will be used"

And the data also does not change to "male" at all. Do I need to work with loops as well?

if and elseif issue in codeigniter

I am trying to calculate the incentive for the people with designation as Assistant Managers and Senior Executives. So, I need to give 1% of the total amount to the Senior Executives and 1.5% to the managers. So, while writing the if, elseif conditions for the same in codeigniter view. Only the if condition is working and elseif conditiion is not working. Since, I am new to codeigniter, please help me out with this.

                                if(isset($target_revenue[0]['target']))
                                {
                                    $amount=$get_rev/$target_revenue[0]['target']*100;
                                    {
                                    if($amount>100 && $designation ="Assistant Manager")  
                                    {

                                        $get_rev1=($get_rev-$target_revenue[0]['target'])*0.015;
                                        }

                                        else if($amount>100 && $designation ="Senior Executive") 
                                    {

                                        $get_rev1=($get_rev-$target_revenue[0]['target'])*0.01;
                                        }

                                    }
                            }

How to extract the same and highest value?

I have a table like below, I like to extract rows if they have the same value in the rows 4 and 8 otherwise the maximum value.

Input: data

1   9708  10948  1  1   9708  10948  1
1  11590  18647  4  1  12897  15040  2
1  11590  18647  4  1  15040  15500  3
1  11590  18647  4  1  15950  16580  2
1 108570 109500  1  1 108570 109500  1
1 440900 443400  2  1 440900 441080  1
1 440900 443400  2  1 443140 443400  1
1 539670 542200  3  1 539700 540450  2
1 539670 542200  3  1 541070 541770  2
1 539670 542200  3  1 540450 541070  3
1 712695 715758 14  1 712799 712900  5
1 712695 715758 14  1 713010 713230  8
1 751500 759199  8  1 752555 752773  5
1 761083 764000  9  1 761083 761198  1
1 761083 764000  9  1 762200 762300  8
1 761083 764000  9  1 762300 762800  9



ideal Output:

1   9708  10948  1  1   9708  10948  1
1  11590  18647  4  1  15040  15500  3
1 108570 109500  1  1 108570 109500  1
1 440900 443400  2  1 440900 441080  1
1 440900 443400  2  1 443140 443400  1
1 539670 542200  3  1 540450 541070  3
1 712695 715758 14  1 713010 713230  8
1 751500 759199  8  1 752555 752773  5
1 761083 764000  9  1 762300 762800  9

I have tried two commands, the first one gives me the same value between columns 4 and 8, but I want something like the second one and ideal Output.

data<-data[which(data$V4 == data$V8),]

data<- data[ifelse(data$V4 == data$V8,data$V4,max(data$V8)),]

is there a way to expand if statement based on number of rows

I have a form that I'm using for change requests to add "exceptions" I have 3 columns : A - Origin B - Destination C - Number

based on this for each row I have a simple 2 step calculation 1step: Ship lane so simple = A2+" - "+B2 and then if statement: if (Ship Lane= Origin - Destination, then Number)

the if statement is used not in excel but in Tableau so I'm trying get excel to build the if statement if extra lines are added in the ship lane tab.

so the final sentence should look like:

if [Ship lane]= "ABC - DE" then 2
elseif [Ship lane]= "ABC - DK" then 2 
elseif [Ship lane]= "ABC - GB" then 2
END

And if we have extra lines it should add them at the bottom:

if [Ship lane]= "ABC - DE" then 2
elseif [Ship lane]= "ABC - DK" then 2 
elseif [Ship lane]= "ABC - GB" then 2
elseif [Ship lane]= "ABC - IT" then 2
elseif [Ship lane]= "DEF - PL" THEN 1
ELSEIF [Ship lane]= "XYZ - IT" then 1
END 

Php Function how to turn integer into varchar on the output

Hi im new here and also just start learn programming.

I'm creating pdf file from my web project, there is 1 integer coloumn in my table which the value is 0,1,2

the output in pdf is number but i want to change the number into text.

example if the "Status" is 1 the output is "Approved", if "Status" is 2 the ouput is "Declined", and if the "Status" is 0 the ouput is "on process"

  function fetch_data()  
  {  
  $output = '';  

  $conn = mysqli_connect("localhost", "root", "", "system");  

  $sql = "SELECT Status from tabel";  

  $result = mysqli_query($conn, $sql);

  while($row = mysqli_fetch_array($result))  
  {       
  $output .= '<tr> 
                <td>'.$row["Status"].'</td>  
              </tr>  
                      ';  
  }  
  return $output;  
  }

How to conditionally compare a list and a pandas dataframe

I'm trying to compare a list of datetimes for the last 12 hours (from timenow) :

print(times)

[datetime.datetime(2019, 4, 30, 11, 0), datetime.datetime(2019, 4, 30, 10, 0), datetime.datetime(2019, 4, 30, 9, 0), datetime.datetime(2019, 4, 30, 8, 0), datetime.datetime(2019, 4, 30, 7, 0), datetime.datetime(2019, 4, 30, 6, 0), datetime.datetime(2019, 4, 30, 5, 0), datetime.datetime(2019, 4, 30, 4, 0), datetime.datetime(2019, 4, 30, 3, 0), datetime.datetime(2019, 4, 30, 2, 0), datetime.datetime(2019, 4, 30, 1, 0), datetime.datetime(2019, 4, 30, 0, 0)]

against a number of slices of pandas main dataframe (filt):

print(filt)

             timestamp  switchID    deviceID  count
0  2019-04-29 10:00:00         1  GTEC122277      3
(...)
16 2019-04-30 09:00:00         1  GTEC122277      1
17 2019-04-30 10:00:00         1  GTEC122277      1
18 2019-04-30 10:00:00         1  GTEC122585      1
19 2019-04-30 10:00:00         2  GTEC122585      1

Typical Slice:

print(d1_sw1)

             timestamp  switchID    deviceID  count
16 2019-04-30 09:00:00         1  GTEC122277      1
17 2019-04-30 10:00:00         1  GTEC122277      1

I want to check the array times against the first column of my SLICED pandas df d1_sw1, if they match, then store in a new df in the format:

             timestamp  count
0  2019-04-30 12:00:00      0
1  2019-04-30 11:00:00      0
2  2019-04-30 10:00:00      1
3  2019-04-30 09:00:00      1
4  2019-04-30 08:00:00      0
5  2019-04-30 07:00:00      0
6  2019-04-30 06:00:00      0
7  2019-04-30 05:00:00      0
8  2019-04-30 04:00:00      0
9  2019-04-30 03:00:00      0
10 2019-04-30 02:00:00      0
11 2019-04-30 01:00:00      0
12 2019-04-30 00:00:00      0

I am really struggling to work out how to achieve this, any help is valued!

How do I put a local-storage item in an if statement?

I'm working on some code that runs a function when it detect the local storage item 'En' is equal to the string "English". Is there any way I could put 'En' = "English" inside the rules for an if statement? My current code:

const En = "English"

document.getElementById("langEn").onclick = function() {remLangEn()};

function remLangEn() {
localStorage.setItem(lang, En);
}

Why does this return NA instead of TRUE/FALSE?

Why does this

as.character(EARLY_TOPUP$STATUS[5]) != "ELIGIBLE"

returns NA instead of boolean value?

EARLY_TOPUP data frame has following values

> EARLY_TOPUP
                    STEP VALUE THRESHOLD       STATUS
1           Days in Loan     3      30.0 NOT ELIGIBLE
2      Present EWS Score     2      10.0     ELIGIBLE
3                Max EWS     2      15.0     ELIGIBLE
4 Weighted Payment Score   NaN       2.5         <NA>
5  Weighted Safety Ratio   NaN       2.0         <NA>

when I do I get expected values

> as.character("NA") != "ELIGIBLE"
[1] TRUE
> as.character("<NA>") != "ELIGIBLE"
[1] TRUE

Gridvew Looping for multiple times even when selected least records in asp.net

I have a gridview in which every row contains a checkbox for selection. That selection will be used for Approve or Reject purpose.

But issue here is If I select 2 rows from the gridview it loops atleast 4-5 times and gives me multiple emails of the same row.

Below is my code. Please suggest.

if (ViewState["CheckedCheckboxes_CMM"] != null)
            {
                var CheckedCheckboxes_CMM = (List<int>)ViewState["CheckedCheckboxes_CMM"];

                foreach (var id in CheckedCheckboxes_CMM)
                {
                    flgCMM = true;

                    int Id = id;

                    foreach (GridViewRow row in grdDisplayCMMData.Rows)
                    {
                        Label SAPID_CMM = (Label)row.FindControl("lblSAP_ID_CMM");

                        ObjIPColoFields.Unique_Id = Id;
                        ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
                        ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
                        ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
                        ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
                        ObjIPColoFields.FCA_STATUS = "1";
                        ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
                        strDate = DateTime.Now.ToString();                                                    

                        strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);

                        if (ObjIPColoFields.Unique_Id != null || ObjIPColoFields.Unique_Id != 0)
                        {
                            strMailContent = Get_Email_Content(ObjIPColoFields.LAST_UPDATED_BY, SAPID_CMM.Text, strIPCOLO_CMM, Convert.ToString(Id), strDate, "Approved");
                            SendEmail(lblUserName.Text, strMailContent, strIPCOLO_CMM);
                        }
                    }
                }

            }

lundi 29 avril 2019

Condition inside the datatabele

I created data table and in this, I want to check the condition, here is the part of my code:

buttons: [
                {
                    extend: 'pdfHtml5',
                    exportOptions: {
                    if(group_id != topManagementUserLevel){
                        columns: [0, 1, 2, 3, 4]
                          }
                    }
                },
            ],

I want to add if condition to check some values but when I am inserted that one into code Its gives an error.

Uncaught SyntaxError: Unexpected token !=

Is there a any other way to do this

How to append all previous indices before reaching the counter target

I have the following code:

indices_to_remove= []
for i in range(0,len(df)):
        if (df.speed.values[i] <= 15 ):
            counter += 1
            if counter > 600:
               indices_to_remove.append(i)        

        else:
            counter= 0

df= df.drop (indices_to_remove, axis=0)

The main goal of this code is to loop through all the rows in my dataset, and in case there are more than 600 consecutive rows that has a speed value less than 15. The code will add the rows indices to the indices_to_remove and then all of these rows will be dropped. My main issue in this code is that: let's consider a case scenario where we have 1000 consecutive rows. The code will only append the rows indices starting from 601 till 1000 and won't ignore the rows from zero to 600. Can someone help me to modify this code so that it includes all the rows starting from zero till the last column that has a speed value less than 15.

Program keeps breaking into infinite loop while trying to input user time using cin with a do while loop in c++

I am trying to write a program for class where we have to take user time (departure + arrival time) and then output whatever the user wrote to the console. I am using a do while loop. I am using an if statement to validate property entry. When I run the program, every single fucking time, it just keeps asking for arrival time over and over again. I need to append "am" or "pm" depending on what the user entered, which is why that char array of two values is there. PLEASE help

char ampm1[2];

    // char ampm = 'p';
    int temp;
    do 
    {
        cout << "Please enter your arrival time in the following format: '10:30'. This IS NOT MILITARY TIME.";
        cin >> temp;
        arrival_hour = temp / 100;
        arrival_min = temp % 100;
        cout << "Is this AM or PM?";
        cin >> ampm1;
    } 
    while (arrival_hour > 12 || arrival_hour < 0 || departure_min >= 60);




    cout << "Your arrival time is: " << setfill('0') << setw(2) << arrival_hour << ":" << setfill('0') << setw(2)
        << arrival_min << ampm1;

What is the proper syntax for multi-conditional if-statements in python?

I'm not having much luck grouping multiple if conditional statements in python.

try:     
  player1_input = input("Enter 1 for Rock, 2 for Paper, 3 for Scissors: ")
  player2_input = input("Enter 1 for Rock, 2 for Paper, 3 for Scissors: ")

  if (player1_input or player2_input) != ("1" or "2" or "3"):
    raise
except Exception:
  print("You did not enter a correct input")

From what I want to achieve, I would like to raise an exception if user 1 or 2 do not enter and input that is 1,2 or 3. However, when I try a test input of user1: 3 and user2: 1 a exception is incorrectly raised. How can I fix this issue? Any help would be greatly appreciated. I do believe I must have a misunderstanding of the syntax of multi-conditional if statements.

Is there an easy way to get longest word that contains a certain letter?

I am trying to get the largest word that contains the letter 'f' through a for loop, through my code I tried to make it as simple as possible with a if and and statement. It is however not working as it returns the largest word but not the one that includes the letter f, why is it not working?

def main():
    sentence = "Absence makes the heart grow fonder"
    letter = "f"
    longest_word = get_longest_word(sentence, letter)
    print('"' + longest_word + '" is the longest word containing the letter "'
          + letter + '".')

def get_longest_word(sentence, letter):
    words_list = sentence.split()
    largest = words_list[0]
    my_list = []
    for word in words_list:
        if letter in word and len(word) > len(largest):
            largest = word
    return largest 


main()

Need to make program know what values are selected and spit out a specfic object based on the seleted values

My friend and I are setting up working on a project and are stuck. We want to make a specific object spit out based on selected values but we're stuck to the point where no matter what we select the same object always gets spat out. How do we make it so it spits out the object we want it to?

This is for a project for a Computer Science class. This is our first experience with anything outside of Applab so we are very new to actual code.

$('p#bread).hide();
getSelectedIngredients = function (){
  var selectedValues = $('#ingredients').val(){
  var cookingIngredients=["1","2","3","4","5"]
  var bread=cookingIngredients.includes("2","3");

  if (bread=true){
     $('p#bread').show();
  }else{
     $('p#bread').hide();
}

As I said before, we want a specific object to spit out based on selected items.

Simplify if-statements in function

The following function includes multiple if-then-else statements. Is it possible to simplify the code without using the inner if-then-else statement?

f x y z = if y >= 15 
            then (if y < 23 then x*5 else f (x+4) (y+7) z) 
            else f(x+4) (y+7) z

if (either or) in python

I need to comparison the output of my program to print out the statement as results.

If any of this two condition is okay, I will print out Okay:

    if ((c+c1)==2 or counter>=(n/2)):
        print(‘okay’) 
    else:
        print(‘not_okay’)

how can I combine two condition in one line?

How to use If-Statement inside the command of tkinter Button, to check that tkinter CheckButton is click or not?

Program Summary

I'm making a python based text processing program. Here I am using following Tkinter widgets with following names for its GUI:

  1. Text widget > "text_input"
  2. Text widget > "text_output"
  3. CheckButton widget > "checkButton_tense"
  4. Button widget > "button_analyse"

And Now I wanted to my program to run in following sequence.

  1. Taking text from "text_input".
  2. Perform the some Basic Text Processing in some other class on clicking the "button_analyse" and show output in "text_output".
  3. But if "checkButton_tense" widget is clicked/checked. Then it should also perform Tense Inspection along with basic text processing, else it should only perform basic text processing.
  4. Above operation no. 3 should be performed after checking status of "checkButton_tense" widget on clicking the "button_analyse" and show output in "text_output"

Problem/Error

Now when I use the if statement inside the "command=lambda:" of the my Tkinter Button "button_analyse" widget to check the status of "checkButton_tense" it gives me error. I have tried to do it with many ways but it don't works.

I have tried the solution mentioned here. But when I tried any solution like this i am unable to show my text in "text_output" widget because it is inside the different python method "main_gui_layout". I have also tried many other solutions given here at stack-overflow but don't found any identical. Kindly guide me in context of above mentioned problem and following code.

Code

from tkinter import *
from Examples import Examples
from TextAnalysis import PerformTextAnalysis


class MyGui:
    useExamples = Examples()
    performTextAnalysis = PerformTextAnalysis()

def __init__(self, master):
    self.main_gui_layout(master)

def main_gui_layout(self, master):

    # InputBox to get the input Text.

    text_input = Text(master, bd=1, height=15, width=100)
    text_input.insert('end', self.useExamples.example2)
    text_input.pack(side=TOP)

    # OutputBox to show the processed Text.

    text_output = Text(master, bd=1, height=15, width=100)
    text_output.pack(side=TOP)

    # CheckButton: it will perform tense analysis if checked/clicked

    tenseCheck_clicked = IntVar()
    checkButton_tense = Checkbutton(master, text="Tense Inspection", variable=tenseCheck_clicked,
                                    bg='#9aa7bc')
    checkButton_tense.var = tenseCheck_clicked
    checkButton_tense.pack(side=TOP)

    # Analysis Button: it will process text and show in output.
    # It will also perform Tense Analysis if Above "checkButton_tense" is check/active.

    button_analyse = Button(master, text="Analyse Requirements", width=20,
                            command=lambda:
                            [
                                self.performTextAnalysis.get_userReqiurement(
                                str(text_input.get('1.0', 'end'))),
                                if tenseCheck_clicked == 1:
                                    ans = self.performTextAnalysis.performBasicAnalysis(),
                                    self.performTextAnalysis.performTenseAnalysis(),
                                    text_output.insert(END, ans)
                                else:
                                self.performTextAnalysis.performBasicAnalysis()

                            ])
    button_analyse.pack(side=TOP)

How to fail a nightwatch.js test within an if failure

I have an if statement that, when it 'fails', I'd like it to fail my nightwatch test.

So at the moment an excerpt of my code looks like this;

   if (rangeFacetEntry.value.length === rangePageElement.length) {
     if (JSON.stringify(rangeArray) === JSON.stringify(rangePageElement)) {
       console.log("Range - they are the same");
         return true;
           } else {
               console.log("Range - they are not the same");
                 return false;
             }
           }
     });

But when it fails (i.e. JSON.stringify(rangeArray) does not equal JSON.stringify(rangePageElement)) then I would like it to fail my test.

But it doesn't.

It simply doesn't output the result to the terminal, and the overall test passes.

Is there a way I can make this failure within my if statement implicitly fail my test? Thanks.

Why does my nim game always choose pile A?

I'm trying to make a game of nim, but when the program asks the user which pile they want to choose from, either A, B, or C, the program always says that the user chose pile A and removes the counters from pile A, even if the user chooses pile B or C.

I have looked over my code a lot and see no reason this would happen. All of the indentation and parenthesis check out and look fine. I tried moving the while statement and getting rid of the individual pile functions, but none of that changes anything.

#include <iostream>
#include <string>

using namespace std;

string player1() {

        string player1;

        cout << "Player one, what is your name?" << endl;
        cin >> player1;

        return player1;
}


string player2() {

        string player2;

        cout << "Player two, what is your name?" << endl;
        cin >> player2;

        return player2;
}

int main() {

        string name1 = player1();
        string name2 = player2();

        int pile1 = 8;
        int pile2 = 10;
        int pile3 = 7;

//      while (pile1 >= 0 && pile2 >= 0 && pile3 >= 0) {

        char which_pile;
        int counters;


        cout << name1 << ", what pile do you want to choose from?" << endl;
        cin >> which_pile;

        while (pile1 >= 0 && pile2 >= 0 && pile3 >= 0) {

                if(which_pile == 'A' || 'a') {

                        cout << "You have chosen pile A. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile1 -= counters;

                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;


                } else if(which_pile == 'B' || 'b') {

                        cout << "You have chosen pile B. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile2 -= counters;
                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;

                } else if(which_pile == 'C' || 'c') {

                        cout << "You have chosen pile C. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile3 -= counters;
                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;

                } else {

                        cout << "Bad input." << endl;
                }

        cout << name2 << ", what pile do you want to choose from?" << endl;
        cin >> which_pile;

                if(which_pile == 'A' || 'a') {

                        cout << "You have chosen pile A. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile1 -= counters;

                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;

                } else if(which_pile == 'B' || 'b') {

                        cout << "You have chosen pile B. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile2 -= counters;
                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;

                } else if(which_pile == 'C' || 'c') {

                        cout << "You have chosen pile C. How many counters do you want to take?" << endl;
                        cin >> counters;

                        pile3 -= counters;
                        cout << "\n" << pile1 << endl;
                        cout << pile2 << endl;
                        cout << pile3 << "\n" << endl;

                } else {

                        cout << "Bad input." << endl;
                }
        }

        return 0;
}

I expect if the user chooses pile B or C, the program says you have chosen pile B or C, and then removes the counters from pile B or C, but the program always chooses pile A and removes counters from pile A.

How to combine multiple actions in ifelse-statement

I am trying to combine multiple actions in one ifelse-statement. The second actions is working with the first one and so on, but I get the error warning: "operations are possible only for numeric, logical or complex types".

The error refers to data I produced before, and it is a working directory, saved as character. Therefore I can not change it to numeric, logical or complex. I tried it, but it becomes NA.

Using as.factor results in the same error warning. When I run the code step by step there is no error, it occurs only if I run the whole ifelse-statement.

The problem occurs in the line of the ifelse-statement "meta_nam <- paste(folders, ".xlsx", sep="")"

I think the "folders" is the problem. The data looks like: "O:/data/Projekt/a"

 condition1 <- as.Date(sub(".*/(.*)","\\1",x), "%Y.%m.%d")>as.Date("2017-03-05")
 ifelse(condition1==T, yes=((meta_nam <- paste(folders, ".xlsx", sep="")) &
                              (exist <- file.exists(meta_nam)) &
                              (for (i in 1:length(folders)) {
                                if(exist[i]==F) 
                              {stop(paste("Meta-Excel fehlt fuer: ", folders[i]))}}) &
                              (me=lapply(meta_nam, function(y) read_excel(y))) &
                              (me=lapply(me, function(y) as.data.frame(y[!is.na(y$dID), 
                               seq(which(colnames(y)=="dID"), which(colnames(y)=="parameter_stop")-1)]))) &
                              (me=lapply(me, function(y) y[,colSums(is.na(y))<nrow(y)])) &
                              (me=lapply(me, function(y) y[rowSums(is.na(y))<(ncol(y)-1),])))

        , no=((meta_nam=paste(folders, ".csv", sep="")) &
                (exist=file.exists(meta_nam)) & 
                (for (i in 1:length(folders)) {
                  if(exist[i]==F) 
                  {stop(paste("Meta-Excel fehlt fuer: ", folders[i]))}}) &
                (me=lapply(meta_nam, function(y) read.table(y, sep="\t", header=T, stringsAsFactors=F))) &
                (me=lapply(me, function(y) y[,colSums(is.na(y))<nrow(y)])) &
                (me=lapply(me, function(y) y[rowSums(is.na(y))<(ncol(y)-1),]))))


The idea behind using an ifelse-statement is to reduce the runningtime, before I used an if... else... argument, there was no problem.

dimanche 28 avril 2019

Modifyig Java if statements

I need to modify the 10% added to the total; if the subtotal is $1,000 or less keep the 10% additional cost, if subtotal is greater than $1,000 the additional cost will be 5%

I know I need to use an if statement but I can't seem to figure it out correctly.

double totalAmount=airFareCost+foodCost+hotelCost+carCost+shuttleCost; 

double tripTotal=totalAmount+(totalAmount*0.1); {

   if(tripTotal > 1000) {
    tripTotal * 0.5 
} 

else(tripTotal < 1000){ 
tripTotal *0.1)
}

summaryLabel.setText("Summary: Trip Total Cost is $"+tripTotal);

How to create new rows of data based on other rows

I have a dataframe (abund) similar to the dune and dune.env datasets used in the vegan package, except my first three columns summarise the sampleID and two methods used to collect the data. Data are the abundances of each species collected.

 SampleID   MethodA     MethodB     SpA    SpB    SpC   ...
 18001        A1          B1          0      3     4 
 18001        A1          B2          1      5     0
 18001        A2          B1          0      7     0          
 18001        A2          B2          0      11    0
 18002        A1          B1          4      1     0
 18002        A1          B2          0      0     3
 18002        A2          B1          0      0     0
 18002        A2          B2          0      8     2
 18003        A1          B1          0      9     0
 ....

I would like to create a new dataset (whole) based on this data, but with only SampleID and MethodA as row identifiers.

 SampleID   MethodA     MethodB     SpA    SpB    SpC   ...
 18001        A1          B3          1      8     4 
 18001        A2          B3          0      18    0          
 18002        A1          B3          4      1     3
 18002        A2          B3          0      8     2
 18003        A1          B3          0      9     1
 ....

An extra twist is that instead of just adding data from B1 + B2, I first want to multiply B1 by 15 (ie: B3 = 15*B1 + B2).

There are two problems that I have.

  1. multiplying only certain rows of data.

I tried using an if statement:

wholeCalc <- function(MethodB, multiplier=15){
  whole <- MethodB* multiplier
  if(MethodB= "B2") {
    whole <- whole/multiplier
  }
}

-> there were a bunch of errors which indicate that I am way off the mark!

  1. figuring out how to group the data depending on SampleID and MethodA.

I have tried multiply ways to group the data, with not much success.

aggregate(abund, 
          list(Group=replace(rownames(abund$MethodB),
                             rownames(abund$MethodB) 
                             %in% 
                               c("B1","B2"), 
                             "B3")), 
          sum)

-> I receive an error that arguments must be the same length (i.e. B1 and B2).

whole <- abund %>%
  group_by(SampleID, MethodA)
whole

-> this gives me the same dataset that I began with.

rbind(abund, 
      c(MethodB = "B3", 
        abund[abund$MethodB == "B1", -3] + 
          abund[abund$MethodB == "B2", -3])) 

-> this gives me an error because the number of rows for B1 and B2 do not match.

As you may see, I'm completely lost and need some help! I've been in the lab for the past couple of months and let my R skills get rusty.

How do i get this code to copy only the rows that mach my object matching criteria? currently if copies every row

currently this code copies every row and not the ones that match my criteria

i had some issues getting it to loop. hence the loggers.

I'm quite new to this.

  function searchAnotherSheetAndReturnRows(){
Logger.clear()
  var tss = SpreadsheetApp.openById('1dX5MMLXGsG_S_KzRhOcquOp00VhzRBSlTCkyw'); // tss = target spreadsheet
  var ts = tss.getSheetByName('Sheet1'); // ts = target sheet
var sss = SpreadsheetApp.openById('1ImDswr6ADS7t4HKIFHpntykN2LS7Mmd-cls34'); // sss = source spreadsheet
  var ss = sss.getSheetByName('Page1'); // ss = source sheet
 var tslast_row = ts.getLastRow();

var i=0;
Logger.log(i)

for (var i = 1; i < tslast_row; i++) {
Logger.log(i)

Logger.log(tslast_row);
 var ssSearch1 = ss.getRange(2,1).getValue();
     Logger.log(ssSearch1); 
 var tsSearch1 = ts.getRange(i,1).getValue();
     Logger.log(tsSearch1);

if (ssSearch1 == tsSearch1); {


     var  tsSearch1Range = ts.getRange(i,1,1,7);
     Logger.log(tsSearch1Range);
     var range2Copy = tsSearch1Range.getValues();//  Copies data from root sheet
     Logger.log(range2Copy);
     var last_row = ss.getLastRow();
     Logger.log(last_row);
     var last_row = last_row+1;
     Logger.log(last_row);
     ss.getRange(last_row,1,1,7).setValues(range2Copy);// Adds  root sheet data to target


}
}

}


How to drop rows that: 1) don't meet a certain criteria and 2) the number of consecutive rows are great?

I am trying to set a certain condition and count the consecutive rows that meet this condition and if the count >100. I don't want to drop all of the rows but to keep the first 10 and last 10 rows and delete everything in between (in this case 80 rows). On the other hand, if the count < 100 no rows will be dropped

count = 0

for i in range (len(df.speed)):
   if (df.speed.values [i] <= 15 ):
       count += 1


       if count > 100: 


I am mainly stuck in how to delete the rows that are in the middle and to keep the first and last 10 rows. Would appreciate if someone can give a hint. Thanks

Keeping original input in consideration for final product

I am attempting to take two inputs, a and b, and perform an operation. My code is as follows:

a = int(input("Enter an integer A to be multiplied: "))
b = int(input("Enter an integer B to be multiplied: "))
x = 0

while True:
    print(a, b)
    b //= 2
    a *= 2
    if b < 1:
        break
    if b % 2 == 1:
        new = [a]
        for i in new:
            x += i
print(x)

If I enter 34 and 19, the output is:

Enter an integer A to be multiplied: 34
Enter an integer B to be multiplied: 19
34 19
68 9
136 4
272 2
544 1
612

The answer should be 646, as the remainder of 19%2 is 1. Why does my code not consider 34, 19 while going through the second if statement?

Performing multiple actions in an IF statement

I want to change the values of multiple variables, based on the condition of another variable

Something like:

df <- iris
df$index <- row.names(df)

if(df$index == 10){
  df$Species <- "test";
  df$Sepal.Length <- 100
}

So if the index value is 10, then I want to change Species to "test" AND change sepal.length to 100.

Instead I get a warning:

Warning message:
In if (df$index == 10) { :
  the condition has length > 1 and only the first element will be used

And the variables remain unchanged.

Better function and approach to calculate intensive matrix constantly re-weighting data? [baseball related]

Apologies for whatever is unclear. I've been told using data.table is one possible fix.

I'm trying to run some baseball savant at bat data through the run_expectancy_code function that is found in the baseballr package in a modified manner. Normally the function will take the dataframe and compute a run expectancy dataframe into the global environment with 2 columns the count_base_out_state and avg_re (average run expectancy). Like such:

 count_base_out_state        avg_re
 <chr>                        <dbl>
1 3 - 1 ,  0  outs,  1b 2b 3b   2.22
2 3 - 0 ,  0  outs,  1b 2b 3b   2.14
3 3 - 2 ,  0  outs,  1b 2b 3b   2.10
4 2 - 0 ,  0  outs,  1b 2b 3b   1.87
5 2 - 0 ,  0  outs,  _ 2b 3b    1.76
6 3 - 0 ,  0  outs,  _ 2b 3b    1.74

What I want to do is to calculate the run expectancy table of my data but to do so in a for loop, where I the run expectancy is calculated after the data is re-weighted each time to increase the value of the primary pitch in these calculations and its 30 most similar pitches which I have stored in another dataframe (pitch_similarity). But I want in the end not just a dataframe with the run expectancy of one given pitch after the data is re-weighted but to be run in a loop reweighting the data each time for the appropriate pitch and its top 30 similar pitches and then in the run_expectancy table including a 3rd column which will let me know the primary pitch in a given situation (the one everything was corrected by.

I want the weighting to be the primary pitch (aka pitch_1) at 20%, 1-5 (pitch_2) closest matches (by rank) to 20% of the data, 6-10 to 5%, 11-30 to 5%, and all other pitches as the remaining 50%.

I at first thought maybe to write a for loop like this which I think would duplicate the approriate rows to the right weighting, but I'm worried about memory exhaustion issues and would need something much more efficient.

for (pitch_1 in pitch_similarity) {

  # temporary weighted dataframe
  # primary correction
  df2 = lefty_abs %>% filter(pitch_1 = pitch_key) %>% slice(rep(1:n(), 
    each = nrow(lefty_abs)*0.2)) %>%
    rbind(lefty_abs)

  df2 = df2 %>% mutate(pitch_key_2 = pitch_key)

  # 1-5 correction
  df2 = df2 %>% filter(pitch_1 = pitch_key & pitch_2 = pitch_key_2 & rank <= 5) %>% 
    slice(rep(1:n(), each = (nrow(lefty_abs)*0.2)/5)) %>%
    rbind(df2)

  # 6-10 correction
  df2 = df2 %>% filter(pitch_1 = pitch_key & pitch_2 = pitch_key_2 & rank <= 10 & rank >= 6) %>% 
    slice(rep(1:n(), each = (nrow(lefty_abs)*0.05)/5)) %>%
    rbind(df2)

  # 11-30 correction 
  df2 = df2 %>% filter(pitch_1 = pitch_key & pitch_2 = pitch_key_2 & rank <= 30 & rank >= 11) %>% 
    slice(rep(1:n(), each = (nrow(lefty_abs)*0.05)/20)) %>%
    rbind(df2)

 # runs through run expectancy calculator, but need to figure out how to create 4th column
 # indicatin that primary pitch and also to bind all these dataframes together in the end

 run_expectancy(df2, level = "pitch")


}

This is the run_expectancy_code function itself:

#' Generate run expectancy and related measures and variables from Baseball Savant data
#'
#' These functions allow a user to generate run expectancy and related measures and variables from Baseball Savant data. Measures and variables will be added to the data frame and a run expectancy table will be assigned to the Global Environment.
#' @param df A data frame generated from Baseball Savant.
#' @param level Whether you want run expectancy calculated at the plate appearance or pitch level. Defaults to plate appearance.
#' @keywords MLB, sabermetrics
#' @importFrom dplyr filter group_by summarise arrange lead mutate left_join
#' @importFrom stringr str_count
#' @export
#' @examples
#' \dontrun{run_expectancy_code(df, level = "plate appearances")}

run_expectancy_code <- function(df, level = "plate appearance") {

  single_outs <- c("strikeout", "caught_stealing_2b",
                   "pickoff_caught_stealing_2b", "other_out",
                   "caught_stealing_3b", "caught_stealing_home",
                   "field_out", "force_out", "pickoff_1b",
                   "batter_interference", "fielders_choice",
                   "pickoff_2b", "pickoff_caught_stealing_3b",
                   "pickoff_caught_stealing_home")
  df <- df %>%
    dplyr::arrange(game_pk, at_bat_number, pitch_number) %>%
    dplyr::group_by(game_pk) %>%
    dplyr::mutate(final_pitch_game =
                    ifelse(pitch_number == max(pitch_number), 1, 0)) %>%
    dplyr::ungroup() %>%
    dplyr::group_by(game_pk, at_bat_number, inning_topbot) %>%
    dplyr::mutate(final_pitch_at_bat = ifelse(pitch_number == max(pitch_number), 1, 0)) %>%
    dplyr::ungroup()

  df <- df %>%
    dplyr::arrange(game_pk, inning_topbot, at_bat_number, pitch_number) %>%
    dplyr::mutate(runs_scored_on_pitch = stringr::str_count(des, "scores"),
                  runs_scored_on_pitch =
                    ifelse(events == "home_run", runs_scored_on_pitch + 1,
                           runs_scored_on_pitch),
                  bat_score_after = bat_score + runs_scored_on_pitch) %>%
    dplyr::arrange(game_pk, at_bat_number, pitch_number) %>%
    dplyr::mutate(final_pitch_inning =
                    ifelse(final_pitch_at_bat == 1 &
                             inning_topbot != lead(inning_topbot), 1, 0),
                  final_pitch_inning = ifelse(is.na(final_pitch_inning),
                                              1, final_pitch_inning))

  if (level == "plate appearance") {
    df <- df %>%
      dplyr::group_by(game_pk, inning, inning_topbot) %>%
      dplyr::mutate(bat_score_start_inning = min(bat_score),
                    bat_score_end_inning = max(bat_score),
                    cum_runs_in_inning = cumsum(runs_scored_on_pitch),
                    runs_to_end_inning = bat_score_end_inning - bat_score) %>%
      dplyr::ungroup() %>%
      dplyr::mutate(base_out_state = paste(outs_when_up, " outs, ",
                                           ifelse(!is.na(.$on_1b), "1b", "_"),
                                           ifelse(!is.na(.$on_2b), "2b", "_"),
                                           ifelse(!is.na(.$on_3b), "3b", "_")))

    re_table <- run_expectancy_table(df)

    df <- df %>%
      left_join(re_table, by = "base_out_state")

    df <- df %>%
      dplyr::filter(final_pitch_at_bat == 1) %>%
      dplyr::arrange(game_pk, inning, inning_topbot) %>%
      dplyr::group_by(game_pk, inning, inning_topbot) %>%
      dplyr::mutate(next_base_out_state = dplyr::lead(base_out_state)) %>%
      dplyr::ungroup() %>%
      dplyr::left_join(re_table,
                       by = c("next_base_out_state" = "base_out_state")) %>%
      dplyr::rename(next_avg_re = avg_re.y,
                    avg_re = avg_re.x) %>%
      dplyr::mutate(next_avg_re = ifelse(is.na(next_avg_re), 0, next_avg_re),
                    change_re = next_avg_re - avg_re,
                    re24 = change_re + runs_scored_on_pitch) %>%
      dplyr::arrange(game_pk, inning, inning_topbot)
  } else {
    df <- df %>%
      dplyr::group_by(game_pk, inning, inning_topbot) %>%
      dplyr::mutate(bat_score_start_inning = min(bat_score),
                    bat_score_end_inning = max(bat_score),
                    cum_runs_in_inning = cumsum(runs_scored_on_pitch),
                    runs_to_end_inning = bat_score_end_inning - bat_score) %>%
      dplyr::ungroup() %>%
      dplyr::mutate(count_base_out_state =
                      paste(balls, "-", strikes, ", ",
                            outs_when_up, " outs, ",
                            ifelse(!is.na(.$on_1b), "1b", "_"),
                            ifelse(!is.na(.$on_2b), "2b", "_"),
                            ifelse(!is.na(.$on_3b), "3b", "_")))

    re_table <- run_expectancy_table(df, level = "pitch")

    df <- df %>%
      left_join(re_table, by = "count_base_out_state")

    df <- df %>%
      #dplyr::filter(final_pitch_at_bat == 1) %>%
      dplyr::arrange(game_pk, inning, inning_topbot) %>%
      dplyr::group_by(game_pk, inning, inning_topbot) %>%
      dplyr::mutate(next_count_base_out_state =
                      dplyr::lead(count_base_out_state)) %>%
      dplyr::ungroup() %>%
      dplyr::left_join(re_table,
                       by = c("next_count_base_out_state" =
                                "count_base_out_state")) %>%
      dplyr::rename(next_avg_re = avg_re.y,
                    avg_re = avg_re.x) %>%
      dplyr::mutate(next_avg_re = ifelse(is.na(next_avg_re), 0, next_avg_re),
                    change_re = next_avg_re - avg_re,
                    re24 = change_re + runs_scored_on_pitch) %>%
      dplyr::arrange(game_pk, inning, inning_topbot)
  }

  assign("run_expectancy_state_table", re_table, envir = .GlobalEnv)

  df

}

Here are links to pastebins of dputs of the first 100 lines of every given dataframe I've mentioned but lefty_abs aka my baseball savant at bat data is a public dropbox link because its 223 mb:

baseball savant data (lefty_abs) - https://www.dropbox.com/s/tgoc2b8vefybi0b/test.txt?dl=0

pitch_similarity - https://pastebin.com/sink1bmD

run_expectancy_state_table - https://pastebin.com/uHnHGDc6

How to set up an IF condition within mysql package in node.js

I'm using mysql package for node.js Studying the documentation did not help me with my question. I want to make following:

if (SELECT table_field WHERE id = some_value ){
  // execute some code
} else{
  // execute some code
}

So I want SELECT to return either TRUE or FALSE (like EXISTS operator) How can I do so with node.js ?

My if-else program keeps printing both, if and else, why?

I tried to program a simple if-else code, its supposed to be a interview sort of thing which asks you questions and you put in the answer.

When I run the .exe and I put in the conditions of the if command, it prints both the if and the else statement, even though the requirements of else haven't been met. Why is that?

already tried to use only if in both statements. tried changing the syntax etc.

import java.io.IOException;
import java.util.Scanner;

public class Abfrage {

 public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner scanner = new Scanner(System.in);
    System.out.println("Wie ist dein Geschlecht? M oder W?");
    String geschlecht = scanner.nextLine();

    System.out.println("Wie ist dein Alter?");
    int alter = Integer.parseInt(scanner.nextLine());
    if (alter >= 18 && alter <= 100) {
        System.out.println("Du bist volljaehrig, herzlichen Glueckwunsch!");
    } 
    else if(alter >= 0 && alter <= 17);
        System.out.println("Du bist leider noch minderjaehrig mein Kind.");
    }

 }

I want the program to give out ("Du bist volljaehrig, herzlichen Glueckwunsch!") when I put in a number between 18 and 100. When I put in a number between 0 and 18 its supposed to tell me "Du bist leider noch minderjaehrig mein Kind."

When I put in 16 for example, it only gives me the else if output which is as I expected. When I put in 19 for example, it gives me both outputs.

Why is there no "return if" statement in programming languages?

First of all, I would like to point out that my theoretical knowledge of the anatomy of programming languages is not as deep as it should be, and I apologize in advance.

This may also be a stupid question, I apologize for that, but I have been wondering for some time why there is no return if statement or at least syntactic sugar for it in (at least the ones I'm familiar with) programming languages, especially in languages like Python or Lua, which are relatively high-level and often allow an alternative spelling with syntactic sugar.

Take the following code, for example:

if(x > y) {
    return x;
}

Of course you know directly what happens, if x > y is true x is returned. However, one could now argue the following:

  1. Depending on the programming language several lines are needed for a simple statement. Of course you could write it inline like if (x > y) { return x }
  2. It doesn't "sound" that great: if x > y, x gets returned

Just to make it clear, I don't mean to say that the "traditional" way is bad, I'm just asking out of interest.

If you were to use a statement like "return if", the above statement could look like this:

return x if (x > y);

It is a one-liner and it reads well x gets returned if x > y


Now I asked myself the following questions:

  1. Is this simply a design decision?
  2. Does a return if syntax cause unnecessary complications for the parser/compiler?
  3. If it's neither the first nor the second, then what is it? Coincidence? I will certainly not be the first one to think about it in all the decades of programming.

Using multiple 'is' variables in a single if statement

Assuming the following if-statement, when using the is keyword with multiple OR conditions, Is there a way to find out which condition passed the evaluation without having to check the values in separate or nested if-statements?

if (value is int xint
 || value is double xdouble
 || value is decimal xdecimal)
{
    // do with value
}

samedi 27 avril 2019

Conditional Goto based on Groovy Result response

first of all, I'm not sure if this is possible but I want to make a groovy script to run conditionally to one or another step based on the groovy script result:

The options I want to have is 3 :

Active Inactive Stop

I have a groovy script step to define a UI window to prompt like this:

def ui = com.eviware.soapui.support.UISupport;
def path = ui.prompt("Active Inactive or Stop","Title","");
def regResult = path

So based on what I type inside the popup window do the following:

If Active / Go to testRunner.gotoStepByName("InjectActive")
If Inactive / Go to testRunner.gotoStepByName("InjectInactive")
If Stop / Go to testRunner.gotoStepByName("Final Results")

Image of current Script

Any Ideas on how can I do this?

Thanks in advance

How can I set a state only if there is a condition?

I have a percentage into a text view that changes, but it can't be more than 100%. I use a function with a setstate and I want that if the percentage in the text view is more than 100% it changes in 100%. Something like this:

onPressLearnMore= () => { this.setState({

rareperc1: (this.state.rareperc2*this.state.boxes),

rareperc:parseFloat(this.state.rareperc1).toFixed(4),

if(rareperc==100){

rareperc:100,

} ... }); }

The actual code is:

onPressLearnMore= () => {

    this.setState({

            rareperc1: (this.state.rareperc2*this.state.boxes)

            rareperc:parseFloat(this.state.rareperc1).toFixed(4),

... }); }

How to echo an HTML link if visitor comes from a specific WordPress page - using page ID?

I am trying to get the ID of a referring WordPress page and show link based on the specific previous page. I know that we can use server http referrer but it would be more suitable for me to get the referring WP page/post ID and echo some html content on the page by if statement.

I have a following code example put together from various parts (it is not structurally correct but I hope you got the idea):

$visitorcamefrom = $_SERVER['HTTP_REFERER'];
if ( $visitorcamefrom == icl_object_id(17, 'page', true) ) { echo <a href="<?php echo(get_permalink(icl_object_id(8, 'page', true))); ?>" class="absolute-top-left left-arrow btn btn-lg btn-primary visible-lg"><span class="icon1"></span></a> }
else { echo <a href="<?php echo(get_permalink(icl_object_id(12, 'page', true))); ?>" class="absolute-top-left left-arrow btn btn-lg btn-primary visible-lg"><span class="icon2"></span></a> };

jQuery - hover and if statement

I'm trying to run hover but only if a given element has certain class.

For exaple:

jQuery

$("#banner").hover(
  if ($(this).hasClass("bannerReady")) {
  function() {
    runOne();
  },
    function() {
      runTwo();
    }
}
);

But this won't work.

How can we use varargs for objects and compare their instance variables in the method

Suppose i have a Person class with some instance variables like age i want to make a varargs method that will return me a younger one object of person I'm choosing varargs because by the span of time the number of objects will be less or more, at time 0 there will be only 1 object, as time increases the number of objects will be more.

This method will give me the younger one and the younger will be removed, these objects will be stored in the arraylist before passing to varargs method

Person p1 = new Person();
Person p2 = new Person();

public Person youngerOne(Person ... p){

//Here i want to compare but I'm not sure how can i do this with varargs
//I.e if(p1.getAge() < p2.getAge()){
Return p1;
}Else{
P2}

}

This program is skipping straight from if statement to else statement even though the codition is true

My program is skipping straight from if statement which is true to the else statement and I cannot seem to find the problem

I have tried moving this around and everything but nothing seems to be working

while keepgoing == 0:
    try:
        valuea = float(input("What is your a value: "))
        valueb = float(input("What is your b value: "))
        valuec = float(input("What is your c value: "))
        print (myQuadFormula(valuea,valueb,valuec))
        user_ask = input("Do you want to enter another set of data (yes or no)?: ") 
        if (user_ask[0].lower == "y"):
           print ("Enter your data below")
        else:   
            exit ()
    except ValueError:
        print ("Input a valid number")

I expected the program to restart the loop when a person types in yes and to exit if the person types in no

Most optimal way to incorporate menu system into program?

I'm creating a small program that will be used to manipulate a phone directory. I obviously will need a menu system of some sort and am wondering what is the most optimal way to incorporate one in my program.

I've seen several different ways however haven't enough experience to judge which is better in the long run.

  • Should I create a Menu class and have its methods in there?

  • Should I have a constructor in my ArrayDirectory class (contains all methods for manipulating directory) that outputs the menu options and asks for input every time a Directory object is made? My current constructor for the class just loads phonebook records from a text file so they can be used.

  • Should I just add the menu methods in the ArrayDirectory class and call them in main method when needed?

Right now I have it set up like so:

public class ArrayDirectory implements Directory {

    // Initialise variables for program
    private final static int MAX_ENTRIES = 20;
    private static Scanner input = new Scanner(System.in);
    DirectoryFile file = new DirectoryFile("C:\\Users\\John\\Documents\\Phonebook.txt");
    static ArrayList<Entry> phonebook = new ArrayList<>(MAX_ENTRIES);

    public ArrayDirectory() throws IOException {
        loadEntries(file.getFile());
        System.out.println("Staff Phonebook Directory Program");
        System.out.println("1) Add Entry");
        System.out.println("2) Delete Entry");
        System.out.println("3) Search Entry");
        System.out.println("4) Edit Entry");
        System.out.println("5) Display All Entries");
        System.out.println("6) Exit Program");

        int choice = input.nextInt();
        switch (choice){
        case 1:

            break;
        case 2:

            break;
        case 3:

            break;
        case 4:

            break;
        case 5:

            break;          
        case 6:

            break;
        default:

            break;
        }
    }

...(Other operation methods)...

So that when I create an ArrayDirectory class in my eventual main class, everything will be loaded straight away. Or is this not as efficient as I am thinking?

Also, is it more efficient to use if-else statements here instead of switch/case statements?

how do i fix simple logic error in codename one?

I am new to codename one. I am trying to build an app in which I am stuck at a point. In attached first screenshot as you can see, there is an accordion named as Environment and inside Environment there is a Picker. Same thing is there for the other accordions. What I want to do is when user selects one of the task from picker, other accordions should be non editable. for instance, user selected picking up a trash from Environment accordion, he shouldn't be able to select any other accordions.

in second picture I don't want the user to select more than one type. can someone help me with that?

https://imgur.com/EYzDLP1

https://imgur.com/SAcu0UN

I tried doing it by if else loop, but its getting worse.

Expected Result: User should be able to select only one deed type as shown in image.

Actual Result: N/A

Why is if statement not working in ElementTree parsing?

I'm trying to parse an xml file using ElementTree which looks like this:

</Event>


-<Event timestamp="2016-08-14T14:23:33.634" id="1713385925" 
version="1471181110290" last_modified="2016-08-14T14:25:11" y="11.0" 
x="89.7" outcome="0" team_id="148" player_id="51327" sec="8" min="23" 
period_id="1" type_id="4" event_id="205">

<Q id="733814222" qualifier_id="265"/>

<Q id="481660420" qualifier_id="286"/>

<Q id="813378778" qualifier_id="152"/>

<Q id="570443899" qualifier_id="56" value="Right"/>

<Q id="420312891" qualifier_id="233" value="248"/>

<Q id="1186861264" qualifier_id="13"/>

</Event>


-<Event timestamp="2016-08-14T14:23:33.634" id="1635888622" 
version="1471181110289" last_modified="2016-08-14T14:25:11" y="89.0" 
x="10.3" outcome="1" team_id="143" player_id="169007" sec="8" min="23" 
period_id="1" type_id="4" event_id="248">

<Q id="1871787686" qualifier_id="56" value="Back"/>

<Q id="176295814" qualifier_id="13"/>

<Q id="69346842" qualifier_id="233" value="205"/>

<Q id="1588029344" qualifier_id="265"/>

<Q id="559785299" qualifier_id="285"/>

<Q id="380723313" qualifier_id="152"/>

The code I'm using is simple and is working as expected. However, everything changes when I try to add an if condition to the code

import xml.etree.ElementTree as ET

root = ET.parse(r'C:\Users\ADMIN\Desktop\Abhishek\PSG - Copy\Sample.xml').getroot()

Games = root.getchildren()
for Game in Games:
    Events = Game.getchildren()
    for Event in Events:
        type_id = Event.attrib["type_id"]
        team_id = Event.attrib["team_id"]
        Qualifiers = Event.getchildren()
        for Qualifier in Qualifiers:
            id_ = Qualifier.attrib['id']
            if id_ == 142:
                print ("val")

Here's the error it's producing:

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 9
    Games = root.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 11
    Events = Game.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 15
    Qualifiers = Event.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

I have tried removing the if statement and that works perfectly. However, I do need to set a condition to call all the id_s which are a certain value. I've tried using "142" as well as 142 but the problem persists. Why exactly is this happening?

R function with two arguments if statement

I am trying to write a function which takes in two arguments, and produces two results. The first function needs to compare an integer to 100, and provide "invalid" for text. This the code for that:

   compare <- function(x) {

   if (!is.numeric(x))  {
   result = "invalid" 
   }
   else if (x>100) {
   result = "Pass"
   }

   else if (x<100) {
   result = "Fail"
   }

   else if (x==100) {
   result = "Neutral"
   }

   print(result)

   }

The second function needs to prints "valid" if a character/text, and provide nothing if an integer.

   compare2 <- function(y) {

   if (!is.numeric(y))  {
   result = "valid" 
   }

   else if (!is.numeric(y)) {
   result = ""
   }

   print(result)

   } 

My question is how to I combine these two functions into one? I've tried multiple things (not shown), but nothing seems to work. I need one function, called compare for example, which has two arguments like so:

 compare <- function(x,y) {....
 }

My problem is that I don't know how to combine the two arguments into one function block. The output should look like this:

 compare(10,"text") ===> "fail","valid"
 compare(100, 90) ===> "neutral"
 compare("text","text") ==> "invalid","valid"

Lapply to a list of dataframes only if column exists

I have a list of dataframes for which I want to obtain (in a separate dataframe) the row mean of a specified column which may or may not exist in all dataframes of the list. My problem comes when the specified column does not exist in at least one of the dataframes of the list.

Assume the following example list of dataframes:

df1 <- read.table(text = 'X   A   B   C
                       name1  1   2   3
                       name2  5  10   4',
                 header = TRUE)  

df2 <- read.table(text = 'X   B   C   A
                       name1  8   1  31
                       name2  9   9   8', 
                 header = TRUE)

df3 <- read.table(text = 'X   B   A   E
                       name1  9   9  29
                       name2  5  15  55', 
                 header = TRUE)

mylist_old <-list(df1, df2)
mylist_new <-list(df1, df2, df3)

Assume I want to rowMeans column C the following piece of code works perfectly when the list of dataframe (mylist_old) is composed of elements df1 and df2, :

Mean_C <- rowMeans(do.call(cbind, lapply(mylist_old, "[", "C")))
Mean_C <- as.data.frame(Mean_C)

The trouble comes when the list is composed of at least one dataframe for which column C does not exist, which in my example is the case of df3, that is for list mylist_new:

Mean_C <- rowMeans(do.call(cbind, lapply(mylist_new, "[", "C")))

Leads to: "Error in [.data.frame(X[[i]], ...) : undefined columns selected

One way to circumvent this issue is to exclude df3 from mylist_new. However, my real program has a list of 64 dataframes for which I do not know whether column C exists or not. I would have like to lapply my piece of code only if column C is detected as existing, that is applying the command to the list of dataframes but only for dataframes for which existence of column C is true.

I tried this

if("C" %in% colnames(mylist_new))
 {
     Mean_C <- rowMeans(do.call(cbind, lapply(mylist_new, "[", "C")))
     Mean_C <- as.data.frame(Mean_C)    
 }

But nothing happens, probably because colnames refers to the list and not to each dataframe of the list. With 64 dataframes, I cannot refer to each "manually" and need an automated procedure.

Can you convert these 2 IfElse Statements to 1

I try to shorten my if statements. I completed 1 but aren't able to see how to shorten the other 1 and clean it up. I Have shortened 1 as an example and I hope I can get some help :D.

I fixed this 1.

if (_clickDestination.Y < Position.Y && 
_clickDestination.Y != Position.Y && Position.X >= _clickWalkStairsX)
            {
                Position.Y -= (int)StairSpeed;  // moves the person up on the stairs.
            }
            else if (_clickDestination.Y != Position.Y && Position.X >= _clickWalkStairsX)
            {
                Position.Y += (int)StairSpeed; // moves the person down on the stairs
            }

To this:

if (_clickDestination.Y != Position.Y && Position.X >= _clickWalkStairsX)
            {
                if (_clickDestination.Y < Position.Y)
                {
                    Position.Y -= (int)StairSpeed;  // moves the person up on the stairs.
                }
                else
                {
                    Position.Y += (int)StairSpeed;  // moves the person down on the stairs
                }
            }

Now I am trying to fix this 1 just like I did above.

else if (
                    (   _clickDestination.Y == Position.Y && 
                        _clickDestination.X > Position.X) || 
                    (   _clickDestination.Y != Position.Y &&
                        _clickWalkStairsX != Position.X)
                    ) 
            {
                Position.X += (int)Speed; // moves the person to the right
            }
            else if (   _clickDestination.Y != Position.Y || 
                        _clickDestination.X < Position.X)
            {
                Position.X -= (int)Speed; // moves the person to the left
            }

I hope someone can actually see how it needs to get fixed and would really appreciate it. ALl the if else will stand after each other.

How do I add tolerance to an if statement in Javascript

I am learning JavaScript with the p5js library and have decided to make a very basic game.

I simply want the game to end when the condition of an if statement is met. Such as

if (x == y) {
>>>endcode here<<<
}

however I need to add a tolerance of 50 to each value

so the code would be something like

if (x == y (give or take 50) ){
>>>endcode here<<<
}

I am unsure of how to add the tolerance to the statement so I have come here for some help. Thanks :)

vendredi 26 avril 2019

How do I solve this problem involving if statements and syntax errors?

The if statement is returning an error of not supported between 'int' and 'str' and I don't know how to fix it

number_of_patients = input("Enter number of patients: ")
if number_of_patients < 1:
    print("Please enter a positive integer")

I expect the print message to appear "Please enter a positive integer" but I instead get the aforementioned error message.

When I try to check if more then 1 parameter is true in IF statement the code won't work anymore...why?

I'm perplex about an IF statement I'm trying to make work. I need to check if the actual hour is in a range of numbers...

Example:

$currentTime=date('H', $dateToCheck);

if($currentTime<18 && $currentTime>7)
{
   do something;
}

The problem is that whenever I try to check the time with only one statement the IF will work but if I use "&&" and add another statement the IF won't work anymore.

(Of course both of the statement are true so the if should be executed)

The code I'm actually working on is the following

    $orarioMess=date('H',$queryDate);
    if($orarioMess<18 && $orarioMess>7)
    {
      $status=12;
      $checkStatus=1;
    }

I expect the IF still to be executed even with 2 statements to check. I have no clue why it isn't working...

How to display multiple consecutive html elements

I'm using ACF on my wordpress site to display HTML text in the search bar next to post titles based on that posts array values.

Right now the script only displays up to 1 of the html values, but I want it to include all of the values if they exist.

add_filter( 'asp_results', 'asp_custom_field_to_results', 10, 1 ); 
function asp_custom_field_to_results( $results ) {
  $custom_field = 'trade_status'; 

  foreach ($results as $k=>&$r) {
    if ($r->content_type != 'pagepost') continue;
    if ( function_exists('get_field') )
        $trade_status  = get_field( $custom_field, $r->id, true ); // ACF support
    else
        $trade_status  = get_post_meta( $r->id, $custom_field, true );
    // Modify the post title to add the meta value
    if ( !empty($trade_status) ) {
      if ( in_array('30', $trade_status) ) {
        $html = '<span class="new">New</span>';
      } else if ( in_array('20', $trade_status) ) {
        $html = '<span class="active">Active</span>';
      } else if ( in_array('10', $trade_status) ) {
        $html = '<span class="closed">Closed</span>';
      } else {
        $html = '';
      }
      $r->title = $html . $r->title;
    }
  }

  return $results;
}

If Else Statement is not being executed

I have a contact form, which includes required fields. I have written an If else statement so that if the required fields are empty, the form will not be sent and if it is, the form will be sent and cleared. The If part of the statement is executing, but the else doesn't seem to be. I am still learning Javascript so i have probably done something incorrectly.

I have tried looking at looking at layouts of If else statements and amending mines, but this has not helped.

<form name="myForm" class="contact-form" 
action="mailto:someone@example.com" method="post" enctype="text/plain">
    <input type="text" name="yname" class="contact-form-text" 
placeholder="Your Name" required>
    <input type="email" name="yemail" class="contact-form-text" 
placeholder="Your Email" required>
    <textarea class="contact-form-text" name="ymessage" placeholder="Your 
Message" required></textarea>
    <input type="reset" class="contact-form-btn-reset" value="Reset">
    <input type="submit" class="contact-form-btn" onClick="return 
submitForm()" value="Send">

    <script>
      function submitForm() {
        var x = document.forms["myForm"][yname][yemail][ymessage].value;
        if (x == "") {
          alert("Please complete form.");
          return false;
        } else {
          alert("Your message has been sent.");
          var frm = document.getElementsByName('myForm')[0];
          frm.submit();
          frm.reset();
          return false;
        }
      }
    </script>
  </form>

When the submit button is pressed, i'm expecting the form to submit with an alert and clear (if all fields are completed), if all fields aren't completed i expect the form to not submit.

Display post meta based on post category

talent_cat which is the category of said post, has 4 values: modelos, atores, musica, djs and inside each individual talent_cat there are these post meta keys:
talent_id_1495127471815 for modelos,
talent_id_1495127471816 for atores,
talent_id_1495127471817 for musica,
and talent_id_1495127471818 for djs

How can I build a conditional to show the right post meta depending on the talent_cat of said post? So if the post belongs to talent_cat = modelos it returns the talent_id_1495127471815 and not the other values.

I tried this but unsuccessfully:

$talent_data = get_the_term_list( $post->ID, 'talent_cat');
switch( $talent_data ) {
                case 'modelos':
                    echo get_post_meta(get_the_ID(), 'talent_id_1495127471815', true);
                    break;
      }

Thanks.

How to make iterative loop for Pandas column name extraction more efficient?

How do I make this code more efficient? I am trying to implement the below-given logic on a much bigger data frame of 100 columns. The idea is to take the required keywords and perform further filtering like filtered_df = df[result]

search_list= ['A','B']
df_column_names=['Apple','Airplanne','Banana','Ball','Bat','Cat','Champ','Dog','OX','Zebra']
result=[]

for search_string in search_list:
    for column_name in df_column_names:
        if search_string in column_name:
            result.append(column_name)

result =['Apple', 'Airplanne', 'Banana', 'Ball', 'Bat']

Get the result and perform filtering like filtered_df = df[result]