samedi 31 mars 2018

I can't get my program to print out a Leap year

The last method I was trying to get it to print out my program can't seem to get it to do it. I don't know what to do. And I'm in an online class so there is no one I could really ask. My teacher takes three days to reply.

import java.util.Scanner;

public class LeapYear {

public static void main(String[] args) {
displayInstructions();
int year = getYear();
isLeap(year);
}

public static void displayInstructions() {
    System.out.println("This program asks you to enter a year as a 4 digit number. The output will indicate whether the year you entered is a leap year.");
}

public static int getYear() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = reader.nextInt();
return year;
}

public static boolean isLeap(boolean year) {
    boolean isLeapYear = false;
    if (year % 4 == 0 && year != 100) {
        isLeap = true;

    }
    else {
        isLeap false;
    }



}
public static void displayResuls( boolean isLeap, boolean year) {
  if (isLeap)
  {
    System.out.println("Year" +year+" is a Leap Year.");
  }

  else {
  System.out.println("Year" +year+" is not a Leap Year");

  }

    }
}

Programming Novice - C - Issue with Fall-through in Menu System

I have recently begun studying C just for the fun of it and I decided to have a go at creating a menu system, but I'm having an issue with what I think is fall through.

#include <stdio.h>

int main (void)
{

int x, y, z;

start:
printf ("Menu 1 -- Please select a number.\n");
printf ("1\n");
printf ("2\n");
printf ("Enter selection: ");
scanf ("%i", &x);
getchar();

if (x == 1) {
    x_one:
    printf ("1.\n");
    printf ("Menu 2 -- Please select a number.\n");
    printf ("1\n");
    printf ("2\n");
    printf ("3 -- Go back.\n");
    printf ("Enter selection: ");
    scanf ("%i", &y);
    getchar();

    if (y == 1) {
        y_one_one:
        printf ("1-1.\n");
        printf ("Menu 3 -- Please select a number.\n");
        printf ("1\n");
        printf ("2\n");
        printf ("3 -- Go back.\n");
        printf ("Enter selection: ");
        scanf ("%i", &z);
        getchar();

        if (z == 1 || z == 2)
            printf ("You selected %i.\n", z);

        if (z == 3)
            goto x_one;

        else if (z > 1 && z < 3)
            goto y_one_one;
    }

    if (y == 2) {
        /* mostly the same as "if (y == 1)". */
    }

    if (y == 3)
        goto start;

    else {
        printf ("Please enter a valid selection.\n");
        goto x_one;
    }
}

if (x == 2) {
    /* Mostly the same as "if (x == 1)". */
}

else if (z > 1 && z < 2)
    goto start;

return 0;

}

The issue is once I have reached the third menu, the program will print out the string of the selected number, but instead of terminating itself it will either display the third menu or go back to the second menu, and it will do this regardless of what number I input.

I've only been studying C for about two weeks and I don't quite have a proper understanding on how nested if statements work, if I could please get an explanation of what's causing this unexpected behavior and how to correct it that would be greatly appreciated, thank you.

I am using GCC 5.1.0 through TDM-GCC-64 on Windows 10.

C++ if statement with ||

I have to print an error if the gender entered is not M/m/F/f/X/x but my if statement always returns true

cout << "Please enter the candidate's information "
        "(enter 'X' to exit).";
cout << endl << "gender: ";
cin.get(gender);
cin.ignore(1000,'\n');

if (gender != 'M' || gender != 'm' || gender != 'F' ||
    gender != 'f' || gender != 'X' || gender != 'x')
    {
        cout << "error";
    }

spss IF loop MISSINGS ignored in special cases

I want to compute a variable X=x1+x2+x3. x1, x2 and x3 have either the values 1 or 0. I recoded system missings to -77. There are some conditions which should be met.

1) If there is a missing value in either x1,x2 or x3, then it should be ignored if one or two of the other variables have the value 1. So the sum should be calculated although there is a missing value but only if there is at least one 1 (Eg. X = x1 + x2 + x3 = 0 + missing + 1 = 1)

2) If there is a missing value in either x1, x2 or x3, then it should not be ignored if there is no 1 at all and the sum should not be calculated. (Eg. X = x1 + x2 + x3 = 0 + missing + missing = missing).

I tried to make a loop with IF but it won't work and I just can't figure out why.

`COMPUTE X =SUM(x1, x2, x3).
IF (x1=-77 AND x2~=1 AND x3~=1) X=999. 
IF (x2=-77 AND x1~=1 AND x3~=1) X=999.
IF (x3=-77 AND x1~=1 AND x2 ~=1)X=999.  
EXECUTE.`

*These are the returned results: when x1=1, x2 = 0, x3=-77 then X=1. (That is the result I want. The problem arises when x1=-77, x2=0, x3=0 because then X=0 and not 999 as I want it to be.

I think that with the loop above I am close to the result but something is missing. Below I post some other loops I made, but neither did work and I think the one above is the closest to the right answer.

Thank you so much for your help and happy easter! Cheers desperate Ichav :)

'COMPUTE X = x1 + x2 + x3.
RECODE X (SYSMIS=-77).
IF ((X = -77 AND x1 = 1) OR (X = -77 AND x2 = 1) OR (X = -77 AND x3 = 1)) X =1.
EXECUTE.'

*Here X is always returned as -77.

Code wont ignore numbers

I am trying to write a simple code but I tried doing a for loop within a if statement but it ended up reversing the numbers and the sentence. I do not know what I am missing or what im doing wrong I commented out the part I was working to get that part to work.

The code is supposed to do this: a FUNCTION which takes in a String as a parameter and returns a Pig Latin version of that string. The program should be able to :

1) handle punctuation

2) Ignore numbers (i.e. if “500” is passed in, “500” is passed back)

3) Handle multiple sentences

  static void Main(string[] args)
    {
        Console.WriteLine("Enter the word or sentence to convert into Pig Latin");
        string sentence = Console.ReadLine();
        string pigLatin = PigLatin(sentence);
        Console.WriteLine(pigLatin);
    }
    static string PigLatin(string sentence)
    {
        string letter = sentence.ToLower();
        string firstLetter, restWord, vowels = "AEIOUaeio";
        //int numbers;
        int current;
        foreach (string word in sentence.Split())
        {
            firstLetter = sentence.Substring(0, 1);
            restWord = sentence.Substring(1, sentence.Length - 1);
            current = vowels.IndexOf(firstLetter);
            if (current == -1)
            {
                sentence = restWord + firstLetter + "ay";

            }
            //for (int numbers = 0; numbers ; numbers++)
            //{
            //   sentence += numbers;
            //}

        }
        return sentence;
    }

React: How to conditionally render?

I have three components A, B & C.

I have two flags showA & showB.

  • If ShowA and ShowB are false then render C.
  • If ShowA is true only then render A.
  • If showB is true only then render B.

How do i achieve this?

Syntax for conditions(if/else) when "views" should be set as a condition in RoR?

My navigationbar is underneath the header... I want to change the header according to the view on which the visitor is on.

What is the syntax for a condition(if/else) when views are set as condition in ruby on rails?

Something like...

<% if index.html.erb %>
  <%= image_tag("index_background.jpg", alt: "index background") %>
<% elsif about.html.erb %>
  <%= image_tag("about_background.jpg", alt: "index background") %>
<% else %>
  <%= image_tag("default_background.jpg", alt: "index background") %>
<% end %>

If you have any question don't hesitate to ask! Thanks in advance!

Python 2: If statements not working

I have 3 if statements one after the other with one extra if statement embedded in the first. The problem is that none of them work unless either the 1st one (and the embedded if statement) is removed (which allows the other two to work) or if the 2nd and 3rd ones are removed, which allows the 1st one to work. Here is the code.

            if usm1 < 350:

                if usm3 < 300:
                    turnRight()

                elif usm2 < 300:
                    turnLeft()

                else:
                    TB.MotorsOff()

            else:
                TB.SetMotors(0.6)


            if usm3 < 200:
                turnRightKinda()
            else:
                TB.SetMotors(0.6)


            if usm2 < 200:
                turnLeftKinda()
            else:
                TB.SetMotors(0.6)

This is the code for the functions:

def turnLeft():
    TB.SetMotor1(-1)
    TB.SetMotor2(1)

def turnRight():
    TB.SetMotor1(1)
    TB.SetMotor2(-1)

def turnLeftKinda():
    TB.SetMotor1(0.4)
    TB.SetMotor2(0.6)

def turnRightKinda():
    TB.SetMotor1(0.6)
    TB.SetMotor2(0.4)

Thanks.

Need help in nested if in php

I,i have this array which define each number it's color

$zero =  array(0=>"Empty",1=>"Red");
$red =   array(3=>"Red",5=>"Red",7=>"Red",9=>"Red",12=>"Red",14=>"Red",16=>"Red",21=>"Red",23=>"Red",25=>"Red",27=>"Red",30=>"Red",32=>"Red",34=>"Red",36=>"Red");
$black = array(2=>"Black",4=>"Black",6=>"Black",8=>"Black",10=>"Black",11=>"Black",13=>"Black",15=>"Black",17=>"Black",22=>"Black",24=>"Black",29=>"Black",31=>"Black",33=>"Black",35=>"Black");

$spin_numbers =array_merge($zero,$red,$black);

and I have form,which ask for number to bet,and it's start choosing random number between 0 and 36

if (isset($_POST['odd']))
{
  $random_number = mt_rand(0,36);
  if ($random_number == 1 OR $random_number == 3 OR $random_number == 5 OR $random_number == 7 OR $random_number == 9 OR $random_number == 11 OR $random_number == 13 OR $random_number == 15 OR $random_number == 17 OR $random_number == 19 OR $random_number == 21)
  {
    echo $random_number." ".$roulette_numbers[$random_number]." Occured,you won!";
  }
  else if ($random_number == 23 OR $random_number == 25 OR $random_number == 27 OR $random_number == 29 OR $random_number == 31 OR $random_number == 33 OR $random_number == 35)
  {
    echo $random_number." ".$roulette_numbers[$random_number]." Occured,you won!";
  }

  else if($random_number == 2 OR $random_number == 4 OR $random_number == 6 OR $random_number == 8 OR $random_number == 10 OR $random_number == 12 OR $random_number == 14 OR $random_number == 16 OR $random_number == 18 OR $random_number == 20 OR $random_number == 22)
    {
      "Sorry,".$random_number."Occured,your stake goes to Roulette";
    }
    else if ($random_number == 24 OR $random_number == 26 OR $random_number == 28 OR $random_number == 30 OR $random_number == 32 OR $random_number == 34 OR $random_number == 36)
    {
      "Sorry,".$random_number."Occured,your stake goes to Roulette";
    }

}

I want Odd numbers which most of them is Red,echo Win Message,and the rest numbers which is Even,echo loose Message,but it's only echo win Message,why?

purpose of multiple else/if statements? NOT single if then else statement

