jeudi 31 août 2017

Do You Trust The If Statement in PHP or Any Other Programing Language?

we may used the If Statement millions times , but do you really trust this single line in expansive code ? . let's say you have a buy button or download button in your website that will give the user a expensive product and to get this product you need to be a VIP user . so do you just use

if($user->IsVip){
//give him 1 million dollar product
}

the value IsVip is just boolean can be 0 or 1 so what if the database get corrupted or hacked or any other issue that cause returning incorrect value from tha reality do you Trust it ? or you use your own class or function to determine the results ? i know some companies that uses the history of user and check it manually by agents so what do you think ? thanks

If/Else statement error [duplicate]

This question already has an answer here:

I'm trying to work on a basic text based "game" to experiment and see certain java functions in use/learn how to debug java code. I've run into an issue where a if/if else statement is print both outcomes if it meets the first section's criteria. I'm not sure what the problem is after looking through it and making changes, nothing I've tried has worked.

        //Initial name input
    System.out.println("Welcome, please input your name...");
    String name = ask.nextLine();
    System.out.println("Your name is "+name+", correct?");

    //Response the name accuracy
    System.out.println("\n(Type Y or N)");
    String nameResponse = ask.nextLine();

    //Name change/correction If/Else block
    if(nameResponse.equals("Y")) {
        System.out.println("Great!");
        }
        else if (nameResponse.equals("N"));{
            System.out.println("What is it then?");
            name = ask.nextLine();
            System.out.println("Oh, so your name is "+name);

What is the best way to compare 2 characters ignoring case in C#?

I am making password validation method using console app and got stuck with comparing two chars. Is there a way to compare two chars without using toUpper() or toLower() method. For example if i am comparing these two chars

 char c1 = 'a', c2 = 'A';

        bool result = c1.Equals(c2);

I want result to be true.

I've tried using toLower() method but i have a problem.

This is my password validation Method.

  private static bool PasswordValidation(string input)
    {        
        if(!(input.Length>=8&&input.Length<=15))
        {
            Console.WriteLine("min 8 characters max 15");
            return false;
        }

        int specialCharacters = 0, uppLatter = 0, lowerLatter = 0;
        char[] charArray = input.ToCharArray();

        for (int i = 0; i < charArray.Length; i++)
        {
            char ch = charArray[i];
            if (char.IsWhiteSpace(ch))
            {
                Console.WriteLine("can't use space in password");
                return false;
            }

            if (!char.IsLetterOrDigit(ch))              
                specialCharacters++;

            if (char.IsUpper(ch))
                uppLatter++;

            if (char.IsLower(ch))
                lowerLatter++;

            if (i < charArray.Length - 1)
            {

                if (char.ToLower(charArray[i])==char.ToLower(charArray[++i]))
                {
                    Console.WriteLine("same characters");
                    return false;
                }

                if(char.IsDigit(charArray[i])&&char.IsDigit(charArray[++i]))
                {
                    int sum = Convert.ToInt32(charArray[i]) + Convert.ToInt32(charArray[++i]);
                    if(sum==input.Length)
                    {
                        Console.WriteLine("sum is equal to length");
                        return false;
                    }
                }
            }

        }

        if (specialCharacters == 0)
        {
            Console.WriteLine("at lesast one special character is required");
            return false;
        }
        if (uppLatter == 0)
        {
            Console.WriteLine("at lesast one upper latter is required");
            return false;
        }
        if (lowerLatter == 0)
        {
            Console.WriteLine("at lesast one lower character is required");
            return false;
        }


        var repeats = input.GroupBy(s1 => s1)
            .Where(s1 => s1.Count() > 3)
            .Select(s1 => s1).ToArray();

        if (repeats.Length > 0)
        {
            Console.WriteLine("one character can't be repeted more than 3 times");
            return false;
        }
        return true;
    }

As you can see i've used integers to count the number of lower and upper letters, as well as special characters but this will only work for the first character of input string. Soon as i hit this

if (char.ToLower(charArray[i])==char.ToLower(charArray[++i]))

line of code, all hell breaks loose.

Any suggestion is helpful. Thank you for your time.

Sass @if directive take multiple conditionals? [duplicate]

This question already has an answer here:

I'm writing a @mixin that handles both pseudo elements and classes. I essentially need my mixin to listen for before and after and then do something different to what it would if it was a pseudo class. My current code is as follows:

@mixin pseudo($elem) {
  @if $elem == "before" {
    // perform task
  } @else if $elem == "after" {
    // perform same task
  }
}

My question is "Can the @if directive take two conditionals?" Leaning on my JS knowledge, I am wondering if something like the following is possible so that I can remove the @else if from the statement:

@mixin pseudo($elem) {
  @if (($elem == "before") || ($elem == "after")) {
    // perform the one task
  }
}

Thanks in advance.

if statement not working as expected

Hello again. I have got my mastermind game working. I have tried to implement difficulty levels, but this section always goes to the else statement no matter what i do.

def ask_number(self):
    while True:
        sleep(0.5)

Here is where it keeps skipping the if. Even when it is true.

        if self.difficulty == "hard":
            guess = input("Guess the number: ")
            self.guess = guess
            if len(guess) == len(str(self.number)):
                return True
            else:
                return "That is an invalid number!"
        else:
            return "Cant find difficulty"

I am not to sure why, but it is driving me mad now!

When obj = null, why doesn't (obj && (obj[1] || obj[2])) throw error?

Since operations inside parenthesis are executed first and obj is null, isn't it supposed to throw error when trying to read property of null? I am confused about order of operations, OR is evaluated before AND right?

Syntax error in executable pbs script

I have a pbs script that I am turning into an executable file then trying to run it, however, I am getting a syntax error. The syntax error is listened below:

./run_correlation_study.pbs: line 4: syntax error near unexpected token then' ./run_correlation_study.pbs: line 4: then'

Line 4 is the first line that says "then" under "if[i==0]". I have another pbs script called correlation_study.pbs that is executed in this script along with 3 command line parameters that are incremented by the for loops. I can't quite spot my syntax error though as my script looks similar to all the examples that I have looked at but something is obviously wrong. Below is my script:

    for((ARC_LENGTH = 1; ARC_LENGTH < 4; ARC_LENGTH++)); do
        for((i = 0; i < 4; i++)); do
           if[i==0]
             then
             qsub -v ARC_LENGTH_ARG=$ARC_LENGTH,NEUTRINO_BOUNDS=$i correlation_study.pbs
           elif[i==1]
           then 
           qsub -v ARC_LENGTH_ARG=$ARC_LENGTH,NEUTRINO_BOUNDS=$i correlation_study.pbs
           elif[i==2]
           then 
           qsub -v ARC_LENGTH_ARG=$ARC_LENGTH,NEUTRINO_BOUNDS=$i correlation_study.pbs
           elif[i==3]
           then 
           qsub -v ARC_LENGTH_ARG=$ARC_LENGTH,NEUTRINO_BOUNDS=$i correlation_study.pbs
           fi
        done
    done

EXCEL: cant perform functions on result from if statement

I have a row in an excel doc with =if(C1=1,C21,""), etc. This gives me a resulting value of 255. I can't seem to do anything with this value, if I set another cell to equal the result cell, it appears as 255 also (makes sense). If I do sum(), average(), etc. of the if result cell I get 0 as an answer (doesn't make sense). I've tried copying and pasting pasting (values only) but no luck.

I'm trying to take the average of a row of these if statements, but am getting the #DIV/0! error. I've tried changing the if statements to =if(C1=1,C21,0) and using =averageif(C50:J50,">0") but i get the same error.

Java Android Studio, I get error on if statement [duplicate]

This question already has an answer here:

This is the error code questionNumber is red

if (inputText == questionNumber) {

            }

I need to test the input number exactly to questionNumber

This is the code:

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

    final TextView numbers = (TextView) findViewById(R.id.textView);
    final Random random = new Random();


    Button generate = (Button) findViewById(R.id.btnRandom);

    generate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String questionNumber = String.format("%04d",random.nextInt(10000));

            numbers.setText(questionNumber);

        }
    });

    Button btnOke = (Button) findViewById(R.id.btnOK);
    final EditText input = (EditText) findViewById(R.id.inputNumber);
    final String inputText = input.getText().toString();
    btnOke.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (inputText == questionNumber) {

            }
        }
    });
}

}

mercredi 30 août 2017

IF statement in android studio - 2 of them works and 1 don't

I want to check on start of App if RGB diodes are lighting on ESP8266. So, I'm sending to smartphone from ESP data via UDP like this:

srvUDP:send("RED="..Fulfillment1.. ";GREEN="..Fulfillment2..";BLUE=".. Fulfillment3);

and receiving on Android App like this:

