samedi 30 juin 2018

IndexError: list index out of range >>> python [duplicate]

This question already has an answer here:

 a=['a','b','c','d']


 b=['l','b','n','d']


 for i in range(len(a)):
   for j in range(len(b)):
     if(a[i]==b[j]):
       b.remove(b[j])  //error here

 print(b)

what is error if i am wring print() statement work fine but b.remove() is not working

WordPress is_single do this and if is not specific single ID do that

I need help with one post.

I have post ID: 236512

I am using function on every is_single() post, but how can continue using the function on all posts except the specific post ID?

<?php if(is_single() && !is_single(236512)):?>
// My regular function
<?php else: ?>
// Do nothing
<?php endif; ?>

Is that syntax Ok or is there any other functional way doing this?

Thanks!

Ionic 3 - all if are activated at the same time (JS)

I have a little problem and i can't find the solution,

i have this little fonction here:

Clicked(){
       for (let i = 0; i < 5; i++) {
          if (this.ShareProvider.ValueFonction(i)) {
            alert(i)
          }
        }
}

There 6 buttons and what i'm trying to do is when I click a button the alert() fonction will launch. The problem is that when I run the program, it shows the 6 alerts in a row. I tried to write different way but same issue.

if (this.ShareProvider.ValueFonction(1)) {
  alert(1)
}
if (this.ShareProvider.ValueFonction(2)) {
  alert(2)
}
if (this.ShareProvider.ValueFonction(3)) {
  alert(3)
}
if (this.ShareProvider.ValueFonction(4)) {
  alert(4)
}
if (this.ShareProvider.ValueFonction(5)) {
  alert(5)
}
if (this.ShareProvider.ValueFonction(6)) {
  alert(6)
}

or

if (this.ShareProvider.ValueFonction(1)) {
  alert(1)
}
if (this.ShareProvider.ValueFonction(2)) {
  alert(2)
}
if (this.ShareProvider.ValueFonction(3)) {
  alert(3)
}
if (this.ShareProvider.ValueFonction(4)) {
  alert(4)
}
if (this.ShareProvider.ValueFonction(5)) {
  alert(5)
}
if (this.ShareProvider.ValueFonction(6)) {
  alert(6)
}

Thanks for you attention

Conditional form drop-downs and outputs

I created a form that produces a custom sentence based on a user's input. I want to make a conditional input thus leading to a conditional addition to the sentence. If the user selects "Okay" (id="z4") for the vehicle condition, I want the "Why?" (id="z5") dropdown menu to appear. Then after he or she selects one of the options from the "Why?" dropdown that is added to the sentence.

For example-

  1. The user inputs 2012 Honda Civic, 96,000, red, good. The output sentence is as follows: Up for sale is a 2012 Honda Civic with 96,000 miles. It is finished in red. It is in good shape.

  2. The user inputs 2012 Honda Civic, 96,000, red, okay, dents. The output sentence is as follows: Up for sale is a 2012 Honda Civic with 96,000 miles. It is finished in red. It is in okay shape because it has some dents.

Any ideas?

<!DOCTYPE html>
<html>

  <head>
        <title>Experiment</title>

        <style type="text/css">
  table,td,th {margin-left: auto;margin-right: auto}
  .display {display: flex;align-items: center;justify-content: center;}
  p {text-align: center;}
  textarea {display: block;margin-left:auto;margin-right: auto;}
        </style>

        <script type="text/javascript">
  function sentence() {
    document.getElementById("s1").value = "";// reset
    document.getElementById("s1").style.display = "block";
    document.getElementById("r1").style.display = "block";
    if (document.getElementById("z1").value == "") {
      alert("Year, Make, and Model are needed");
      document.getElementById("z1").focus();
    } else if (document.getElementById("z2").value == "") {
      alert("Mileage is needed");
    } else if (document.getElementById("z3").value == "") {
      alert("Exterior color is needed");
    } else {
      const input1 = document.getElementById("z1").value;
      const input2 = document.getElementById("z2").value;
      const input3 = document.getElementById("z3").value;
      const input4 = document.getElementById("z4").value;

      document.getElementById("s1").value =
        "Up for sale is a " + input1 + " with " + input2 + " miles. It is finished in "
        + input3 + ". It is in " + input4 + " shape.";

    }
  }

  function reset() {
    document.getElementById("s1").value = "";
  }

  function hide() {
    document.getElementById("s1").style.display = "none";
    document.getElementById("r1").style.display = "none";
  }
        </script>
  </head>

  <body onload="hide()">
    <table>
      <tr>
        <td> <input type="text" id="z1" placeholder="Year, Make, Model" name="name" maxlength="100"></td>
        <td> <input type="text" id="z2" placeholder="Mileage" name="name" maxlength="100"></td>
        <td> <input type="text" id="z3" placeholder="Exterior Color" name="name" maxlength="100"></td>
        <td> <select name="condition" id="z4"> <option value="" disabled selected>Condition</option> <option value="excellent">Excellent</option> <option value="good">Good</option> <option value="okay">Okay</option></select></td>
        <td> <select name="condition" id="z5"> <option value="" disabled selected>Why?</option> <option value="scratches">Scratches</option> <option value="dents">Dents</option> <option value="mechanical issues">Mechanical Issues</option></select></td>
    </table>
    <br>
    <div class="display">
      <button onclick="sentence()"> Submit </button>
    </div>
    <hr>
    <br>
    <textarea rows="10" cols="100" id="s1">

  </textarea>
    <br>

    <div class="display">
      <button onclick="reset()" id="r1">Reset</button>
    </div>

  </body>
</html>

AWK 'if' in loop doesnt work [duplicate]

This question already has an answer here:

So. I have problem with my variable "$i" because AWK cant read this. But if I was write "echo $i", It be 1.

for ((i=1; i<=$var; i++))

do

awk '{if(NR==$i) print $1}' /ip

done

false if statements being called/variable not being assigned?

I wasn't too sure what to call this post.

Anyways, what I'm trying to do is assign 'diff' to a user input, and if 'diff' is not average or advanced, recall the function so that the user can (hopefully) enter average or advanced.

However, no matter what I input, it will always recall the function, even if the input is 'average' or 'advanced'.

Code -

def choices():
    global diff
    diff = input("Choose a difficulty: Average/Advanced ")
    diff = diff.lower()
    x = 0
    while x > 1:
        if diff == 'average':
            print('Difficulty set to average.')
            x = x + 1
        elif diff == 'advanced':
            print('Difficulty set to advanced.')
            x = x + 1

    if diff != 'average' or 'advanced':
        print('Your input is invalid. Please try again.')
        choices()

choices()

The same thing is also happening for another decision I have that is similar to this, but I figured that there's no point in putting it down if it follows the same logic.

Sorry if this is a stupid question. I'm only a beginner.

I got expected primary-expression before ')' token on my if-statement in the second function

The error occurs in both statements where it says string, but the same code works just fine in the first function above it! how do I make it stop?

void Store::FindBook(const char* string) const