I just wanted to know if there is any purpose to writing else if or if this is purely written for better code readability. For instance, this code taken from the oracle java tutorials:

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

    int testscore = 76;
    char grade;

    if (testscore >= 90) {
        grade = 'A';
    } else if (testscore >= 80) {
        grade = 'B';
    } else if (testscore >= 70) {
        grade = 'C';
    } else if (testscore >= 60) {
        grade = 'D';
    } else {
        grade = 'F';
    }
    System.out.println("Grade = " + grade);
}
}

surely writing the "else if" parts with just if would do that same thing? If anyone can help explain this to me I would greatly appreciate it. Thanks

Issue with multiple if statements with different outcomes giving the same outcome everytime [duplicate]

This question already has an answer here:

this is probably a very simple answer but I am having a problem with the choice1() function in my program. I am making a text adventure game in python to help with GCSE revision and can't get past this problem. I have looked for an answer on the site but haven't found what I was looking for. I have had trouble copy and pasting the code into the site so instead i have put a link to an image of it below:

https://i.stack.imgur.com/5ZDEB.png

As you can see choice1() doesn't work properly. When i type 'Weapon' the character should break of the chair leg, when i type 'Fists' He should not and when i type something else it should say that the input is invalid and ask the question again. So in conclusion I need a way for the if, elif, else statements to have the correct outcome. Again i am quite new to python so sorry if this is a stupid question, thank you in advance!

Ending input() by "if ... is not None" using Python3.6

I'm very new to Python. I'm trying to make a todo-list (a txt file) that I can then add stuff to. I'm struggling with the correct method of making the script stop when I'm done entering things.

I've tried different ways of making while loops and if statements, but the script always either just stops or goes on forever.

I think the problem might lie with me assigning "not None" to a changing variable, but I'm not sure. This is my code:

import time
from datetime import date

todo_file = open(f"ToDos_{date.today()}", 'a')

todo_file.write(input("What do you need to do tomorrow? "))
todo_file.write("\n")

todo = input("What else? ")

if todo is not None:
    todo_file.write(todo)
    todo_file.write("\n")
else:
    pass

todo_file.close()

Any other criticisms to how I wrote this are also very welcome.

how do I handle with 180000 if statements in c?

Deal All, I'm trying to implement c program with 180000 if statements as the below. I'm on Visual Studio 2013. the problem is that build never goes to done. I know there are so many if statements. so is there any way to resolve this kind of problem?

   if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 0))  data[i*rwsize + j] =    2;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 1))  data[i*rwsize + j] =    12;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 2))  data[i*rwsize + j] =    100;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 3))  data[i*rwsize + j] =    20;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 4))  data[i*rwsize + j] =    0;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 5))  data[i*rwsize + j] =    30;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 6))  data[i*rwsize + j] =    0;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 7))  data[i*rwsize + j] =    40;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 8))  data[i*rwsize + j] =    0;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 9))  data[i*rwsize + j] =    120;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 10))  data[i*rwsize + j] =    3;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 11))  data[i*rwsize + j] =    4;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 12))  data[i*rwsize + j] =    7;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 13))  data[i*rwsize + j] =    3;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 14))  data[i*rwsize + j] =    5;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 15))  data[i*rwsize + j] =    30;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 16))  data[i*rwsize + j] =    0;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 17))  data[i*rwsize + j] =    0;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 18))  data[i*rwsize + j] =    1;
if ((  pre_data[i*rwsize + j]  == 0) && ( bdata[i*rwsize + (j)] == 19))  data[i*rwsize + j] =    0;
...

if ((  pre_data[i*rwsize + j]  == 255) && ( bdata[i*rwsize + (j)] == 255))  data[i*rwsize + j] =    25;

IF and LOOKUP formula not giving all of the correct corresponding values

I have a table on the right hand side of the spreadsheet where it looks through the columns T and Z, finding the corresponding value. For instance if Arsenal was on T5 I would want it to get the value for Z5. This formula does it for some of the values but then is giving the wrong values for others and I'm not entirely sure why? It looks like the same syntax for each. Any ideas?

=IF(C2="Arsenal",LOOKUP("Arsenal",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Liverpool",LOOKUP("Liverpool",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Man United",LOOKUP("Man  United",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Man City",LOOKUP("Man City",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Aston Villa",LOOKUP("Aston Villa",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Newcastle",LOOKUP("Newcastle",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Chelsea",LOOKUP("Chelsea",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Everton",LOOKUP("Everton",$T$2:$T$21,$Z$2:$Z$21),IF(C2="West Ham",LOOKUP("West Ham",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Portsmouth",LOOKUP("Portsmouth",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Blackburn",LOOKUP("Blackburn",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Wigan",LOOKUP("Wigan",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Middlesbrough",LOOKUP("Middlesbrough",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Birmingham",LOOKUP("Birmingham",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Sunderland",LOOKUP("Sunderland",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Reading",LOOKUP("Reading",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Fulham",LOOKUP("Fulham",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Tottenham",LOOKUP("Tottenham",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Bolton",LOOKUP("Bolton",$T$2:$T$21,$Z$2:$Z$21),IF(C2="Derby",LOOKUP("Derby",$T$2:$T$21,$Z$2:$Z$21)))))))))))))))))))))

R ifelse statement only return number

 this is house$room

enter image description here type<-c('2室1厅','2室2厅','3室2厅','1室1厅','4室2厅', '3室1厅','1室','2室','1室2厅','5室2厅','4室3厅')

enter image description here Why return number???? Please help me!!!

Filling a table with additional columns if they doesnt exist

I've the following difficult problem. I calclulated a frequency table, that Looks like this

  a=12 a=15 a=16 a=17 a=18 a=19 a=22 a=32 h=1 a=4 a=5 h=7 h=9 a=12
0  1    4   0    2    1    ..   ..   ..   ..   ..   ...
1
2
3
4

I want to extend and manipulate my table in the following way: First the table should go over a range of a=12 to a=64. So if there is a missing column, it should be added. And 2nd) I want to order the columns from 1 to 32. For the first problem I tried

if(foo$paste0("h=",12:96) == F){freq_table$paste("h=",12:96) <- 0}

but this should work only for data frames and not for tables. Also. i've no idea how to order the columns with an ascending order

vendredi 30 mars 2018

android if Statement

i have a problem with android if, this is my Code:

private String getCode = null,getIn = null,getOut = null,getBold = null;

 if (getIntent().getExtras().getString("pos_code") != null){
        getCode = getIntent().getExtras().getString("pos_code");
    }
    if (getIntent().getExtras().getString("pos_in") != null){
        getIn = getIntent().getExtras().getString("pos_in");
    }
    if (getIntent().getExtras().getString("pos_out") != null){
        getOut = getIntent().getExtras().getString("pos_out");
    }
    if (getIntent().getExtras().getString("pos_bold") != null){
        getBold = getIntent().getExtras().getString("pos_bold");
    }

if (response.body().get(i).getAcf().getPosCode().toString().contains(getCode.toString())
                            && response.body().get(i).getAcf().getPosDInside().toString().matches(getIn.toString())
                            && response.body().get(i).getAcf().getPosDOutsid().toString().matches(getOut.toString())
                            && response.body().get(i).getAcf().getPosBBold().toString().matches(getBold.toString())) {

                        list.add(new Model(Model.IMAGE_TYPE
                                , response.body().get(i).getAcf().getPosCode()
                                , response.body().get(i).getAcf().getPosDInside()
                                , response.body().get(i).getAcf().getPosDOutsid()
                                , response.body().get(i).getAcf().getPosBBold()));
                    }

and its working But i want if one or more of 4 Strings was null the IF steel Working and give the results without considering the nulled string and match others

actually i want to say that: i want to get all of data that matched or contains the EditText from user and if there was naull just NOT compare the nulled one

Fragment is not grabbing my IntentData

I have a first fragment which I send data to another fragment depending on which button they press by

mButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), AddItemsActivity1.class);
            intent.putExtra("ToButton", 1);
            ((AddItemsActivity1)getActivity()).ToNextPage(view);
        }
    });

mButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), AddItemsActivity1.class);
                intent.putExtra("ToButton", 2);
                ((AddItemsActivity1)getActivity()).ToNextPage(view);
            }
        });

The buttons are sending data to it's own fragment's activity.

Then I retrieve my Data in my other Fragment that is also in the AddItemsActivity1 activity by

int toButton = getActivity().getIntent().getIntExtra("ToButton", 0);

then depending on the value it gets it adds to a certain child in my database.

if (toButton == 1) {
                    String key = mDairyDataBase.push().getKey();
                    HashMap<String, String> dataMap = new HashMap<>();
                    dataMap.put("Name", item);
                    dataMap.put("Key", key);
                    mDairyDataBase.child(key).setValue(dataMap);
}

 else if (toButton == 2){
                String key = mFruitsDataBase.push().getKey();
                HashMap<String, String> datamap = new HashMap<>();
                datamap.put("Name", item);
                datamap.put("Key", key);
                mFruitsDataBase.child(key).setValue(datamap);
}

My problem is that it doesn't return a value so it never adds to the database. When I change the default value of toButton to 1 then it adds it to the mDairyDatabase and same goes for the other one.

Ternary Operator if else if issue

Been staring at this for days and from everything iv found it should be working but always ends up with ''. I'm checking the price change that can be positive or negative, hence the >0 <0.

 {parseInt(item.CheeseBarrelChange) > 0 ? <i className={styles.up}></i> :
 parseInt(item.CheeseBarrelChange) < 0 ? <i className={styles.down}></i>  :''} 

MySQL: SET Variable in if exists condition

I am trying to set the variables while checking the if exists condition. I have used := to set the variables, however, it for some reason it seems that when I try to set the variable in the if exists condition, it displays the result for the previous query. Following is the code snippet from the stored procedure.

if exists (select @AccountVerified := AccountVerified, @IsActive := IsActive  from tblUserLookUp where UserName = inUserName) then
        begin
            select "1: From if condition", @AccountVerified, @IsActive;

            select @AccountVerified := AccountVerified, @IsActive := IsActive  from tblUserLookUp where UserName = inUserName;
            select "2: From select condition", @AccountVerified, @IsActive;
            select @AccountVerified, @IsActive;

            if @AccountVerified = 0 then
                set outErrorCode = 3;
            elseif  @IsActive = 0 then
                set outErrorCode = 4;
            end if;
        end;
    else
        set outErrorCode = 1;
    end if;

I observed this by trying to print the values through the select statement after the if condition and after again running the select query on the table. The

2: From select condition

seems to display the actual current results However,

1: From if condition

seems to display the value from previous query.

Is there any concept of variable caching or it is that you cannot set variables in the if condition? I am also open to any other recommendation that you might have.

The only reason to do this is to save that select query on the same table as that of the if exists select query.

A loop to iterate over different data.frames

This is a little tough to explain but I will do my best. I get several datasets with different tests in different terms (Fall, Winter, Spring, Summer). The terms are loaded into the variable "term". The tests are labeled Test1, Test2, Test3, Test4, Test5. I was able to make an IF statement that takes into account these different Terms, and does some other functions I need completed. Everything works great but I need to write a looping function to iterate over the 5 different tests. I have been trying to find out how to do this but have not been able to. You do not need to pay much attention to what is in the function I am just wondering is I can iterate that function over Test1,Test2,Test3,Test4,and Test5. The current if statment is:

if(is.data.frame(Test1)){
  if(term== "Fall"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Fall", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Winter"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Winter", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Spring"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Spring", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Summer"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Summer", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }
}

I tried

L <- list(Test1,Test2,Test3,Test4,Test5)

for(i in L)
{if(is.data.frame(Test1)){
  if(term== "Fall"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Fall", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Winter"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Winter", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Spring"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Spring", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Summer"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Summer", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }
}

This did not work but I think it is close to working. Any guidance would be greatly appreciated. Again the function does not need to be paid much attention to just the ability to iterate over the 5 tests.

Thank you

Counter variable not increasing inside of if statement

I have a function that is suppose to capitalize the first letter of the next word. "this is a! Test." is the desired result.

var splitUp = ["this", "is", "a!", "test."];

I increment the variable inside the "for loop" only if the "if" statement runs.

if (punctuation.indexOf(translationString[iii]) != -1) {
  console.log(iii+ ": " +translationString[iii]);
  console.log("iii is on: " + iii);
  iii + 2;
  console.log("after increment, iii is on: " + iii);
  translationString[iii].toUpperCase();
}

I can not figure out the reason the value of "iii" is not increasing. Is there a work around or am I missing something entirely?

JSFiddle

R:How to repeat for loop from row 1 to last row in dataframe?

    N<-nrow(MedFIX)
      for(i in 1:N)
      {
          med<-MedFIX[i,]

          #These series of code does not do what I need the loop to do

          medidstrings0<-substring(med$MED_ID, 4,10) #extract digits after 
          "MED" for first medication in row
          medidstrings1<-substring(med$MED_IDj, 4,10) #extract digits after 
          "MED" for second medication in row

          if (medidstrings0 < medidstrings1)
          {dftest<-paste(medidstrings0,medidstrings1,sep = "-") #combine 
          strings with "-" in between
          }
          else (medidstrings0 > medidstrings1)
          {dftest<-paste(medidstrings1,medidstrings0,sep = "-")}

          combomed<-rbind(dftest,combomed) #combine all rows in dftest 
          combomed<-na.omit(combomed) #remove NAs
    }

combosample$CT_ID<-combomed #paste CT_IDs in data in respective column

I am assigning number codes to a specific code, but I would like to do this repeatedly for each row of my data set to the end. Is there a short way similar to this to do this? I also would like to paste this column of codes back into the main data frame but the code I have does not do that either.

How to map through a object array while it is uncertain if all fields in the object exist?

As mentioned in the title, I need to get single object values from an array which contains many (nested) objects and save these values in a new array. This works fine with map like:

var newArrayA = array.map(x => x.PI[0].ZZ);
var newArrayB = array.map(x => x.FS.CC.FR);
var newArrayC = array.map(x => x.FS.BD.FR);

In case all objects contain all values as you can see here:

var array =
     [ 
      { _id: 'MEuDZjQDw8XQk4ny7Y',
         PI: [        
              {ZZ: "ABC"}
             ],
         FS:
          { CC: {FR: 1},
            BD: {FR: 2} 
          }
       },
       { _id: 'gFsya9tHMAkAoPgvw',
         PI: [        
              {ZZ: "DEF"}
             ],
         FS:
          { CC: {FR: 3},
            BD: {FR: 4} 
          }
       }
     ]

There could be many more 'id' objects as well as more fields within the data structure of the array. However, I receive an error if for example the second object does not contain a FS field:

var array =
 [ 
  { _id: 'MEuDZjQDw8XQk4ny7Y',
     PI: [        
          {ZZ: "ABC"}
         ],
     FS:
      { CC: {FR: 1},
        BD: {FR: 2} 
      }
   },
   { _id: 'gFsya9tHMAkAoPgvw',
     PI: [        
          {ZZ: "DEF"}
         ]
   }
 ]

The problem is that I still need to get the FS.CC or FS.BD values from the objects which contain these values. It would be perfectly fine if I get a "empty or "undefined" in case the values are not in an object and the values if they are in the object:

var neededNewArrayC = [2, "empty"];

Or is there maybe another solution? I would appreciate any help! Thanks.

Why my if elif logic in Python is not working.. Please explain

Dataframe(test1):

cons_flag

Mas

Mas

Wood

Wood

Wood

Mas

Conc

Wood

OUTPUT:

cons_flag new_var

Mas MASOM

Mas MASOM

Wood MASOM

Wood MASOM

Wood MASOM

Mas MASOM

Conc MASOM

Wood MASOM

CODE USED:

for x in test1['cons_flag']:
    if x.find('Mas'):
        test1['new_var']="MASOM"
    elif x.find('Wood'):
        test1['new_var']= "WOODEN"

My IF wont work?

when i make adjoint inverse program, i found a problem like this

         for(byte f = 0; f < 3; f++){
                for (byte g = 0; g < 3; g++){
                    if(proses[f][g] != 51251) {

                        loop:
                        for(byte h = 0; h < 2; h++){
                            for (byte i = 0; i < 2; i++){
                                if(hasil [h][i] == 0) {
                                    hasil [h][i] = proses [f][g];
                                    System.out.printf("Hasil dari [%d][%d]: %d%n", h, i, proses[f][g]);
                                    break loop;
                                }
                             }
                        }
                        for(byte h = 0; h < 2; h++){
                            for (byte i = 0; i < 2; i++){
                                System.out.print(hasil [h][i]+ ", ");
                            } System.out.println("");
                        }
                    }    
                }
            }

its print like this

Hasil dari [0][0]: 5
5, 0,
0, 0,
Hasil dari [0][0]: 2
2, 0, 
0, 0, 
Hasil dari [0][0]: 2
2, 0, 
0, 0, 

why this if(hasil [h][i] == 0)do something strange? i want to convert and array with length 3x3 to 2x2.

anyone can explain this, please?

Kindly help to solve this data validation with user's input using python 3

This Images involves the process to which the program should be made. I am sorry i couldn't have typed the question.

Image 1

Image 2

Image 3

MySQL While Loop to fillup Table with incremental values where Auto-Increment is no option

My attempt to fill a MySQL Table with at the moment incremental values. Later on there could be changes why AUTO-INCREMENT is no solution here.

I tried to do a loop:

CREATE PROCEDURE fill()

BEGIN DECLARE v1 INT DEFAULT 1; DECLARE a INT DEFAULT 1; #autoIncrement DECLARE b INT DEFAULT 1; #counting upwards DECLARE c INT DEFAULT 1; #only 1 mixer DECLARE d INT DEFAULT 1; #product from 1-6

 WHILE v1 < 64 DO


    INSERT INTO `settingsoperationmixer`(`settingsOperationMixerId`,                    `settingsOperationId`, `mixerId`, `productId`) VALUES (a,b,c,d)

    IF d < 6 THEN SET d = d + 1;
    ELSE SET d = 1;

    SET b = b + 1;
    SET v1 = v1 + 1;
END WHILE;

END;

This should loop trough 63 times while the settingsOperationId will be 1-63 incremental and the productId should go from 1-6 and then start over again at 1

and get this error message:

Error

SQL query:

CREATE PROCEDURE fill()
BEGIN
DECLARE v1 INT DEFAULT 1

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

Design pattern for replacing nested if statements (arrow anti-pattern)

I noticed my code looks really ugly, and is hard to maintain. Basicaly i need do to some person check. Pseudo code is like this (BTW i can't "cut" anything in query, and it's not realy the point of my question):

List<Person> persons = getPersonsBySomeQuery();

if (checkAnyPersonExists(persons)) {
  if (atLeastOneWithGivenNameExist(persons)) {
    if (noOneWithOtherNameExists(persons)) {
      filteredPersons = filterPersonsWithGivenName(persons);
      if (singleName(filteredPersons)) {
        // single person found
        if (someParameterFromQueryIsTrue) {
          if (someComplicatedLogicIsOK) {
            // found exactly one person, all OK!!!
          } else {
            // found exatcly one person with given name, but not OK
          }
        } else {
           // found exactly one person but parameter from query is not OK
        }
      } else {
        // found only persons with given name, but more then one
      }
    } else {
      // found person(s) with given name, but also some with different name
    }
  } else {
    // found person(s), all have different name
  }
} else {
  // noone found
}

So i don't have that much experience with design patterns, but i read about them, and i started thinking i could implement Chain of Responsibility pattern. Like, every if-else could be one element in chain, and also this filter element on line 6 could also be "Chainable".

In the end it could look something like:

AbstractChainElement getCheckChain() {
   return new CheckAnyExist(
          new CheckOneWIthGivenNameExist(
          new CheckNoOneWithOtherNameExist(
          new FilterOnlyGivenName(
          new CheckIsSingleName(
          new CheckOtherParameters(
          new CheckWithSomeComplicatedLogic()))))));          
}

getCheckChain().doChain(persons);

Do you think it's good way to do it or is there anything more elegant?

With this i could construct chain for checking for different check types also, using factory or even abstract factory pattern.

Something like:

FactoryCheckThesePersonsByTheseParameters implements AbstractFactory {

     List<Person> getPersons() {
       // get persons with THIS query
     }

     AbstractChainElement getCheckChain() {
       // check persons THIS way
     }
}

FactoryCheckThatPersonsByThatParameters implements AbstractFactory {

     List<Person> getPersonsBySomeParameters() {
       // get persons with THAT query
     }

     AbstractChainElement getCheckChain() {
       // check persons THAT way
     }
}

why all of my data is showed even i've put the conditional to show it per 3 data in a slideshow?

this is my code

$produk = $_GET['produk'];
                $sql = "select * from tbproduk where namaproduk = '$produk' ";
                $query = mysqli_query($con,$sql) or die("error $sql");
                $num = mysqli_num_rows($query);
                echo $num;
                if(!empty($num)) {
                    for ($x = 1; $x <= $num / 3; $x++) {
                        echo '<div class="w3-content w3-display-container  mySlides">
                <div class="row">';
                        for ($i = 0; $i <= 5; $i++) {
                            $result = mysqli_fetch_array($query);
                            $namaproduk = $result['namaproduk'];
                            $harga = $result['harga'];
                            $pembeli = $result['pembeli'];
                            if(!empty($harga)) {
                                echo '<div class="col-4">
                             <img class="gbr"/>
                             <span> ' . $harga . ' </span><button class="tengbr" onclick="beli(' . $namaproduk . ',' . $pembeli . ')">Beli</button>
                            </div>';
                            }else{
                                echo "";
                            }
                        }
                        echo '</div>
                        </div>';
                    }
                }else{
                    echo "
                    <script>
                    alert('tidak ada produk yang dimaksud');
                    document.getElementsByClassName('navigasi').style.display = 'none';
                    </script>
                    ";
                }

it's actually worked, but all of my data in variabel $num is showed onload and i have to move to another slideindex and it will be normal. This is my script code

var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
    showDivs(slideIndex += n);
    document.getElementById('slideindex').innerText = slideIndex;
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    if (n > x.length) {slideIndex = 1}
    if (n < 1) {slideIndex = x.length}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    x[slideIndex-1].style.display = "block";
}

and this is my html code to move to another slide index

<div class="navigasi">
<a style="border: 1px solid black;padding: 10px;background-color: grey;color: white;cursor: pointer;" onclick="plusDivs(-1)">&#10094;</a>
<span id="slideindex"></span>
<a style="border: 1px solid black;padding: 10px;background-color: grey;color: white;cursor:pointer;" onclick="plusDivs(1)">&#10095;</a>

the <span id="slideindex"> is to show where was the index is

how to minimize the nested if conditions in the below statement

  if (billAccounts.isEmpty()) {
      EvaluationResult.stopAnalysisWithResult(CreditCheckResultCode.TECHNICAL_FAULT_ERROR);
    } else {
      for (Long billAccountNumber : billAccounts) {
        if (noOverDueInvoice) {
          try {
            result = getOverdueInvoiceResponse(String.valueOf(billAccountNumber), requestHeader);
          } catch (Exception e) {
            result = "Operation aborted due to technical causes." + e.getMessage();
          }
          if (!result.equals(NO_DEBT)) {
            noOverDueInvoice = false;
          }
        } else {
          break;
        }
      }
      if (result.equals(NO_DEBT)) {
        creditCheckResponse.setResult(Long.valueOf(NO_DEBT_CODE));
      } else {
        creditCheckResponse.setResult(Long.valueOf(DEBT_CODE));
      }
      creditCheckResponse.setResultText(DEBT);
    }

Asp.net MVC if statement working in a view but not a modal (same logic)

I am using logic to display certain text one on view that is working, and using that same logic in a modal which is only showing the else part of the statement, not the if.

This is the one that works as it should:

@if (Model.JobId > 0)
{ <a href='@Url.Action("Index", "Summary", new { id = Model.ScenarioId }, null)'>@Model.JobName&nbsp;&nbsp;Summary</a> }
else
{ <a href='@Url.Action("Index", "Summary", new { id = Model.ScenarioId }, null)'>@Model.Name&nbsp;&nbsp;Summary</a> }

and here is the one that only shows the else part of the statement, the if just returns blank.

@if (Model.JobId > 0)
{ <h4 class="modal-title" id="myModalLabel">@Model.Customer.FirstName @Model.Customer.LastName &nbsp;&nbsp;|&nbsp;&nbsp; @Model.JobName</h4> }
else
{ <h4 class="modal-title" id="myModalLabel">@Model.Customer.FirstName @Model.Customer.LastName &nbsp;&nbsp;|&nbsp;&nbsp; @Model.Name</h4> }

Better way to write nested if-else statements

What is a most Scala way to write the following piece of logic?

def collatzAlgorithm(target: Int): Int = {
    if (target % 2 == 0) {
      val new_target = target / 2
      if (new_target == 1) {
        new_target
      } else {
        if (new_target % 2 != 0) {
          new_target * 3 + 1
        } else {
          new_target
        }
      }
    } else {
      target
    }
  }

Thanks!!!!

No more than a number of the same string name in the same array?

The problem I have encountered is as follows: I have created 10 row outputs representing docking spaces for ships.

But the dock can accommodate two sizes of ship; cargo and container. The rows are made up of 5 small and 5 medium. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space, but not in small spaces.

So if I enter shipName and Container for example it searches the array making sure there is less than 5 Container's so it can dock i.e. save in the array. Can you help? Here's my dock method:

public static void dock() {

    int dockCapacity = 0;

    System.out.println("Enter ship's name: ");
    String name = scan.nextLine();

    System.out.println("Enter ship's size: ");
    String size = scan.nextLine();

    System.out.println("Enter the ships dock:");
    //search for 5 small 3 med 2 large
    for(int i = 1; i < dock1.length; i++) {
        if (dock1[i].getShipSize().contains("Cargo").) {
        }
        else {
            System.out.println("Couldn't dock");
        }
    }
    //Check if the dock number is valid
    int i = Integer.valueOf(scan.nextLine());
    if (i >= 0 && i < 10 && dock1[i] == null){
        //Add ship to the dock
        dock1[i] = new Ship(name, size);
        System.out.println("Ship has been docked");
    }
    else{
        System.out.println("Couldn't dock");
    }

}

if statement to check list items

if I have the following list and variable:

x = [1,2,18,4,5,7,11]
v = 17

and I want (in a single if statement) to search in the list to check if it contains an item that if we subtract it from v variable will equal to one "as example".

For the above example, the If statement will yield True since we have the item 18 (18-17=1) ..

Can we do that in a single if statement with python?!

How do I code a triangle

I need to make a program which creates a hollow triangle like so (c programming)

*
**
* *
*  *
*   *
******

The user can enter a size (the one above is size 6) and it draws a triangle. So if the user enter's 6, it draws it 6 high and has a 6 character base.

I can draw the height down, and the base, but not the diagonal line.

I can only use while loops, if statements printf and scanf.

Python "if" statement. Ignore specific input if certain criteria is already met

I need to add a line to this so that if octave == 1 and pygame.K_s is pressed it will ignore the input. Currently it crashes because it's expecting a > 0 value or something like that. I've tried adding if octave == 1 & even.key == pygame.k_s: octave +=1 and it does keep it from crashing, but then I can no longer go back to octave 1 once I pass it. Here's the portion of the code I'm having issues with.

        if event.key == pygame.K_a: octave += 1
        if event.key == pygame.K_s: octave -= 1
        if event.key == pygame.K_q: scale += 0.005
        if event.key == pygame.K_w: scale -= 0.005
        if event.key == pygame.K_SPACE:
            if mode == 1: mode = 2
            elif mode == 2: mode = 3
            elif mode == 3: mode = 1

How to get the real time while opening and closing the file in python?

I need the real time while opening and closing the file. Also i have used

#####
file1 = open("file.txt",mode="r+")
file1.close()
if (file1.close()==True):
    print(datetime.datetime.now())

it is not showing the output.

What is wrong with this code? VBA

The value of the cell is always "error" no matter if the condition is true or not. I've tried using else but it doesn't work either.

Sub ejer_4()
    Cells(3, 1).Value = "hola"
    For i = 2 To 21:
        If Int(Cells(i, 3).Value) <> Int(Cells(i + 1, 3).Value) - 1 Then
            Cells(3, 1).Value = "Error"
        End If
    Next
End Sub

wanted to create flag for salary in python

if salary > 200 then flag='high' else 'low'. test1 is my DataFrame. I'm using below code:

for i in test1['salary']:
    if i > 200:
       test1['flag']='high'
    elif i < 200:
       test1['flag']='low'

print (test1)

it's giving me flag = high only.

multiple actions after if statement in R

Is there a way to make it simple?
"multiple actions after if statement"

if (abnormal$Lab in c("2018AV")) {abnormal$v1="20x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v2="7x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v3="8x3"}
if (abnormal$Lab in c("2018AV")) {abnormal$v4=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v5=NA}
if (abnormal$Lab in c("2018AV")) {abnormal$v6=NA}

jeudi 29 mars 2018

perl conconditional script not working

i made this small Perl script but when i run it in the terminal ($ Perl perltest.pl) it says syntax error at perltest.pl line 6, near ") {" Execution of perltest.pl aborted due to compilation errors. i am not sure what is wrong with my code, I've fiddled with it for hours. Thanks!

use strict;
use warnings;
print "enter a number\n";   
my $num = readline STDIN;
chomp ($num)
if ($num < 10) {
    print "its less than 10\n";
}
elsif ($num > 10) {
    print "its greater than 10\n";
}
else (
    print "its 10\n";
)

Char variable comparison issue in java [duplicate]

This question already has an answer here:

I have a problem try to compare variables char the program do not comppile...

will you plase showme the problem...

Scanner sc = new Scanner(System.in);
double desca=0.05;

System.out.println("Categori type *A* o *B*");
char cate = sc.nextChar();
System.out.println("type total to pay a" + cate + ".");
double map = sc.nextDouble();

if(cate=='a')
map=map-(desca*map);

System.out.println("Monto a pagar es de " + map + " pesos.");

Excel table function: if then or

i am crunching a large dataset. one column is "date". i want to have a column of Invoice Date. for any transaction happened in january, i want the invoice date to be Jan-31-2017...so on and so forth.

  • Jan 2, 2017 (invoiceDate Jan 31, 2017)
  • Jan 18, 2017 (invoiceDate Jan 31, 2017)
  • Feb 5, 2017 (invoiceDate Feb 28,2017) ......

How to write the If function? thanks.

Checking to see if the password matches the particular user- PostgreSQL and Java

I am trying to implement a section of code which checks that the hashed_password and user_name match. The code below first checks to see if the username is valid, then if valid the code will then check to see if the password matches the username. However, that is section of the code that is not working. I can enter the correct username from the database and the corresponding correct password from the database and it displays the correct message You can proceed!. But if I enter the correct username from the database but an incorrect password it still displays You can proceed!. Any help is appreciated!

public void letsLogin() throws SQLException
 {

  System.out.print("Enter your user name: ");
  username = in.next();


  sql = "SELECT " + "username " + "FROM" + " users_table" + " where username = "
        + "'" + username + "'";


  result = s.executeQuery(sql);

 // select hashed_password
  sql_hash = "SELECT " + "hashed_password = " + "crypt(" + "'"
                 + hashed_password + "'" + ","+ "hashed_password)" +
                 " as matched " + "from users" +  " where username = "
                 + "'" + username + "'";

 result2 = s2.executeQuery(sql_hash);

  if(result.next())
  {
        System.out.println("You are registered!");
         // ask user to enter password

        System.out.println("Enter your password: ");
        hashed_password = stdin2.next();

        // check to see if username and hashed_password match
        if(result2.next())
        {
           System.out.println("You can proceed!");
        }

        else
        {
           System.exit(0);
        }


  }

Javascript if and for loop confusion

I'm creating a Pig Latin translator and this function below checks for a double consonant.

Everything runs great up until it checks the word more in the function. It outputs the second letter as "m" as well. After that word the function seems to malfunction the word smile outputs the first and second letter to the console as "st". What confuses me is the last word in the array "string" ends up with the correct output to the console "st".

If anyone can look over my code and see something that I'm not seeing, I would be grateful. My JSFiddle is below.

var vowel = ["a", "e", "i", "o", "u"];
var consonant = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"];

doubleConsonate();

function doubleConsonate() { // add the sent as a parameter
  var theSent = ["ctt", "cheers", "to", "your", "mother", "chzek", "a", "few", "more", "smile", "its", "a", "string"];
  console.log("the word or phrase: " + theSent);
  var consonantCount;
  for (var i = 0; i < theSent.length; i++) {
    for (var j = 0; j < consonant.length; j++) {
      if (theSent[i].slice(0, 1) == consonant[j]) {
        console.log(theSent[i]);
        console.log("1st letter being checked is:  " + theSent[i].slice(0, 1));
      } else if (theSent[i].slice(1, 2) == consonant[j]) {
        //      consonantCount = true;
        console.log("2nd letter being checked is:  " + theSent[i].slice(1, 2));
      } //else if (consonantCount == true) {
      //theSent[i] = theSent[i].slice(2) + theSent[i].slice(1,2) + "ay";
      //consonantCount = false;
      //}
    }
    //console.log(consonantCount);
  }
  console.log(theSent);
}

Round certainr row

I want to round when the variable 'value' only when the variable 'pct' is n.

                  Course4 Q_21 pct value
    MNO6201 Sect 011 1182     1   n 32.00
    MNO6201 Sect 011 1182     2   n  6.00
    MNO6201 Sect 011 1182     3   n  5.00
    MNO6201 Sect 011 1182     1 pct 74.42
    MNO6201 Sect 011 1182     2 pct 13.95
    MNO6201 Sect 011 1182     3 pct 11.63

The result should looks like

              Course4 Q_21 pct value
    MNO6201 Sect 011 1182     1   n 32
    MNO6201 Sect 011 1182     2   n  6
    MNO6201 Sect 011 1182     3   n  5
    MNO6201 Sect 011 1182     1 pct 74.42
    MNO6201 Sect 011 1182     2 pct 13.95
    MNO6201 Sect 011 1182     3 pct 11.63

Is it possible? Thank you for your help.

How to look through column names in R and perform operations then store it in a list of unknown row size

I am a new R programmer and am trying to create a loop through a large amount of columns to weigh data by a certain metric.

I have a large data set of variables (some factors, some numerics). I want to loop through my columns, determine which one is a factor, and then if it is a factor I would like to use some tapply functions to do some weighting and return a mean. I have established a function that can do this one at a time here:

weight.by.mean <- function(metric,by,x,funct=sum()){

if(is.factor(x)){
a <- tapply(metric, x, funct)
b <- tapply(by, x, funct)
return (a/b)
} 
}

I am passing in the metric that I want to weigh and the by argument is what 
I am weighting the metric BY. x is simply a factor variable that I would 
like to group by.

Example: I have 5 donut types (my argument x) and I would like to see the mean dough (my argument metric) used by donut type but I need to weigh the dough used by the amount (argument by) of dough used for that donut type.

In other words, I am trying to avoid skewing my means by not weighting different donut types more than others (maybe I use a lot of normal dough for glazed donuts but dont use as much special dough for cream filled donuts. I hope this makes sense!

This is the function I am working on to loop through. It is not yet functional because I am not sure what else to add. Thank you for any assistance you can provide for me. I have been using R for less than a month so please keep that in mind.

weight.matrix <- function(df,metric,by,funct=sum()){


  n <- ncol(df) ##Number of columns to iterate through
  ColNames <- as.matrix(names(df))
  OutputMatrix <- matrix(1, ,3,nrow=, ncol=3)

 for(i in 1:n){


 if(is.factor(paste("df$",ColNames[i], sep=""))){
  a[[i]] <- tapply(metric, df[,i], funct)
  b[[i]] <- tapply(by, df[,i], funct)
}
OutputMatrix <- (a[[i]]/b[[i]])
}
}

Using 'Case' or 'If' statement in declaration portion of PL/PGSQL stored procedure

As a newbie to PL/PGSQL I am trying to do something which works in (at least one) other PL/SQL environments and I haven't been able to isolate the way to do this in PL/PGSQL.

I am creating a function, and passing a variable into the function. With this variable I am building (or leaving blank) a variable which is then included into the final SQL Statement which is then executed.

I have left my attempts to use CASE and IF in the code adding comments to denote the attempts. I have looked up in the documentation which states there are SQL versions of CASE and IF and PL/PGSQL versions of CASE and IF, but I have not been able to nail down their differences and proper use of each, and, of course, whether the way I am trying to use it is allowed, or how to achieve this properly.

--DROP FUNCTION public._1_ExampleQuery(varchar);

CREATE OR REPLACE FUNCTION public._1_ExampleQuery(namefield varchar(50) DEFAULT 'name')
RETURNS TABLE(id double precision , name character varying(100), frc smallint) 
  LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
-- ------ GOAL ------------------------------------------------------------- 
--
--  If 'namefield' is blank, set namedwhere as empty, if namefield is 
--  present build sql structure to omit blanks

-- ------ Attempt using CASE ----------------------------------------------- 
--
--  CASE namefield
--      WHEN '' THEN
--          namedwhere varchar(50) := '';
--      ELSE 
--          namedwhere varchar(50) := ' and ' || namefield || ' <> '''' ';
--  END CASE;

-- ------ Attempt using If  ------------------------------------------------ 
--
--  IF namefield = '' THEN
--      namedwhere varchar(50) := '';
--  ELSE 
        namedwhere varchar(50) := ' and ' || namefield || ' <> '''' ';
--  END IF;
-- ---------------------------------------------------------------------------

sqlQuery varchar(500) := 'SELECT id,name,frc FROM road_nw WHERE frc = 1 ' || namedwhere;

BEGIN
    -- RAISE NOTICE 'SQL Query Statement: %',sqlQuery;
    RETURN QUERY EXECUTE sqlQuery;
END;

When I uncomment the CASE section I get this error:

ERROR:  syntax error at or near "CASE"
LINE 10:  CASE namefield
          ^
SQL state: 42601
Character: 480

And when I uncomment the IF Section I get this similar error:

ERROR:  syntax error at or near "IF"
LINE 17:  IF namefield = '' THEN
          ^
SQL state: 42601
Character: 752

The version of PostgreSQL that I am using is: PostgreSQL 9.3.19 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4, 64-bit

So in summary, Can CASE and IF be used in the declaration portion of the function, and if so how? If they cannot, what is the proper way to achieve this goal of having a conditional portion of the SQL statement.

How do I fix my if-statement that uses Date values and needs to be 20 years from the Current Date?

Being a newbie, any help is appreciated. I am trying to create a quick macro that:

1) Sets 2 variable in date format. 2) 1 variable cannot be more then twenty years from the current date. 3) Those variables then set another variable's cell values which are set to a numerical format.

I have included the macro below, it is not functional and I am getting issues with trying to code the worksheet as worksheet.

**Macro**
Sub Date_Check()

'Coding Variables

Dim WB As ThisWorkbook
Dim Test_Data As Sheet1
Dim statedate as String
statedate = Format(Date, "mm/dd/yyyy")
Dim enddate as string
enddate = Format(Date, "mm/dd/yyyy")
Dim todaydate as date
'Coverage date is enddate-statedate cell 
Dim CvgDate as Range
Set CvgDate(26) = enddate.value - statedate.value
Dim jj as Integer
Dim x as boolean
x = True

'set the ranges as the last cell to contain values

With Worksheet("TestData")
.Range("V2:V"). Offset(-1,0).xldown.Value2 = startdate
.Range("W2:W").Offset(-1,0).xldown.Value2 = enddate
.Range("FutureDate").Format(Date, "yyyy") = True

 'Create function that will check if range is 20 years within today's date.
FutureYear = 20  < DateSerial(Year, 1)
.Range("enddate").Offset(-1, 0).Select =x
.Cell.Number = "mm/dd/yyyy"

'Create an if statement using fuction
If Range("enddate").Cell <> = FutureYear Then
 MsgBox "Please check that the end reporting date is within 20 years from today's date!" 
   End If
 'Ensure that enddate meets criteria before being put in numerical format
.Range("Cvgdate").Offset(-1,0).Select
.Selection.NumberFormat = "jj"




End With

Any suggestions are helpful. But I am focused on ensuring that the enddate variable is within 20 years of the current date, but I cannot seem to use my code for the if-statement. I really appreciate the help and thanks in advance!

if in shell scripting not giving actual response [duplicate]

This question already has an answer here:

#!/bin/sh
read name
if test "$name"=akash
then 
echo "Hello how are you"
else
echo "sorry"

This is my script but at both case I am getting "Hello how are you" response

Javascript if statement only returns true

I am writing a rock paper scissors game.

console.log for the player shows the selected value.

console.log for the computer shows the selected value.

The if statement to check if the values match always returns true, even if the console log shows them to be different.

I have tried writing it a few different ways but always end up with this issue.

// Player Choice Selection 
var player = function() {
  const playerSelects = "rock";
  return playerSelects;
};
console.log(player());

// Computer Choice Selection
var computer = function() {
  const computerSelects = ['rock', 'paper', 'scissors'];
  let randomSelection = Math.floor(Math.random() * 3);
  return computerSelects[randomSelection];
};
console.log(computer());

// Game 
var game = function(player, computer) {
  if (player == computer) {
    const draw = "its a draw";
    return draw;
  }
};
console.log(game());

Can anyone tell me where I am going wrong with this?

Thanks

Jenkins declarative pipeline. Conditional statement in post block

Have a Jenkins pipeline. Need/want to send emails when build succeeds. Email about all branches to maillist-1 and filter builds of master branch to maillist-master.
I tried using if and when statements-steps but both of them fail in post block.

pipeline {
  agent ...
  stages {...}
  post{
    success{
      archiveArtifacts: ...
      if( env.BRANCH_NAME == 'master' ){
        emailext( to: 'maillist-master@domain.com'
                , replyTo: 'maillist-master@domain.com'
                , subject: 'Jenkins. Build succeeded :^) 😎'
                , body: params.EmailBody
                , attachmentsPattern: '**/App*.tar.gz'
        )
      }
      emailext( to: 'maillist-1@domain.com'
                , replyTo: 'maillist-1@domain.com'
                , subject: 'Jenkins. Build succeeded :^) 😎'
                , body: params.EmailBody
                , attachmentsPattern: '**/App*.tar.gz'
        )
      }
    }

}

How wanted behavior could be achieved?

Formula for an algorithm in excel

I have this table:

Queue¦  Room 1¦ Room 2¦  Room 3¦    Room 4¦ Room 5¦     Room 6¦ 
1    ¦    1   ¦    0  ¦    0
2    ¦    2   ¦    0  ¦    0
3    ¦    3   ¦    0  ¦    0
4    ¦    4   ¦    0  ¦    0
5    ¦    5   ¦    0  ¦    0
6    ¦    6   ¦    0  ¦    0
7    ¦    7   ¦    0  ¦    0
8    ¦    8   ¦    0  ¦    0
9    ¦    9   ¦    0  ¦    0
10   ¦    10  ¦    0  ¦    0
11   ¦    11  ¦    0  ¦    0
12   ¦    12  ¦    0  ¦    0
13   ¦    12  ¦    1  ¦    0
14   ¦    12  ¦    2  ¦    0
15   ¦    12  ¦    3  ¦    0
...  ¦    ..  ¦    .. ¦    ..
36   ¦    12  ¦    12 ¦    1
37   ¦    12  ¦    12 ¦    2
38   ¦    12  ¦    12 ¦    3
...  ¦    ..  ¦    .. ¦    ..

To give some background I am trying to create essentially a formula that can look at the "Queue" column and place those in the "Queue" to "Room 1" and keep placing them in "Room 1" until it is full (it's full when it reaches 12) I then want it to place those in the "Queue" to "Room 2", so when it hits 13 (in the Queue column) and onward they are placed in "Room 2", until it's full at 12 places again, pushing on to "Room 3" and so on so on.

I'm new to excel and I'm not to sure if I am going about this the right way. the formula I have so far:

=OFFSET(A2, 0, $A$2)

This basically looks at "Queue", then returns the number next the to cell it's looking at. I can populate the fields from "Room 3" onward with this formula, but i am wondering is there is a better way to do this? I was also thinking of using an IFstatement but i'm not sure how to increment the IFstatement such as below:

=IF(a13=12,"1","0")

but how would I increment "1" to make it "2", then to make it "3" in the formula, until it reaches 12 again and starts on the next row?

after 12 in the same column I would want the rows below it to say 12 as well.

Apologies if I have confused anyone but I am finding it tricky to search for help online as I don't know how to describe the formula I am looking for.

ALSO: Is there a better title for my query to help others in a similar challenge to mines, find this question?

Visual Studio C# if statement not working in Debug

So I have a weird situation, where I get to an if statement while debugging, and I'm finding that even though EM=="M", my if statement if(EM=="E") is being entered anyway... I'm also noticing that some of my code seems to be just getting skipped over when I'm stepping though the code(F11).

I'm using C# in VS2015 and VS2017, it's having the issue in both versions. I was using Framework 4.5, I had switched it to 4.6.1 to build a compatible version for a different program. But switching that back didn't change anything...

try
{
  if (EM == "E") //If english
  {
    topText.TextString = rad + "\" minimum bend radius";
  }
  if (EM == "M") //Metric
  {
    topText.TextString = Convert.ToString(Math.Round((Convert.ToDouble(rad)) * 0.3048, 2)) + "\" minimum bend radius";
  }
}
catch (IOException e)
{
      // Extract some information from this exception, and then   
      // throw it to the parent method.  
      if (e.Source != null)
        System.Windows.Forms.MessageBox.Show("IOException source: {0}", e.Source);
      throw;
}  

If anyone else is aware of this issue or know's what I may be doing wrong, help would be appreciated.

PHP IF Statement conditions using content of variable [on hold]

I could not find these question, altough i think this was already questioned.

Problem: If you want to build your IF Statement conditions with variables, like:

<?php
//DEFINE IF STATEMENT CONDITIONS INSIDE A VARIABLE
$var =  '$t == 1';
$var .=  ' AND $x == 1';
//END OF DEFINE IF STATEMENT CONDITIONS

//DEFINE VARIABLES
$t = "1";
$x = "2";
//END OF DEFINE VARIABLES

//NOW CHECK THE IF STATEMENT, YOU CAN SEE THE CONDITION SHOULD BE FALSE BECAUSE $x != 1
if( print($var) == TRUE)
{   echo "TRUE";    }
else
{   echo "FALSE";   }
//I KNOW THE CODE (print($var) == TRUE) WONT WORK, ONLY SHOWN FOR A BETTER UNDERSTANDING
?>

The If statement above just proofs if the variable exists, but i want to proof if the content of the variable is true: $t == 1 AND $x == 1.

The IF statement in the code above should be similar to:

if( $t == 1 AND $x == 1)
{   echo "TRUE";    }
else
{   echo "FALSE";   }

I tried a lot. Now i would be happy for a solution, which includes an If statement in the form of If (PROOF CONTENT OF VARIABLE) {}.

Why if ... else if ... else have common scope? And what scope is common with last else?

TIL that if and else have common scope:

if (int x = foo()) {
  // ....
}
else if (int x = bar()) {
  // ...
}
else {
  cout << x; // which x here?
}

I checked ( https://godbolt.org/g/mAvW7B ) that x in else is first.

But why? What is the explanation of this non-obvious behavior?

In this example:

if (int x1 = foo()) {
  // ....
}
else if (int x2 = bar()) {
  // ...
}
else {
  cout << x2; // why x2 is visible here
}

Why x2 is visible in last else then? And why in the first case x is from first if?

Using VLOOKUP and IMPORTRANGE to find a match and return one of two potential values

I am trying to change the value of cell B1 depending on if cell A1's value is found in another spreadsheet. If there is a match, I want the cell to say "banned". If A1 isn't found in the other spreadsheet, I want it to say "active'.

I've been playing around with this

=if((VLOOKUP(A3,IMPORTRANGE("https://docs.google.com/xyz","ALL BANNED ACCOUNTS!$G$2:$G$300"),1,false))=A3,"Banned","Active")

and can only get it to return "Banned". If there is no match, it always returns #N/A.

How can I remedy this?

Thanks!

Prolog - Custom 'if-then-else'

I'm experimenting with Prolog and tried to make my own "if-then-else" method, so that I don't use the -> ; method, for experimenting's sake. My goal is to make it so that there can be nested ifs and elses in my code if required. Thus far I have got this:

ifthenelse(_, G, G):- G.    %no matter the condition, the goals are the same
ifthenelse(true,G,_):- G.   %if
ifthenelse(false,_,G):- G.  %else

I think my way hardly seems correct. How can I make my own ifthenelse/3 properly?

Thank you

vba excel - if cycle

I have 2 columns with USD amounts of payments I need to compare. Data is from two different sources but they should match. Every month there is different number of payments so I dont know if next time there will be 20 or 30 of them. So I need to compare these 2 columens. What I want to do is using if function

If [n3] = [u3] Then
    [q3] = "yes"
Else
    [q3] = "no"
End If

and I dont know how to use cycles to do this with every payment. Can you help me please. Thank you

Ruby's if / else in methods

Currently learning Ruby and curious if it's idiomatic / preferred to always use an else when using if/else in a method.

For example, in JS, this is stylistically acceptable (and sometimes preferred)

function jsFunc(x) {
  if (x == 0) {
    return "Yes";
  }

  return "No";
}

and I've also seen a similar style in Python:

def py_func(x):
    if x == 0:
        return "Yes"
    return "No"

but from the Ruby I've seen, it's always:

def ruby_method(x)
  if x == 0
    "Yes"
  else
    "No"
  end
end

I've also gotten a comment that not using an else in Ruby seems messier? Do Rubyists prefer the "explicit" else? (Also curious a lot of the language is implicit.) Thanks!

Using AND on Android

I have an if statement the check if all item is selected or not (Android )

        if(region_id == null && City == SelectAll && Distric == SelectAll && itemid== SelectAll){ 
         // DO something 
        }
else{    
            if(City == SelectAll && Distric == SelectAll && itemid== SelectAll){

         // DO something 

        }else
      if(Distric == SelectAll && itemid == SelectAll)){
       // DO something 


    }else{
    // DO something 
    }

My issue that if dos not working

I am trying to sum the columns of specific headers in a particular row but I am getting total sum of all columns of that row irrespective of header

'I am trying to sum the columns of specific headers in a particular row but I am getting total sum of all columns of that row irrespective of header. Can someone please tell me my mistake?Please see the attached image for sample input output.enter image description here

Dim DSum As Integer
Dim PSum As Integer
With wsn
    NIMsLastRow = Worksheets("NIMSCarrierCount").Cells(Rows.Count, 1).End(xlUp).Row
    NIMsLastCol = Worksheets("NIMSCarrierCount").Cells(1, Columns.Count).End(xlToLeft).Column
    For j = 2 To NIMsLastRow
        DSum = 0
        PSum = 0
        For k = 2 To NIMsLastCol
            If .Cells(1, k).Value = "LTE 1900Deployed" Or "LTE 2500Deployed" Or "LTE 800Deployed" Or "UnassignedDeployed" Then
                DSum = DSum + CInt(.Cells(j, k).Value)
            End If
            If .Cells(1, k).Value = "LTE 1900Planning" Or "LTE 2500Planning" Or "LTE 800Deployed" Or "UnassignedPlanning" Then
                PSum = PSum + CInt(.Cells(j, k).Value)
            End If
        Next k
        .Cells(j, NIMsLastCol + 1).Value = DSum
        .Cells(j, NIMsLastCol + 2).Value = PSum
    Next j
End With

How to use multiple values for one variable depending on the resulty of an if-else staement?

In the code sample below I want to make it so that deductions would equal one of the 4 values depending on the input the user enters (look at the if-else statement). Is this possible?

deductions1 = 0.12 + 0.04 + 0.01 + 0.06
deductions2 = 0.20 + 0.07 + 0.03 + 0.06
deductions3 = 0.30 + 0.09 + 0.05 + 0.06
deductions4 = 0.38 + 0.11 + 0.07 + 0.06
deductions = monthly_salary = hours_worked * hourly_pay

if monthly_salary < 4000:
    deduction_rate = deductions1
elif monthly_salary >= 4000 and monthly_salary < 8000:
    deduction_rate = deductions2
elif monthly_salary >= 8000 and monthly_salary < 16000:
    deduction_rate = deductions3
else:
    deductions = deductions4

net_salary = monthly_salary - (deductions * monthly_salary)

how to fix the display format of the return result in python

i have a function that read file and display the matching word using regular expression .

the system display the result like this :

if
Exist on Line 1
if
Exist on Line 2

what i want is to make the result look like this :

if exist 2 times
on line 1
on line 2

code:

def searchWord(self,selectedFile):
        fileToSearchInside = self.readFile(selectedFile)
        searchedSTR = self.lineEditSearch.text()

        textList = fileToSearchInside.split('\n')

        counter = 1
        for myLine in textList:
            theMatch = re.findall(searchedSTR,myLine,re.MULTILINE|re.IGNORECASE)

            if(len(theMatch) > 0 ):
                print(theMatch[0])
                print("Exist on Line {0}".format(counter))
                counter+=1        

mercredi 28 mars 2018

Why does my code ignore the Exception?

My code should make entering anything other than a letter or a '$' in discountCode String result in throwing an exception however this doesn't happen. The user can type anything and still not receive an exception message. Any help is much appreciated, thanks.

private String normalizeDiscountCode(String discountCode) {
  String upperDiscountCode = discountCode.toUpperCase();

    for (char i : upperDiscountCode.toCharArray()) {
      if (Character.isLetter(i) || i == '$') {
        return upperDiscountCode;
      } else {
        throw new IllegalArgumentException("Invalid discount code");
        }
    }
    return upperDiscountCode;
  }

  public void applyDiscountCode(String discountCode) {
    this.discountCode = normalizeDiscountCode(discountCode);
  }
}

Why do I get an invalid syntax error while using the “if else” line?

I try to retrieve some data by scraping a html file. However, I get the invalid syntax error (see below, after code) when running the code in a Python 3 notebook (Spyder).

I have the following code:

from lxml.html import parse
parsed = parse('Factiva.html')
doc = parsed.getroot()
cells = doc.findall('.//td')
len(cells)
fout = open('factiva-parsed.txt', 'w')
fout.write("TITLE\tSOURCE\tTIME\tDATE\tWORD COUNT\n")
fout.flush()
NA = "N/A"
T = "\t"
NL = "\n"
for (i, cell) in enumerate(cells):
  if (i<2):
    #ignore first two results, they are from the page header
    continue
  #col1: title, from <b>
  titles = cell.findall('.//b')
  if titles:
    #Two unicode chars (left/right quo) cause problems --> replace
    fout.write(titles[0].text_content().strip().replace(u"\u2018", "'").replace(u"\u2019", "'") + u"\t")
  else:
    fout.write(NA+T)
  #col2-5: from div class=leadFields, comma-separated
  fields = cell.find_class('leadFields')
  if fields:
    raw_fields = fields[0].text_content()
    field_split = raw_fields.split(',')
    # ['Reuters News', ' 13:33', ' 27 April 2016', ' 896 words', ' (English)']
    #col2: source
    fout.write(field_split[0] + T)
    #col3: time - optional
    has_time = ":" in field_split[1]
    date_col = 2
    words_col = 3
    if has_time:
      fout.write(field_split[1].strip() + T)
    else:
      #skip the time field
      fout.write(NA+T)
      date_col = 1
      words_col = 2
    #col4: date
    fout.write(field_split[date_col].strip() + T)
    #col5: number of words
    fwordss = [int(s) for s in field_split[words_col].split() if s.isdigit()] #get the integers
    if fwordss:
      fout.write(str(fwordss[0]) + NL)
    else:
      fout.write(NA+NL)
  else:
    fout.write(NA+T+NA+T+NA+T+NA+NL)
  fout.flush()
fout.close()

However, when running it... I get the following error:

  else:
       ^
SyntaxError: invalid syntax

If statements with checkboxgroupinput, how to call out dynamic variables in the server.

How can I edit the code below so that when one of the check boxes is checked, it'll add days to the Approval.Date? I can't seem to get the if statements below to recognize the input variable. Any help? I know my main problem is in the if statement. I've tried several things but I think that I don't quite understand how to call out variables that I create in the second observe event in the server.

# loading libraries ####
#rm(list = ls())
library(shiny)
library(ggplot2)
library(dplyr)
library(shinythemes)
library(reshape)

# UI ####
ui <- fluidPage(theme = shinytheme("cerulean"),
                tags$style(type="text/css",".shiny-output-error { visibility: hidden; }",".shiny-output-error:before { visibility: hidden; }"),  #Hides errors when the date is too low. 
                titlePanel("Drug Schedule"),
                tabsetPanel(
                  tabPanel("Plot", fluid = TRUE,
                           sidebarLayout(
                             sidebarPanel(dateRangeInput("DateRange","Date Range",  min= as.Date("2000/01/01"), max= as.Date("2060/01/01"), start = as.Date("2010/01/01"), end = as.Date("2019/01/01")),
                                          htmlOutput("IndicationGroup"),#add selectinput boxs
                                          htmlOutput("DrugName"),
                                          htmlOutput("UpdatingDates")),
                             mainPanel(plotOutput("DrugSchedule"))))

))

# Server ####
server <- function(input, output) {
  # Data ####

  mdfr2 <- read.table(header=TRUE, stringsAsFactors = FALSE,
                     text="ID Drug.Name Indication.Group Filing.Date Approval.Date MyBreak PriorityReview
                     1 HDrug_one HIV 2014-01-21 2015-04-11 yes yes
                     2 HDrug_two HIV 2017-09-22 2018-02-21 no yes
                     3 HDrug_three  HIV 2012-11-17 2016-05-15 no yes
                     4 HDrug_four HIV 2014-11-22 2016-10-18 no no
                     5 HDrug_five HIV 2010-12-30 2013-04-19 yes yes
                     6 HDrug_six AIDS 2012-11-22 2016-10-18 no no
                     7 HDrug_seven AIDS 2011-12-30 2013-04-19 yes yes"
  )
  mdfr2$Filing.Date <- as.Date(mdfr2$Filing.Date) 
  mdfr2$Approval.Date <- as.Date(mdfr2$Approval.Date)

  mdfr <- melt(mdfr2, measure.vars = c("Filing.Date","Approval.Date"),na.rm = TRUE)

  output$IndicationGroup <- renderUI({ 
    selectInput("IndicationGroup", "Indication Group", choices= unique(mdfr$Indication.Group),selected = unique(mdfr$Indication.Group)[4])
  })

  observeEvent(input$IndicationGroup,({
    output$DrugName <- renderUI({
      data_available <- mdfr[mdfr$Indication.Group==input$IndicationGroup,]
      checkboxGroupInput(inputId = "DrugName", label = "Drug", choices = unique(data_available$Drug.Name), selected = unique(data_available$Drug.Name)[1])
    })
  })
  )

  observeEvent(input$DrugName,({
    output$UpdatingDates <- renderUI({
      updatedDates <- vector("list",length(input$DrugName)) 
      for(i in 1: length(input$DrugName)){
        updatedDates[[i]] <- list(checkboxGroupInput(inputId = paste0("updatedDates",i),paste("Update:",input$DrugName[i]),choices = c("None"="None", "Priority Review"="PR", " Priority Review and Breakthrough"="BRK"), selected = "None"))
      }
      return(updatedDates)
    })
  })
  )

observeEvent(input$UpdatingDates,({
  data_available <- mdfr2[mdfr2$Indication.Group==input$IndicationGroup & mdfr2$Drug.Name==input$DrugName,]
  for(i in 1:length(input$DrugName)){
    if(updatedDates[[i]] == "None"){
      mdfr[mdfr$Indication.Group==input$IndicationGroup & mdfr$Drug.Name==input$DrugName[[i]] & mdfr$variable == "Approval.Date","value"]<- data_available$Approval.Date[i] + 125
    }else if(updatedDates[[i]] == "BRK"){
      mdfr[mdfr$Indication.Group==input$IndicationGroup & mdfr$Drug.Name==input$DrugName[[i]] & mdfr$variable == "Approval.Date","value"]<- data_available$Approval.Date[i] + 125 +25
    } else if(updatedDates[[i]] == "None"){
      mdfr[mdfr$Indication.Group==input$IndicationGroup & mdfr$Drug.Name==input$DrugName[[i]] & mdfr$variable == "Approval.Date","value"]<- data_available$Approval.Date[i]
    }
  }
})
)



  filtered <- reactive({
    filtered <- mdfr %>%
      filter(Indication.Group  %in% input$IndicationGroup,
             Drug.Name  %in% input$DrugName)
  })

  output$DrugSchedule <- renderPlot({
    if (is.null(filtered())) {
      return()
    }
    ggplot(filtered(), aes(as.Date(value, "%m/%d/%Y"), Drug.Name))+ 
      geom_point(data= filtered()[filtered()$variable=="Filing.Date",], aes(as.Date(value, "%m/%d/%Y"), Drug.Name))+
      #geom_point(data= filtered()[filtered()$variable=="PDUFA.Date",], aes(as.Date(value, "%m/%d/%Y"), Drug.Name))+
      geom_point(data= filtered()[filtered()$variable=="Approval.Date",], aes(as.Date(value, "%m/%d/%Y"), Drug.Name))+
      #geom_point(data= filtered()[filtered()$variable=="Start.Marketing.Date",], aes(as.Date(value, "%m/%d/%Y"), Drug.Name))+
      xlab("Date") + ylab("") +  ggtitle("Drug Schedule")+
      scale_x_date(date_breaks = "1 year", date_labels =  "%b %Y")+
      theme(axis.text.x=element_text(angle=60, hjust=1),axis.text.y = element_blank(),axis.ticks.y = element_blank())+
      geom_line(data=(filtered()[filtered()$variable=="Filing.Date" |  filtered()$variable=="Approval.Date",]), aes(as.Date(value, "%m/%d/%Y"), Drug.Name), linetype="solid", size=1)+
      #geom_line(data=(filtered()[filtered()$variable!="PrimCompDate",]), aes(as.Date(value, "%m/%d/%Y"), name), size=1)+
      #facet_wrap(~Country, nrow=2,scales = "free")+
      geom_text(data= subset(filtered()[filtered()$variable=="Approval.Date",]),aes(as.Date(value, "%Y-%m-%d"), Drug.Name, label=Drug.Name), hjust = -.1)+
      coord_cartesian(xlim=c(as.Date(input$DateRange[1]),as.Date(input$DateRange[2])))
  })
}

# Running the app ####
shinyApp(ui = ui, server = server)

whenever i try to

How to take Postal Code Checker using Regular expression and Input in Python 3

My code should allow user's input to match the Regular expression of my "postal code" and print out Match found - Valid postal code. I need help to get my result, but i keep getting TypeError: expected string or bytes-like object.

import re

print("--- POSTAL CODE CHECKER PROGRAM --- ")
# user_input_1 = input('Please enter the city/province: ')
user_input_2 = input('Please enter the postal code: ')

postalCode = ["T, V, R, E, A, X, B, K, L, M, N ,P, C , G, H, J, S, Y, 0-9"]

pattern = re.compile(r'[TVREAXBKLMNPCGHJSY]\d[TVREAXBKLMNPCGHJSY] \d[TVREAXBKLMNPCGHJSY]\d')

if user_input_2 == pattern.match(postalCode):
    print('Match found - Valid postal code:{}'.format(user_input_2))
else:
    print("Error - No match found")

Update textbox through vlookup if value not in range

I'm using this code

Private Sub ComboBox2_Change()
    On Error Resume Next
    Dim myRange As Range
    Set myRange = Worksheets("cash").Range("BF:BH")
    Price.Value = Application.WorksheetFunction.VLookup(ComboBox2.Value, myRange, 2, 0)
End Sub

select value from textbox2 using vlookup to match value selexted from textbox2 in price , if the value not included in textbox2 there is last price shown. I need if i entered value not in range no price shown.

What's the diference between if with OR operators and if with multiple elif?

Example code (Python):

A:

if a == 1 OR b == 1:
something

B:

if a == 1:
    something

elif b == 1:
    something

What are advatages and disadvangates of both variants?

Excel MATCH text but return a value to left or right depending on other text

I have a terribly inelegant formula to return a value from the left or the right of a string depending on the MATCH. It works, but I am hoping that someone can help with making this a bit easier to read. The general read of the formula is:

  • If you find "; T" (the full text could also be "TestSpec;")
  • Then return the value to the Right
  • Else, return the value to the Left

My problems are:

  • The IF statement by itself can only return either the LEFT or the RIGHT
  • The MATCH statement returns a Boolean so it's not helpful in determining LEFT or RIGHT
  • 2 IFERROR statements

Here's the Excel Formula in all it's glory:

=IFERROR( 
   IFERROR(
     IF(MATCH("*; T*",Table1[@Tags],0), 
       LEFT(Table1[@Tags],FIND(";",Table1[@Tags])-1)
     ), 
     RIGHT(Table1[@Tags],LEN(Table1[@Tags])-FIND(";",Table1[@Tags])-1)
   ), \*First Error Catch*  
 "") \* Second Error Catch*

Elseif doesn't work properly

I'm trying to make form validation with ajax. Mine problem is elseif statement doesn't work properly

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

    //Create safe values for input into database
    $username = mysqli_real_escape_string($mysqli, $_POST['username']);
    $password = mysqli_real_escape_string($mysqli, $_POST['password']);
    $company = mysqli_real_escape_string($mysqli, $_POST['company']);
    $mail = mysqli_real_escape_string($mysqli, $_POST['mail']);
    $adress = mysqli_real_escape_string($mysqli, $_POST['adress']);

    $errorEmpty = false;
    $errorTaken = false;
    $errorMail = false;

    //Check are required fields empty
    if(empty($username) || empty($password) || empty($company) || empty($mail) || empty($adress)){
        echo "<span class='form-error'>Fill in all fields!</span>";
        $errorEmpty = true;
    }

    //Check is username already taken HERE IS THE PROBLEM!
    elseif(isset($_POST['username'])){

        $username = mysqli_real_escape_string($mysqli, $_POST['username']);

        if(!empty($username)){

            $username_query = mysqli_query($mysqli, "SELECT * FROM users WHERE user_username = '$username'");
            $count=mysqli_num_rows($username_query);

            if($count!=0)
            {
              echo"<span class='form-error'>Username is already taken! </span>";
              $errorTaken = true;
            }
    }

}
    //Check is mail adress correct
    elseif(!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
        echo "<span class='form-error'> Write a valid e-mail adress!</span>";
        $errorMail = true;
    }
    else{
            //Create user
            $add_user_sql = "INSERT INTO users (user_username, user_password, user_company, user_mail, user_adress) 
                            VALUES ('".$username ."', '".$password."', '".$company."', '".$mail."', '".$adress."')";

            $add_user_res = mysqli_query($mysqli, $add_user_sql)
                or die(mysqli_error($mysqli));

            //Close connection to MySQL
            mysqli_close($mysqli);

            echo "<span class='form-success'>Succesifuly registrated!</span>";
        }
}

Problem is when i check is username already in database,because after that step every next elseif statement won't execute. When I put it on first place it stops execution of rest of code,same situation is when I put it on last place.Other conditions for checking empty fields and mail validation are working properly.

My 'if' statements are being totally skipped in Java. How can I get them to be acknowledged? What is the issue?

import java.util.Scanner;

public class Class_3_26 {

public static void type() {
    System.out.println("Student or Teacher?");
    Scanner input = new Scanner(System.in);
    String userInput = input.next();
    if (userInput == "Student") {
        student("Jono", 12);
    }
    if (userInput == "Teacher") {
        teacher("Mr. Fomenko", "Technology");
    }
    else {
        System.out.println("DOES NOT COMPUTE");
        System.out.println("TRY AGAIN");
        type();
    }
}

public static void student(String name, int grade) {
    System.out.println(name + " is a student at Waterford High School. This person is in grade " + grade + ".");
}

public static void teacher(String name, String subject) {
    System.out.println(name + " is a teacher at Waterford High School. This person teaches " + subject + "class.");
}



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

}

}