(... Bla Bla Bla... DatagramSocket and DatagramSocket...)
 protected void onPostExecute(Boolean result){
            if (result){
                      receive = false;  }
            else {
                if(receive=true) {
                    if(reveivedData!=null) {
                        colors.clear();
                        TextView textViewOdebrane = (TextView) findViewById(R.id.textViewReveivedData);
                        textViewReveivedData.setText(" " + reveivedData);
                        receive = false;
                        String color = null;
                        String value = null;
                        StringTokenizer stringTokenizer = new StringTokenizer(odebrane, "=;");
                        StringBuilder string123 = null;
                        while (stringTokenizer.hasMoreTokens()) {
                            color = stringTokenizer.nextToken();
                            value = stringTokenizer.nextToken();
                            colors.add(new color_value(Color, Value));
                        }
                        string123 = new StringBuilder();
                        int sizeOfList=  colors.size(); //colors is List<>
                        for (int i = 0; i < sizeOfList; ++i){
                        string123.append("\n Fulfillment of " + colors.get(i).getColor() + " = " + colors.get(i).getValue() + "%");
                        }
                        TextView textviewOdebrane = (TextView) findViewById(R.id.textViewOdebraneDane);
                        textviewOdebrane.setText(string123);

                        if (sizeOfList == 3) {
                            ToggleButton toggleButtonRed = (ToggleButton) findViewById(R.id.toggleButtonRED);
                            ToggleButton toggleButtonGreen = (ToggleButton) findViewById(R.id.toggleButtonGREEN);
                            ToggleButton toggleButtonBlue = (ToggleButton) findViewById(R.id.toggleButtonBLUE);

                            if (!(colors.get(0).getValue().toString().equals("0"))){
                                toggleButtonRed.setChecked(true);
                            }
                            else { toggleButtonRed.setChecked(false);}

                            if (!(colors.get(1).getValue().toString().equals("0"))){
                                toggleButtonGreen.setChecked(true);
                            }
                            else { toggleButtonGreen.setChecked(false);}

                            if (!(colors.get(2).getValue().toString().equals("0"))){
                                toggleButtonBlue.setChecked(true);
                            }
                            else { toggleButtonBlue.setChecked(false);}
                        }

and I've got problem at the last if statement. if's for get(0) and get(1) works fine, but if statement for get(2) always gives me toggleButtonBlue.setChecked(true) Can somebody tell me what is wrong here? How can I fix it?

How can you create a while loop using only if statements?

As the questions reads, can it be done?

r - lapply, ifelse and trying to compare row vs previous row in one column

Forgive me in advance for trying to use my excel logic in R, but I can't seem to figure this out. In a function, given X I am trying to find out if the row prior to it has a greater value or not using simple logic. If it is, show in the new column as "yes" if not "no".

Here is the sample data:

temp <- data
GetFUNC<- function(x){
         temp <- cbind(temp, NewCol = ifelse(temp[2:nrow(temp),8] > temp[1:(nrow(temp)-1),8], "yes","no"))
}
lapply <- GetFUNC(test)

Just so you can see column 8 it looks like this:

testdata$volume
 [1] 32216510 10755328  8083097  6878500  8377025  6469979 10675856  8189887  5337239
[10]  5156737

The error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 11, 10

Thanks for any insight you can provide!

David

Copy cell data and paste on different ranges based on date

Hi I'm extremely new to this and I would like to seek assistance with my code.

Please see my code below:

Sub Copy_Cells_Loop()

Application.ScreenUpdating = False

If Range("B1").Value = "8/1/2017" Then Worksheets("Dispute").Range("C2:C76").Value = Range("H9:H83").Value

Application.ScreenUpdating = True

End Sub

So what i'm looking for is that if the value of B1 changed from 8/1/2017 to 8/2/2017, the date will be paste to another worksheet to a different range. Please help me. :(

if statement does not alert variable

<html>
<head>
<title></title>
<script src="https:/code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
    <button>Button</button>
    <script>
        var user_response='';
        $('button').on('click',ask_a_question);

        function ask_a_question(){

            user_response = prompt('What is your item name?').toLowerCase();

            if (user_response === 'apple')

//Between here is where i dont understand why, 
//when the if statement is true, that it does not "alert" the bucketlist
//variable and then tells the user **"'learn to juggle', 'take a falconry
//class', 'climb mt everest'."** Does this code even make sense?

            alert(bucketList);

            var bucketList = [
                'learn to juggle', 
                'take a falconry class', 
                'climb Mt Everest'
            ];

        }
    </script>
</body>
</html>

R : Which is the fastest option? Using subset, if statement or object[]?

Which is the least time consuming option? Using subset, if statement or object[] ?

Converting a with statement to a togglable if

I am trying to make a bookmarklet that I can use to quickly toggle the class/id of elements. I found this [old] code for toggling highlighting links. I have read that the with statement should be avoided unless you are using use strict;. I couldn't find any walk through on how with would look like if, and not sure how it would look

javascript: for (nIx5Bs = 0; nIx5Bs < document.all.length; nIx5Bs++) {
  if (document.all[nIx5Bs].tagName == 'A') {
    with(document.all[nIx5Bs].style) {
      if (backgroundColor == 'yellow') {
        void(backgroundColor = document.bgColor)
      } else {
        void(backgroundColor = 'yellow')
      }
    }
  }
}

I found another bookmarklet to show ids, but it isn't togglable.

javascript: var t = document.getElementsByTagName('div');
for (i = 0; i < t.length; i++) {
  void(t[i].style.padding = '5px;');
  b = t[i].className;
  h = t[i].innerHTML;
  void(t[i].innerHTML = '<p style=\'color:red;font-weight:bold;\'>' + b + '</p>' + h);
}

Any hints to make this togglable would be great.

If Statements - Populating cell data based on zip code list

I have a list of zip codes and I'd like to associate a color code to a particular zip code. I have the list of colors that belong to the zip codes and want a formula that will populate the color code to the zip codes as I'm constantly looking at new data and having to fill in the data.

This is what I have so far =IF(B3=I3:I20, "Blue", IF(B2=I21:I34, "Orange", IF(B3=I35:I56, "Purple", IF(B3=I57:I74, "Yellow")))) but it only worked for one cell and the rest are showing errors. B3 is the cell where the zip code in question is and column I is the column where I have all zip codes sorted by color.

C++ Guessing game (is it as easy as it seems?)

Hi I am new to code and I want to advance on my basic skills. I have been able to do the simple program of the 'guess random number game' but I wanted to see if anyone was able to do this but with four numbers, so the computer would generate 4 random numbers and then the user would have to guess what all four are whilst the number of guesses is incremented. The user could also be told how many numbers they have correct so far. I have attempted it but haven't been able to succeed and this is the only platform I can really recieve any feedback on code.

Combining the results of two if statements - python / jupyter notebook

I have a bit of code that calculates pay / overtime pay based on the hours worked in a week. There are two if statements that calculate the pay for week1 and week2. What I am trying to do is then calculate the total pay which is the pay for the results of the week1 if statement plus the results of the week2 if statement, but I'm struggling. I'm probably making this much more difficult than it needs to be.

I'm using a Jupyter Notebook where each of the chunks below are in a separate cell. The results of the first if statement = 440 the second if statement = 473. The desired result is to combine these so that the output is 913.

Any help or suggestions are greatly appreciated!

rate = 11
week1 = 40 
week2 = 42

if week1 <= 40:
    print((rate * week1))
else:
    print((week1 - 40)*(rate * 1.5) + (40 * rate))

if week2 <= 40:
    print(rate * week2)
else:
    print((week2 - 40)*(rate * 1.5) + (40 * rate))

If statements don't work on Tensorflow variables

I tried to program a self driving car in Python and Tensorflow with this code:

import tensorflow as tf
from PIL import ImageGrab
import numpy as np
import pyautogui as pag
import time

x_p = tf.placeholder(tf.uint8)
y_p = tf.placeholder(tf.float32)

weights = [tf.Variable(tf.random_normal([5,5,3,32],0.1)),
           tf.Variable(tf.random_normal([5,5,32,64],0.1)),
           tf.Variable(tf.random_normal([5,5,64,128],0.1)),
           tf.Variable(tf.random_normal([25*25*128,1064],0.1)),
           tf.Variable(tf.random_normal([1064,1],0.1))]

def CNN(x, weights):
    output = tf.nn.conv2d(x, weights[0], [1,1,1,1], 'SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[1], [1,2,2,1], 'SAME')
    output = tf.nn.relu(output)
    output = tf.nn.conv2d(output, weights[2], [1,2,2,1], 'SAME')
    output = tf.nn.relu(output)
    output = tf.reshape(output, [-1,25*25*128])
    output = tf.matmul(output, weights[3])
    output = tf.nn.relu(output)
    output = tf.matmul(output, weights[4])
    output = tf.reduce_sum(output)
    return output

prediction = CNN(tf.cast(x_p, tf.float32), weights)
saver = tf.train.Saver()
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    saver.restore(sess, 'saved/model.ckpt')
    for t in range(5):
        print(t+1)
        time.sleep(1)

    while True:
        x = ImageGrab.grab()
        x = x.resize((100,100))
        x = np.asarray(x)
        output = sess.run(prediction, feed_dict={x_p:[x]})
        print(output)
        if output < 0.5 and output > 1.5:
            pag.keyDown('W')
            pag.keyUp('S')
            pag.keyUp('D')
            pag.keyUp('A')
        elif output < 1.5 and output > 2.5:
            pag.keyUp('W')
            pag.keyDown('S')
            pag.keyUp('D')
            pag.keyUp('A')
        elif output < 2.5 and output > 3.5:
            pag.keyDown('W')
            pag.keyUp('S')
            pag.keyDown('D')
            pag.keyUp('A')
        elif output < 3.5 and output > 4.5:
            pag.keyDown('W')
            pag.keyUp('S')
            pag.keyUp('D')
            pag.keyDown('A')
        elif output < 4.5 and output > 5.5:
            pag.keyDown('W')
            pag.keyUp('S')
            pag.keyDown('D')
            pag.keyUp('A')
        elif output < 5.5 and output > 6.5:
            pag.keyDown('W')
            pag.keyUp('S')
            pag.keyUp('D')
            pag.keyDown('A')
        elif output < 6.5 and output > 7.5:
            pag.keyUp('W')
            pag.keyDown('S')
            pag.keyDown('D')
            pag.keyUp('A')
        elif output < 7.5 and output > 8.5:
            pag.keyUp('W')
            pag.keyDown('S')
            pag.keyUp('D')
            pag.keyDown('A')
        else:
            pag.keyUp('W')
            pag.keyUp('S')
            pag.keyUp('D')
            pag.keyUp('A')

But the problem is that only the else statement fires, even though output has (for example) the value 1.3. I was able to find out, that the problem is caused by the variable output in the if statements, but I didn't manage to fix the problem. Can some of you please help me?

Printing only some properties of an object using for-in loop and if-else

I am wondering how to get only some of the elements of an object using only for-in and if-else.

For example, if we have the following object:

var person,
property;

person = {
    firstName: "John",
    lastName: "Smith",
    profession: "Lawyer",
    age: 31,
    eyeColor: "blue",
    hairColor: "blonde"
}

How do I print out only the second and fourth property of this object with for-in and if-else?

Speeding up Python 'for' Loop with nested 'if' Statements

I'm trying to speed up this loop I'm running to separate data into 2 categories. Normally I wouldn't care all that much about speed, but I am finding that right now the speed of this code is actually slowing down dramatically after multiple iterations. Here is how I wrote the code:

plane1Data = []
plane2Data = []
plane1Times = []
plane2Times = []
plane1Dets = []
plane2Dets = []
t1 = time.time()
for i in range(0,len(adcBoardVals)):#10000):
    tic = time.time()
    if adcBoardVals[i] == 5:
        if adcChannel[i] == 0:
            #detectorVal = detectorVal + [0]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [0]
        elif adcChannel[i] == 1:
            #detectorVal = detectorVal + [1]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [1]
        elif adcChannel[i] == 2:
            #detectorVal = detectorVal + [2]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [2]
        elif adcChannel[i] == 3:
            #detectorVal = detectorVal + [3]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [3]
        elif adcChannel[i] == 4:
            #detectorVal = detectorVal + [4]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            #plane1Dets = plane1Dets + [4]
        elif adcChannel[i] == 5:
            #detectorVal = detectorVal + [5]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [5]
        elif adcChannel[i] == 6:
            #detectorVal = detectorVal + [6]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [6]
        elif adcChannel[i] == 7:
            #detectorVal = detectorVal + [7]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [7]
    elif adcBoardVals[i] == 7:
        if adcChannel[i] == 0:
            #detectorVal = detectorVal + [16]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [16]
        elif adcChannel[i] == 1:
            #detectorVal = detectorVal + [17]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [17]
        elif adcChannel[i] == 2:
            #detectorVal = detectorVal + [18]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [18]
        elif adcChannel[i] == 3:
            #detectorVal = detectorVal + [19]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [19]
        elif adcChannel[i] == 4:
            #detectorVal = detectorVal + [20]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [20]
        elif adcChannel[i] == 5:
            #detectorVal = detectorVal + [21]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [21]
        elif adcChannel[i] == 6:
            #detectorVal = detectorVal + [22]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [22]
        elif adcChannel[i] == 7:
            #detectorVal = detectorVal + [23]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [23]
    elif adcBoardVals[i] == 6:
        if adcChannel[i] == 0:
            #detectorVal = detectorVal + [8]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [8]
        elif adcChannel[i] == 1:
            #detectorVal = detectorVal + [9]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [9]
        elif adcChannel[i] == 2:
            #detectorVal = detectorVal + [10]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [10]
        elif adcChannel[i] == 3:
            #detectorVal = detectorVal + [11]
            plane1Data = plane1Data + [rawDataMat[i,:]]
            plane1Times = plane1Times + [timeVals[i]]
            plane1Dets = plane1Dets + [11]
        elif adcChannel[i] == 4:
            #detectorVal = detectorVal + [12]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [12]
        elif adcChannel[i] == 5:
            #detectorVal = detectorVal + [13]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [13]
        elif adcChannel[i] == 6:
            #detectorVal = detectorVal + [14]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [14]
        elif adcChannel[i] == 7:
            #detectorVal = detectorVal + [15]
            plane2Data = plane2Data + [rawDataMat[i,:]]
            plane2Times = plane2Times + [timeVals[i]]
            plane2Dets = plane2Dets + [15]
    if i%100000 == 0:
        print('k = ',i)   
        toc = time.time()
        print('tictoc = ',toc-tic)
        print('elapsed = ',toc-t1)
    elif i>900000:
        if i%1000 == 0:
            print('k = ',i)
            toc = time.time()
            print('tictoc = ',toc-tic)
            print('elapsed = ',toc-t1)

#detectorVal = np.array(detectorVal,dtype='float')
plane1Data = np.array(plane1Data,dtype='float')
plane2Data = np.array(plane2Data,dtype='float')
plane1Times = np.array(plane1Times,dtype='float')
plane2Times = np.array(plane2Times,dtype='float')
plane1Dets = np.array(plane1Dets,dtype='int')
plane2Dets = np.array(plane2Dets,dtype='int')

I vaguely remember from a c++ course I took a while ago that you can make lists that can run faster than nested 'if' statements. Is this correct and if so can I do this in python? I am running python 3.5 right now. Thank you for your help.

Creating rule to create time based on delivery rate

I have a condition on my form that calculates the delivery time of the orders, follows the rule below:

date_default_timezone_set('America/Sao_Paulo');
$Agora = date('H:i:s');
$HoraServico = date('H:i:s', strtotime('+69 minute', strtotime($Agora)));

if ( $entrega = '5.00'){
    $HoraServico = date('H:i:s', strtotime('+120 minute', strtotime($Agora)));
}

if ( $entrega = '2.00'){
    $HoraServico = date('H:i:s', strtotime('+30 minute', strtotime($Agora)));

}

else if  ( $entrega = '7.00'){
    $HoraServico = date('H:i:s', strtotime('+20 minute', strtotime($Agora)));

};

What I need is to create a rule where $HoraServico is based on the delivery value $entrega

Example: If the delivery fee costs $ 7.00 then the delivery time will be the sum of the current time ($Agora) + 120 minutes.

If the delivery fee costs $ 2.00 then the delivery time will be the sum of the current time ($Agora) + 30 minutes. And so on.

The idea is, the more expensive the delivery rate (because it is far) the more time it will cost to deliver.

I tested like this, but it's not going! He is adding only the line:

$HoraServico = date('H:i:s', strtotime('+69 minute', strtotime($Agora)));

That is, always adding 69 minutes

As I understand it, he is not computing correctly the delivery rate that actually takes information from this line:

$entrega = $_POST["taxadeentrega"];

Sorry for the English, I'm Brazilian and I'm using a translator, in the community in Portuguese, nobody has answer!...

Using If Statement to Alter a Label's Contents

I am very new to Java, and really enjoy coding. However, I, personally, have found it is much more difficult to really understand than certain other languages (like Visual Basic or Lua).

It is only through 3 or 4 straight days or searching up hundreds of different questions on Google pertaining to various aspects of Java and the NetBeans compiler that I've made it this far.

I explain more in my comments in the code below:

private JLabel label;
private JTextField field;

public CalcTest() {
  
  super("Experimentation");                 // This sets the title of the
                                           // program to "Experimentation"(?)
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  
  setPreferredSize(new Dimension(400, 90));
  ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13));
  setLayout(new FlowLayout());
  JButton btn = new JButton("Change");
  
  btn.setActionCommand("myButton"); // Need Confirmation: What exactly
  btn.addActionListener(this);     // do these two lines do? Please
                                  // explain like I am 5.
  
  label = new JLabel("Hello World");
  add(btn);
  add(label);
  
  pack();     // This makes it so that all components in the program
             // are at or above their preferred sizes(?)
  
  setLocationRelativeTo(null);
  setVisible(true);
  setResizable(false);
}
public void actionPerformed(ActionEvent e)
  // I am trying create a program where you click a button that will
 // change label back and forth from "Hello Universe" and "Hello World"

{

    // Another thread suggested creating a String
   // variable to store the contents of a label
  String text = label.getText();

  if (e.getActionCommand().equals("myButton"))
    // Need Confirmation: This basically says "If the button is clicked(?)..." 

  {
    if (text = ("Hello World")) {
      // However, the compiler states that String cannot be converted to boolean
      label.setText("Hello Universe");
    } else
        label.setText("Hello World");

  }

Using [] if statement

I have the following issue, I want to use the following piece of code inside my function, but it doesnt work:

object[logical] = matrix of length 32
object[logical2] = dataframe of length 35
object[logical3] = matrix of length 31
object[logical4] = dataframe of length 33

However I get an error that the object 'object' is not found. If I define the object before these statements, I am not able to set it to different values with different lengths. All the matrixes and data frames are composed of one row and columns with names. These names are necessary for the latter part of this function to work as intended.

How should I define the object before these statements? Is using a regular if statement slower than this kind of [] if?

I am concerned with speed as I am working with a big dataframe and the function will be used in the shiny application.

Also, in reality there are 28 different logicals.

thx in advance

Ruby Program not performing as expected? If block executes despite failing the condition

The Following program is intended to iterate over the holiday_hash, capitalise all keys and values and puts them out:

def all_supplies_in_holidays(holiday_hash)
  holiday_hash.each do |key, value|
  key_string = key.to_s
  key_string.capitalize!
  puts "#{key_string}:"
  value.each do |key2, value2|
    if key2 == :new_year || :fourth_of_july || :memorial_day 
     key_to_string = key2.to_s
     key_string1 = key_to_string.split
     final_array = []
     key_string1.each do |splitted_string|
     final_array = splitted_string.capitalize!
    end
    final_string = final_array.join(" ")
    print "#{final_string1}:"
  else
    key_string1 = key2.to_s
    print "#{key_string1}"
  end
  value2.each do |array_value|
    new_array_capitalized = []
    new_array_capitalized << array_value.capitalize!
    new_array.join(" ")
   end
  end
 end
end

The expected output format is:

Winter:
Christmas: Lights, Wreath
New Years: Party Hats
Summer:
Fourth of July: Fireworks, BBQ
Fall:
Thanksgiving: Turkey
Spring:
Memorial Day: BBQ

The holiday_hash is as follows:

  {
  :winter => {
    :christmas => ["Lights", "Wreath"],
    :new_years => ["Party Hats"]
  },
  :summer => {
    :fourth_of_july => ["Fireworks", "BBQ"]
  },
  :fall => {
    :thanksgiving => ["Turkey"]
  },
  :spring => {
    :memorial_day => ["BBQ"]
  }
}

The problem is:

  1. The if block executes even if the conditions fails to evaluate to true.

Suggestions needed:

  1. How can I simplify the process of capitalising symbols who have two words in them like :new_york to be capitalised to New York? (As the #capitalised method will return New york)

XSLT with test and otherwise

I have below xslt where ID and LASTNAME are the input parameters. When ID matches the EMPLOYEE_ID in the VW_JAX_EMP_JOB_DEPTRECORDSELECT then set the Last_Name element as s0:PREFERREDLASTNAME otherwise se the input parameter LASTNAME. Below one doesnt work.

 <xsl:template name="GetLastNameVW_JAX_EMP_JOB_DEPT"> 
 <xsl:param name="ID" />
 <xsl:param name = "LASTNAME" />
 <xsl:element name="Last_Name">
 <xsl:choose>
 <xsl:when test="//s0:VW_JAX_EMP_JOB_DEPTRECORDSELECT[s0:EMPLOYEE_ID = $ID]/s0:PREFERREDLASTNAME">
 <xsl:value-of select="//s0:VW_JAX_EMP_JOB_DEPTRECORDSELECT[s0:EMPLOYEE_ID = $ID]/s0:PREFERREDLASTNAME" />
 </xsl:when>
 <xsl:otherwise> LASTNAME
 </xsl:otherwise>
 </xsl:choose>
 </xsl:element> 
 </xsl:template>

Can anyone please suggest me ho to set the otherwise tag here.

Mysql select with if else and order by statement

Without any training (and deaf) I developed a town portal system but I gave up on a specific select statement.

ORDER BY FIND_IN_SET(`townfield`,'TownA'), date LIMIT 3

ID1 TownB 2017-08-30 ID2 TownA 2017-08-22 ID3 TownA 2017-08-22 ID4 TownA 2017-08-22 ID5 TownC 2017-08-22 ID6 TownB 2017-08-10

The goal is that Town A select ID 2, 3 and 4, Town B select ID 1, 6 and 2 and Town C select ID 5, 1 and 2

In other words the town select his OWN articles first in date order with limit 3, ELSE select the remaining of the limit 3 in date order.

Using if_else, I can't return the column used as the conditional if the conditional is false

Like the title says, but basically, I've created a flag variable of different job descriptions in a dataset. I would like to change the each flag==true into the same row position from another variable. I've tried ifelse, if_else; all I've been able to get is a list of the changed values for the true conditional and NA's. Here is reproducible example below using the diamonds.

mydata <- diamonds[1:10,c(3,4)] 
mydata$position <- c('flag','cathy')
mydata
mydata$new.vary <- mydata %>% if_else(color=='E',position,color)

R Error: unexpected 'else' in "else" [duplicate]

This question already has an answer here:

I'm having a simple R code which returns Error: unexpected 'else' in "else":

if(1==1)
{
    x = 1
}
else
{
    x = 2
}

Can someone please explain how thats possible?

something wrong with if statement in my code

for line in dictionary:
    var=editdistance.eval(token[0],line.strip())
    if var <=best_var:
        best_var=var
        best_str.append(line.strip())
for String in best_str[-4:]:
    print(String)
    print(token[2])
    #print(best_var)
    if (String == token[2]):
        print('ddf')

For this code, it seems the if statement for string == token[2] never process, I check the condition it have the condition string=token[2]

Appending elements to a list based on condition

I was trying to append few elements to a list list_accepted_outsidenestant. I have shown part of code relevant to the current section. When i try to print the list list_accepted_outsidenestant, i get: list_accepted_outsidenestant- [([971, 977, 728, 740], set([728, 977, 971, 740]))]. The list is showing the same elements in set too. Can anyone pointout the mistake i am doing? Because of this, i am getting an error: set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant TypeError: unhashable type: 'list'

def leo(tag_data):
    available_ants_outside = []
    ori = []
    for id, (x, y) in tag_data:
        available_ants_outside.append(id)
        if for_coordinates_outside_nest((x, y)) is True:
            ori.append(id)
    return ori


def virgo(tag_data):
    available_ants_inside = []
    list_insidenest_ant_id = []
    set_inside_nest_ant_id = set()
    for id, (x, y) in tag_data:
        available_ants_inside.append(id)
        if for_coordinates_inside_nest((x, y)) is True:
            list_insidenest_ant_id.append(id)
            set_inside_nest_ant_id = set(list_insidenest_ant_id)
            return list_insidenest_ant_id,set_inside_nest_ant_id

 def bambino(ori,list_insidenest_ant_id):
    list_accepted_outsidenestant = []                       
    set_accepted_outsidenest_antlist = set()
    set_accepted_insidenest_antlist = set()
    if len(list_accepted_outsidenestant) < num_accepted:
        if (len(ori) > 0) or (len(list_insidenest_ant_id) >0):
            list_accepted_outsidenestant.append(ori[0:min(len(ori),             
            num_accepted-len(list_accepted_outsidenestant))])
            set_accepted_outsidenest_antlist = set(list_accepted_outsidenestant)  
            print "list_accepted_outsidenestant-" + str(list_accepted_outsidenestant)
            set_accepted_insidenest_antlist  = set(list_insidenest_ant_id)
    return set_accepted_outsidenest_antlist,set_list_outsideant_id,set_accepted_insidenest_antlist

A nice way to check these conditions

I have this piece of code which checks conditions:

def is_important(data_row):
    if data_row.get('important', None):
        return True
    add_data = get_additional_data(data_row)
    for word in NEGATIVE_WORDS:
        if word in add_data.lower():
            return False
    for word in POSITIVE_WORDS:
        if word in add_data:
            return True
    return False

This is quite hard to follow (in my opinion) so is there a nice (shorter) way to write this? Could I for example merge the two for loops? Or will this increase search time.

Adding a second if in a all(... with a for loop in it)

I would like to add an if after the getal in the for loop.

if all(number % getal != 0 for getal in primes):
                primes.append(number)

I tried this, that did not work. Is if possible to add an if to the getal in the for loop?

if all(number % getal != 0 for getal if getal <= sqr_number in primes):
                primes.append(number)

how to put an alert on empty text box using asp

Okay iam using this code to make a forum

" />
Gender: >Male >Female

i want to make sure that the user fill all the text boxes giving an alert message beside the nonfilled one any help??

How to get a expected result by comparing array using a specific value

I'm trying to print the result by using a condition

let say I have a class that contain 1 set of array

let array1 = ["0001", "0002", "0003"]

and I have another class that contain struct return an "Int" to call the string inside array

Struct {
value1: Int
value2: Int
}

and in viewController I want to give it a condition to print only the specific string ie. only print if 0001, 0003 is detected

func printValue() {

if someclasss.value1 == ["0001", "0003"] {
print(value1, value2)
    }
}

but every time i try to check it return error on if condition line ,is there any suggestion ?

mardi 29 août 2017

Is there a BUG in PHP "IF block" parsing method or what?

Consider the following hypothetical PHP example:

$bar = 'bar';
$foo = 'foo';

if (isset($bar)):
   if (isset($foo)) echo "Both are set.";
elseif (isset($foo)):
   echo "Only 'foo' is set.";
else:
   echo "Only 'bar' is set.";
endif;

Disconsider the dumb logic and focus on the elseif line. If you try it yourself you will get a PHP EXCEPTION error saying "syntax error, unexpected ':' "

Now, you may think the fix is to have the sub-if enclosed in between { } instead of being a single line statement, like this:

$foo = 'foo';
$bar = 'bar';

if (isset($bar)):
   if (isset($foo)) {
     echo "Both are set.";
   }
elseif (isset($foo)):
   echo "Only 'foo' is set.";
else:
   echo "Only 'bar' is set.";
endif;

Wrong! The error remains. Exactly the same EXCEPTION as before...

So, what is wrong with those examples?

Drop multiple elements from a list (drop row2 from list of lists), conditional on a value in a different row

I have a list of lists. Example here:

    list_of_data = 
['Joe', 4, 4, 4, 5, 'cabbage', None], 
['Joe', 43, 2TM, 41, 53, 'cabbage', None],
['Joe', 24, 34, 44, 55, 'cabbage', None],
['Joe', 54, 37, 42, 85, 'cabbage', None],

['Tom', 7, 2TM, 4, 52, 'cabbage', None],
['Tom', 4, 24, 43, 52, 'cabbage', None],
['Tom', 4, 4, 4, 5, 'cabbage', None],

['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage']]

Notice that for index #2, Joe has value '2TM' in the 2nd row of his list (row index #1 of the overall list_of_data). Tom has value '2TM' in the 1st row of his list (row index #5 of the overall list_of_data).

Each tie the value '2TM' appears in my data, I want to remove/delete/skip the next two rows.

So here is my final desired output:

    list_of_data = 
['Joe', 4, 4, 4, 5, 'cabbage', None], 
['Joe', 43, 2TM, 41, 53, 'cabbage', None],

['Tom', 7, 2TM, 4, 52, 'cabbage', None],

['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage']]

I don't know if I'm even close on the code, but I've tried using the .pop method like so:

for row[x] in list_of_data:
    if '2TM' in row:
        list_of_data.pop[x+1:x+2]

Using switch–case statements to verify user input

screenshot of the application

Currently, I am trying to test something but I am stuck. Now I do not have to use switchcase. I could use ifelse instead, but I just figured that switchcase statements are easier.

Anyway, I want to use either switchcase statements or ifelse statements to verify that the user only inputs numbers and then re-direct them somewhere depending on if the verification failed or passed. Now I have tested this. It works, but it like crashes when the user enters in anything other than only numbers. I would like to put the verification code under the comment /*Error message for if the user entered any non-numbers.*/ if possible. How would I accomplish this?

When running my function my if statement is not running

I am trying to make a simple bubble sort, and the if statement i'm using to sort the numbers in my array is not running. Can anybody help me get this to run?

Here is my code:

def Bubble( a ):
    Flag = False
    while not Flag:
        Flag = True
        for i in range(0, len(a), -1):
            if a[i] > a[i+1]: #this if statement isn't running
                a[i], a[i + 1] = a[i + 1], a[i]
                print("hi")
                Flag = False



def main():
    a = GRN(10)
    acopy = a[:]
    Bubble(a)
    acopy.sort()
    print(a==acopy)
    print(a)
    print(acopy)


main()

I need help writing an if then statement using 2 criterion of ltv and credit score

Please help! I've been ripping my hair out trying to figure this out on Excel.

I'm trying to write a code that outputs a percentage value based off of LTV and Credit score range. If the LTV is equal to or above 75, and has a credit score >725 then -.25. If the LTV is equal to or above 75 with a credit score between 724 and 675 then +1.25. If the LTV is equal to or above 75 with a credit score 625-674 then +1.75

I also need to write a statement if the LTV is below 75 for the same credit socres above. 725, 724-675, 674-625.

I keep getting an error that Im using too many arguments.

c# thread work every 1 second and send even

i want to create a thread that will work every 1 second , when it finish(when i get true) it will send event for another object.

something like

fun(run on another thread)
{
       while true
          if(cond==true)
          {      send event
                 break
                 finish the thread
          }
          else
         sleep(1000)(and to the function again

}

the another object will do something when it get the even that the function return true and the thread finish

i think the threadpool it best here.

but i not success to write simple code on c# to implement it

please help me

IF statement not working for my code [on hold]

first off sorry if i'm being extremely stupid but i can't seem to get this if statement to work, help would be greatly appreciated. Thanks!

def battle ():
    battle = random.randint(1,2,3,4,5,6,7,8,9,10)
if:
        battle>7
            print("you survived the battle")

else:
    print("you died.")

Python: How to properly modify a global variable that's already been used

I am doing a beginner's exercise in Python.

The code asks for a name and age. If the age is higher than 100, I want to modify age_goal to 150. Any age entered above 150 will not be accepted.

current_year = 2017
age_goal = 100
question = "Would you like to know which year you will turn " + str(age_goal) + " years old? (Yes/No): "

user = input("What is your name?: ")
print("Hello, " + user + ".")

age = input("How old are you, " + user + "?: ")  

if int(age) > 100 and int(age) < 150:
    global age_goal
    print("Whoa, that's old!")
    age_goal = 150
elif int(age) >= 150:
    print("No one's THAT old...")
    age = input("How old are you, " + user + "?: ")
else:
    print("You are " + str(age) + " years old.")

calc = age_goal - int(age) + current_year

response = input(question)

while response != "Yes" and response != "No":
    print("Answer not accepted, try again: ")
    response = input(question)
if response == "No":
    print("That's no fun. Goodbye.")
else:
    if response == "Yes":
        print("You will be" + str(age_goal) + " years old in " + str(calc) + "!")

The if statement in question is listed below.

if int(age) > 100 and int(age) < 150:
    global age_goal
    print("Whoa, that's old!")
    age_goal = 150

Right now it says "name 'age_goal' is used prior to global declaration", and I understand what that means and why it's throwing that error, but I don't know how to organize the code to accept the modified global from that point on, versus trying to make it work for the code as a whole.

Hide Content With MS Word Checkboxes

I would like to check a content control checkbox and have it only show some text content when the box is checked.

I have attempted to do this with IF statements and bookmarks, but I have not been able to get it to do what I want.

Even just trying to reference the checkbox in Word is proving to be difficult:

{IF check = ☒ "CHECKED" "UNCHECKED"} 

Where the title and tag of the checkbox are 'check', and the ☒ is a content control checkbox.

Any steering in the right direction would be helpful! I am trying to avoid using VBA.

Sum Experiment array / loop dilemma

I am writing a program and I can't seem to make the IF action loop and check all of the arrays in the main. My job is to figure out whether there exists any pair of numbers (i.e., any two elements) in this ascending sorted array that will add up to 20. All you need to do is to sum the values these two pointers point to and see if they are equal to 20, if so, output. otherwise, inspect the sum, if the sum is greater than 20,decrement the second pointer and if the sum is less than 20, increment the first pointer. cannot use the nested for loop approach!! Not sure how to fix this... i've been at it for hours and have handwritten it with no luck. thank you!!

// if val of arr at index i is smaller than at arr j, then return
    // smaller value
    // This function will inspect the input to find any pair of values that
    // add up to 20
    // if it find such a pair, it will return the *index* of the smallest
    // value
    // if it does not find such as pair, it will return -1; 

public class SumExperiment {

public static int check_sum(int[] array) {
int i = array[0];
int y = array.indexOf(array.length); // need value @ index of array.length to begin

//loop to repeat action

for (int arraysChecked = 0; arraysChecked < 5; arraysChecked++ )
{
    if ( i + y == 20)
        {
        return i;
    //  System.out.print(array[i]);
        }
            else if ( i + y > 20)
                {
                y--; //index @y
                }
            else if (i + y < 20)
                {
                i++; //index @x
                }

    if ( i + y != 20)
    {
        return -1;
    }
    arraysChecked++;
}
return -1;  //because must return int, but this isn't correct
}


public static void main(String[] args) {
    int[] array1 = new int[] { 5, 7, 8, 9, 10, 15, 16 };
    if (check_sum(array1) != 0)
        System.err.println("TEST1 FAILED");

    int[] array2 = new int[] { 3, 5, 8, 9, 10, 15, 16 };
    if (check_sum(array2) != 1)
        System.err.println("TEST2 FAILED");

    int[] array3 = new int[] { 3, 4, 6, 9, 10, 14, 15 };
    if (check_sum(array3) != 2)
        System.err.println("TEST3 FAILED");

    int[] array4 = new int[] { 6, 7, 8, 9, 10, 15, 16 };
    if (check_sum(array4) != -1)
        System.err.println("TEST4 FAILED");

    System.out.println("Done!!!");
}
}

R guessing game syntax

I'm having trouble with proper bracket syntax when making a guessing game. Here is a brief example of my code

number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)

input = number_result


while(input != rand){

  if(input < rand){
    print("Higher!")
  }
  else if(input > rand){
    print("Lower!")
  }
  else(input = rand){
  return(print("You got it!"))
}
    }

My error is:

Error: unexpected '{' in:
"  }
  else(input = rand){"
>     return(print("You got it!"))
[1] "You got it!"
Error: no function to return from, jumping to top level
> }
Error: unexpected '}' in "}"
>     }
Error: unexpected '}' in "    }"
> 

Reviewing IF conditional code to save CPU cycles

I am reviewing the usage of if condition in my program, in there, i have lines like the following:

if(count > 4) count = 4;

Would it be a good idea to write the above if conditional statement as the following non-branched one?

count = 4*(count> 4) + count*(count<= 4);

I also have the following snippet there:

for (j=0, i=0; j<NCARD_PER_SUIT && i<CARDS_PER_PLAYER+CARDS_ON_BOARD; ++j) {
    if (card_cfg.hearts & cfg_mask[j]) {
        player_hand[i].card.face = j;
        player_hand[i++].card.suit = HEART;
    }
    if (card_cfg.spades & cfg_mask[j]) {
        player_hand[i].card.face = j;
        player_hand[i++].card.suit = SPADE;
    }
    if (card_cfg.clubs & cfg_mask[j]) {
        player_hand[i].card.face = j;
        player_hand[i++].card.suit = CLUB;
    }
    if (card_cfg.diamonds & cfg_mask[j]) {
        player_hand[i].card.face = j;
        player_hand[i++].card.suit = DIAMOND;
    }
}

and wondering if there is good (non-branched) way to right the above, any suggestions?

Calculating dates in excel

How can I calculate dates as number in google drive excel as formula? I have 2 dates and I want to prepare a formula if I have 2 dates, then this is total 2.

Swift iOS - Relational Operator - UITextField .text

Developing a Single-View app for iOS using Swift 3 syntax to allow a UIButton to call on a function named CheckAnswer() that argues if the string value in a UITextField is equal to a specific value.

I keep receiving an error (unresolved identifier) when my CheckAnswer() function begins to execute a condition to argue the string value for my UITextField variable called Answer. I am not sure how to debug this error. :) Thanks for any suggestions!

   override func viewDidLoad() {
    super.viewDidLoad()

    //INPUT BOX - User Input!
    let Answer : UITextField = UITextField(frame: CGRect(x: 35, y: 150, width: 250, height:50))
    Answer.placeholder = "Enter Your Answer"
    Answer.font = UIFont.init(name:"times", size: 24)
    Answer.backgroundColor = UIColor(red:0xff ,green:0xff, blue:0x88 ,alpha:1)
    self.view.addSubview(Answer)

    //BUTTON - Check Answer!
    let Button : UIButton = UIButton(frame: CGRect(x: 35, y: 200, width: 250, height:50))
    Button.setTitle("Submit Answer", for: .normal)
    Button.titleLabel!.font = UIFont.init(name:"times", size: 24)
    Button.backgroundColor = UIColor(red:0x00 ,green:0x00, blue:0x00 ,alpha:1)
    Button.addTarget(self, action: #selector(CheckAnswer), for: .touchUpInside)
    self.view.addSubview(Button)
}

func CheckAnswer(_ sender: UIButton){
    if Answer.text == "answer" || Answer.text == "Answer"      
    { print("Correct ! Response") }
    else { print("Incorrect x Response") }
  }

If-Else ladder in Excel To sort data

I was doing R&D on Excel. And wanted to use If-else ladder in column of excel. Let's say I have a 2 columns and I calculated the difference between the two columns. Now, If the difference is between a range of (-5 to +5), if should display something or if Difference greater than 5, it should display something and for rest i.e. difference < -5, should display something else.
I tried and came up with this

=IF("H2>5",<something1>, IF("H2<5",<something2>))

How to put the range part in this if-else ladder? Also the above If else is not giving value but the result is turning out to be #VALUE.

Thanks for your help.

Sort the age of 3 individuals

/* to find the age of individuals according to youngest to oldest */

#include <stdio.h>

int main(void)
{
  int age1, age2, age3, youngest, middle, oldest;
  {
    printf ("Enter the age of the first individual: ");
    scanf  ("%d", &age1);
    printf ("Enter the age of the second individual: ");
    scanf  ("%d", &age2);
    printf ("Enter the age of the third individual: ");
    scanf  ("%d", &age3);
  }
  if (age1==age2==age3);
  {
    printf("All individuals have the same age of %d", &age1);
  }
  else
  {
    youngest = age1;

    if (age1 > age2)
      youngest = age2;
    if (age2 > age3)
      youngest = age3;

    middle = age1;

    if (age1 > age2)
      middle = age2;
    if (age2 < age3)
      middle = age2;

    oldest = age1;

    if (age1 < age2)
      oldest = age2;
    if (age2 < age3)
      oldest = age3;

    printf("%d is the youngest.\n", youngest);
    printf("%d is the middle.\n", middle);
    printf("%d is the oldest.\n", oldest);
  }
  return 0;
}

I keep getting the error on line 21 which states that I have an 'else' with a previous 'if'. Any of the experts here can tell me where I went wrong? The display is also a little weird if I were to remove the 'else'.

Another If-else-then statment in bash

I am running to a "weird" "if then else" problem (or I am just a novice). Or, I do not fully understand the semantics of specified statement.

What I want to do is read through a table (csv) like the one below

/home/trotos/I16_1505_09.fastq.gz,34,hg19
/home/trotos/I16_1505_06.fastq.gz,34,hg19
/home/trotos/I16_1505_12.fastq.gz,40,hg19
/home/trotos/I15_1277_01.fastq.gz,42,gg5
/home/trotos/I15_1458_01.fastq.gz,42,gg5
/home/trotos/I15_1314_01.fastq.gz,36,gg5
/home/trotos/I15_1458_03.fastq.gz,36,gg5

and then use input from each column (sequentially) to perform several commands. the script I am using (not refined yet) where file is the statedcsv

#!/bin/bash

shopt -s nullglob

#initialazation 


file="$3" #the file where you keep your variables
human="$1" #the path of the first genome
mouse="$2" #the path of the second genome

echo "START"    #for test purposes no need for them to be here
echo $human     #for test purposes no need for them to be here
echo $mouse     #for test purposes no need for them to be here
echo $file      #for test purposes no need for them to be here


#How to read columns from files and loop
#visit http://ift.tt/2x0Ux44

while IFS=, read col1 col2 col3 ; do  # the file need to be loaded at the end of the loop, check a done
    echo "LOOP"    
    echo $col1   #for test purposes no need for them to be here
    echo $col2   #for test purposes no need for them to be here
    echo $col3   #for test purposes no need for them to be here


#Loop into the file per line 
for i in $col1; do

#do some naming control to use as outputs
    base1=${i##*/}  # Get the file name from the path use this one for the following applications.
    NOEXT1=${base1%.*}  #leave the extension out
    NOEXT2=${NOEXT1%.*} #leave the second extension out
    FOLDER1=${col1%/*}

echo $base1
echo $NOEXT1 
echo $NOEXT2
echo $FOLDER1
echo "...."


#per line read the third column and decide the the genome to be used with an if statement
if [$col3="hg19"]
    then
       ref_genome=$human
echo "1"
echo $ref_genome
    else
        ref_genome=$mouse
echo $ref_genome
echo "2"

echo $ref_genome
fi

echo "....."

echo "END LOOP"


done
done < $file
echo "SCRIPT IS DONE"

the command is the following

./test '/home/trotos/Downloads/chromosomes/hg19.fa' '/home/trotos/Downloads/chromosomes/gg5.fa.gz' 'csv_file'

What it does correctly is to read the columns of the file, and get the data I need from a column per line in a loop.

But when I am using the third column (hg19 or gg5) as a statement of TRUE or FALSE to get a different condition:

if hg19 is TRUE then 'hg19.fa' is the correct

if gg5 is TRUE then 'gg5.fa.gz' is the correct but script's output differs:

LOOP
/home/trotos/lane2_I15_1458_08.fastq.gz
42
**gg5**
/home/trotos/lane2_I15_1458_08.fastq.gz
/home/trotos/lane2_I15_1458_08.fastq
/home/trotos/lane2_I15_1458_08

....
1
**/home/trotos/Downloads/chromosomes/hg19.fa**
.....
END LOOP

The first problem is that when col3==hg19 it gives the correct output that would be "/home/trotos/Downloads/chromosomes_hg19/hg19.fa". But when col3==gg5 i still get the same "/home/trotos/Downloads/chromosomes_hg19/hg19.fa". So who will I get the correct answer? The second is how to use the "if then else" statement to get the specific file that corresponds to the 3rd column and to use that information inside the loop defined by:

 for i in $col1; do.

Thank you in advance. I hope my description will not confuse you.

Is it stylistically acceptable to omit the 'else' when returning within a javascript function? [on hold]

When writing a javascript function, I commonly need to check if an error has been thrown before returning. I might have something like this:

() => {
    let error = false
    // do some stuff, perhaps making error=something if an error is found
    if (error) { 
        return error
    } else {
        //carry on with the function
    }
}

However, I would much rather write something like

() => {
    let error = false
    // do some stuff...
    if (error) {return error}
    // carry on with the function...
}

There is no explicit 'else', but the function will return and stop in the presence of an error, and the code looks neater and has less indentation. But I feel like this might violate some important stylistic principle - when and 'if' has an alternative path based on its failure, that should always go in an 'else'.

Am I worrying over nothing, or should I stick with the first style?

if loop win while not working in shell script

I have a simple if else loop inside while but its not giving me a proper output needed. Please help #!/bin/bash

set -x
inputFile=/data2/example/output1.txt
while read col1 col2 col3; do
if [ $col2=='Success' ]
then
echo " This is Green"
else
echo " This is Red"
fi
done < ${inputFile}

Output am getting is:

+ read col1 col2 col3
+ '[' Success==Success ']'
+ echo ' This is Green'
 This is Green
+ read col1 col2 col3
+ '[' Success==Success ']'
+ echo ' This is Green'
 This is Green
+ read col1 col2 col3
+ '[' Failed==Success ']'
+ echo ' This is Green'

Here its not entering the else part and continuously displaying "This is Green".

Thanks for the help!

Why my if/else statement is not working!!! JavaScript [on hold]

I do not have any idea about why my if statement is not working... I have tried both == and ===, but it still not working, I will be very happy if you will help, thanks for you attention PLEASE HELP!!!

var images = [$('.image1'), $('.image2'), $('.image3')];
var x = true;
if(x == true ){
setTimeout(() => {
    images[1].fadeIn();
    images[1].animate({
        'backgroundSize': '100%',
        'opacity': 1
    }, 2000, () => {
    });
    images[0].animate({
        'backgroundSize': '350%',
        'opacity': 0.2
    }, 3000, () => {
        images[0].attr('id', 'none');
    });
}, 4000);
x = false;
}
else{
setTimeout(() => {
    images[2].fadeIn();
    images[2].animate({
        'backgroundSize': '100%',
        'opacity': 1
    }, 2000, () => {
    });
    images[1].animate({
        'backgroundSize': '350%',
        'opacity': 0.2
    }, 3000, () => {
        images[1].attr('id', 'none');
    });
}, 4000);
x = true;
console.log(true)
}

lundi 28 août 2017

if inside if inside if statements - is it possible?

I'm trying to display a calculation of two radio groups, in real time, before users click submit button.

<div class="container-5">
    <div class="choices1">
      <h1 class>Regular<br>Regular Choice</h1>
      <input type="radio" id="thirteen" name="style" value="13.00">
    </div>

    <div class="choices2">
      <h1>Popular<br>Popular Choice</h1>
      <input type="radio" id="fifteen" name="style" value="15.00">
    </div>

    <div class="choices3">
      <h1>Fancy<br>Fancy Choice<br>Literally.</h1>
      <input type="radio" id="twenty" name="style" value="20.00">
    </div>

  </div>

<div class="container-8">
    <div class="gratuity1">
      <h1 class>15%<br>Good.</h1>
      <input type="radio" id="15" name="tip" value=".15">
    </div>

    <div class="gratuity2">
      <h1>20%<br>Excellent Service.</h1>
      <input type="radio" id="20" name="tip" value=".20">
    </div>

    <div class="gratuity3">
      <h1>25%<br>Beyond Excellent</h1>
      <input type="radio" id="25" name="tip" value=".25">
    </div>

  </div>

I'm using pure javascript.

Each of these categories is suppose to represent the value of the selected radio button. Once I've defined the variables I created if statements to test if both buttons were selected and event would occur

   var styleVal1= 3.0;
   var styleVal2 = 5.0;
   var styleVal3 = 10.0;
   var tipVal1 = 0.1;
   var tipVal2 = 0.15;
   var tipVal3 = 0.2;
   var total = 0.00;

 if (document.getElementById("thirteen").selected) {
  document.getElementById("thirteen").addEventListener("click", function() {
      total = styleVal1;
       document.getElementById("total").innerHTML = "Total:$ " + total;
  if (document.getElementById("15").selected) {
     total += total * tipVal1;
      document.getElementById("total").innerHTML = "Total:$ " + total;
} else if (document.getElementById("20").selected) {
     total += total * tipVal2;
      document.getElementById("total").innerHTML = "Total:$ " + total;
} else (document.getElementById("25").selected) {
     total += total * tipVal3;
        document.getElementById("total").innerHTML = "Total:$ " + total;
       }
    });
   }     

I also did the same for:

       if (document.getElementById("fifteen").selected) {
       &&
       if (document.getElementById("twenty").selected {

Am I not putting this in the right order or am I missing something? Is it even possible to do else if statements inside if statements?

Code to check if a post item is in a category keeps failing

I'm trying to add the name of a specific custom taxonomy to my shop loop on my website. I'm getting a few issues with my code and would like a bit of help if possible.

/*Add category name to loop*/

function trodproducttax() {
    global $product_id;
    global $post;
    $product_id = $post->ID;
    if ( in_category('men', $product_id) ) {
        echo 'Men ';
    }
    else {
        echo 'dunno';
    }

}
add_action(woocommerce_after_shop_loop_item, trodproducttax, 10);

I keep getting my logical test for the if statement failing even though some of the items in my loop do belong to the category Men. This seemed like a simple snippet when I started writing lol. Now not so much.

Can not solve my IF condition about isChecked

What is wrong with my code? My condition doesn't end when I check if the radio button is checked I want to make 3 options :

  • radio button 1 is checked -> end of condition
  • radio button 2 is checked -> end of condition
  • none of them checked -> toast messeage

code:

package com.ofekb.app_pt1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class settings extends AppCompatActivity {


    Button btnWaitress;
    EditText etSalaryWaitress;
    EditText etSalaryBartender;
    //------------
    RadioButton rbPercentage;
    RadioButton rbShekel;
    int HafrashaP;
    int HafrashaS;
    int etSWNum;


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

        btnWaitress =(Button)findViewById(R.id.btnWaitress);
        etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
        etSWNum = Integer.parseInt(etSalaryWaitress.getText().toString());
        etSalaryBartender = (EditText) findViewById(R.id.etSalaryBartender);
        //-----------
        rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
        rbShekel = (RadioButton)findViewById(R.id.rbShekel);

    }
    public void onClickWait (View v) {

        if (rbPercentage.isChecked()) {
            HafrashaP = 1 - (etSWNum / 100);
        }   else if (rbShekel.isChecked()) {
                HafrashaS = - etSWNum;
            }  else {
                    findViewById(R.id.btnWaitress).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(settings.this, "XXXXXX", Toast.LENGTH_SHORT).show();
                        }
                    });
                    }
    }
}

Zapier - Python IF/ELIF not printing result, "output_missing: Please define output or return early."

I'm incredibly weak with Python, but I thought I could knock together a basic script to alert me when a new user adds a card, and compare their credentials against the account sign-up information (to check for spammers)

Here's what I have in Zapier:

if input_data['card_name'] == input_data['account_name'] and input_data['card_country'] == input_data['account_country'] and input_data['card_type'] != 'prepaid': print "Low Risk (valid credentials)"
elif input_data['card_name'] == input_data['account_name'] and input_data['card_country'] == input_data['account_country'] and input_data['card_type'] == 'prepaid': print "Medium Risk (prepaid card)"
elif input_data['card_name'] != input_data['account_name'] and input_data['card_country'] == input_data['account_country'] and input_data['card_type'] != 'prepaid': print "Medium Risk (name mismatch)"
elif input_data['card_name'] == input_data['account_name'] and input_data['card_country'] != input_data['account_country'] and input_data['card_type'] != 'prepaid': print "Medium Risk (country mismatch)"
elif input_data['card_name'] != input_data['account_name'] and input_data['card_country'] != input_data['account_country'] and input_data['card_type'] == 'prepaid': print "High Risk (consider investigating)"

It's a big CF of IF/ELIF, but for some reason it's not printing the output. I had it working when it was only two conditions per argument, but with three it seems to not want to print the output.

I'm getting this error now: "output_missing: Please define output or return early."

Am I making any dumb mistakes that's preventing this from printing properly? Help would be most appreciated!

How do you make two options possible in if/else statements in Python 2.7? [duplicate]

I am trying to right a script based calculator in Python 2.7. I am using if/else statements so that the computer knows which operation the user wants to use. I tried this:

import time
while 1 == 1:
    num1 = raw_input("Number 1: ")
    num2 = raw_input("Number 2: ")

    sum = num1 + num2
    difference = num1 - num2
    product = num1 * num2
    quotient = num1 / num2

    operation = raw_input("Do you want:\n Sum\n Difference\n Product\n Quotient\n\n")
    if operation == "Sum" or "sum":
        print sum

    elif operation == "Difference" or "difference":
        print difference

    elif operation == "Product" or "product":
        print product

    elif operation == "Quotient" or "quotient":
        print quotient

    else:

    time.sleep(2)

However, the program no longer works. I was hoping someone could tell me the syntax for having to possible options in only one if/else statement. Thanks!

If statement skipping outcome action

I've got a problem that I'm struggling to make sense of and I'm hoping you guys can assist.

My if statement is not executing the action for a true result and I'm not sure why. I have used a similar condition earlier in the code and there were no issues.

here's the section of the code that I'm struggling with:

Dim Descr1 as String, Descr2() as String, Descr3() as String
Dim erow1 as Long
Dim I as Long
Dim p as Long
Dim q as Long

erow1 = Sheets("report").Cells(1, 1).CurrentRegion.Rows.Count + 1

If Descr1 = Trim(Descr3(q)) And Descr1 = Trim(Descr2(p)) Then
                ThisWorkbook.Sheets("report").Cells(erow1, 1) = WS1.Cells(i, "b")
                ThisWorkbook.Sheets("report").Cells(erow1, 2) = WS1.Cells(i, "c")
            Else
           End If
        Next q
        Next p

I'm getting a true condition but the cells information is not coming through into the intended sheet. I'm really stunned, please help.

Thanks in advance.

R: Nesting an if statement within a While loop

I want to nest an "if" condition within a while loop, but I keep getting Error: unexpected '}' in " }"

I've written a line of code that checks if any pattern from a vector is present within a text string:

i <- 1
while (i <= 6) {
  print(i)
  print(Names[i])
  print(grepl(Names[i], test))
  i <- i+1
}

This works fine at spotting the names in the vector: ``

[1] 1
[1] "A"
[1] FALSE
[1] 2
[1] "B"
[1] FALSE
[1] 3
[1] "C"
[1] FALSE
[1] 4
[1] "D"
[1] FALSE
[1] 5
[1] "E"
[1] FALSE
[1] 6

Now I'm trying to have it display only the names that are indeed present in the string of text, for that I tried the following if condition that returns the afore mentioned error:

i <- 1
while (i <= 6) {
  print(i)
  print(Names[i])
  if (grepl(Names[i], test)) = TRUE {
    print(grepl(Names[i], test)) }
  i <- i+1
    }

I guessed it would print i, then the name of at that position of i, then check if the IF condition is TRUE, but instead it only returns errors. What am I doing wrong, am I forgetting to set a break condition or something?

Values not being written to cells get popup though

Need help on below code which is not writing values to the cells but displays the msgbox

Sub SPD()
    Dim Col1, col2, col3, i, j, LRow, LCol As Long
    Dim st1, st2, st3 As String
    i = 0
    j = 0
    ThisWorkbook.Sheets.Add
    st1 = "Salus Hosting"
    LRow = Workbooks("Data").Sheets("Data").Cells(Rows.Count, 2).End(xlUp).Row

    For i = 2 To LRow
        If ThisWorkbook.Sheets("Data").Cells(i, 10).Value = "Salus Hosting" And ThisWorkbook.Sheets("Data").Cells(i, 30).Value = "EC2" Then
            MsgBox ThisWorkbook.Sheets("Data").Cells(i, 10).Value & ThisWorkbook.Sheets("Data").Cells(i, 30)
            ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value = ThisWorkbook.Sheets("Data").Cells(i, 10).Value
            ThisWorkbook.Sheets("Sheet1").Cells(i, 2).Value = ThisWorkbook.Sheets("Data").Cells(i, 17).Value
            ThisWorkbook.Sheets("Sheet1").Cells(i, 3).Value = ThisWorkbook.Sheets("Data").Cells(i, 20).Value
            ThisWorkbook.Sheets("Sheet1").Cells(i, 4).Value = ThisWorkbook.Sheets("Data").Cells(i, 21).Value
            ThisWorkbook.Sheets("Sheet1").Cells(i, 5).Value = ThisWorkbook.Sheets("Data").Cells(i, 29).Value
        End If
    Next i
End Sub

Java, Spring data jpa

Spring data jpa how can i search with multiple optional parameters like

  • firstname
  • industry
  • job title

and other more than 12 paramaters, the parameters are optional may or may not be entered by user. I can easily write queries like findallByFirstnameAndIndustryAndJobTitle but the problem is i need to generate methods based on provided parameters which give me lot of if and else for more than 13 prameters. Is there any effective way to use loop or may be sol;ve this kind of problem ?

Calling scripts in loops

Can I call scripts in a loop? I am trying to call two scripts in a MATLAB main code, but it keep freezing and I have to force quit MATLAB.

I am using this code:

pos=2;
for i=1:Size-1
    Electrification_limit(1,i)=electrification(pos-1,2);
    if Electrification_limit(1,i) == 1
       FUNCTION_E;
    else
       FUNCTION_FC;
    end
end

Am I doing something wrong?

Python breaking a nested loop with multiple if functions in it

I have a code in which I need to find the prime factor of a number. I need to know how to break my code after it found the prime factors, so when it reaches 1. I'm just starting coding with python and I'm not yet that familiair with other librairies, so I wondered if I could make a break with just the regular python code. It should stop after num reaches 1.

num = int(input("Give me a number:"))
priemgetallen = []

for reeks in range(2, num+1):
    print(reeks)
    for priemgetal in range(2,reeks):
        if reeks % priemgetal != 0:
            print(priemgetal)
            if num%priemgetal == 0:
                print("This is the old num", num)
                num = num/priemgetal
                print("This is the new num", num)
                priemgetallen.append(priemgetal)
                if num > 1:
                    if num%priemgetal == 0:
                        print("This is the new num", num)
                        num = num/priemgetal
                        print("This is the old num", num)
                        priemgetallen.append(priemgetal)
                else:
                    print(priemgetallen)
                    break
            else:
                print("Num stays old")

print(priemgetallen)  

If statement issue enter [duplicate]

This question already has an answer here:

I have this JS var, followed by this if statement :

if ($('custom_t4'))
                var contratType = $('custom_t4').value === 'Nouvelle_affaire' ? 'Nouvelle Affaire' : $('custom_t4').value === 'Avenant' ? 'Avenant' : '';



if (contratType && (contratType !== 'Nouvelle Affaire' || contratType !== 'Avenant')){ }

The problem I have, is that when contratType is defined and his value is 'Nouvelle Affaire', is still enter that if.

Did I miss something ?

Using the result of a for loop statement for a condition in an else if statement

My second else if statement condition should be the result of the for loop. How do I use the loop for the condition?

        //If player clicks centre on first move go in corner square
        if (current[4] === playerToken && this.state.stepNumber === 1) {
          let move = cornerSquares[Math.floor(Math.random() * cornerSquares.length)];
          drawSquare(move);
        } 
        //If player clicks corner square on first move go in centre square
        else if (this.state.stepNumber === 1) {
          for (let i = 0; i < cornerSquares.length; i++){
            if (current[cornerSquares[i]] === playerToken) {
              drawSquare(4);
            }
          }
        }
        //If player or computer has 2 in a row, place in 3rd square to win or block
        else if (/*CONDITION OF THE BELOW FOR LOOP*/) {
          for (let i = 0; i < twoInRow.length; i++) {
            const [a, b, c] = twoInRow[i];  
            if (current[a] && current[a] === current[b]) {
              drawSquare(c);
            }
          }
        }
        //Place in random empty square
        else {
         //code to randomly place x/o in random square
        }
      }

How do I fire a message box with if else condition and timespan value?

I have this code

*start time is another DateTime.now

*timeSinceStart is an array of timeSpan

*i believe that the for loop is for me to be able to create and store many values for the timespan and update the listview items(see link below for the photo of the form)

*f.ToString() is default 60(its an integer)

*the MH column in the picture is counting upwards, for ex. 1 2 3 4 5 6 etc etc

private void timer2_Tick(object sender, EventArgs e)
    {

        for (int w = 0; w < listView1.Items.Count; w++)
        {
            timeSinceStart[w] = DateTime.Now - startTime[w];
            listView1.Items[w].SubItems[6].Text = (timeSinceStart[w].TotalSeconds.ToString());
            if (f.ToString() == listView1.Items[w].SubItems[6].Text)
            { 
                MessageBox.Show("dedede");
            }
            else
            {
                label3.Text = timeSinceStart[w].TotalSeconds.ToString();
            }
        }

I really cant make the message box pop up and also, the timespan value has decimal values, does it have a connection why the if condition doesn't trigger?

I have tried converting timespan to datetime and use datetime and timespan in the if else condition, it also doesnt seem to work.

here is the picture as i was saying.

dimanche 27 août 2017

Why does combining if elif else, str.contains, and .any() in a pandas dataframe give me uniform result?

I try to make new lable tor every lines in a dataset based on text that contained in previous column, heres my code

import pandas as pd
import numpy as np
data = pd.read_excel('C:\\Users\\data july 2017.xlsx')
#data['Description'].fillna('')
pawoon = data[data['Description'].str.contains('Pawoon')]
pawoon['time'] = "0"
if pawoon.Description.str.contains('1 Bulan').any():
    pawoon['time'] = 1
elif pawoon.Description.str.contains('3 Bulan').any():
    pawoon['time'] = 3
elif pawoon.Description.str.contains('6 bulan').any():
    pawoon['time'] = 6
elif pawoon.Description.str.contains('1 Tahun').any():
    pawoon['time'] = 1
else:
    pawoon['time'] = 0

Here's the partial result that i've got, when I print partial result of the code above

Pawoon POS Software (1 Bulan)   1
Software Pawoon (6 bulan)       1
Pawoon POS Software (1 Tahun)   1
Pawoon POS Software (3 Bulan)   1
Pawoon POS Software (1 Bulan)   1

The result that I expected is showed below (based on if elif else statement that I mention in my code)

Pawoon POS Software (1 Bulan)   1
Software Pawoon (6 bulan)       6
Pawoon POS Software (1 Tahun)   12
Pawoon POS Software (3 Bulan)   3
Pawoon POS Software (1 Bulan)   1

Why does it's happen? How to get my desired result? I guess .any() should be change, but if I change to .all every result uniformly 0

In C#, what would be a nicer way to show this while loop?

namespace StringProgramFruits
{
public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("What is your favourite fruit?, (Apples), (Bananas), (Kiwi) or (Peaches)?");
        string fruit = Console.ReadLine();
        if (fruit == "Apple")
        {
            Console.WriteLine("Apples!");
        }
        if (fruit == "Kiwi")
        {
            Console.WriteLine("Kiwi!");
        }
        if (fruit == "Bananas")
        {
            Console.WriteLine("Bananas!");
        }
        while (fruit != "Apple") while (fruit != "Bananas") while (fruit != "Kiwi")
                {
                    Console.WriteLine("Try Again!");
                    fruit = Console.ReadLine();
                    if (fruit == "Apple")
                    {
                        Console.WriteLine("Apples!");
                    }
                    if (fruit == "Kiwi")
                    {
                        Console.WriteLine("Kiwi!");
                    }
                    if (fruit == "Bananas")
                    {
                        Console.WriteLine("Bananas!");
                    }
                    return;

                }
    }
}

If you look at the while loop there, I just added 3 while functions in a single line to add more conditions. This doesn't look very nice in the code base, so I was wondering if there was a different or easier way to add multiple conditions to while loops. I have tried using

while (fruit != "Apple") || (fruit != "Bananas") || (fruit != "Kiwi")

but the above code just showed up as an invalid expression :/

It's probably quite apparent that I am very new to C-sharp, and while this is a very trivial question, I would still like to know if there is any other way nonetheless.

What is the meaning of ? and : in if statement? [duplicate]

This question already has an answer here:

I'm lost at int result(int result = (input == 0 ? 0 : (input < 0 ? -1 : 1));

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        int input = console.nextInt();
        int result = (input == 0 ? 0 : (input < 0 ? -1 : 1));
        System.out.println(result);
    }
}