{ if(ReportFind(string)<0) cout << "no books found" << endl;

   else
   {
       for(int i = 0; i < currentSize; i++)
       {
           if (strcmp(bookList[i].GetTitle(),string) == 0)
                   bookList[i].Display();
       }

       for(int i = 0; i < currentSize; i++)
       {
       if (strcmp(bookList[i].GetAuthor(),string) == 0)
                   bookList[i].Display();
       }
   }

======================================================================

int Store::ReportFind(const char*) const { for(int i = 0; i < currentSize; i++)

   {
   if (strcmp(bookList[i].GetTitle(),string) == 0)

           return i;
   }

for(int i = 0; i < currentSize; i++)
{
if(strcmp(bookList[i].GetAuthor(),string) == 0) return i;
}

return -1; }

Why do functions print automatically when put in 'if' statement

Why is it that when this code is executed, I would get 'hi'?

Thanks!

def b():
    print("hi")
def c():
    return True
if b() == 'hi':
    print("Done")

vendredi 29 juin 2018

Why is scanner skipping the if else statement

Pretty straightforward code, if I change string K to "Bye" I receive an error, only the if else structure works, not the if else if else. Please help me understand why.

public static void main(String [] args){
    String k = "Hi";
    Scanner scnr = new Scanner(k);
    if (scnr.next().equals("Hi")){
        System.out.println("Yes");
    }
    else if (scnr.next().equals("Bye")){
    System.out.println("No");
    }
    else {
    System.out.println("Maybe");
    }
}

Change the size of a colored rectangle in YUV file in C

I am trying to re-purpose this C code for my purposes. It creates a YUVY file with a colored box in the center and black background. The Y'CbCr colors are entered on the command line for the rectangle in the center. It works great with the only exception being I would like to change the size of the colored box. I've spent hours trying to figure out for how to change it with lots of trial and error and searching online for answers with no luck. Not being a programmer, I don't understand how the logic elements of this code works.

My goal: The overall resolution is 1920 x 1080 and I want the box to be 1/3 of both the vertical and horizontal grid in the center. So the x coordinates would be between 360 and 720 with the y coordinates between 640 and 1280. I've tried creating if, then logic that specifies these intersections but I get all black or red files or a red box in the corner, etc. No matter what I try I can't get the desired result. Any help would be appreciated.

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

#define TRUE        1
#define FALSE       0

int main(int argc, char **argv)
{
    FILE    *fpout;
    unsigned int    i, j;
    unsigned char   y, cb, cr, temp;

    if (argc != 5) {
        fprintf(stderr, "usage: pat<outfile> <Y> <Cb> <Cr>\n");
        exit(-1);
    }

    /*--- open binary file (for parsing) ---*/
    fpout = fopen(argv[1], "wb");
    if (fpout == 0) {
        fprintf(stderr, "Cannot open output file <%s>\n", argv[1]);
        exit(-1);
    }

    for(j = 0; j < 264; j++)  {
        for(i = 0; i < 960; i++)  {
            y = 16;
            cr = 128;
            cb = 128;
            fwrite(&cb, 1, 1, fpout);
            fwrite(&y, 1, 1, fpout);
            fwrite(&cr, 1, 1, fpout);
            fwrite(&y, 1, 1, fpout);
        }
    }
    for(j = 0; j < 552; j++)  {
        for(i = 0; i < 960; i++)  {
            if(i < 240 || i > 719)  {
                y = 16;
                cr = 128;
                cb = 128;
                fwrite(&cb, 1, 1, fpout);
                fwrite(&y, 1, 1, fpout);
                fwrite(&cr, 1, 1, fpout);
                fwrite(&y, 1, 1, fpout);
            }
            else  {
                temp = atoi(argv[2]);
                y = temp;
                temp = atoi(argv[3]);
                cb = temp;
                temp = atoi(argv[4]);
                cr = temp;
                fwrite(&cb, 1, 1, fpout);
                fwrite(&y, 1, 1, fpout);
                fwrite(&cr, 1, 1, fpout);
                fwrite(&y, 1, 1, fpout);
            }
        }
    }
    for(j = 0; j < 264; j++)  {
        for(i = 0; i < 960; i++)  {
            y = 16;
            cr = 128;
            cb = 128;
            fwrite(&cb, 1, 1, fpout);
            fwrite(&y, 1, 1, fpout);
            fwrite(&cr, 1, 1, fpout);
            fwrite(&y, 1, 1, fpout);
        }
    }

    fclose(fpout);
    return 0;

If statement that checks a list of numbers

I want to write an if statement that will return if a variable does not equal one number in the list. Conceptually I want it to do this:

if (VARX [DOES NOT EQUAL ONE OF THESE NUMBERS] 194||301||177||249||22||131||56. . .){ return; }

The actual list of numbers I have is approx 250 different numbers. Is there an easy way to accomplish this with one if statement?

How do I fix the logic? [duplicate]

This question already has an answer here:

I have a program where I am trying to make an account and store it in a text file to be used in another program, the problem is that there is a problem with the if statements but I don't know what it is.

Here is the code:

import java.io.*;
import java.util.*;

public class Log_In_User_and_Pass {
public static void main(String[] args) {


    Scanner lineReader = new Scanner(System.in);
    BufferedWriter bw = null;
      try {

          File file = new File("C:\\Users\\home\\Desktop\\UserAndPassStorage.txt");

         /* This logic will make sure that the file 
          * gets created if it is not present at the
          * specified location*/
          if (!file.exists()) {
             file.createNewFile();
          }


          System.out.println("Would you like to create a new account? (Yes/No)");
          String response = lineReader.nextLine();

          if(response == "Yes" || response == "yes" || response == "No" || response == "no") {
              if(response == "Yes" || response == "yes") {
                  System.out.println("Please put a username: ");
                  String username = lineReader.nextLine();
                  System.out.println("Please put a password: ");
                  String password = lineReader.nextLine();
                  FileWriter fw = new FileWriter(file);
                  bw = new BufferedWriter(fw);
                  bw.write("Username: ");
                  bw.write(username);
                  bw.newLine();
                  bw.write("Password: ");
                  bw.write(password);
                  System.out.println("Account created.");
              }

              else {
                  System.out.println("Okay.");
              }
          }

          else {
              System.out.println("That is not one of the options.");
          }

      } catch (IOException ioe) {
       ioe.printStackTrace();
    }
    finally
    { 
       try{
           lineReader.close();
           if(bw!=null) {
         bw.close();}
       }catch(Exception ex){
           System.out.println("Error in closing the BufferedWriter"+ex);
        }
    }
}
}

And here is the output of the program:

Would you like to create a new account? (Yes/No)
Yes
That is not one of the options.

It should be going to the part where you make a username and password but it doesn't so I am really confused. Thanks for the help.

Exhaustive Search Through Inverse Coordinates

I have a table of TRUE and FALSE values and would like to create a list/table based on the pattern of those TRUE and FALSE values.

Specifically, I want to consider the relation of coordinates with inverted coordinates.

For example, if the cell mydata[x,y] has a value of TRUE, and the cell mydata[y,x] has a value of TRUE, I want to record the column name of mydata[x,y] and the column name of mydata[y,x] with a "<->" printed in between.

I am able to cycle through the number of rows using the following code, but this does not consider the pattern of TRUE and FALSE exhaustively. It is restricted by the number of rows. Without this restriction, the for loop ends up out of bounds.

What can I do with my code to consider all of the TRUE and FALSE combinations of coordinates/inverted coordinates without going out of bounds?

random.base <- data.frame(replicate(30,sample(0:1,30,rep=TRUE)))
boolean.table <- random.base == "1"

# this code varies the distance of i and j, but it only records 29 patterns 

output <- NULL

for(i in 1:(nrow(boolean.table)-1)){
  print(i)
  for(j in (i+1):nrow(boolean.table)){
    if(boolean.table[i,j] == "TRUE" & boolean.table[j,i] == "TRUE"){
      output[i] <- paste(colnames(boolean.table)[i], "<->", colnames(boolean.table)[j])
} else if(boolean.table[i,j] == "TRUE" & boolean.table[j,i] == "FALSE"){
  output[i] <- paste(colnames(boolean.table)[i], "<-", colnames(boolean.table)[j])
} else if(boolean.table[i,j] == "FALSE" & boolean.table[j,i] == "TRUE"){        
  output[i] <- paste(colnames(boolean.table)[i], "->", colnames(boolean.table)[j])
} else {
  NULL
}
}
}

Makefile execute echo only one time inside a rule

I have this Makefile

$(MAIN) : $(OBJECTS)

$(OBJECTS) : %.c
     compile file

And i want to use printf for print something like "compiling" whenever a file needs compile and "done" if a file has been compiled at the end of every compiled for example:

Compiling
file1.c
file2.c
file3.c
Done

I have tried to use sentences like if from shell or ifeq from makefile but i need a variable and makefile doesn't let me change the value of a variable inside of a if i don't know why. How can i archive this?

If/else condition in dplyr 0.7 function

I'd like to make a simple if/else condition in a dplyr function. I've looked at some helpful posts (e.g., How to parametrize function calls in dplyr 0.7?), but am still running into trouble.

Below is a toy example that works when I call the function without the grouping variable. The function then fails with the grouping variable.

# example dataset
test <- tibble(
  A = c(1:5,1:5),
  B = c(1,2,1,2,3,3,3,3,3,3),
  C = c(1,1,1,1,2,3,4,5,4,3)
)

# begin function, set default for group var to NULL.
prop_tab <- function(df, column, group = NULL) {

  col_name <- enquo(column)
  group_name <- enquo(group)

  # if group_by var is NOT null, then...
  if(!is.null(group)) {
      temp <- df %>%
        select(!!col_name, !!group_name) %>% 
        group_by(!!group_name) %>% 
        summarise(Percentages = 100 * length(!!col_name) / nrow(df))

  } else {
  # if group_by var is null, then...
      temp <- df %>%
        select(!!col_name) %>% 
        group_by(col_name = !!col_name) %>% 
        summarise(Percentages = 100 * length(!!col_name) / nrow(df)) 

  }

  temp
}

test %>% prop_tab(column = C)  # works

test %>% prop_tab(column = A, group = B)  # fails
# Error in prop_tab(., column = A, group = B) : object 'B' not found

If Statement for Visible Cells Only

I am creating a form that autopopulates data when another form is pasted onto the workbook. I combined numbers from 5 different cells into one cell using this formula =TEXT(L2,IF(L2=0," ","$000,000"))&"; "&TEXT(L3,IF(L3=0," ","$000,000"))&"; "&TEXT(L4,IF(L4=0," ","$000,000"))&"; "&TEXT(L5,IF(L5=0," ","$000,000"))&"; "&TEXT(L6,IF(L6=0," ","$000,000")).

Sometimes I will need to hide 3 rows, meaning I only need 2 of the numbers combined. The problem is that it still captures the 5 numbers. Is there a way to combine the visible cells only?

aspx c# extra semi colon appear with inline if statement on onclick event

first time here.

I'm having trouble with c# inline if statement in aspx page, i'm trying to call a different onClick method depending if my Parent has Child or not, however, for some reason, it adds a ; in the code but the fonction is never called, however, with the same if statment in a text field, everything shoes fine without any semicolon.

any idea why?

here are both OnClick and text code snippet

OnClick='<%#(int)Eval("nbChild") != 0 ? "Expend" : "AddSub" %>'

Text='<%#(int)Eval("nbChild")!=0 ? "Expend":"AddSub" %>'

Skip part of script on error

I've been banging my head against the wall for awhile on this one. No amount of Googling has yielded me any successful results thus far. Wondering if someone can give me a hand?

# Load the PowerShell module for Active Directory
Import-Module ActiveDirectory

# For each computer in AD that is a member of the target group
Get-ADGroupMember -Identity "CN=RenameComputer,CN=Users,DC=int,DC=example,DC=com" | ForEach {

        # Define the new name as the old one, minus one letter at the end
        $NewComputerName = $_.Name -replace ".$"

        # Perform the rename operation
        Rename-Computer -ComputerName $_.Name -NewName $NewComputerName -Force -PassThru -Restart -WhatIf

        # Remove the computer from the target group
        # THIS SHOULD NOT OCCUR IF THE RENAME ABOVE FAILED!!!
        Remove-ADGroupMember -Identity "CN=RenameComputer,CN=Users,DC=int,DC=example,DC=com" -Members $NewComputerName -WhatIf

}

TL;DR: This script finds a bunch of computers in a designated group, renames them, and then removes them from the group. I need help telling the script to NOT remove them from the group in the event that the rename fails (machine is offline, etc.) or throws some error.

Thoughts?

Thanks in advance!

How to differentiate the returned value of a function in Objective C?

I have a function that gives 2 different String values that are returned :

-(NSString*)load:(NSDictionary *)dict
{

    NSDictionary *dataDict = [self objectForId:@"data" fromDict:dict withDefault:nil];
    if (dataDict) {
        NSDictionary *success = [self objectForId:@"success" fromDict:dataDict withDefault:nil];

        NSString *str = [NSString stringWithFormat:@"%@", success];

        if ([str isEqualToString: @"1"])
        {
            NSDictionary *idDict = [self objectForId:@"id" fromDict:dataDict withDefault:nil];
            if (idDict) {
                NSString *idString = [NSString stringWithFormat:@"%@", idDict];
                return idString;
            }

        } else {
            NSDictionary *messages = [self objectForId:@"messages" fromDict:dataDict withDefault:nil];
            if (messages) {
                NSDictionary *messageDict = (NSDictionary *)messages;
                NSArray *type = messageDict[@"type"];
                if (type.count > 0) {
                    NSString *messageString = type[0][@"message"];
                    return messageString;
                }
            }
        }
    }
    return  nil;
}

And accessing the stringValue like this :

 NSString *string = [className load:dict];

Now I want to write if else statements for "idString" and "messageString" return values. How do I differentiate the 2 return values?

How can I pass the filename from a variable locally into ssh?

I am checking whether a file exists on a remote server but instead of hardcoding the filename I want to pass in a variable. Is this not possible this way? Should I take an alternative route?

Works:

if ssh "$SSH_USER"@"$SSH_IP_ADDRESS" "echo $OUTPUT1 && cd $SSH_LOC && pwd && echo $SSH_LOC && [ -f live_29-06-2018.txt ];"
    then
        echo "This file exists."
    else
        echo "This file doesn't exist."
    fi

Displays "This file exists."

Doesn't work:

if ssh "$SSH_USER"@"$SSH_IP_ADDRESS" "echo $OUTPUT1 && cd $SSH_LOC && pwd && echo $SSH_LOC && [ -f $OUTPUT1 ];"
then
    echo "This file exists."
else
    echo "This file doesn't exist."
fi

Displays "This file doesn't exist."

How to perform an if statement on NULL variable?

In my database I have subjects. Each subject can have many exams, assignments and attendance. For each subject I am trying to find which exams have "examGradeAchieved" as NULL. (As in the exams the student does not have a result for yet)

If examGradeAchieved is set to null then I want to find the grade worth of that exam (another variable, for example one exam is worth 20% of the whole subject), add "ExamGradeWorth" to a list then find the sum of that list to equal the grade so that I can find the remaining potential marks the student can achieve in that subject. However it is displaying the wrong numbers. If examGradeAchieved is set to null it should display the 20% but it is displaying 0. Also for any subjects where there is no potential remaining marks it is displaying the total value of all the exams instead of displaying 0.

        for(int i=0; i<subjects.size(); i++){ //for each subject in the list
        Subject subject = subjects.get(i);
        remExamMarks =0;
        remAssignMarks = 0;
        remAttenMarks = 0;

            List<Exam> exams = subject.getExam();
        for(int z=0; z<exams.size(); z++) {
            Exam exam = exams.get(z);

            ArrayList<Double> examRemMarks = new ArrayList<Double>(); 
            if(exams.get(z).getExamGradeAchieved() !=null) {
                examRemMarks.add(exams.get(z).getExamGradeWorth());
            }
            for(int h=0; h < examRemMarks.size(); h++) {
                remExamMarks = remExamMarks + examRemMarks.get(h);


            }

        }
        System.out.println(remExamMarks + "EXAM REM MARKS ==================");

s-Function TCP/IP does not send because of if-else

my problem is specific, but hopefully I can describe it simple.

I wrote a level-2 s-Function in C++ to connect my simulink model with my C++ - code. The s-Function is the client, C++ - code the server. Connecting works well. I also can send data from client to server in a session or from server to client in an other session. The s-Function has a sample time of 0.001 seconds.

The source ot the client sends data every 0.5 seconds, but because of my sample time I put a rate-transition block between the source and the client, so that the client has data available every step (Input1 and Input2). I decieded to use two memory blocks (Input3 and Input4 / Output2 and Output3) and to check every time step if there is new data or not. If there is new data, the client should send the data to my c++ - code. If not, the client shouldn't do anything.

My problem is, that I can't send AND receive data with the client in a session. It only sends the data one time at the beginning of the simulation and receives the data. After the start of the simulation it should send data every 0.001 seconds, but it doesn't. My C++ - code is waiting for the data the whole time, so it can't send new data, because it is in blocking mode.

Here is the part of the s-Function Code:

    double* Input1 = (double*)ssGetInputPortSignal(S, 0); 
    double* Input2 = (double*)ssGetInputPortSignal(S, 1); 
    double* Input3 = (double*)ssGetInputPortSignal(S, 2); 
    double* Input4 = (double*)ssGetInputPortSignal(S, 3);  

    int *Output1 = (int*)ssGetOutputPortSignal(S, 0); //Output of received values
    double* Output2 = (double*)ssGetOutputPortSignal(S, 1); //Output to the memory block
    double* Output3 = (double*)ssGetOutputPortSignal(S, 2); //Output to an other memory block

    if (*Input1 != *Input3 && *Input2 != *Input4) //New data available
    {
        send(socket, (char *)Input1, sizeof(double), 0);
        send(socket, (char *)Input2, sizeof(double), 0);
        *Output2 = *Input1; //set output to new value, so that it can't send this data again
        *Output3 = *Input2; //set output to new value, so that it can't send this data again
    }
    else //Don't do anything. Just specify the output
    {
        *Output2 = *Input3;
        *Output3 = *Input4;
    }
    //Receive
    int recvBytes;      
    recvBytes = recv(socket, (char *)Output1, sizeof(int), 0);

    if (recvBytes < 0) //No Bytes Available
    {
        *Output1 = -1;
    }

All of inputs and outputs are 1-D. I also checked the if-else: Every 500 steps the if-statement is true (like it should be), but my client doesn't send anything.

The programm is running without the if-else-statement, but I need it this way.

I appreciate any help! Thank you.

create variable based on multiple similar variables in R

My data looks like this:

  zipid1 zipid2 zipid3 zipid4 zipid5 zipid6 zipid7 zipid8 zipid9 zipid10 zipid11 zipid12 zipid13 hospid local
1      0      0      0      0      1      0      0      0      0       0       0       0       0      5     0
2      0      0      1      0      1      0      0      0      0       0       0       0       0      5     0
3      0      0      0      0      0      0      1      0      0       0       0       0       0      5     0
4      0      0      1      0      0      0      0      0      0       0       0       0       0      5     0
5      0      0      1      0      1      0      0      0      0       0       0       0       0      5     0
6      0      0      0      0      1      0      0      0      0       0       0       0       0      5     0

How can I create a local variable = 1 when zipid1 ==1 & hospid =1, zipid2 == 1 & hospid == 2.etc. and else = 0 (ie, zipid = hospid)?

I tried ifelse but did not work well.

for (i in 1:13) {
name = paste0("zipid", i)
local$local <- with(local, ifelse(name == 1 & hospid == i, 1, 0))
}

Thanks!

Is it a correct way to use try-catch block over if statement to check a condition?

I was just wondering what's the best practice between using try-catch block to check a condition and an if statement ? For example to try if we are below the range of a List in a loop :

List<int> foo = new List<int>();
for(int cpt=1; cpt<=10; i++)
{
    if (cpt > foo.Count) foo.Add(cpt);
    Console.WriteLine(foo[cpt]);
}

But we can achieve this by using a try-catch like this :

List<int> foo = new List<int>();
int bar = 0;
for(int cpt=1; cpt<=10; i++)
{
    try
    {
        Console.WriteLine(foo[cpt]);
    }
    catch(ArgumentOutOfRangeException)
    {
        foo.Add(cpt);
    }
}

So for this example, obviously the if statement is better as it's able to display the foo[cpt] even if we are out of bound but in another context, could the try-catch block be more efficient ?

Error in conversion of upper and lower cases

Below code is to convert upper case to lower case and vice vers?

  if(s1.charAt(i)>=97 && s1.charAt(i)<=122){
     s1.charAt(i)=s1.charAt(i)-32;
  }
  else if(s1.charAt(i)>=65 && s1.charAt(i)<=90){
      s1.charAt(i)=s1.charAt(i)+32;
  }

Please refer above and help what is the issue with this program?

Check for something in database within a echo tag

I'm using a while loop to echo out the users that are in the database in a table. Now, I want to check if the column "loggedin" is set to 1 (and if so, I want to put something with online after the name). This is my code:

<tr>
          <th>Name</th>
          <th>Date</th>
          <th>Actions</th>
        </tr>
        <?php
        while($row = mysqli_fetch_array($resultUsers))
        {
          echo "<tr>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['date'] . "</td>";
            echo "<td><a class='btn btn-default' href='member.php?user=" . $row['id'] . "'>Bekijk</a> <a class='btn btn-default' href='member.php?user=" . $row['id'] . "&sendrequest=1s'>Stuur vriendschapsverzoek</a></td>";
          echo "</tr>";
        }
        ?>

Now, I want to add some sort of code that checks if the user is online. Like this:

echo "<td>" . $row['name'] . "" . if($row['loggedin'] === 1) {"<p>Online</p>"} . "</td>";

jeudi 28 juin 2018

r ifelse condition for the calculation on multiple dataframes

I have 3 data frames, df 1 = a time interval, df2 = list of IDs, df3 = list of IDs with associated date.

df1 <- structure(list(season = structure(c(2L, 1L), .Label = c("summer", 
"winter"), class = "factor"), mindate = structure(c(1420088400, 
1433131200), class = c("POSIXct", "POSIXt")), maxdate = structure(c(1433131140, 
1448945940), class = c("POSIXct", "POSIXt")), diff = structure(c(150.957638888889, 
183.040972222222), units = "days", class = "difftime")), .Names = c("season", 
"mindate", "maxdate", "diff"), row.names = c(NA, -2L), class = "data.frame")

df2 <- structure(list(ID = c(12345, 12345, 12345)), .Names = "ID", row.names = c(NA, 
-3L), class = "data.frame")

df3 <- structure(list(ID = c(12345, 123456), time = structure(c(1420866000, 
1451624400), class = c("POSIXct", "POSIXt"))), .Names = c("ID", 
"time"), row.names = c(NA, -2L), class = "data.frame")

What i would like to achieve, is if the ID in df2 finds a match in df3, and if the time in df3 is equal or larger than the mindate & equal or smaller than the maxdate in df1, then calculate the time difference between maxdate (df1) and time (df3) of the associated ID. I tried using the ifelse function. It works when I manually specify the match in IDs between df2 and df3, but i need the function to find the match in IDs, and then execute the time difference calculation.

df1$result <- ifelse(df2[1,1] == df3[1,1] & df3[1,2] >= df1$mindate & df3[1,2] <= df1$maxdate, 
                     difftime(df1$maxdate,df3[1,2],units="days"),
                     difftime(df1$maxdate,df1$mindate,units="days")

Thanks for any help

How to start java swing timer?

Right now, the object moves a certain increment each time I manually click a button, but its actually suppose to move on its own across the screen on its own once a button is clicked. I tried calling timer.start(); various times in my code. As well as, setting up an 'if' statement in the actionPerformed method that checks for a button being pressed and then calls timer.start() as a result. But, it didn't get the object to move on its own.

Can anyone lead me in the right direction? Am I not writing the code right? Or is does this problem have something to do with java swing timer.

PS. I am new to java,

This is what I have imported in the beginning :

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;

And this is part of my code :

 public void actionPerformed(ActionEvent e){

    if (e.getSource() == rightBtn) {    
        objXpos += objMoveIncrement;
        direction = "right";
        direction.equals("Right");

    }
    if (e.getSource() == leftBtn) {
        direction = "left";
        direction.equals("Left");
        objXpos -= objMoveIncrement;
    }

    repaint();

} } **edit the timer is suppose to start once a button is clicked, and the timer is what allows the object to move across the screen

Node js if condition is not working properly

I want to initialize global variable with body of json object. But in my code if is not being executed instead of if, else part of code executes, if console.log typeof ticker I get undefined. What appears to be the problem.

var ticker ; 
request ({
      method : 'POST',
      url    :  'xyz'
 },(err,res,body)=>{

  if (typeof ticker === undefined) {
    ticker = body ; 
     }
    else {

      console.log(ticker) 
   }

How do I create a formula in excel that compares text in cells and returns a percentage

I have a excel spreadsheet that every cell will have either three values, Pass, Fail or na(not available). This is an example of what the spreadsheet will look like

So I will like to have a formula that will compare all the cells and returned 100% "completion" when all the cells have "Pass" on them.

geting each failed results in if multiple conditions

I have below conditions . IF all conditions are meet then it passes. If it fails then need to know which condition makes it to fail ?

if [[ -z “$pas” ]] && [[ $dd_check_pass == “pass” ]] && [[ $asmresultcheck == “pass” ]];
then
zzz=Passed;
else
zzz=Failed;
aaa=”Due to unknown process running”
fi

Haskell simple If-then-else error

I'm really new to Haskell and programming in general. I'm trying to add up the contents of a list without using the sum function from Data.List. Here's what I've got so far:

module Summ
    where
summ :: [Int] -> Int
summ xs = 
  if null xs == False
    then let y = x + (head xs)
         let xs = tail xs
    else print y

I'm pretty sure there's a lot wrong with this code, but for now the latest error is "parse error on input" for the else statement. What's wrong?

Javascript variable in form

I'm creating a process which pulls down a static Google map image using their API.

I have a form which has radio buttons with the following map image options:

 Satellite
 Roadmap
 Hybrid
 Terrain

The radio buttons are in a form - part of which is below:

<summary>Basemap</summary>
<div class="group">
<p>Select a Map Style:</p>
<p>
<label><input type="radio" name="basemapStyle" id="basemapStyle" value="Satellite" checked /> Satellite</label>
<label><input type="radio" name="basemapStyle" id="basemapStyle" value="Roadmap"/> Roadmap</label>
<label><input type="radio" name="basemapStyle" id="basemapStyle" value="Hybrid" /> Hybrid</label>
<label><input type="radio" name="basemapStyle" id="basemapStyle" value="Terrain" /> Terrain</label>
</p>
</div>

I have an underlying javascript document which is called from the html page.

It contains the following code:

var bmStyle = document.getElementById("basemapStyle").value;


    if (bmStyle = "Satellite" ) {       
            var basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
            }
        else if (bmStyle = "Roadmap" ) {        
            var basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
            }
        else if (bmStyle = "Hybrid" )  {        
            var basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
            }
        else if (bmStyle = "Terrain" )  {       
            var basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
            }       

The page loads successfully and a "basemap" is generated. However, the selected radio button makes no difference and the only first variable in the if else statement seems to get loaded.

I feel there's some logic error in the if else statement but I can't seem to get my head round it.

How the IF statement accept C and D values?

enter image description here

Please Help me as fast as you can

Is there a way to use the <=> operator in a perl if statement?

To start off with, I realize that I can write an if statement with this operator that compiles and runs. I'm wondering if there's a way it can be used to make an if/elsif/else block a little more elegant.

I currently have a block of code that looks like this

 if( $a == $b) {
        # Do some stuff
} elsif( $a < $b) {
        # Do different stuff
} else {
        # Do really weird stuff
}

So there are specific things I want the script to do based on whether the two values are equal, or if they aren't equal, whichever one is lower. It seems like the <=> operator would be well suited to this.

Laravel: using Javascript inside blade @if

I was wondering. It's not possible to put Javascript inside blade @if right? Is blade @if some form of php but using php code will be discouraged in view right? What should I do? Here's the logic of what I'm trying to achieve. Basically, what alternative ways are there to achieve what I'm trying to do?

@if(isToday($one_parking_info->booking_data->m_bkl_end_date) && isBeforeElevenPM() && notEndInT($one_parking_info->booking_data->m_plots_address_city))
    <button type="button" class="btn btn-primary btn-sm" onClick="cancelBooking('')">取消</button>
@endif

error in element existing identification when using 'if in'

Here is my code:

df1 = pd.DataFrame({'a': [1,2,3,1,2,3,3],'b':[1,2,3,1,2,3,3],'type':[1,0,1,0,1,0,1]})
def add_buy_label(group):
    behavior_type = group.type.astype(int)
    if 1 in group['type']:
        group['buy_label'] = 1
    else:
        group['buy_label'] = 0

    return group[['a', 'b', 'type','buy_label']]

The functions above is to make the buy_label to 1 for all the a-b item as long as one (type = 1) in the group exist, however, the result after

df1.groupby(['a','b'],as_index = False).apply(add_buy_label)

is

    a  b  type  buy_label
0  1  1     1          0
1  2  2     0          1
2  3  3     1          0
3  1  1     0          0
4  2  2     1          1
5  3  3     0          0
6  3  3     1          0

It is pretty obvious that the row with 3 is wrong, because there is type = 1 existing in the group of (a=3,b=3), but the according buy_label is 0.

How can I fix it ?

list comprehension looping with if/else statement from 2d nested dictionary working with pulp

another pointer needed.

the following snippet works and it produces exactly what I want, however
i need soms pointers on how to be more pythonic with the line "if avail[employee, day, "Morning"].varValue==0 and
avail[employee, day, "Mid"].varValue==0 and avail[employee, day, "Night"].varValue==0:"

Shift_pattern_Master = ["Morning", "Mid", "Night"]

for employee in Employees:
    for day in Days:
        if avail[employee, day, "Morning"].varValue==0 and    
            avail[employee, day, "Mid"].varValue==0 and 
            avail[employee, day, "Night"].varValue==0:
                print (f"{employee} on {day} is off.")
        else:
            for shift in Shift_pattern_Master:
                if avail[employee, day, shift].varValue==1:
                    print (f"{employee} on {day} works in {shift}.") 

so I tried "if avail[employee, day, shift].varValue==0 for shift in Shift_pattern_Master:" to make it a generic condition and it keeps saying "for" is INVALID SYNTAX.

i think i am missing something, but i don't know what. thanks for any help in advance.

mercredi 27 juin 2018

How to Account for "-" in Excel

I have been working on an excel document where I'm essentially just adding up costs for a made up company. I want to make it so that I can track the differences from year to year. For a some cells, this isn't a problem, as most of them have numerical values inputted in them. However, for cells that have no cost associated with them, I have put "-" to fill the cell. This is because, while some cells have "0" inputted in them, this 0 is meant to represent a value under 50,000 (as each cell has a value that is meant to be read in the millions). To try to get around this problem, I have been fiddling around with IF, OR and AND statements to try to tell excel to do different things depending on which cells are filled with what. There are three problematic cases: (1) when the first year I'm evaluating has a "-" in a cell and the second has a numerical value; (2) the inverse of (1); (3) when both years have "-" values. The third one I have solved separately by just putting:

    IF(AND(ISTEXT(N3), ISTEXT(D3), "-", N3_D3))

However, I can't seem to be able to add solutions to problems (1) and (2). Any advice on the matter would be greatly appreciated. Thanks in advance.

Why my if statement gives false negatives?

I want to iterate over a list of files in Python 3. They are CSV files containing matrices. I want to do the same with all of them so I wanted to create a list with their names, remove all other files in the folder from the list and do my transformation with the relevants.

My target files all end with "2m.csv" (e.g.: 14-17_CCK_all_2m.csv) and my results at the end of the process will end with "1m.csv". Still when I run the following script in Jupyter notebook, the result contains some files ending with "1m.csv" (they remained there from an earlier cycle of the development)

import os
myfiles = os.listdir()

for item in myfiles:
    if item[-6:] != "2m.csv":
        myfiles.remove(item)

Interestingly, if I test one of the false negatives in a separate lines, I get a True answer, so the if statement should have eliminated it from my list in the script above - which it did with some of them, but not with some others:

myfiles[1][-6:] != "2m.csv"
>>> True

All the files in question have very similar name structure. Thanks for your help.

How do I use a macrovariable in an if or case statement

I have a while loop that runs over several years of data. During this time one attribute in some tables I need to join to has changed its name. To get around this I thought I could use a case or if statement. But I'm unable to get the Boolean expression to understand or accept the value in my macrovariable.

Very simplified (with a very short period just for example and all the other code in the while loop is working) my code looks like this:

declare @StartYear smallint = 2010
declare @Year smallint = @StartYear
declare @EndYear smallint = 2013
declare @YearVC varchar(4) = ''
declare @CreateTable varchar(MAX) = ''

while @Year <= @EndYear
  begin

   set @YearVC = cast(@Year as varchar)

   set @CreateTable = '
     if ' + @Year + ' < 2011
       select t1.*, t2.a, t2.b, t2.c as e /*Variable t2.e change it´s origin name over time.*/
       into ResultTable_' + @YearVC + '
       from TableOne_' + @YearVC + ' as t1 left join TableTwo_' + @YearVC + ' as t2 on t1.a=t2.a

     if ' + @Year + ' >= 2011
       select t1.*, t2.a, t2.b, t2.d as e /*Variable t2.e change it´s origin name over time.*/
       into ResultTable_' + @YearVC + '
       from TableOne_' + @YearVC + ' as t1 left join TableTwo_' + @YearVC + '  as t2 on t1.a=t2.a
     '

     exec (@CreateTable)

set @Year = @Year + 1

end

I've also tried with a case statement (all the variable declarations, the while-loop and the @CreateTAble statement is the same so I just write my select syntax below):

select t1.*, t2.b,
  case
    when ' + @Year + ' < 2011 then t2.c
    else t2.d
  end as e
into ResultTable_' + @YearVC + '
from TableOne_' + @YearVC + ' as t1 left join TableTwo_' + @YearVC + ' as t2 on t1.a=t2.a

Both these examples give me a Msg 245 error:

Conversion failed when converting the varchar value '

with references to my Boolean expressions?

I've made certain in several and different ways that the macrovariable value that I send to that expression is not a varchar. When I try with a varchar variable I get a Msg 207 error instead:

Invalid column name 'd'.

This means that it can't find the attribute name for the attribute which will be valid from 2011 and later.

What am I missing here? How should I define my "if" or "case" statement so that SQL-server will understand that for the years before 2011 it should look for the attribute c and for the years from 2011 and further it should look for attribute d?

I use MS SQL-server version 14.

VBA - Nested "With Statements" within "IF Statements"

Language: VBA - MS Access

I am using User-Defined-Types (UDT) within my code. I would like to be able determine which section of the UDT i'm loading data into based on a state variable. My first attempt was to use "With" statements nested into an "IF" statement. This doesn't work (I get a compiler error that says Else without if). Is there a way to make this work? or another way of going about using a state variable to determine which section of the UDT i'm loading?

Type MyOtherType
    Name as String
    Age as Integer    
End Type

Type MyType
    aMyOtherType() as MyOtherType
    X as Integer
    Y as Integer
    Z as Integer  
End Type

Sub QuestionableCode()
Dim UDT(0 To 0) as MyType
Dim State as String
ReDim Preserve UDT(0).X(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Y(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Z(0 to 0) as MyOtherType

    State = "B"

    If State = "A" Then
        With UDT(0).X(0)
    ElseIf State = "B" Then
        With UDT(0).Y(0)
    Else 
        With UDT(0).Z(0)
    End If
            .Name = "George"
            .Age = 30
        End With
End Sub

Conditional should change based on even/odd of the counter within the conditional

I am trying to append either "X" or "O", depending on whether the counter (in this case, var = turn) is odd or even.

The counter works as intended (it counts per clicK), but it won't bounce back and forth between the if/else if as the clicks go back and forth between odd/even.

Here are the two functions that are pertinent to the question.

My turn variable is at the top of my script.

var turn = 0

function player() {
    return turn % 2 ? "O" : "X";
    //based off even/odd of turn number, sets the player token
}


$(function gameFunction() {
    $('#myBoard tr').each(function() {
        $(this).find('td').each(function() {
            if ($(this).html() == '' && player() == "X") {

                    $(this).on("click", function() {
                        $(this).append("X");
                        console.log(turn++);
                });

            } else if ($(this).html() == '' && player() == "X") {

                    $(this).on("click", function() {
                        $(this).append("O");
                        console.log(turn++);
                });
            }   
        });
    });
});

Basically, it keeps appending "X", when I need it to append "O" when turn = odd.

Thanks!

Java Program Logical Error. The IF..Part is not working/Executing

Hello Guys,
I was writing a code for bank portal and I stuck onto a creepy error. I have a login() Function which is called through switch case present in the main function. But whenever I put login details and login My else part get executed even if the condition is true. Can you please check whats wrong. I'm a beginner to java programming.
I would also love to hear some suggestions on what new functionality should I add to this code.
Also, rate the quality of my code, I would love to hear from you.

package e.banksolutions;
import java.util.Scanner;
import java.util.Random;
import java.util.Date;
public class EBankSolutions {

    long accountNumber;            // Variable for Storing account number
    long accountNumberGenerator=0000;   // Variable for generating and assigning account number
    String AccountHolderName;     // Variable for Storing account holder name
    String AccountType;           // Variable for Storing account type in string
    int AccTypeNumVal;
    long accountBalance;          // Variable to Store Current Account Balance. 
    String password;                //27-06-2018
    //----------------------------------------------------------------------------//

public void createAccount() throws InterruptedException
{
    Random rand = new Random();
    Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user
    System.out.println("----------------Welcome to Account Creation Portal-------------------");
    //accountNumberGenerator++; //Incrementing the account number generator var
    accountNumber=rand.nextInt(1000);; //assigning the account number
    System.out.println("Enter Your Name(Without Space Between Name) : ");
    AccountHolderName=scan.next();
    System.out.println("Enter New Password : ");                //27-06-2018
    password=scan.next();                                       //27-06-2018
    System.out.println("Enter Your Account Type Savings/Current");
    AccountType=scan.next();

   /* if(AccountType == "Savings"){
        AccTypeNumVal=1;
    }
    else if(AccountType == "Current"){
        AccTypeNumVal=2;
    }*/

bal:System.out.println("Enter your starting balance : ");
    accountBalance=scan.nextLong();
    if(accountBalance<5000){
        System.out.println("Oops!!! Your Account balance should be minimum 5000 or more.\nYou need to fill the form again.");
        System.exit(0);
    }

    System.out.println("Account Created Successfully.\nYour Account Number is: "+accountNumber+" Please Note it Down.");
    System.out.println("------------------------------------------------------------");
    //Delay code below
    Thread.sleep(5000);
    System.out.flush();
}

public void DisplayAccount() throws InterruptedException
{
    System.out.println("Displaying Account Information for Account Number : "+accountNumber);
    System.out.println("------------------------------------------------------------");
    System.out.println("Account Number  : "+accountNumber);
    System.out.println("Account Name    : "+AccountHolderName);
    System.out.println("Account Type    : "+AccountType);
    System.out.println("Account balance : "+accountBalance);
    System.out.println("Your Password   : _Hidden_"); //27-06-2018
    System.out.println("------------------------------------------------------------");
    Thread.sleep(5000);
    System.out.flush();
}

public void DepositAmount() throws InterruptedException
{
    Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user
    long depositAmt;
    System.out.println("---------------Welcome to Deposit Portal----------------");
    System.out.println("You are Depositing amount for Account Number: "+accountNumber);
    System.out.println("\nEnter the Amount to Deposit : ");
    depositAmt=scan.nextLong();
    accountBalance=accountBalance+depositAmt;
    System.out.println("Amount Deposited Successfully.. \nUpdated Balance: "+accountBalance);
    System.out.println("------------------------------------------------------------");
    Thread.sleep(5000);
    System.out.flush();
}


public void WithdrawAmount() throws InterruptedException
{
    Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user
    long withdrawAmt;
    System.out.println("---------------Welcome to Deposit Portal----------------");
    System.out.println("You are Withdrawing amount for Account Number: "+accountNumber);
    System.out.println("\nEnter the Amount to Withdraw : ");
    withdrawAmt=scan.nextLong();
    accountBalance=accountBalance-withdrawAmt;
    System.out.println("Amount Withdrawn Successfully.. \nUpdated Balance: "+accountBalance);
    System.out.println("------------------------------------------------------------");
    Thread.sleep(5000);
    System.out.flush();
}

public void login() throws InterruptedException
{
    int ch=0;
    Scanner scan = new Scanner(System.in);
    long accNum=0;
    String passWd="0";
    System.out.println("Enter Account Number : ");
    accNum=scan.nextLong();
    System.out.println("Enter Your Password  : ");
    passWd=scan.next();           
    if (accNum==accountNumber && passWd==password) {
        System.out.println("Logged In Successfully with account number: "+accountNumber+"\n-------------------------------------");   
        System.out.println("Choose Option Number From Below Menu");
        System.out.println("1.Deposit Amount\n2.Withdraw Amount\n3.Display Account Info\n4.Close Account\n5.Exit");
        switch(ch)
        {
            case 1: DepositAmount();
                    break;
            case 2: WithdrawAmount();
                    break;
            case 3: DisplayAccount();
                    break;
            case 4: System.out.println("You cannot close your account. Feature Coming Soon...");
                    break;
            case 5: System.exit(0);
                    break;
        }
    } 
    else if(accNum!=accountNumber && passWd!=password) {
        System.out.println("You have Entered Incorrect Account Number or Password. Please Check Again.");
        Thread.sleep(5000);
        System.out.flush();
        System.exit(0);
    }
    else{
        System.out.println("Unknown Error Occured. Try Agian Later");
        Thread.sleep(5000);
        System.out.flush();
        System.exit(0);
    }
}


EBankSolutions()
{
    accountNumber=0000;
    AccountHolderName="UNDEFINED";
    AccountType="UNDEFINED";
    accountBalance=0000;
    accountNumberGenerator=0000;
    AccTypeNumVal=9;
}

public static void main(String[] args) throws InterruptedException {
    Scanner scan = new Scanner(System.in); // Scanner variable for accepting value from user
    EBankSolutions a1 = new EBankSolutions();
    int ch;
    int i=0;
    System.out.println("Welcome to Bank E Portal\n");
   while(i!=5)
   {
    System.out.println("Select any Choice Number From below menu...");
    System.out.println("1. Create Account\n2. Login\n3. Exit Portal");
    System.out.print("Enter Your Choice Code 1-4: ");
    ch=scan.nextInt();
    switch(ch)
    {
        case 1: a1.createAccount();
                break;

        case 2: a1.login();
                break; 

        case 3: System.exit(0);
                break;

    }

   }
}

}

Batch file check for multiple criteria for ipconfig | find /i statement

I've the following batch file to check the IP range the computer is in to decide whether or not the ABC.exe needs to be launched.

This works fine and since the first part of all 3 office locations share the same numbers at the beginning of their IP ranges up till the first number of the third octet (10.41.1) I'm currently just check for that.

@ECHO OFF
SET OFFICE_ALL=10.41.1
REM SET OFFICE_1=10.41.168.
REM SET OFFICE_2=10.41.162.
REM SET OFFICE_3=10.41.172.

REM SET VPN_CONNECTION=10.36.

ipconfig | find /i " %OFFICE_ALL%" >nul 2>nul && ( 
  start C:\ABC-tool\ABC.exe 
) || (
  exit
) 

That all said, we're going to move to a new location and the network colleagues told me that the IP range for the new office will become 10.44.121.x.

I've tried to adjust my script like this:

@ECHO OFF
SET OFFICE_MOST=10.41.1
REM SET OFFICE_1=10.41.168.
REM SET OFFICE_3=10.41.172.

SET OFFICE_2=10.44.121.

REM SET VPN_CONNECTION=10.36.

ipconfig | find /i " %OFFICE_MOST%" >nul 2>nul && ( 
  start C:\ABC-tool\ABC.exe 
) || ipconfig | find /i " %OFFICE_2%" >nul 2>nul && ( 
  start C:\ABC-tool\ABC.exe 
) || (
  exit
) 

But somehow that doesn't work... My understanding of the || is that the code after it only gets executed when the code prior to it wasn't successful, so it basically acts like an if-else construction. But apparently there is more to it and I can't figure it out. Where and why do I go wrong in my adjusted code?

Returning a list if certain parameters are met

I was looking for some help on returning specific account entries if certain values on their row was below 5% in a different worksheet.

For example, if Account A was -2% in column 1 and Account B was -10% in column 1, I would want only Account B and its corresponding -10% to be returned.

R: Function stops after internal IF statement

I wrote a function to do some calculations with frequencies (of values in the dataframe) and put them in a new column. Some calculations cannot be perform if the value is NA, so I changed them to 0. Subsequently, because a value cannot be divided by 0, I want the outcome to be the first frequency.

Now, the function stops after the IF-statement inside the function. Can you guys see what is wrong with it, without the data?

B <- function(frame1, frame2, col){
    Bframe <- merge(frame1, frame2, by = column, all = TRUE)
    Bframe$freq.x[is.na(Bframe$freq.x)] <- 0 
    Bframe$freq.y[is.na(Bframe$freq.y)] <- 0 
    if (Bframe$freq.y == 0) { 
      Bframe$result <- Bframe$freq.x
    }
    Bframe$result <- Bframe["freq.x"] - Bframe["freq.y"]
    Bframe$percentage <- (Bframe["result"]/Bframe["freq.y])*100
    Bframe$percABS <- abs(Bframe$percentage)
    return(Bframe)
}

So, the function works up to Bframe$result. Is something in the structure wrong?

I also got an error: Warning message: In if (Bframe$freq.y == 0) {: the condition has length > 1 and only the first element will used.

If you do need some input data, please tell me.

if statement evaluates as true but doesn't go into the code

i have this code in android project

for (int j = 0; j < chosenShoppingList.size(); j++) {
        if (_product.getProductID() - chosenShoppingList.get(j).getProductID() == 0) {
            isInList = true;
            break;
        }
    }

i see in debug mode that on one pass it evaluates as true but it just skip the code

when i try this

for (ShoppingListItem item: chosenShoppingList) {
        if (item.getProductID() == _product.getProductID()) {
            isInList = true;
            break;
        }
    }

all is good, i just want to understand what is the problem there

Protractor: Else statement isn't working as expected

I'm trying to click on a link if it exists, if not it should add that corresponding link and then click on the same.

In below If loop, 'Else' condition is not getting executed if first condition is not satisfied. The same is working if its placed outside IF loop.

I'm confused.

Could anyone help me out in resolving this please ?

var ConfigLink = element.all(by.partialLinkText('Provide Configuration')).get(0);

        ConfigLink.isDisplayed().then(function(result) {
        if (result) {
                ConfigLink.click();
        } 

        else {
                element.all(by.css('input[name="checks"]')).get(0).click();
        }

        });

If the initial If condition fails , I want the script to execute the else part, but this is not working.

kindly suggest how this can be resolved Thank you

Excel - search for missing values and return these values based on 3 columns - MATCH/INDEX/IF combo?

This gets a bit too expert for me, hopefully one of you can help me!

See the image for what I am trying to achieve. The red text shows what I want. List3 contains all the possible values for List1. List2 displays the currently active values for List1, and I want to return the missing values based on List3.

enter image description here

I'm guessing I'm looking at a MATCH/INDEX/IF function but I cannot figure this one out. Anyone out there willing to give me a hand? <3 Thanks a bunch!

why blank input print if statement in python

s1 = input("enter 1st string: ")
s2 = input("enter 2nd string: ")

if s2 in s1:
    print("found")
else:
    print("not found")

in the above program if i give "anything" input to s1 and give blank input to s2 it output it print if statement. I want to ask why it is happing?

if else statement in the controller not responding in Laravel

am trying to prevent a logged in user from accessing some passages exception the user has his information in the NextofKin table by using this method in my controller

public function checkValidTenant($tenant_id){
    $check = NextOfKin::where('tenant_id', '=', $tenant_id)->findOrFail('tenant_id');
    return $check;
}

While in the method that will display such page, I add the following code for restriction

if($this->checkValidTenant(\Auth::user()->id)){
        $rents = RentDue::where('tenant_id', '=', \Auth::user()->id)->get();
        return view('/tenant/rent', compact('rents'));
    }else{
        return redirect()->route('tenant/profile');
    } 

I also tried it like this

if($this->checkValidTenant(\Auth::user()->id) === true){
        $rents = RentDue::where('tenant_id', '=', \Auth::user()->id)->get();
        return view('/tenant/rent', compact('rents'));
    }else{
        return redirect()->route('tenant/profile');
    }

Here is the route

 Route::get('rent', 'TenantController@rent');

The problem is when I try accessing the page with a logged user that satisfy the condition, it will throw the following error

Sorry, the page you are looking for could not be found. 

But I noticed that this page gets displayed only when I remove this restriction. How can I solve this issue?

Java: Trying to get the value of an HTML element

I am trying to extract the value of an HTML table element from a website and compare it to a user input value but it seems that my if-else loop is not being recognized when I run the program. It works with no errors but I am not getting an output from Eclipse, I'm new to Selenium Java and still learning.

See my code below:

        String inputString = basePrem;

     try {

    //Print to console the value of Base Prem
     WebElement table = driver.findElement(By.xpath(".//td[text()='Base Premium']/following-sibling::*"));
     List<WebElement> allrows = table.findElements(By.tagName("tr"));
     List<WebElement> allcols = table.findElements(By.tagName("td"));   

        for(WebElement row: allrows){
            List<WebElement> Cells = row.findElements(By.tagName("td"));
            for(WebElement Cell:Cells){
                if (Cell.getText().contains(basePrem))
                {
                    System.out.print("Base Premium = "+ basePrem + "   ");
                }
                else if (!Cell.getText().contains(basePrem))
                {
                    System.out.print("Base Premium = " + basePrem + " ");
                    break;
                }
             }
          }

        }
   catch (Exception e) {
        errorMessage = "Value discrepancy";
        System.out.println(errorMessage + " - " + e.getMessage());
        driver.close();
    }
}

Also, inputString is where I input the value I use for comparison (I use a separate excel file for testing)

Since the control is not going inside my if loop, I probably have some logical error?

Perl multiple conditions in IF

This is my code

my @usage = `df -hT | grep -e CC -e usr`;
foreach (@usage) {
    if ($_ =~ m/([0-9]{0,3})% \/(.*)/) {
        print "$1 - $2\n";
        if ( ($2 == "CC" && $1 >= 80) || ($2 == "usr" && $1 >= 90) ) {
            print "/$2 parition is at $1% utilization\n";
        }
    }
}

It is a simple script to check if a partitions usage. The problem is in the IF condition.

if ( ($2 == "CC" && $1 >= 80) || ($2 == "usr" && $1 >= 90)

Should translate to IF (partition is CC and if use is more than 80% ) OR (IF partition is usr and its use is more than 90%) then output.

The my CC partition is at 83% and my usr is at 85%. Therefore I should only see

/CC partition is at 83%

But I get

83 - usr
/usr parition is at 85% utilization
83 - CC
/CC parition is at 83% utilization

How to simplify this test if variable is "something"?

In node I want to test whether the variable i give to a function is "something". With that I mean not a null value or an empy array or empty object. So I wrote the following, which works as expected:

function f(v) {
    if (v === null) {
        return false;
    }
    if (v.constructor === Array) {
        if (v.length) {
            return true;
        } else {
            return false;
        }
    }
    if (v.constructor === Object) {
        if (Object.keys(v).length) {
            return true;
        } else {
            return false;
        }
    }
}

f(null);  // false
f([]);  // false
f({}); // false
f([1]); // true
f({a: 1}); // true

This just seems horribly verbose. I presume there's an easier/simpler way of doing this. This is an option, but less readable and I think still too verbose:

function f(v) {
    if (v === null) {
        return false;
    }
    if (v.constructor === Array) {
        return !!v.length;
    }
    if (v.constructor === Object) {
        return !!Object.keys(v).length;
    }
}

I would expect it to be possible to reduce this to a one liner. Any idea how I would be able to do that?

C# IF that checks wether a textbox input is greater than 0 and also checks if it's an integer(Numeric)

I made a scoreboard where the user inputs the max number of points allowed in a textBox1. I have two buttons. The left one increases the value on the left side of a label and the right one increases the value on the right side of the label. Once one side reaches the maximum number of points I declare the winner using a MessageBox.

I want to know how to check if the user didn't input an integer in the textbox. I already made te condition for it to be greater than 0.

This is what I have: SCOREBOARD IMAGE

 public void winner()
    {
        int max = Convert.ToInt32(textBox1.Text);

        if (max <= 0 || //this is where i want to check if its an integer)
        {
            MessageBox.Show("Press RESET and use a value greater than 0");
            btn_left.Enabled = false;
            btn_right.Enabled = false;
            textBox1.ResetText();
        }
        else if (left == max)
        {
            MessageBox.Show("Winner: Left Player");
            textBox1.Enabled = false;
            btn_left.Enabled = false;
            btn_right.Enabled = false;
        }
        else if (right == max)
        {
            MessageBox.Show("Winner: Right Player");
            textBox1.Enabled = false;
            btn_left.Enabled = false;
            btn_right.Enabled = false;
        }
    }
   private void btn_left_Click(object sender, EventArgs e)
    {
        left = left + 1;
        lbl_score.Text = left.ToString() + " - " + right.ToString();
        winner();
    }

    private void btn_right_Click(object sender, EventArgs e)
    {
        right = right + 1;
        lbl_score.Text = left.ToString() + " - " + right.ToString();
        winner();
    }

    private void btn_reset_Click(object sender, EventArgs e)
    {
        textBox1.Enabled = true;
        textBox1.Text = "0";
        btn_left.Enabled = true;
        btn_left.Enabled = true;
        left = 0;
        right = 0;
        lbl_score.Text = left.ToString() + " - " + right.ToString();
    }

mardi 26 juin 2018

Extract Rows of Data that meets multiple criteria then get Percentile of the values

I have a raw data that contains the following structure

enter image description here

There are essentially two things I want to do in a formula: 1) Extract rows that contains Route=2 (cell G1), Direction=North (cell G2, Segment=14_15 (cell G3) 2) Get the 0.5 percentile of the values in those extracted rows.

Based on that logic I have written:

=PERCENTILE.INC(IF(AND(CT_Query!$A:$A=G1, CT_Query!$B:$B=G2, $C:$C=G3), $E:$E), 0.5)

After I pressed CSE, I got value 0.

Can anyone help tell me what went wrong?

Thanks a lot in advance for your help!

Get rid of if statement

In code I come to situation like this:

if (a && b || c && d || e && f || g && h){
    // do something
}

Like this:

if len(env.workers) == 0 && env.minQueue.Len() == 0 || len(env.workers) == len(env.daemonList) && env.minQueue.Len() == 0 || len(env.workers) > 0 && len(env.workers) == len(env.daemonList) {
        env.shouldStop = true
        return nil
    }

But it's hard to debug and find errors. Is there any way to use more friendly constructuion to replace such statement.

Python: ValueError with zip, tuple, enumerate, and if condition

The second line in the following code gives ValueError: not enough values to unpack (expected 2, got 0), however there is no error if I remove if condition from it.

xIn,yIn=zip(*[(xSrcList[i]-2,ySrcList[i]*0.1) for i in range(len(xSrcList))])

xOut,xOuti=zip(*[(x,i) for i,(x,y) in enumerate(zip(xIn,yIn)) if x<5 and y>3])

Please help me to understand this error and fix this line of code. Thanks in advance.

Variable declaration inside 'if' statement

My question is potentially embarrassing. I'd consult google if I knew what question to ask specifically, but alas, I'm a code newbie and as such am not familiar with the jargon...

I'm following a written tutorial @https://javascript.info. I'm on the lesson about conditional operators and if statements, having trouble wrapping my head around the behaviour of one of the tasks (http://javascript.info/ifelse#tasks), specifically task #4. "Check the login".

Here's the code:

let userLogin = prompt("Who's there?", "");

if (userLogin == 'Admin') {

  let pass = prompt("Password?", ""); // *******    

  if (pass == 'TheMaster') {
    alert('Welcome!');
  } else if (!pass) {
    alert("Canceled.");
  } else {
    alert('I do not know you');
  }

} else if (!userLogin) {
  alert("Canceled");
} else {
  alert("I don't know you")
}

My question revolves around the (****) line. The code doesn't work properly if that line isn't nested in the 'if', which threw me way off ( had it as a "global" variable to begin with, had to check the solution because I couldnt find the bug ).

I ask of you, please, clarify why that is so. :(

Macro to loop through all worksheets except the first two and copy a cell and range into another workbook

I have a master workbook that I have that already looks through all the files in a folder. However, one of the tabs needs to look through all the tabs in a different selected workbook "Data". The workbook has roughly 30 worksheets, and I need to loop through each worksheet except "Investments" and "Funds". If it makes it easier these are the first two tabs in the workbook. I then need to copy cell F9 in each worksheet, paste it into a different workbook "Master" cell "C4", go back to the same worksheet in the "data" workbook and copy range "C16:C136" and paste that into cell "E4" of the "master" workbook. Then it would need to loop to the next worksheet in the "data" workbook and continue the loop. For each new worksheet, I need it to paste one row lower in the "master" file. i.e. the second worksheet would paste in "C5" and "E5".

If it makes it easier I can split this up into two macros. And Just paste all the data from the worksheets into a new blank sheet in the data work book and then I can have another one to copy all of that over into the "master" workbook once done.

Thanks in Advance

pxe rc.local linux Stretch script not executed

I need to run a script via a linux stretch pxe. The script that is run in the rc.local that runs an ex.sh script does not run directly. I have the following message

"expected unary operator"

. It is a test (if entry = yes ...) following a read.The command

journalctl

shows that the rc.local is well executed and the script .sh too. In fact the script passes the entry to the keyboard and gives the login! Of course I tried:

- put == instead of =,
- put the rc.local via systemclt and systemd ...

  • ... In Debian 6 and 7 it's ok not in 9! An idea ?

Want to get maximum values from output and apply them to equation

Input code is:

# Input data:
S = pd.S = 2000 # Saturation flow
L = pd.L = 5 # Lost time
eb = pd.eb = 1000 
wb = pd.wb = 600
sb = pd.sb = 400
nb = pd.nb = 500

# a) C_min = Minimum cycle length calculation
Y_eb = pd.Y_eb = eb / S
Y_wb = pd.Y_wb = wb / S
Y_sb = pd.Y_sb = sb / S
Y_nb = pd.Y_nb = nb / S
Y_eb_wb_sb_nb = [Y_eb,Y_wb,Y_sb,Y_nb]
Y_eb_wb_sb_nb

Output:

[0.5, 0.3, 0.2, 0.25]

Then

if Y_eb > Y_wb:
print(C_min = L / 1 - (Y_eb + Y_wb))

I want to:

Get maximum values from (Y_eb;Y_wb) and (Y_sb;Y_nb) and apply these values to formula:

C_min = L / (1- [max of (Y_eb;Y_wb)] + [max of (Y_sb;Y_nb)])

Use "if" function to identify specific hours

I have an excel table (Attached picture)enter image description here . I want to find which cells (rows) contain specific hours. To do so I used the if function:

=IF(B2=HOUR("12:00:00");"xx";"yes")

The outcome was not correct. As you can see the outcome was "yes" corresponding to false.. What is the problem?

In addition, I tried to embed the "and" function, in order to select multiple hours, but the excel prompt error message. The formula I tried in cell B2 is:

Code: =IF(B2=HOUR(AND("12:00:00";"3:00:00");"xx";"yes"))

error message: contain many conditions

ksh if loop vs [[ ]] && { cmd1 ; } || { cmd2 ; }

I am working on a shell script and following syntax works fine:

if [[ 1 -eq 1 ]] ; then
   [[ 2 -eq 1 ]]
else
   echo hi
fi

Debug run : + [[ 1 -eq 1 ]] + [[ 2 -eq 1 ]]

If i shrink the statement it jumps to the else condition:

**[[ 1 -eq 1 ]] && { [[ 2 -eq 1 ]] ; } || echo hi**

Debug run:

+ [[ 1 -eq 1 ]]
+ [[ 2 -eq 1 ]]
+ echo hi
hi

any ideas what is missing?

Thanks much. Sam

Postgres | IF statement with OR conditional

I have a stored procedure which is used to validate an incoming variable. If the variable is not 'maker' or 'member', then it should throw an error. If the variable is of the two above mentioned, it should continue normal processing.

The current issue with the below code is that it always returns false, therefore always throwing an error, no mater if the variable is of 'maker', 'member', or something else.

Any ideas on where I may be looking at my logic structure wrongly?

CREATE OR REPLACE FUNCTION validate_creator_type (
  "creator_type" VARCHAR(25)         -- $1
) RETURNS VOID AS $$
DECLARE
  _maker VARCHAR(25) := 'maker';
  _member VARCHAR(25) := 'member';
BEGIN

  -- Validate the creator type is allowed
  IF ($1 <> _maker) OR ($1 <> _member) THEN
    RAISE EXCEPTION 'Invalid creator type ---> %', $1
      USING HINT = 'The creator type can only be member or maker';
  END IF;

END $$
SECURITY DEFINER
LANGUAGE plpgsql;

Three logical operators in R

I would like to check three logical operators in R in the same line. That is I want Y1 to become 1 if x1 or x3 are smaller than 0.05 or x2 is smaller than 0.1

if (x1 <0.05 | x2 < 0.1 | x3 <0.05) {  
    Y1 <- 1 
  } 

However, R gives me the following error message:

## Warning in if (x1 < 0.05 | x2 < 0.1 | x3 < 0.05) {: the condition has length > 1 and only the first element will be used

Why does R give me an error message? And if it is a problem how can I solve this without using two if-statements?

How to run SELECT queries in PL/pgSQL IF statements

I am trying to run SELECT queries in PL/pgSQL IF statements using the code below:

DO
$do$
DECLARE
    query_type   real;
    arr real[] := array[1];
BEGIN
    IF query_type = 1 THEN
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster"
        WHERE ("Westminster".intersects = false AND "Westminster".area <= 100);
    ELSE IF query_type = 0 THEN 
        RETURN QUERY
        SELECT "Westminster".*
        FROM "Westminster";
    END IF;
END
$do$

However I get the following error, ERROR: cannot use RETURN QUERY in a non-SETOF function.

Does anyone know how I can get the above code to work? Thank you.

Cesar code function, two "check" if's seem not to work

I was making a function which chenges textto cesar code, i wanted to make it in this way, that if after adding value to ASCII, it would exceed 122 or 90 then it checks the differance and adds to either 64 or 96

Those ifs seem not to work, any idea why? Here is all code necessary

    std::string CesarCode(std::string begin, int howmanychar, bool encrypt_decrypt)
{
    char cSpace = ' ';
    std::vector<char> vecLett(0);
    for (auto y : begin)
    {
        vecLett.push_back(y);
    }

    std::vector<int> vecCharSwapToInt;
    int iTemp;
    for (auto x : vecLett)
    {
        iTemp = (int)x;
        vecCharSwapToInt.push_back(x);
    }
    std::vector<char> vecIntSwapToChar;
    char cTemp = ' ';
    int iCheck;
    for (char v : vecCharSwapToInt)
    {
        if (v == cSpace)
        {
            vecIntSwapToChar.push_back(v);
        }
        else if(v != cSpace)
        {
            cTemp = (int)v + howmanychar;
            if (((int)v + howmanychar) > 90)
            {
                iCheck = (int)cTemp - 90;
                (int)cTemp == 64 + iCheck;
            }
            else if (((int)v + howmanychar) > 122)
            {
                iCheck = (int)cTemp - 122;
                (int)cTemp == 96 + iCheck;
            }
            cTemp = (char)cTemp;
            vecIntSwapToChar.push_back(cTemp);
        }
    }
    std::string sComplete = "";
    for (auto s : vecIntSwapToChar)
    {
        sComplete += s;
    }

    return sComplete;
}

Recursion to print the sum of first ten numbers using a single like if else in Python

def ad(a): 
    return a+ad(a+1) if a<10 else return a ad(1)
ad(1)

Returns an error that tells invalid syntax any thoughts?

Preferred Style for IF ELSE Statements Involving Return

I am curious what is typically better, in terms of readability and effeciency:

Option 1: Least indentation but slightly less clear flow

if (foo) {
   // do very little stuff
} else {
   // do other stuff
   return
}
// do stuff given foo must equal true to have reached here
return

OR

Option 2: More indentation but clearer flow

if (foo) {
    // do very little stuff
    // do stuff given foo must equal true to have reached here
    return
} else {
    // do other stuff
    // return
} 

I understand this question is quite broad, and may even have a different answer depending on enviorment, language etc. but I curious if there is any difference typically?

lundi 25 juin 2018

VBA For Loop Where Each Answer must = True

I have a VBA macro I'm working on that has several loops running.

Where I'm stuck, however, is that I want the macro to go through all m's and if all are True, then move on to the next set of code. If any one is false, then I want it to go to the next For loop within which this is embedded.

         For m = 2 To 29
            If Worksheets("Current Content Analysis").Cells(contentrownum, contentcolnum) = False And _
            (Worksheets("Keyword Categorization").Cells(keywordrownum, m) = Worksheets("Product Categorization").Cells(productrownum, (m + 1)) Or _
            Worksheets("Keyword Categorization").Cells(keywordrownum, m) = "All") Then Next m

Above is the specific piece of code that I want to identify whether, for each m, the conditions mentioned are False. If any are False, then it should move on to the next j in the outer loop.

Below is the full loop code if needed.

Full Code:

'outer loops through each ASIN (i)
 For Each i In Worksheets("Background Search Term Analysis").Range("B5", Worksheets("Background Search Term Analysis").Cells(LastRow, 2)).Cells
    contentrownum = Application.Match(i, Worksheets("Current Content Analysis").Range("B1", Worksheets("Current Content Analysis").Cells(LastRow, 2)).Cells, 0)
    productrownum = Application.Match(i, Worksheets("Product Categorization").Range("A1", Worksheets("Product Categorization").Cells(LastRow, 1)).Cells, 0)

    'inner loops through each keyword (j)
    For Each j In Worksheets("Current Content Analysis").Range("M2", Worksheets("Current Content Analysis").Cells(2, LastColumn)).Cells
        contentcolnum = Application.Match(j, Worksheets("Current Content Analysis").Range("A2", Worksheets("Current Content Analysis").Cells(2, LastColumn)).Cells, 0)
        keywordrownum = Application.Match(j, Worksheets("Keyword Categorization").Range("A1", Worksheets("Keyword Categorization").Cells(LastKeywordRow, 1)).Cells, 0)

        'prints the current values for each variable as the loop progresses
        'end values should match printed last row and column; helps identify where breaks occur
        Worksheets("Current Content Analysis").Cells(1, 4).Value = contentrownum
        Worksheets("Current Content Analysis").Cells(1, 5).Value = productrownum
        Worksheets("Current Content Analysis").Cells(1, 6).Value = contentcolnum
        Worksheets("Current Content Analysis").Cells(1, 7).Value = keywordrownum

       'if this product doesn't currently have the keyword (j) in it and the keyword tags match the product tags then
       For m = 2 To 29
        If Worksheets("Current Content Analysis").Cells(contentrownum, contentcolnum) = False And _
        (Worksheets("Keyword Categorization").Cells(keywordrownum, m) = Worksheets("Product Categorization").Cells(productrownum, (m + 1)) Or _
        Worksheets("Keyword Categorization").Cells(keywordrownum, m) = "All") Then Next m 

        'if all of m loop are True, then move on to this step; if any m is False, then move on to next j
        WrdArray() = Split(j)
            For k = LBound(WrdArray) To UBound(WrdArray)
                If InStr(LCase(result_no_dup), LCase(WrdArray(k))) = 0 _
                And InStr(LCase(Worksheets("Current Content Analysis").Cells(contentrownum, 12).Value), LCase(WrdArray(k))) = 0 Then
                    result_no_dup_compact = result_no_dup_compact & WrdArray(k)
                    If Len(result_no_dup_compact) > Worksheets("Instructions").Range("B4").Value Then Exit For
                    result_no_dup = result_no_dup & " " & WrdArray(k)
                End If
            Next k
            result_no_spaces = result & j
            If Len(result_no_spaces) > Worksheets("Instructions").Range("B4").Value Then Exit For
            'if true and character limit not exceeded, add the keyword (j) to our result concatentation
            result = result & " " & j
            'if true and character limit not exceeded, add the keyword (j) to our results concatenation with commas
            result_commas = result_commas & ", " & j
        End If
    Next j

   'once i go through all of my keywords, set ASIN background search term cell value equal to result
   Worksheets("Background Search Term Analysis").Cells(contentrownum, 4).Value = Right(result, Len(result) - 1)
   Worksheets("Background Search Term Analysis").Cells(contentrownum, 5).Value = Right(result_commas, Len(result_commas) - 2)
   Worksheets("Background Search Term Analysis").Cells(contentrownum, 6).Value = Right(result_no_dup, Len(result_no_dup) - 1)
   'reset results to empty for next ASIN (i)
   result = ""
   result_no_spaces = ""
   result_commas = ""
   result_no_dup = ""
   result_no_dup_compact = ""
Next i

Thank you for the help!

Instead of using if's, would it better to write an 'equation' that gives you the results you want? (in cases where it makes sense)

Instead of:

float dotProduct = Vector3.Dot(dir, transform.right);
int front = 0;
int back = 0;

if (dotProduct > 0)
{
    // right
    front = 1;
    back = -1;
}
else if (dotProduct < 0)
{
    // left
    front = -1;
    back = 1;
}

Rotate(front, back, angle);

Having something like

float dotProduct = Vector3.Dot(dir, transform.right);
int front = Mathf.Abs(dotProduct) ...;
int back = Mathf.Abs(dotProduct) ...;
Rotate(front, back, angle);

Errh, I know int front = Mathf.Abs(dotProduct) ...; wont give me either 1 or -1, but I think you understand what I'm thinking, instead of using if's, I'd be "funneling" through an equation that would give me either 1 or -1.

Why can't the compiler warn against this programming error?

If I write the following code:

int a = 5;
if (a == 1 || a == 1) {
   // do something
}

Why can't the compiler point out that the second part of the if statement is unnecessary, or warn that the programmer has likely made a mistake?

Data restructuring help: How to identify maximum number of days between 'events' and copy that value

I cannot find a thread which answers this specific question, so help would be appreciated. I have a dataset that looks like this, where the variable 'EventCount' counts the number of days between events occurring for each person in the dataset (if EventCount=0, then event has occurred).

Day = c(1:8,1:8)
EventCount = c(NA,NA,0,1,2,0,1,0,0,1,2,3,0,1,2,0)
Person = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)
dat <- data.frame(Person,Day,EventCount);dat

I am trying to restructure the dataset so that it takes the maximum value BETWEEN events occurring for each person, and copies or fills that value. I want it to look like this:

NewEvent = c(NA,NA,0,2,2,0,1,0,0,3,3,3,0,2,2,0)
dat2 <- dat <- data.frame(Person,Day,NewEvent);dat2

Thanks in advance!

If else ladder not working in R

I have this in my dataframe after reading and rearranging multiple csv files. Basically I want an if else ladder to refer to the ID column and if it matches a number from the list of concatenates then place a word in a new "group" column

    # of int.   int.     not.int.  ID
1      50      218.41     372.16    1
3      33      134.94     158.17    3

I then made these concatenates to refer to.

veh = as.character(c('1', '5'))
thc1 = as.character(c('2', '6'))
thc2 = as.character(c('3', '7'))
thc3 = as.character(c('4', '8')) 

Then I made an if else ladder to list the corresponding values.

social.dat$group =  if (social.dat$ID == veh) {
     social.dat$group == "veh"
     } else if (social.dat$group == thc1) {
     social.dat$group == "thc1"
     } else if (social.dat$group == thc2) {
     social.dat$group == "thc2"
     } else {
     social.dat$group == "thc3"
     }

However, I then get this warning message.

Warning message:
In if (social.dat$ID == veh) { :
the condition has length > 1 and only the first element will be used

I have looked up this warning message in multiple different variations and have not found anything that really helped. Any help for this would be much appreciated or and alternate options would be good as well. I apologize in advance if there was a solution on stack already if I missed it.

Booleans, if-else statements, and scanner?

I am trying to make the "yes" (or "y" in this case) response to a question a true statement. Any other response to the question below is known to be a false statement.

System.out.print("Do you smoke?(y/n): ");
        boolean smoker = console.nextBoolean();
        if (smoker.equalsIgnoreCase("y")) {
            smoker = true;
        } else {
            smoker = false;
        }

I get the error

HealthPlan.java:32: error: boolean cannot be dereferenced
        if (smoker.equalsIgnoreCase("y")) {
              ^

Does anyone know how I can fix this? I have searched this online and I am not so sure.

Conditional Formatting of grouped Data in R

UPRN    Start.Date  End.Date  Disability
1       2006-12-20 17-NOV-17         Y
1       2006-12-20 17-NOV-17         N
2       1991-12-06                   N
2       1991-12-06                   N
3       1991-04-29 2015-04-21        N
3       2015-04-22                   Y
4       2005-02-15                   Y
4       2005-02-15                   N

I have a dataset that looks something like the above (but much bigger). I would like to create a new column called Any_Disability.

The way I want to do this is to group by UPRN, Start.Date and End.Date and if any row in that group has a disability then both rows would have a "Y" for Any_Disability.

What I've tried already is:

test3<-all_data%>%
  group_by(UPRN, Start.Date, End.Date)%>%
  mutate(Any_Disability = ifelse(Disability=="Y", "Y","N"))

But this doesn't work as it gives the below answer:

UPRN    Start.Date  End.Date  Disability  Any_Disability
1       2006-12-20 17-NOV-17         Y          Y
1       2006-12-20 17-NOV-17         N          N
2       1991-12-06                   N          N
2       1991-12-06                   N          N
3       1991-04-29 2015-04-21        N          N
3       2015-04-22                   Y          Y
4       2005-02-15                   Y          Y
4       2005-02-15                   N          N

If statement not returning correct value in VBA

I am doing a date compare with ticket items, and if the ticket is closed it compares it to the close date. If ticket is still active it does the age to our current day. The code is skipping the if statement even if it is true. I made sure they are both strings while doing the compare. I have tried many things and can't seem to find out why. Any help would be awesome. Thanks!

Created = Rng.Column
Compare = Rng2.Column
Status = Rng3.Column
original = cells(i, Created)
Test = cells(i, Created)
Test2 = cells(i, Compare)

TestDate = CDate(Test)
TestDate2 = CDate(Test2)
cells(i, Created) = TestDate
cells(i, Compare) = TestDate2
CellStat = cells(i, Status)
Stuff = "Closed"

If CellStat = Stuff Then
    DDiff = cells(i, Compare) - cells(i, Created)
    Days = (Int(DDiff))
    ValHold = Days
    cells(i, Created) = ValHold
    cells(i, Created).Interior.ColorIndex = 3

Else
    DDiff = Now - cells(i, Created)

    Days = (Int(DDiff))
    ValHold = Days
    cells(i, Created) = ValHold

End If
i = i + 1

Loop

How can i add if statement in email code

I have this code in email, is it php?

How can i add "if statement" here?

I need only attachment.file.originalName where attachment.file.originalName like "%sheet%"



Creating IF statement with multiple conditions that WORKS

Can someone spend a little time going through a relatively easy IF statement with me with multiple conditions?

Tried everything I can to make this work - it seems pretty simple but OMG can I not get it to do anything! What's the best way? Any help is appreciated! I can send examples if need be.

Thanks, Cherry

dimanche 24 juin 2018

inserting cell comments based on multiple logical validations VBA

I have a table which has 4 columns with headers. Column A has the employee names, B has the organization names (the employees have worked in), C has the date of birth and D has the present designation. The number of columns are fixed; however, the number of rows is dynamic. Now I want the logic to check the first date of birth (and then the second one and so on) and then run this through the entire column (date of birth column) to find a match/ matches. The next step will be - wherever this finds a match, there will be additional checks for employee names and organization names. If these three values match for multiple rows, only the first data point (among all the matches) of employee name will have a cell comment "The employee has been with multiple organizations". This will be done for all the rows. Also, kindly note that the employee names and the organization names are not perfect match (there might be little discrepancies on how these names have been reported). Can someone please help me to build the code for this one? I am pretty new to VBA and this seems to be a little complex logic to build on. Also if you could have the comments for the codes, it will be easier for me to learn and change according to my dataset. Thanks a lot.

why my if statement alternates with else every time i run the function

So here i made a function from a button to upload images using ajax to show on the canvas but to specify the width and height I use the if statement. I specify if width greater than height the width = 300 and height = 200, if width less than height width = 200 and height = 300.

But i dont know how the if i click the button for first time after refresh my page the if statement is not correct or else sometime it is. And the next following click is alternately. Here my code.

      var image2 = new Image();   
      image2.src = '../img/template/'+e; 
      tmpWidht = parseInt(image2.width);
      tmpHeight = parseInt(image2.height);

      if( tmpWidht > tmpHeight ){
        var imgWidth = 300;
        var imgHeight = 200;
      }else{
        var imgWidth = 200;
        var imgHeight = 300;
      }

run the script according to logical conditions in R

In my data set, I work with groups(stratum) SKU-acnumber-year. Here little example:

df=structure(list(SKU = c(11202L, 11202L, 11202L, 11202L, 11202L, 
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L
), stuff = c(8.85947691, 9.450108704, 10.0407405, 10.0407405, 
10.63137229, 11.22200409, 11.22200409, 11.81263588, 12.40326767, 
12.40326767, 12.40326767, 12.99389947, 13.58453126, 14.17516306, 
14.76579485, 15.94705844, 17.12832203, 17.71895382, 21.26274458, 
25.98779894, 63.19760196), action = c(0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), 
    acnumber = c(137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 
    137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 137L, 
    137L, 137L, 137L), year = c(2018L, 2018L, 2018L, 2018L, 2018L, 
    2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
    2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L)), .Names = c("SKU", 
"stuff", "action", "acnumber", "year"), class = "data.frame", row.names = c(NA, 
-21L))

Very important:

The action column has only two values 0 and 1. As we can see in this example there is 3 observations by stuff of 1 category of action and 18 obs by stuff of zero category.

I need set logic condition. so, for groups which have from 1 to 4 observations by stuff of 1 category of action, then run script1.r

and for groups which have >=5 observations by stuff of 1 category of action then must be run script2.r

I would imagine it in this way, the script3.r is created, with the following content(condition), but I do not know how to correctly set these logical conditions.

# i take data from sql
dbHandle <- odbcDriverConnect("driver={SQL Server};server=;database=;trusted_connection=true")
sql <- paste0(select needed columns)
df <- sqlQuery(dbHandle, sql)



   for groups where from 1-4  observations by stuff of 1 category of action then  C:/path to/скрипт1.r
(or if  groups have from 1-4  observations by stuff of 1 category of action then  C:/path to/script1.r)
    for  groups   where >=5 observations by stuff of 1 category of action then C:/path to/script2.r
( of if groups  have >=5 observations by stuff of 1 category of action then C:/path to/script2.r)

How do I implement this? the script.3r runs by schedule, it will work according to the schedule, in order to run two scripts. I just do not want to make my Shedule for each script seaprately.