So here is my code. I am doing this for a project in class and for some reason, the IFs are just being skipped over. No matter what you input, even if it's "Student" or "Teacher" which should be correct, it prints the else. Any ideas?

What is the correct IF ELSE syntax in SQL server? - Preventing Duplications in a Column with SP

I have to prevent a column from duplicating so I made this Stored Procedure

CREATE PROCEDURE [dbo].Agregar_Personal
    @nom varchar(20),
    @apll varchar(20),
    @tel int,
    @dep int,
    @sal float
AS
IF dbo.UnicoApellido(@apll) = 0
    INSERT INTO Personal (Nombre,Apellido,Telefono,Departamento,Salario)
    VALUES (@nom,@apll,@tel,@dep,@sal)  
    RETURN 0;
ELSE    
    RETURN 1;

(the function dbo.UnicoApellido returns 0 if the value is repeated in the table)

the issue here is that I'm getting an error in ELSE, saying that the syntax is wrong. Can anyone tell me what is the error, or if there's another way to prevent duplications when performing an INSERT?

If then else in R

I am an old dog struggling with R as a new trick

I want to replicate the follow SAS code in R (using a dataframe with multiple columns):-

if sum5 > 0 then gbind = 1;
else if  sum4 > 0 then gbind = 2;
else if block19 in ('B') then gbind = 3; (many other elements)
else gbind = 0;