Creating an if-statement without hard-coding

I have an array that I want to check, for example:

 var str = ["a","b","c","d","e","f"];

but I want check if this array's string values are in a database or of some sort. I want to find out which one matches and store the found matches inside an array.

 var dataFound = [];
 var count = 0;
 for(var stringData in someDatabase){
    if(stringData == str[0] || stringData == str[1] ...etc){
         dataFound[count] = stringData;
         count++;
    }
 }

 //someDatabase will consist of strings like random alphabets 
 from a-z

I don't want to hardcode the if-statement because a query array can be anywhere from a, b, c .. (n) as n can represent any amount of strings. I tried to use a for-loop from 0 to str.length but that can take quite a while when I can use or operator to search in one go with all the string values, is there a way around this?

If/else statement - make "else" same as before state

I have certain -select- option on my future web page where costumers have option to select between 2 values (value white and value black). These options change how some content look. Value white is default option and i don't need to change there anything when user chooses that one. Value black is additonal one and when customer selects it, some visual things change. I do those changes using jquery and statemants if/else (if value is selected do that or else...).

My question now is, is there any easy way to make else statment "delete" all those changes from "if" statement and return everything to default state, without much writing same things over and over again?

I hope you understand. Thanks.

PHP: RegEx for nested {IF} {ENDIF} Conditions

I am searching the whole day for a RegEx that matches just the inner {IF} - {ENDIF}-Statement in a nested condition code. Does anyone have an idea?

for example:

{IF bla}Text 1{ELSEIF ble}Text 2 {IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF} Main text end{/ENDIF}

I just want to get

{IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF}

i tried #\{IF .*\}.*\{ENDIF\}#is but this is not working as i only get the whole string.

And also important: The code can have several lines and line breaks!

the bla, ble, bli etc are dynamic and can differ

Boolean inside the If Statement

I have to create multiple if results and end with a catch all which I would assume would be the false in the Boolean result. I am having trouble assigning the Boolean.

            if this.Label.Text = Frank)
            {
                this.Result.Text = "Correct";
            }
            {
                if this.Label.Text = Puppet)
                {
                    this.Result.Text = "Great";
                }
                {
                    if this.Label.Text = Merida)
                    {
                        this.Result.Text = "Ohyea!";
                    }
                    {
                        if this.Label.Text = ANYTHING ELSE)
                        {
                            this.LblResult.Text = "No way";

I can't Convert SQL Select Query Result to Bit

After the user has registered; the user's membership is saved as "passive" by default. I do this in the following way: I have a line called "active" in my user table and the data type of this field is bit and default value of this field is 0. What I want to do is: If the user has not activated his account, I want him to get warning but I got System.IConvertible error. My login.aspx.cs is as follows:

DataRow drlogin = function.GetDataRow("SELECT isactive FROM user WHERE email = '" + TxtEMail.Text + "'");
if(Convert.ToInt32(drlogin) == 0)
{
    string message = "<script>alert('You can't login because your account is not active!');</script>";
}
else
{
    // Login operations
}

SQL update if exist, insert if not exist not working

I want to update a record if it exists or create a new record if it does not exist yet but somehow it is throwing an error and I cannot find out why.. I want to update the status of a customer if it exists or create a new customer if not exist.

my query:

$sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM sms WHERE number = '123456789' AND customer_id = '1' ) THEN UPDATE sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) values ('+32485386902', '1', '1') END"