Please Help

php IF / ELSEIF inside IF / ELSEIF

Hi there I have the following php that I have been developing

<?php

$URI = $_SERVER['REQUEST_URI'];
$activepage = $_SERVER['SERVER_NAME'];
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

if (
    strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit/") !== false ||          
    strpos($_SERVER["HTTP_USER_AGENT"], "Facebot") !== false
) {
    // it is probably Facebook's bot
    if ($activepage=="www.example.co.uk") {
    $link = 'http://www.example.co.uk' . $URI;
    header("location:$link");
    exit;
    }
    elseif ($activepage=="test.example.co.uk") {
    $link = 'http://test.example.co.uk' . $URI;
    header("location:$link");
    exit;
    }
    elseif ($activepage=="www.example.us") {
    $link = 'http://www.example.us' . $URI;
    header("location:$link");
    exit;
    }

}
elseif {
    // that is not Facebook
    if ($activepage=="test.example.co.uk" & $country_code=="CA") {
    $link = 'http://www.example.us' . $URI;
    header("location:$link");
    exit;
    }
    elseif ($activepage=="test.example.co.uk" & $country_code=="US") {
    $link = 'http://www.example.us' . $URI;
    header("location:$link");
    exit;
    }
    elseif ($activepage=="test.example.us" & $country_code=="GB") {
    $link = 'http://www.example.co.uk' . $URI;
    header("location:$link");
    exit;
    }
    elseif ($activepage=="test.example.us" & $country_code=="UK") {
    $link = 'http://www.example.co.uk' . $URI;
    header("location:$link");
    exit;
    }

}