This throws error: [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) value' at line 1

However if I change the update and insert into to 1 and 2 it shows 1 if exist, or 2 if not.

Can anyone help me out :) ? Thanks a lot!

how to create 3 variables equal together.

i am making a code which identify if its equilateral, isosceles and scalene but i am having trouble coding at equilateral part because the size should be equal here's my code.

:triangle
echo enter the three size:
echo size a
set /p s1=
echo size b
set /p s2=
echo size c
set /p s3=

:: Isosceles triangle 

if %s1%==%s2% (
    goto isosceles
    ) else if %s1%==%s3% (
    goto isosceles
    ) else ( 
    goto scalene
    )
pause

:: equilateral triangle

if %s1%==%s2%==%s3% (
    goto equilateral
)   
pause   

:: for triangles 
:equilateral
echo the triangle is equilateral 
goto pause
:scalene
echo the triangle is scalene 
goto pause 
:isosceles
echo the triangle is isosceles 
goto pause

is my equilateral statement correct?

Rounding numbers to multiple of 5 C++

#include <iostream>
#include <vector>
int main(){
    std::ios::sync_with_stdio(false);
    int n;
    std::cin>>n;
    std::vector<int> grades(n);
    int fives[20];
    for(int i=0;i<20;i++)
        fives[i]=5*(i+1);
    for(int i=0;i<n;i++)
        std::cin>>grades[n];
    for(int i=0;i<n;i++){
        for(int j=0;j<20;j++){
            if(grades[i]==fives[j]-2||grades[i]==fives[j]-1||grades[i]==fives[j])
                grades[i]=fives[j];
        }
    }
    for(int i=0;i<n;i++)
        std::cout<<grades[i]<<" ";
}