?>

the second if / elseif works fine which by itself looks like this

<?php

$URI = $_SERVER['REQUEST_URI'];
$activepage = $_SERVER['SERVER_NAME'];
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

if ($activepage=="www.example.co.uk" & $country_code=="CA") {
$link = 'http://www.example.us' . $URI;
header("location:$link");
exit;
}
elseif ($activepage=="www.example.co.uk" & $country_code=="US") {
$link = 'http://www.example.us' . $URI;
header("location:$link");
exit;
}
elseif ($activepage=="www.example.us" & $country_code=="GB") {
$link = 'http://www.example.co.uk' . $URI;
header("location:$link");
exit;
}
elseif ($activepage=="www.example.us" & $country_code=="UK") {
$link = 'http://www.example.co.uk' . $URI;
header("location:$link");
exit;
}

?>

However when I pop it inside this

if (
    strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit/") !== false ||          
    strpos($_SERVER["HTTP_USER_AGENT"], "Facebot") !== false
) {
    // it is probably Facebook's bot
}
else {
    // that is not Facebook
}

it stops working all together.

what I want to do is have it so facebook bot goes to the site which the link is used however failing this if it is a normal user, then if a user from US hits the UK site they're redirected and if a user from the UK gets the US site they get redirected - using cloudflares HTTP headers.