I'm trying to round up numbers which is close to 2 or less point to multiple of 5. But output is just 0. Whats wrong with my code ?

How do you write this shorter?

I thought there was and better nice way to write this but I can't remember.
Is there an nicer way to write this in Lua?

if curSwitch == "shapes" then
  curSwitch = "colors"
elseif curSwitch == "colors" then
  curSwitch = "shapes"
end

I need about if c# if there is a xpath or not

im using selenium web driver with firefox driver. i have to look this xpath if in the page or not so i can forward next step but i dont know how to do it.

//*[@id='view_container']/form/div[2]/div/div/div/ul/li[1]/div/div[2]



if (idk what i have to write here) driver.FindElement(By.XPath("//[@id='view_container']/form/div[2]/div/div/div/ul/li[1]/div/div[2]"));

{

if we found xpath

}

else
{

if dont find xpath

}

sorry my bad english. thank you.

Unexpected results (int and if)

This is part of a program that's a simple dice simulator.

int x,y;
cin>>y;
    if(y<=0){cout<<"Invalid input";}
    else{
        for(x=0;x<y;x++){ 
            cout<<rand()%6<<endl;
        }
    }

I added the if(y<=0) to check if the input was a negative number but it also displays the message even if the input is an alphabet,special character or decimal.

I get that it outputs the statement for decimal because it ignores the decimal part of the input.