Any thoughts on where I might be going wrong here?

Thanks

Saving worksheet Renditions Within single Workbook based on List Value

My goal is to save numerous renditions of a worksheet based on the value of a single cell, used as the identifier of the worksheet.

Ideally, these renditions are all accessible through a single workbook, that when a different 'identifier' is chosen, the values previously saved under that rendition will automatically populate the cells they correspond with.

If it were a simply reference I would just use an IF() statement, but I'm trying to adapt it to the entire worksheet.

Any help or hints would be greatly appreciated.

awk to create new variables based on conditions of other columns

I have a file input.txt (~100'000 lines) with this structure:

Z0        Z1        Z3
0.9746    0.0254    0.0000     
0.0032    0.0000    0.9433  
0.2464    0.5603    0.9008 
0.4034    0.4982    0.0069 
0.0072    0.9996    0.0472 
...       ...       ...

And I want to create a new file output.txt with an additional column named SCORE based on the following conditions:

  • SCORE = 1 if: 0.17 ≤ Z0 ≤ 0.33 and 0.40 ≤ Z1 ≤ 0.60
  • SCORE = 2 if: 0.40 ≤ Z0 ≤ 0.60 and 0.40 ≤ Z1 ≤ 0.60
  • SCORE = 3 if: Z0 ≤ 0.05 and Z1 ≥ 0.95 and Z2 ≤ 0.05
  • SCORE = 4 if: Z0 ≤ 0.05 and Z1 ≤ 0.05 and Z2 ≥ 0.95
  • SCORE = 5 if the other 4 conditions did not apply.

output.txt would look like this:

Z0        Z1        Z3         SCORE
0.9746    0.0254    0.0000     5
0.0032    0.0000    0.9433     4
0.2464    0.5603    0.9008     1
0.4034    0.4982    0.0069     2
0.0072    0.9996    0.0472     3           
...       ...       ...

Here is what I tried:

awk 'NR==1{$4="SCORE";print;next} \
  0.17<$1 && $1<0.33 && 0.40<$2 && $2<0.60 {$4="1"} \
  0.40<$1 && $1<0.60 && 0.40<$2 && $2<0.60 {$4="2"} \
  $1<=0.05 && $2>=0.95 && $3<=0.05 {$4="3"} \
  $1<=0.05 && $2<=0.05 && $3>=0.95 {$4="4"} \
  *other* 1' input.txt > output.txt

However, something is wrong in the first 5 command lines and I don't know how to write the last condition (for score 5) in the last line.

RANK IF formula on Google Sheets with SUM

I am trying to create a ranking of summed numbers out of a database. The Database has a list of individual offices of companies in certain countries (numbered 1-10). In some cases, the same company is in multiple countries. Countries are listed in Column A; Companies are in column B; Offices are in column C.

Each individual office has a score. Office scores are in column D of the database.

I would like to create a rank of companies based on the company's total score per country. The company's total score per country is the sum of scores of all offices of the same company in the same country.

In order to build such a ranking one would have to:

1 - Get the company's total score per country. I have done this using a SUMIFS function. This is the function I've used to calculate this score: =SUMIFS($D$2:$D, $A$2:$A, $A2, $B$2:$B, $B2)

2- Rank it against the list of other companies' total score per country only for those companies that are in the same country.

I am having trouble defining the range for the RANK and have learnt that this is not possible to do using a function like this. The range against which to rank the value calculated on step 1 needs to be a conditional sum as well - the sum of all scores in the country of the office we are ranking. How can this be done?

After doing some research, I have tried solutions involving SUMPRODUCT and COUNTIFS but have failed to achieved the desired result. How can I do this?

I have created a sample sheet here that might help to understand the problem here.

Thank you

Javascript programmer FOR loop with IF logic for career - Challenge

Javascript programmer FOR loop with IF logic for career - Challenge :

How can we make this FOR loop Logic for a young JS programmer Better ??

for(var salary=0; salary<=ideal.minSalReq; salary++){

  if(postionOffrd[salary]<basicSalReq)
  {
    continue;
  }
  else if(postionOffrd[salary]===basicSalReq)
  {
     ideal.salNegotiate(postionOffrd[salary]);
  }



if(postionOffrd.indexOf(postionOffrd[salary])=== postionOffrd.length-1)
 {
   ideal.acceptServitude( postionOffrd[salary] );
   break;
 }


} /*end of for-loop*/