But why does this happen for special characters and alphabets?

PHP check variable against an array of values with or operator

So i have this array of values

$veg = array('tomatoes', 'potatoes');

How do i check this array against my variable but with "or" operator

Something like

if if ($veggies == ('tomatoes' || 'potatoes'))  {
 ...
}

but i have no idea how to use my array there

What is wrong with my if statement? It doesn't work

I'm trying to implement Shunting Yard algorithm. When I run this program I somehow receive NullPointerException in one line(comment that one). I've set an if statement there but seems that doesn't do anything. I've also tried to compare 2 strings like If(!string.equalsIgnoreCase("(")) but it didn't work too. Why is that so? What is wrong with my code?

/**
 * Main class of the Java program.
 */
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;

public class Main{

    public static LinkedStack<String> stackForNumbers;
    public static LinkedStack<String> stackForOperators;
    public static Map<String, Integer> operatorPrecedance = new HashMap<String, Integer>();

    public static void main(String[] args) {
        String str = "1+2-3*(4+5)";
        stackForNumbers = new LinkedStack<>();
        stackForOperators = new LinkedStack<>(); 
        int b = 0;
        int e = -1;
        for(int i = 1; i<=str.length(); i++){
            if(!Character.isDigit(str.charAt(i-1))){
                b = e + 1;
                e = i-1;
                String s = str.substring(b,e);
                if(!s.equalsIgnoreCase("")){
                    stackForNumbers.push(s);
                }
                String string = String.valueOf(str.charAt(i-1));
                System.out.println("String is " + operatorPrecedance.containsKey(string));
                if(operatorPrecedance.containsKey(string)){ // This should prevent further if but it does not  
                    if(!stackForOperators.isEmpty() && isPrecedanceHigher(string, stackForOperators.peek())){    //Here is NullPointer Excpetion is detected.
                        String item = stackForOperators.pop();
                        stackForOperators.push(string);
                        stackForOperators.push(item);
                    }else{
                        stackForOperators.push(string);
                    }
                }else if(str.charAt(i-1)=='('){
                    stackForOperators.push(string);
                }else if(str.charAt(i-1)==')'){
                    System.out.println("Position is " + (i-1) + " Char is  " + str.charAt(i-1));
                    while(!stackForOperators.peek().equalsIgnoreCase("(")){
                        System.out.println("h");
                        calculation((double)0, (double)0);
                    }
                }
            }
        }
        /*for(String s:stackForOperators){
            System.out.println("Operator in stackForOperators is " + s);
        }
        for(String s:stackForNumbers){
            System.out.println("Number in stackForNumbers is " + s);
        }*/
    }

    public static void calculation(Double i, Double j){
        for(String s:stackForOperators){
            System.out.println("Operator in stackForOperators is " + s);
        }
        for(String s:stackForNumbers){
            System.out.println("Number in stackForNumbers is " + s);
        }
        i = Double.parseDouble(stackForNumbers.pop());
        j = Double.parseDouble(stackForNumbers.pop());
        if(stackForOperators.peek().equalsIgnoreCase("+")){
            i = j + i;
        }else  if(stackForOperators.peek().equalsIgnoreCase("-")){
            i = j - i;
        }else if(stackForOperators.peek().equalsIgnoreCase("*")){
            i = j * i;
        }else if(stackForOperators.peek().equalsIgnoreCase("/")){
            i = j / i;
        }
        stackForOperators.pop();
        stackForNumbers.push("" + i);
    }

    public static boolean isPrecedanceHigher(String a, String b){
        System.out.println(b + " " + operatorPrecedance.get(b));
        System.out.println(a + " " + operatorPrecedance.get(a));
        return (operatorPrecedance.containsKey(a) && operatorPrecedance.get(b)>=operatorPrecedance.get(a));
    }
}

LinkedStack class:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedStack<Item> implements Iterable<Item>{
    Node original;
    int n;

    public LinkedStack(){
        original = null;
        n = 0;
    }

    public void push(Item item){
        Node node = original;
        original = new Node();
        original.item = item;
        original.node = node;
        n++;
    }

    public boolean isEmpty(){
        return n == 0;
    }

    public Item peek(){
        if(original==null){
            throw new NullPointerException();
        }
        return original.item;
    }

    public Item pop(){
        Item item = original.item;
        original = original.node;
        n--;
        return item;
    }

    public int size(){
        return n;
    }

    private class Node{
        private Node node;
        private Item item;
    }

    public Iterator<Item> iterator(){
        return new myIterator();
    }

    private class myIterator implements Iterator<Item>{
        private Node node = original;
        public boolean hasNext(){return node != null;}
        public void remove(){throw new UnsupportedOperationException();}
        public Item next(){
            if(!hasNext()){
                throw new NoSuchElementException();
            }
            Item item = node.item;
            node = node.node;
            return item;
        }
    }
}