samedi 30 avril 2016

if (string or string or string) not in variable

I'm trying to get an if statement to work, but for some reasons it doesn't work. It should be very simple.

Assume that the string title = "Today I went to the sea"

My code is:

 if "Today" or "sea" in title:
      print 1

 if "Today" or "sea" not in title:
      print 1

Both specifications result in 1.

JAVA How to get the summation of 14-based values?

Currently, I am trying to write a program where it would ask the user for a 14-based number and it would shoot out a 14-based number. The prompt is as follows... "An alien species uses 14-based numbering system. Their ten digits, 0 through 9, are the same as our decimal system. They use A, J, Q and K to represent decimal 10, 11, 12 and 13, respectively. They hire you to write a Java program to do the summation of their two numbers. The program should prompt users for two 14-based numbers and then display the summation of those two numbers. The output should also be 14-based. (They are unwilling to learn our decimal systems!) For example, if inputs are 17 and 96, the output should be AK."

when i enter 17 and 96, it shoots out AK, which is what i wanted. When i enter something like 1Z, it would pop up the "Your first/second input is invalid," which is also what is expected. But When i input something like 1A, or j1, it would give me the same error " Your first/second input is invalid" , though it should go through. I feel like i did something wrong in the validateinput method, but i am not quite sure. Any help would be greatly appreciated. Thanks! Thanks,

enter code here

import java.util.Scanner;

public class H5_hieu {

   public static void main(String[] args)
   {
       System.out.println("Please enter a 14 base value: ");
       Scanner input = new Scanner(System.in);
       String first = input.nextLine(); 
       String second = input.nextLine();
       boolean isFirstValid = validateInputs(first);
       boolean isSecondValid = validateInputs(second);
       while (!isFirstValid || !isSecondValid){
          if (!isFirstValid){ 
            System.out.println("Your first input is invalid");
          }
          if (!isSecondValid){
            System.out.println("Your second input is invalid");
          }
          System.out.println("Please enter a 14 base value: ");

          first = input.nextLine();
          second = input.nextLine();
          isFirstValid = validateInputs(first);
          isSecondValid = validateInputs(second);
       }

       int firstInDecimal = convertFrom14To10(first.toUpperCase());
       int secondInDecimal = convertFrom14To10(second.toUpperCase());
      System.out.println(convertFrom10To14( firstInDecimal + secondInDecimal));




   }

   public static boolean validateInputs(String input) {
      for ( int i = 0;i < input.length(); i++){
         char currentChar = input.charAt(i);
         if (!Character.isDigit(currentChar) && (currentChar != 'A' || currentChar != 'J' || currentChar != 'Q' || currentChar != 'K' || currentChar != 'a' || currentChar != 'j' || currentChar != 'q' || currentChar != 'k')) {
            return false;
         }
      }
      return true;
   }



   public static String convertFrom10To14(int input){
      boolean done = false;
      int quotient = input;
      int remainder = 0;
      String result = "";
      while (!done) {
         remainder = quotient % 14;

         quotient = quotient / 14;


         //System.out.println("quotient: " + quotient + " remainder: " + convertDigit(remainder));
         result = convertDigit(remainder) + result ;

         if (quotient == 0)
            done = true;
      }
      return result;
  }

   public static int convertFrom14To10(String input) {

      int length = input.length();
      int result = 0;

      for(int i = 0; i < length; i++){

         char currentChar = input.charAt(i);
         //System.out.println("Character at index " + i + " : " + currentChar);
         int valueOfChar = getCoeff(currentChar);
       // System.out.println("Decimal value of currentChar: " + valueOfChar);
         int power = length - 1 - i;
         //System.out.println("Power: " + power);
         result = result + (valueOfChar * (int)Math.pow(14, power));
        //System.out.println();
      }
     // System.out.println("Decimal of " + input + " is: " + result + "\n");   
      return result;
   }

   public static int getCoeff(char character) {
      if (character == 'A'){
         return 10;
      } else if (character == 'J'){
         return 11;
      } else if (character == 'Q'){
          return 12;
      } else if (character == 'K'){
          return 13;
      } else {
          return Integer.parseInt(String.valueOf(character));
      }

    }
    public static String convertDigit( int number)
    {
    if (number == 10){
      return "A";
    } else if ( number == 11){
         return "J";
      } else if (number == 12){
           return "Q";
        } else if (number == 13){
            return "K";
          } else {
               return String.valueOf(number);
               }
    }


  }

Haskell and multiple conditions

If I have multiple conditions that are only slightly different, what is the best way to write a function (considering and inability to nest guards) of the form:

f | a && b && c  = 1
  | a && b && d  = 2
  | a && b && e  = 3
  | a && g && e  = 4

etc

Imagine there are more a lot more conditions. Ideally I would like to write a nested if that would check for a then b then something else, but I have been told that this not possible in Haskell.

Also, in the example. If the first line returns falls, are the conditions a and b checked again if they not defined in a where clause?

Changing Form BackColor in a If Statement

I am working on this form which has a list box full of items that are of a class called Team. I want that when a item is selected the main form will change its BackColor. I have this in a SelectedIndexChange event within a if statement, but when I run the program nothing happens when the item is slected. Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TicketMaster
{
    public partial class frmMaster : Form
    {
        public frmMaster()
        {
            InitializeComponent();

            Team minnesotaTwins = new Team();
            minnesotaTwins.teamName = "Minnesota Twins";
            minnesotaTwins.stringPrice = "$79.00";
            minnesotaTwins.ticketPrice = 79.00;

            Team coloradoRockies = new Team();
            coloradoRockies.teamName = "Colorado Rockies";
            coloradoRockies.stringPrice = "$54.00";
            coloradoRockies.ticketPrice = 54.00;

            Team balOrioles = new Team();
            balOrioles.teamName = "Baltomore Orioles";
            balOrioles.stringPrice = "$86.00";
            balOrioles.ticketPrice = 86.00;

            Team bosRedsoxs = new Team();
            bosRedsoxs.teamName = "Boston Redsoxs";
            bosRedsoxs.stringPrice = "$75.00";
            bosRedsoxs.ticketPrice = 75.00;

            listTeams.Items.Add(minnesotaTwins);
            listTeams.Items.Add(coloradoRockies);
            listTeams.Items.Add(balOrioles);
            listTeams.Items.Add(bosRedsoxs);



        }

        public void listTeams_SelectedIndexChanged(object sender, EventArgs e)
        {
            Team team = (Team)listTeams.SelectedItem;

            lblSelectedPrice.Text = lblSelectedPrice.Tag + team.stringPrice;

            if (listTeams.SelectedIndex == 1)
            {
                this.BackColor = System.Drawing.Color.SteelBlue;
            }

        }

        private void form1_Load(object sender, EventArgs e)
        {

        }

        private void listTeams_MouseHover(object sender, EventArgs e)
        {
            lblPrices.Visible = true;
        }

        private void listTeams_MouseLeave(object sender, EventArgs e)
        {
            lblPrices.Visible = false;
        }
    }
}

How can i use if statement UItextfield in Swift

My code like this

@IBOutlet var variable: UITextField!
var variable2 : String = "magpie";
@IBAction fun c login(sender: AnyObject) {
    if (variable == variable2 ) {

    self.performSegueWithIdentifier("login", sender: self)
        }

I want to do like this but it does not work what can i do ? if i use

if (variable.text! == "a") 

its working but i dont want to do this. i want to use variable thank you all

showing different buttons in the GUI depending on if statements

I am trying to create a game that has two options: that the student can answer a question by introducing the answer or by clicking a button that contains the correct answer. I created the texfield and the buttons for the two types of questions and made if statements that depending on which type of question it is (the type is predetermined) if going to show the buttons or the textfield but it does not work (it does not get into the if). My code looks like this:

    SanswerTextField = new TextField();
    SanswerTextField.setPrefWidth(300.0);
    SanswerTextField.setMinWidth(300.0);
    SanswerTextField.setMaxWidth(300.0);
    SanswerTextField.setPrefHeight(50.0);
    SanswerTextField.setStyle("-fx-font: 30 timesnewroman; -fx-base: #AE3522");



    SanswerButton1 = new Button();
    SanswerButton1.setPrefWidth(50.0);
    SanswerButton1.setMinWidth(50.0);
    SanswerButton1.setMaxWidth(50.0);
    SanswerButton1.setPrefHeight(50.0);
    SanswerButton1.setStyle("-fx-font: 30 timesnewroman; -fx-base: #AE3522");


    SanswerButton2 = new Button();
    SanswerButton2.setPrefWidth(50.0);
    SanswerButton2.setMinWidth(50.0);
    SanswerButton2.setMaxWidth(50.0);
    SanswerButton2.setPrefHeight(50.0);
    SanswerButton2.setStyle("-fx-font: 30 timesnewroman; -fx-base: #AE3522");



    SanswerButton3 = new Button();
    SanswerButton3.setPrefWidth(50.0);
    SanswerButton3.setMinWidth(50.0);
    SanswerButton3.setMaxWidth(50.0);
    SanswerButton3.setPrefHeight(50.0);
    SanswerButton3.setStyle("-fx-font: 30 timesnewroman; -fx-base: #AE3522");



    if(saveTypeQ.getText().equals("Choose Answer"))
    {
        SanswerButton1.setText(saveAnswer.getText());
        System.out.println("answer in button: " + SanswerButton1.getText());
        SanswerButton2.setText(saveAnswer.getText());
        SanswerButton3.setText(saveAnswer.getText());

        mathTestButtonPane.add(SanswerButton1,1,4);
        mathTestButtonPane.add(SanswerButton2,2,4);
        mathTestButtonPane.add(SanswerButton3,3,4);

        System.out.println("I am a question to choose an answer");
    }
    else if(saveTypeQ.getText().equals("Introduce Answer"))
    {
        mathTestButtonPane.add(SanswerTextField,1,4);
        System.out.println("I am a question to introduce an answer");
    }
    else
    {
        System.out.println("Not working");

    }

it is accessing always the else and I have no idea why. I would really appreciate the help. Thank you in advance.

Shortened method to reduce statements in an Ada procedure?

I am creating a procedure that uses an if statement to perform a descission.


I have 4 variables: Altitude, Velocity, Angle and Temperature.

The procedure is as follows:

procedure Test3 is

begin if (Integer(Status_System.Altitude_Measured)) >= Critical_Altitude and (Integer(Status_System.Velocity_Measured)) >= Critical_Velocity and (Integer(Status_System.Angle_Measured)) >= Critical_Angle and (Integer(Status_System.Temperature_Measured)) >= Critical_Temperature then DT_Put ("message 1");
else null; end if; end Test3;

This procedure is bassicaly taking the idea that if all the critcal values for the variables are met for each and every variable then it will print a message.

I want to be able to have a shorter way of paring up the statements so I can do the following:

if I have 4 variables: Altitude, velocity, angle and temperature and I want to have a statement that says, If atleast 3 of these varibles (doesnt matter which three) are all exceeding their critical values then display a message.

Is it even possible to do this? I would hate to think That i would have to write each and every possible combination for the if statements.

so In short an if statement that says atleast 3 of the variables shown are at their criticle value so print a message.

the same would be good for atleast 2 of these variables aswell.

mysql different row updates depending on a variable (stored procedure)

CREATE PROCEDURE update_table(
    IN choice INT(4),
    IN id VARCHAR(50),
    IN string VARCHAR(50)
)
BEGIN
UPDATE salesman
set salesman_name = IF(choice = 1, string, salesman_name)
where salesman_id = id
UPDATE salesman
set date = IF(choice = 2, string, date)
where salesman_id = id
END

if choiceis 1, change salesman_name as string

if choice is 2, change date as string

can you explain me what i'm doing wrong?

it works fine with a single update, my guess is there is another way to implement if but i couldn't.

if choice = 1 then
update salesman set salesman_name = string where salesman_id = id

...i tried this version too but still, not working.

Javascript - Search for whole words inside an array and create new array with coincidences

Having an array of arrays named data with following format:

> data[1].toString()
"Seed Keywords,disconnectors,EUR,210,0.03,,,,,N,Y," 

And another array named groupKeywordsText with a list of words to find inside the array data:

> console.log(groupKeywordsText);
["switch", "ac", "high", "switches", "disconnect", "voltage", "isolator"]

I need to create a set of new arrays that include only elements from data which contains a whole word from groupKeywordsText.

SOME EXAMPLES:

An array can be assigned in only one of the new arrays:

> data[3].toString()
"Keyword Ideas,ac,EUR,1900,0.00,1.58,,,,N,N,"

  • Will be assigned to the second new array, because "ac" is exactly one of the searched term.

An array can be assigned in multiple new arrays:

> data[12].toString()
"Keyword Ideas,high voltage,EUR,27100,0.00,1.58,,,,N,N,"

  • Will be assigned to the third new array, because "high side" contains the term to search: "high".
  • Additionally, it will be included in the 5th array, as "voltage" also appears.

An array can be assigned in multiple new arrays, but not in others:

> data[18].toString()
"Keyword Ideas,isolator for switch,EUR,1100,0.00,1.58,,,,N,N,"

  • Will be assigned to the first new array, because "isolator for switch" contains the term to search: "switch".
  • Additionally, it will be included in the 6th array, as "isolator" also appears.
  • However, it will not appear in the 4th array ("switches"), because we search for, and only exactly for, "switch".

An array cannot be assigned in new arrays:

> data[28].toString()
"Keyword Ideas,stackoverflow,EUR,1900,0.00,1.58,,,,N,N,"

  • Wont be assigned to a new array, because "stackoverflow" isn't a searched term.

So far, my code looks like:

    for ( var i = 0, l = groupKeywordsText.length; i < l; i++ ) {

        keywordToSearch = groupKeywordsText[i];
        var length = data.length;
        this["keywordGroup"+i] = [];

                for(var j = 0; j < length; j++) {
                    if (data[j][1] == keywordToSearch) {
                    this["keywordGroup"+i].push(data[j][1]);
                    }
                }

        console.log(this["keywordGroup"+i]);
    }

How can I search for whole (not partial) words inside a string?

PHP Check if specific query is in url

I am trying to check if a url has a specific query within a url with multiple params

$parts = parse_url('http://my url?queryA=valueA&queryB=valueB&queryC=valueC ....');
parse_str($parts['query'], $query);

I have used the below to get the value of the query;

$query['queryA']//outputs valueA

however, I want to check if "queryA" is indeed within the url queries

echo $parts['query']//outputs the full query - queryA=valueA&queryB=valueB&queryC=valueC

//trying for
if($parts['query'] == 'queryA') {
//queryA is in the url
}

EasyGUI How to define input in if loop

I was wondering how I could use input from a choicebox into a if loop. All help appreciated! e.g:

title = 'Title'
msg = 'Message'
choices = ['Choice1', 'Choice2']
decided = choicebox(title, msg, choices)

if decided == 'Choice1':
    print'Choice 1 is a choice that you have selected.'

How to check user agent in nginX config?

Is there a way to say if user agent contains a word like Android then do the rest?

I have a config like below:

valid_referers server_names;
if ($invalid_referer) {
   error_page 403 = @deny;
   return 403;
}

What I want to do is to say if there is an invalid referrer and user agent does not contain android then give the user 403. Is it possible? How to accomplish such a problem?

how to find a label is exist or not in Windows Forms panel

if (panel1.Contains(label1)) // if label1 is exist it shows label is exist if label2 is not exist then mean else part... how to identify it is not exist.
        {
            MessageBox.Show("Label 1 is Exist");
        }

mean to say my else part is not working if the label is not exist.

vendredi 29 avril 2016

Using If else Or Cases from More Table In Sql Server

I Need to Select all from Log Table and import Data when Cases

If UserGrade =1 this is Admin User and I need to select Admin Name by Log.User

If UserGrade =2 this is Teacher User and I need to select Teacher Name by Log.User

If UserGrade =3 this is Student User and I need to select student Name by Log.User

I try This

select L.[UserID],L.[UserGrade],L.[Operation],L.[OpDate],

case

when L.[UserGrade]=2 then (select teacherNAME from Teacher ,[Log] where teacherID=[Log].[UserGrade] )

when L.[UserGrade]=1 then (select [Adm_Name] from Administrator ,[Log] where [Adm_ID]=[Log].[UserGrade] )

when L.[UserGrade]=3 then (select [studentNAME] from student ,[Log] where [studentID]=[Log].[UserGrade] )

end from [Log] L ,Teacher , Administrator ,student

I Need Help ...

compare answers in database php

hi i have an exercise on doing quiz in database. below is my requirement that has been done. -i have done retrieve question randomly from database -user can select answer *there is a problem when i have to compare the answer selected by the user with my database.

in my database, i have created id_question, question,ansA,ansB, ansC, ansD and correctAns.

so, i am stuck on doing the comparison, when i do the if-else statement, its going wrong as below

my problem is : how to compare the answer clicked from user with my database answer, thanks for helping

I can't figure out why my if statement is working

so if Sequence 1 :CAG and Sequence 2 :AG, i am supposed to get the response

"Best alignment score :2 CAG AG"

but instead i am getting "Best alignment score :0 CAG AG"

I believe my issue is in the 2nd if statement, as that what it seems like with the debugger.

when using the debugger it shows that the computer not going into the if statement.

can anyone please tell me how to fix this issue? thanks

can anyone please tell me how i can make my question clearer? thanks

    public static int allignment (String dnaSequence1 , String dnaSequence2 /*,int offset*/){
    int newScore = 0;
    int bestScore = 0;
    int newOffset = 0;
    int bestOffset = 0;

    for(int offset =0; offset<=(dnaSequence1.length()-dnaSequence2.length());offset++){
        //newOffset ++;
        newScore = 0;
        for(int place =0; place<dnaSequence2.length();place++ ){
            if(dnaSequence1.charAt(place) == dnaSequence2.charAt(place/*+offset*/)){

                newScore ++;
                if(newScore>bestScore){
                    bestScore = newScore;
                    bestOffset = newOffset;

                }
            }else{ continue;}
        }
        newOffset ++;
    }

    String space = " ";
    System.out.println("Best alignment score :"+bestScore);
    System.out.println(dnaSequence1);
    System.out.print( space(bestOffset) + dnaSequence2);

    int alignmentScore = dnaSequence1.compareToIgnoreCase(dnaSequence2);

    return alignmentScore;
}

public static String space (int bestOffset){
    String space = " ";
    String offsetScaces = "";

    for(int i = 0; i<bestOffset; i++){
        offsetScaces+=space;
        return offsetScaces;
    }
    return offsetScaces;
}

How to find the most duplicates in an array?

I'm don't know how to find duplicates in an array. After finding the duplicates, I also need the program to figure out which duplicate to use to print the highest score (based on a formula)

e.g. input: 3 5 7 7 7 7 7 12 12 12 18 20

/* program calculating n * n * n * y = score

7 appears 5 times = 5*5*5*7 = 875

12 appears 3 times = 3*3*3*12 = 324 */

output: 7 is the highest scoring duplicate at 875.

I am restricted to using only arrays, if/else, printf/scanf, loops..

My code so far (only works for some inputs):

#include <stdio.h>

#define MAX_NUMBERS 15

int main(void){

int nNumbers, i, j;
int sum;
int selectNumber;

int array[MAX_NUMBERS]; 

//Reading the numbers
scanf("%d", &nNumbers); //Enter the number of elements in the array
for(i = 0; i < nNumbers; i++){    
    scanf("%d", &array[i]);
}

//This is the part I'm having trouble with, 
//writing conditions for it to find the highest scoring duplicate.
j = 0;
selectNumber = array[0];
for(i = 0; i <= nNumbers - 1; i++){
    selectNumber = array[i];
    for(i = 1; i <= nNumbers - 1; i++){
        if((array[i] == runNumber) && (array[0] != selectNumber)){
            array[j] = selectNumber; //^ doesn't work if 1st num is duplicate
            j++;
        }
    }
}

How to test if a value is already in my HashMap while reading a file

I am working currently on a program to find similar sets so i need to map all my items contained in many sets in a HashMap with key,value pairs but i don't want redundant items to have many keys like key=1 value=bread and key=2 value=bread

So I wrote the following code

public static void main(String[] args) throws FileNotFoundException, IOException {
    // HashMap to stock all my items with keys that i will use for minhashing
    HashMap<Integer,String> hmap= new HashMap<>();
    List<List<Integer>> MinHash = new ArrayList<>();

    //to read my sets that i defined 
    FileReader in=new FileReader("C:\\items\\items.txt");
    BufferedReader brr = new BufferedReader(in);
    String item ; 
    int key=1; //for checking value pairs
    while( (item = brr.readLine()) != null)
        {
            System.out.println(hmap.containsValue(item));
            if(hmap.containsValue(item))//problem
                System.out.println("Item already in my map");
            else{
            hmap.put(key, item);
            key++;
            }
        }
    System.out.print(hmap);
}

But this test doesn't seem to return value true even if i have already this value in my HashMap

Javascript if function

I have a very simple java calculator which includes 9 check box input choice, a, b, c, d, e, f, g, h, i

I have created a simple script to calculate the overall total (output property name a) based on input selection as follows:

return {  a: inputs.a + inputs.b*2 + inputs.c*3 + inputs.d + inputs.e + inputs.f + inputs.g + inputs.h + inputs.i }

I wish to include another calculation which returns a specific value (output property name b) based on the cal.

If a = 0 then b value should display 0.7% or if a = 1, b value should display 1.1% or if a = 2, b = 1.7% or if a = 3, b = 2.7% or if a = 4, b = 4.4% or if a = 5, b = 6.9% or if a = 6, b = 11% or if a = 7, b = 16% or if a = 8, b = 24% or if a = 9, b = 34% or if a = 10, b = 45% or if ...

I hope this makes sense

Thank you

Javascript redirect URL

Below is a bit of script I'm using in related to a form for a site. I'm trying to get it to redirect to a specific page if the first two functions aren't valid.

What's happening is that the redirect is happening even if the functions are valid

I'm sure I'm missing something really simple here...

Any help appreciated!

(function(){
var f1 = fieldname2,
    valid_pickup_postcode = function (postcode) {
    postcode = postcode.replace(/\s/g, "");
    var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
    return regex.test(postcode);
    };
var f2 = fieldname7,
    valid_dropoff_postcode = function (postcode) {
    postcode = postcode.replace(/\s/g, "");
    var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
    return regex.test(postcode);
};

if( AND(f1,f2))
{
   if( valid_pickup_postcode(f1) && valid_dropoff_postcode(f2))
   {
      return 'Please select the vehicle you require for your delivery';
   }
   else
   {
      return window.location.href = "http://www.bing.com";
   }
}
else
{
return '';
}
})()

Compare 2 columns in Excel, removing values from a 3rd and provide results in a 4th, Possibly a nested If Index/Match Formula?

Sorry that I am having to post this but my mind just cannot make sense of this today and I cannot find it in the similar questions.

I am trying to find missing SKU's based on the master list in sheets A, B, C - thus;

I have a master SKU list in a column in sheet D. I want to compare that list against SKU's in a column in sheet A and a column in sheet B. However I want to ignore any SKU if it is in sheet C. Provide the final list of results in sheet E.

For simplicity, assume the SKU is in col A for each sheet.

Sounds like a maths problem I know, but I just cannot find the switch that will ignore the values from sheet C.

I was hoping for a formula probably using IF, index and match, but I just can't get my head around it.

Any help gladly received.

insert formula with function in vba

I have made two functions that makes a calculation from two different linest (UpperCalc and LowerCalc). This works fine. Then I will need to fill in formulas for an unknown number of cells (depending on the input on another sheet). I have been able to fill in formulas for the correct number of cells. But when I try to include an "IF"-formula in the VBA programming together with the function names, it does not work? My VBA code to fill in the formula looks like this now;

Dim lastRow As Long, i As Long, ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Sheets("Sheet1") Set ws2 = Sheets("Sheet2")

lastRow = ws1.Range("B" & Rows.Count).End(xlUp).Row

     With ws1
        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then _
            ws2.Range("A" & i).Value = ws1.Range("A" & i).Value
            ws2.Range("B" & i).Value = ws1.Range("B" & i).Value
            ws2.Range("C" & i).Formula = "=IF(RC[-1]>R4C12,UpperCalc(RC[-1]),LowerCalc(RC[-1]))"
        Next i
    End With
End If

I am able to insert formula with one of these functions (for instance ws2.Range("C" & i).Formula = "=UpperCalc(RC[-1])", and also only with an "IF" formula (for instance ws2.Range("C" & i).Formula = "=IF(RC[-1]>R4C12,RC[-1],RC[-1]^2)" - This is of course not the actual calculation needed - only to test the "IF"-function). Since the calculation behind UpperCalc and LowerCalc is rather "dirty", I would like to utilize the functions. Any ideas?

If ELSE condition not working properly

I have a Multiple Select DROPDOWNLIST to select items. See the Dropdownlist below

dropdownlist

What I am doing is, I am selecting 2 items from the list. One of PROCESSED and another of PENDING

So what's happening wrong here is, when the condition is PROCESSED it works properly and goes in IF condition but second time it is PENDING but still it goes in the IF condition.

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
        {
            using (SqlCommand sqcmd = new SqlCommand("select  month(a.dt_of_leave)month, year(a.dt_of_leave)year   " +
                                    "from emp_mst a where month(a.dt_of_leave) >= month(getdate())-1  and   " +
                                    "year(a.dt_of_leave)= case when  month(getdate())=1   " +
                                    "then year(getdate())-1 else year(getdate()) end  " +
                                    "and emp_card_no IN (" + str_emp_sel + ") order by emp_name", conn))
            {
                SqlDataAdapter damonthyear = new SqlDataAdapter(sqcmd);
                damonthyear.Fill(dtspmonthyear);

                for (i = 0; i < dtspmonthyear.Rows.Count; i++)
                {
                    if (cmbEmp_Name.SelectedItem.Text.Contains("PROCESSED") == true)
                    {
                        //CF.ExecuteQuerry("exec Emp_Resign_Allocate_Leave '" + str_emp_sel + "','" + dtspmonthyear.Rows[0]["month"].ToString() + "', '" + dtspmonthyear.Rows[0]["year"].ToString() + "'");
                    }
                    else
                    {
             // not going in else for `PENDING`
                    }
                }
            }
        }

Simple if statement not working (string comparison)

This block of code is not working:

DECLARE @CollationName varchar(50)
set @CollationName = (
    select collation_name
    from information_schema.columns
    where table_name = 'MeteringPointPrice' and column_name = 'MeteringPointId'
)

if OBJECT_ID('tempdb..#MPLIST2') IS NOT NULL
    drop table #MPLIST2
if @CollationName = 'SQL_Danish_Pref_CP1_CI_AS'
    create table #MPLIST2 (MeteringPointId varchar(18) COLLATE SQL_Danish_Pref_CP1_CI_AS)
if @CollationName = 'Danish_Norwegian_CI_AS'
    create table #MPLIST2(MeteringPointId varchar(18) COLLATE Danish_Norwegian_CI_AS)

select @CollationName gives: Danish_Norwegian_CI_AS

But both if statements are run so the temporary table #MPLIST2 is created 2 times, which of course gives an error.

I cannot figure out why.

Here is the code changed a little bit:

DECLARE @CollationName varchar(50)
set @CollationName = (
    select collation_name
    from information_schema.columns
    where table_name = 'MeteringPointPrice' and column_name = 'MeteringPointId'
)


if OBJECT_ID('tempdb..#MPLIST2') IS NOT NULL
    drop table #MPLIST2

if @CollationName = 'Danish_Norwegian_CI_AS'
    begin
        create table #MPLIST2 (MeteringPointId varchar(18) COLLATE Danish_Norwegian_CI_AS)
    end

if OBJECT_ID('tempdb..#MPLIST2') IS NULL
    begin
        select 'hellooo'
        --create table #MPLIST2 (MeteringPointId varchar(18) COLLATE SQL_Danish_Pref_CP1_CI_AS)
    end

This part executes succesfully without 'hellooo'. But if I comment in the "create table' line below, then it gives the error "There is already an object named '#MPLIST2' in the database."

If Statement in Arguments

im currently coding a Chat-Bot, for his answers I made the method following method:

// Choose Randomly From Given Answers
public String chooseAnswer(String... strings){
    int i = (int) strings.length;
    int random = (int)(Math.random() * i); 
    return strings[random];
}

That works totally fine. Now the following problem occurs: If the bot doesnt understand what the user said, he displays a random question or statement, for example.

chooseAnswer("Sounds great", "Whats your favorite color?", "Whats your favorite food?", "Tell me something");

The User can now answer, for example what his favorite color is. If he answered that once, the bot should never choose the question about his color again.

I have a variable for that, that counts how many times the user said something about his favorite color, so that isnt the problem.

Now it would be great if something like that would work:

chooseAnswer("Sounds great", if(favorite_color_count == 0){"Whats your favorite color?"}, "Whats your favorite food?", "Tell me something");

This obviously doesnt work.

I think i need an if statement outisde, but there are so many cases, because I have about 50 standard questions, so i would have to make one for every case und thats like i dont know.. 50+49+48...+2+1?

Has someone an idea how to handle this?

Unexpected else

I am grappling with the error:

unexpected 'else' (T_ELSE) i

My code is:

<div class="ship_amt">
<?php if(!empty($custarea)){ ?>
    <a>
     Minimum Order Amount -
     <?php 
        echo $areaMinAmt;
     ?>
    </a>
    <?php} ?>
    <?php else { ?>
    <a>
        Choose area to know min delivery amount
    </a>                                                            
    <?php }?>
</div>

What am I doing wrong?

Bash script if -eq

New to bash script, i need to check if the first word in Group equals the second word in Users.

Group=`echo $rules | egrep -v 'Test'`
Users=`echo $rules | grep -i 'Test' | awk '{print substr($0, index($0,$2))}'`

if [ '$Group' -eq '$Users' ];
then
echo $Group
echo $Users

else
:
fi

Can I use something like this or how is this possible?

if [ '$Group $1' -eq '$Users $2' ];

or

if [ '^$Group' -eq '^$Users' ];

if statement in a php code

I have a code that will display data in a table form. there is a field called value that will store some values. I need to have an if statement that will force a window to popup whenever the value exceeds 30. I have an if statement that is not working. can anyone help ??

this is the code I used

<?php

$link = mysql_connect("localhost", "root", "");
$select= mysql_select_db("");
mysql_select_db("form");


$query = mysql_query("SELECT * FROM demo ORDER BY parameter ASC");
$record = mysql_fetch_array($query);
echo "<table border=1
<tr>
<th>Record ID</th>
<th>Parameter</th>
<th>Value</th>
<th>Time</th>

</tr>";
$con = mysql_connect("localhost", "root", "");
//$query = "select * from demo";

$query1 = mysql_query("Select * from demo where parameter = \"conductivity\"");
    while($row = mysql_fetch_array($query1)){

        echo " <tr><td>" . $row["recordID"] . "</td><td>" . $row["parameter"] . "</td><td>" . $row["value"] . "</td><td>" . $row["time"]  . "</td><tr>";

    }

if ("value">"30"){
echo "<script>alert('Alert');</script>";
}



echo "</table>";



mysql_close($link);



?>

What is wrong with my IF function in Excel?

I would like some feedback on the following formula for the specified range, this code seems to work on my laptop but not my desktop for an unknown reason.

68 & below = "Within Alert Level"

Inclusively between 69 and 98 = "Exceeded Alert Level"

99 & Above = "Exceeded Suspension Level"

=IF(A1>=99; "Exceeded Suspension Level"; IF(A1>=69; "Exceeded Alert Level"; IF(A1<=68; "Within Alert Level")))

jeudi 28 avril 2016

Batch file to print first match of findstr results only to text file

Im trying to write a batch file that reads a list from fileA.txt then checks fileC.txt if match exists, if match not exist write first matching line only from fileB.txt to fileC.txt

fileA.txt example

aaa1
aaaa
aaaa4
bbb
ccc12

fileB.txt example

aaa1 some text
aaa1 blah bla
aaa1 .r
aaaa some info
aaaa blah bla
aaaa4 some name
bbb some name to
bbb more blah blah
ccc12 another name
ccc12 blah bla

resulting fileC.txt

aaa1 some text
aaaa some info
aaaa4 some name
bbb some name to
ccc12 another name

What Im trying to do

for /F %%i in (C:\filecopy\fileA.txt) do (
If exist (findstr /B /C:%%i fileC.txt) (
echo %%i exists ) else (
findstr /B /C:%%i fileB.txt >> fileC.txt )
)

But that code isnt correct and im not sure how best to handle it

Code to solve a system of conditional binary equations

I have a set of dependent and independent boolean variables with given rules. I am trying to find the values of independent variables to satisfy all the rules.

For example, n1,n2,n3 and out are dependent boolean variables and a,b,c are independent boolean variables. How to search for all values of a,b,c such that out will be 1? Is there any code already available to solve this kind of problems?

n1=0 if a!=b;
n1=a if a==b;
n2=a if a!=b;
n2=1 if a==b;
n3=~n1 if b!=c;
n3=n2 if b==c;
out=~n3;

How to make a matrix to the power of a number under some conditions without using loops in Python?

I would like to compute this simple code in python, given a matrix modify it according to its entries. If the (i, j)-th entry is greater than or equal to 1 then make it to the power of a else make it 1.

import numpy 

def restricted_power(k, n, d, a):
    """
    :param d: a distance matrix
    :param k, n: shape of d
    :param a: a positive real number 
    :return: a modified distance matrix 
    """
    x = numpy.zeros((k,n))
    for i in range(k):
        for j in range(n):
            if d[i, j] < 1:
                x[i, j] = 1
            else: 
                x[i, j] = d[i, j] ** a
    return x

Is there a way to code this without the loops ?

Two workbooks, Same Sheets Names: Copy and Paste if Sheets are matched

I have two workbooks, with same sheets name (but in different order), and I'd like to copy info of all of the sheets of one workbook, and pasting that info in the respective sheet of the other workbook (matching sheet names). I feel like this code is on track, but maybe there is a more efficient or cleaner way to do this. Code is working, but it says a warning like " there's a big amount of data in the windows clipboard... etc... "

Sub ActualizarNoticias()
     Dim aw As Workbook
     Dim y As Workbook

Set aw = Application.ActiveWorkbook
Set y = Application.Workbooks.Open("G:\Estudios\Biblioteca\Mercado Accionario Chileno\BBDD Oficial.xlsm")


For i = 1 To aw.Sheets.Count
For j = 1 To y.Sheets.Count

If aw.Worksheets(i).Name = y.Worksheets(j).Name Then

y.Worksheets(j).Range("A3").Copy
aw.Worksheets(i).Range("A100").PasteSpecial
End If

Next j
Next i

y.close
' ActualizarNoticias Macro
'
'
End Sub

if else statement in PHP for Magento Site, need to hide on Homepage, checkout and success page

Here's what is currently working with not displaying on the homepage. And displaying on all other pages, need help not displaying on /checkout/cart/ and /onepage/ and onepage/successs.

<?php if(Mage::getBlockSingleton('page/html_header')->getIsHomePage()): ?>
<?php else: ?>

(Div I am trying to display only on pages other than homepage,checkout,success)

<?php endif; ?>

if($p > 0 && $p <= 1 not worsk in tho decimals

i put this code for calculate price in a function Getprecio.

un producs under cost price its under 1 for example 0.2 or 0.02 this function not woorks `` Why ?

This its the code:

 function getPrecio($p)

{

if($p > 0 && $p <= 1) return $p*1.99;

}

C# Pairing The Elements of 2 Array For Once

I'm working on fixture project(still :) ) and trying to assign teams with each other.I have 18 teams and half of this is playing at home and the other half is playing at away.I created 2 structs.First struct is named "Teams" and holds the infos about each team(it's code is at below)

public struct Teams                        
    {
        public String name;                    
        public int[] day;                     //It's match day
        public int[] dayCount;                //Holds how much time the theam played match at days
        public bool isMatching;      
        public bool TeamPlace;                 //true=plays at home - false plays at away
        public bool isUefa;                    //Is team plays at Uefa
        public bool isCL;                      //Is team plays at CL
        public int extraMatchDay;              
        public int extraMatchWeek;             
        public bool extraMatchInfo;          //If team has extra match?
        public int[] rivals;                //holds team's previous rivals

        public void CreateArray()
        {
            day = new int[34];
            dayCount = new int[4];  //0->pzt  1->cuma   2->cmt   3->pzr
            rivals = new int[17];
            extraMatchWeek = 1; 

            for (int i = 0; i < rivals.Length; i++)
            {
                rivals[i] = -1;
            }
        }

        public void NULL()
        {
            name = null;
            TeamPlace = false;
            isUefa = false;
            isCL = false;
            Array.Clear(day, 0, day.Length);  //clear the day array
        }
    }

Second struct is named "matchedTeams" and holds the infos about the competitions.(it's code is at below)

public struct matchedTeams  //holds competitions
    {
        public Teams team1;
        public Teams team2;
        public int MatchDayDate; 

        public void CreateArrayFromTeams() //the objects from Teams struct which uses the function thet "CreateArray" from "Teams" struct encountered the NULLException error so I had to create them again.
        {
            team1.CreateArray();
            team2.CreateArray();
        }

        public void NULLmatched()
        {
            team1.NULL();
            team2.NULL();
            MatchDayDate = 0;

        }

        public void EqualTheDays(int i)
        {

            team1.day[i] = this.MatchDayDate;
            team2.day[i] = this.MatchDayDate;
        }
    }

And I seperated and assigned teams to 2 array."Home" and "Away" arrays.And assigned 2 teams from these 2 arrays(1 team from each array) to matchedTeams' "team1" and "team2".But I want that each team pairs once with each other.I tried it but I failed.My code is at below:

public static void ShuffleTeamsWithoutWeek(int weekDay, int[] randomHomeNumArray, int[] randomAwayNumArray, matchedTeams[,] weeklyMatched, matchedTeams[] matchTeams, Teams[] home, Teams[] away, Teams[] teams)
    {

        int randomHome; //It indicates the element which will be chosen from Home Array
        int randomAway; ////It indicates the element which will be chosen from Away Array

        Random randomNum = new Random();

        for (int j = 0; j < weekDay; j++)
        {
            for (int i = 0; i < weeklyMatched.GetLength(1); i++)
            {
                weeklyMatched[j, i].CreateArrayFromTeams(); //weeklyMatched is a 2 dimensional array instantiated from matchedTeams struct and it's size is weeklyMatched[34,9]
            }
        }

        for (int week = 0; week < weekDay; week++)
        {

            if (week < weekDay / 2)
            {

                for (int i = 0; i < 9; i++)   //It equals the elements of 2 arrays to -1
                {
                    randomHomeNumArray[i] = -1;   //Holds the random numbers for Home array
                    randomAwayNumArray[i] = -1;  //Holds the random numbers for Away array
                }

                for (int homeArrayCounter = 0; homeArrayCounter < randomHomeNumArray.Length; homeArrayCounter++)
                {
                    randomHome = randomNum.Next(home.Length);    

                    if (!randomHomeNumArray.Contains(randomHome))
                    {
                        randomHomeNumArray[homeArrayCounter] = randomHome;   
                        //Console.WriteLine(homeArrayCounter + ". iterasyon in Home " + randomHomeNumArray[homeArrayCounter]); 
                    }
                    else
                    {
                        homeArrayCounter--;
                    }
                }
                for (int awayArrayCounter = 0; awayArrayCounter < randomAwayNumArray.Length; awayArrayCounter++) 
                {
                    randomAway = randomNum.Next(randomAwayNumArray.Length);    

                    if (!randomAwayNumArray.Contains(randomAway))
                    {
                        randomAwayNumArray[awayArrayCounter] = randomAway;     
                    }
                    else
                    {
                        awayArrayCounter--;
                    }
                }
                int RivalCounter = 1;

                for (int c = 0; c < 9; c++) //There are 9 matches each week
                {
                    if (weeklyMatched[week, c].team1.isMatching == false)  //choose a team from unchosen ones
                    {
                        weeklyMatched[week, c].team1 = home[randomHomeNumArray[c]];

                        weeklyMatched[week, c].team1.isMatching = true;
                    }

                    if (weeklyMatched[week, c].team2.isMatching == false)   choose the second team from unchosen ones
                    {
                        weeklyMatched[week, c].team2 = away[randomAwayNumArray[c]];

                        if (weeklyMatched[week, c].team1.rivals[RivalCounter] != Array.IndexOf(teams, (weeklyMatched[week, c].team2))) //if team 1 didn't encountered with team2 before
                        {
                            weeklyMatched[week, c].team1.rivals[RivalCounter] = Array.IndexOf(teams, (weeklyMatched[week, c].team2));//assign team as team2
                            weeklyMatched[week, c].team2.isMatching = true; 

                        }
                        else {
                            RivalCounter--; //I'm not sure about this line
                        }
                        RivalCounter++;
                    }
                }
            }
        }
    }

The output is here: Output Code

Thanks for your kind helps.

PHP in_array() not working properly

I have an if statment below that checks if a value is present in an array and adds it in there if it's not. Apparently even if the value is in the array, it triggers it again.

As far as I understand, it should only display 1 of each value, because it will only trigger 3 times, like this:

Digital Photography -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0

The code:

if (!in_array($unit['course_name'], $courseList)) {

  $courseList[$unit['course_name']]['name'] = $unit['course_name'];
  $courseList[$unit['course_name']]['seconds'] = 0;
  echo $courseList[$unit['course_name']]['name'] . ' -> ' . $courseList[$unit['course_name']]['seconds'];
  echo "<BR>";

}

But it outputs:

Digital Photography -> 0
Step by Step Macintosh Training -> 0
Step by Step Macintosh Training -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
How to become a Powerful Speaker -> 0

Here is the var_dump($unit):

array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(19) "Digital Photography" [1]=> string(19) "Digital Photography" ["unit_id"]=> string(3) "181" [2]=> string(3) "181" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "227" [2]=> string(3) "227" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "231" [2]=> string(3) "231" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "233" [2]=> string(3) "233" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 
array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(32) "How to become a Powerful Speaker" [1]=> string(32) "How to become a Powerful Speaker" ["unit_id"]=> string(4) "1080" [2]=> string(4) "1080" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 
array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(32) "How to become a Powerful Speaker" [1]=> string(32) "How to become a Powerful Speaker" ["unit_id"]=> string(4) "1084" [2]=> string(4) "1084" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" } 

Thank you for any help!

Nested IFELSE in adding a column to a data frame

I am trying to add a column to a data frame conditioned on values in existing column.

Data Frame:- df

Country

India
Mexico
Germany 

I am now adding the Continent Column based on the country value.

df$Continent <- ifelse(df$Country=="India","Asia","Europe")

Output:-

Country   Continent 
India       Asia
Mexico      Europe
Germany     Europe

This leads to Mexico being categorized as in Europe. How can I add more if statements or it would be helpful if someone can hint me an alternate method?

How to have multiple conditionals in an if statement in Ada

How would I go about having multiple conditionals in an if statement?

Eg. The user is asked a set of questions by the program:

1.) Enter an altitude between 0 and 1000

(user types in data)

2.) Enter Velocity between 0 and 500

(user types in data)

3.) Enter Temperature between 0 and 200

(user types in data)

the program then prints back

  1. altitude = user value
  2. velocity = user value
  3. temperature = user value //ignore those list numbers

I have set in my (.ads) file that each of these ranges has a criticle value.

I want to create an if statement that has multiple conditionals. in pseudo : If velocity = critical velocity & temperature = critical temperature & altitude = critical altitude then print ("some message") else do nothing

BAT: Script that makes DNS changed automatically

Im from abroad USA and i pretty like Pandora and Netflix. That's why I insisted to change my DNS by one click. I wrote some code, but it doesnt work and i have no idea, why it doesn't. Here it is:

Echo On IF netsh interface ipv4 set dnsserver "Wi-Fi" source=dhcp==netsh interface ipv4 set dnsserver "Wi-Fi" source=dhcp DO ( netsh interface ipv4 add dnsserver "Wi-Fi" 46.101.36.120 netsh interface ipv4 add dnsserver "Wi-Fi" 46.101.149.135 index=2 ECHO DNS has changed to specific. ) ELSE ( netsh interface ipv4 set dnsserver "Wi-Fi" source=dhcp ECHO DNS has changed to automatic. ) ipconfig /flushdns

Even can't check what's wrong, because the cmd exits automatically. Each one of the command works, so did i mess up with the "if"? Help would be appreciated <3

Match List of Numbers in For Loop in Bash

I have a script that loops over a curl command, which pulls in data from an API.

LIST_OF_ID=$(curl -s -X POST -d "username=$USER&password=$PASS&action=action" http://link.to/api.php)

for PHONE_NUMBER in $(echo $LIST_OF_ID | tr '_' ' ' | awk '{print $2}');
do
  $VOIP_ID = $(echo $LIST_OF_ID | tr '_' ' ' | awk '{print $1}')
done

I also have a variable of 16 numbers in the range of "447856321455"

NUMBERS=$(cat << EOF
441111111111
441111111112
441111111113
... etc
)

The output on the API call is:

652364_441111111112

As you may notice I have taken the output and cut it into 2 parts and put it in a variable.

What I need is to match the 6 digit code from the output where the number in the output, matches with the number in the variable.

I've attempted it using if statements but I can't work my head around the correct way of doing it.

Any help would be appreciated.

Thank you.

If condition that pushes values that contain/match a string

I have a nicely functioning full calendar script. I have some filters for it, which basically have the following form:

$("input[name='event_filter_select']:checked").each(function () {
    // I specified data-type attribute in HTML checkboxes to differentiate
    // between risks and tags.
    // Saving each type separately
    if ($(this).data('type') == 'risk') {
        risks.push($(this).val());
    } else if ($(this).data('type') == 'tag') {
        tagss.push($(this).val());
    }
});

However the else if statement should check if the checked value 'tag' is contained within the result set, not be the only value of the result set (as implied by the ==).

Now I can only filter results that have the checked tag-value only. But i want to filter those, which have the tag-value amongst many others.

I figure this is to be done with match(/'tag'/) but i cannot figure out for the life of me how to put that into an if-statement.

Would be really glad if someone could lead me in the right direction.

Shortening Code - DateTime & ELSE IF Statement - Making it Dynamic

I've got a big list of start and end DateTimes to calculate the user's Zodiac sign.

If the User's Birthday is between this date, the application spits out the relevant star sign.

I'm trying to cut my code down to that I can make it so that the Developer (me) can input additional Star Signs without having to specify a name and dates.

So for example:

(If UserBD >= DateStart && UserBD <= DateFinish)
{
  Console.WriteLine(“Your star sign is {0}”, StarSign);   
}

At the moment I have the following:

    DateTime AquariusStart = new DateTime(userBD.Year, 01, 20);
    DateTime AquariusEnd = new DateTime(userBD.Year, 02, 18);

    DateTime PiscesStart = new DateTime(userBD.Year, 02, 19);
    DateTime PiscesEnd = new DateTime(userBD.Year, 03, 20);


    if (userBD >= AquariusStart && userBD <= AquariusEnd)
    {
        Console.WriteLine("Your Star Sign is Aquarius!");
    }
    else if (userBD >= PiscesStart && userBD <= PiscesEnd)
    {
        Console.WriteLine("Your Star Sign is Pisces!");
    }

etc etc

What would I need to add in order to be able to make the code 'dynamic'?

Thanks in advance! :)

condition has length > 1 - if or ifelse? Vector or matrix?

I create a matrix

y <- matrix(as.numeric(x > mean(x)), nrow = nrow(x))

and would like to calculate certain predictors on this data. However, some conditions do not have enough observations and I get NA (always 80 of them). That is OK, but I would like the other elements to be calculated. When I write:

if (is.na(y) != 80) {
    corr <- cor(as.numeric(y),as.numeric(z))} 
else { data$corr[trial] <- NA }

I get the error message that the condition has length > 1 and only the first element will be used. So apparently R sees y as a vector? But when I type is.vector(y) the output is FALSE. How can I adapt my code? Or is my thinking wrong?

If...Else Statements within quotes

I want merge if else statement within my string bellow. When I try it I get Uncaught SyntaxError: Unexpected token if in my browser console. How can I do it...

        for(var i=0; i<articles.length; i++) {

            var $article = "<div class='col-xs-12 col-sm-6 col-md-3 col-lg-3 fix-box-height'>" +
                "<a class='shadow-hovering' href="+"'"+articles[i].full_url+"'"+">" +
                "<div class='thumbnail color-after-hover'> " +
                "<img class='thumbnail-img' src="+"'"+ articles[i].thumbnail_url +"'"+" data-src='3' alt=''>" +
                "<div class='caption box-read-more'>"+
                    if(articles[i].title.length > 28){
                        "<h4>"+"'"+ articles[i].title.substr(0, 28) +"'..."+"</h4>"
                    } else if (articles[i].title.length > 16) {
                        "<h4>"+"'"+ articles[i].title +"'"+"</h4>"
                    } else {
                        "<h4>"+"'"+ articles[i].title +"'"+"</h4> <br>"
                    }
                    if(articles[i].subtitle.length > 37){
                        "<h4>"+"'"+ articles[i].subtitle.substr(0, 37) +"'..."+"</h4>"
                    } else if (articles[i].subtitle.length > 15) {
                        "<h4>"+"'"+ articles[i].subtitle +"'"+"</h4>"
                    } else {
                        "<h4>"+"'"+ articles[i].subtitle +"'"+"</h4> <br><br>"
                    }
                    +"<p> <span class='btn btn-primary more-box-button'>More</span> </p> " +
                    "</div>" +
                    "</div>" +
                    "</a>" +
                    "</div>";
        }

Why the R loop did not work

I had a data frame with 184 obs. of 5 variables:

'data.frame':   184 obs. of  5 variables:
     $ Cat     : Factor w/ 10 levels "99-001","99-002",..: 1 1 1 1 1 1 1 1 1 1 ...
     $ No      : int  1 1 1 1 1 1 1 1 1 1 ...
     $ ehs     : int  0 0 0 0 0 0 0 0 0 0 ...
     $ Onset   : int  0 0 0 0 0 0 0 9 9 9 ...
     $ STARTING: Factor w/ 149 levels "1:37PM1","1:42PM1",..: 3 4 5 63 64 65 66 67... 

The data frame comes from a repeated measurement study, that means each case was measured several times:

Now I want to create a new variable (provoke) by judging the onset situation of each case. If the onset is "0" first, than the new variable (provoke) will be coded as "0", otherwise "1".
The R script of mine :

no1 <- seq[seq$No == 1, ]
if (no1[1,4]==0) {no1$provoke =0} else {no1$provoke =1}
no2 <- seq[seq$No == 2, ]
if (no2[1,4]==0) {no2$provoke = 0} else {no2$provoke = 1}    

For the large case number, I intend to write a loop to finish the task

 for (i in 1:10) {    
 noi <- seq[seq$No == i, ]    
 if (noi[1,4]==0) {    
 noi$provoke = 0}     
 else {noi$provoke = 1}    
}

but the loop seems not functioned. Could you please help me find out the bug or point out my mistake?

mercredi 27 avril 2016

c# if else statement

i am having a problem with an if-else statement (note: i am fairly inexperienced with programming) using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;

            Console.WriteLine("Please enter a number between 0 and 10:");
            number = int.Parse(Console.ReadLine());

            if(number > 10)
                Console.WriteLine("Hey! The number should be 10 or less!");
            else
                if(number < 0)
                    Console.WriteLine("Hey! The number should be 0 or more!");
                else
                    Console.WriteLine("Good job!");

            Console.ReadLine();
        }
    }
}

I use mono for compiling. i got these errors:

testif.txt(10,11): warning CS0642: Possible mistaken empty statement

testif.txt(13,9): error CS1525: Unexpected symbol `else'

IF folder exist , create other folder c# [duplicate]

This question already has an answer here:

Hi everyone I have problem related to folders. I have 2 datetimepicker and I want to program create relevant between this datetimepickers .But if program find first folder exist , doesn,t create other folders

How to find 3 largest even numbers in an array with C?

I need to find 3 largest numbers in an array and then add them together.

For example: Input: 3 4 7 10 11 16 16 23 26 Output: The sum of the 3 largest even numbers are: 16, 16, 26. The sum is 58

In my code, I'm getting weird outputs like "16, 1245782582792, 1".

Note: I can only use ifs/else, for/while loops, and arrays for this.

#include <stdio.h>

#define MAX_NUMBERS 13

int main(void) {

int nNumbers, i;
int even_sum;
int array[MAX_NUMBERS];
int greatest1, greatest2, greatest3;

//Reading the numbers
scanf("%d", &nNumbers);
for(i = 0; i < nNumbers; i++) {    
    scanf("%d", &array[i]);
}

//Finding largest even numbers
greatest1 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
    if(array[i] > greatest1 && array[i] % 2 == 0){
        greatest1 = array[i];
    }
}

greatest2 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
    if(array[i] > greatest2 && array[i] % 2 == 0 && array[i] != greatest1){
        greatest2 = array[i];
    }
}

greatest3 = array[0];
for(i = 0; i <= MAX_NUMBERS; i++){
    if(array[i] > greatest2 && array[i] % 2 == 0 && array[i] != greatest1 && array[i] != greatest2){
        greatest2 = array[i];
    }
}

even_sum = greatest1 + greatest2 + greatest3 + 2;

printf("The largest even numbers are %d, %d, %d. The sum is %d.\n", greatest1, greatest2, greatest3, even_sum);

return 0;

}

Why is the switch statement to be avoided in Java?

One of my teachers said that we should avoid using the switch statement. Why? what's bad about it?

I find it to be useful if you have an if statement with 4 or 5 else if. With the switch once it hits what it's looking for, it leaves the switch block. While with an if, else if statement, it will verify every else if even if it "entered" one already.

BASH : find fileX[1-20] in directory Y and look if fileX[1-20].pid exist

I hope you're having a great day and sorry about the title, I didn't know how to write it in a way everyone could understand what I'm stuck with.

So far, I have made this code (bash/linux):

    RESEARCH=`find $DIRECTORY_NAME -type f -name "$PROGRAM_NAME[1-9]" -perm -ugo=x`
    while [ #That's where I'm stuck (see below for explanation) ]
    do
        if [ #$PROGRAM_NAME[X] don't have an existing pid file ($PROGRAM_NAME[X].pid) ]
        then
            echo "Starting $PROGRAM_NAME[X]..."
            ./$PROGRAM_NAME[X]
            echo "$PROGRAM_NAME[x] started successfully!"

        else
            if [ #Number of $PROGRAM_NAME < 9]
            then
                echo "Compilation of $NEW_PROGRAM[X]..."
                gcc -Wall tp3.c -o $DIRECTORY_NAME/$NEW_PROGRAM[X]
                echo "$NEW_PROGRAM[X] compiled with success!"
                echo
                echo "Starting $NEW_PROGRAM..."
                ./$NEW_PROGRAM[X]
                echo "$NEW_PROGRAM[X] started successfully!"

            else
                echo "The number of process running is at its limit."
            fi
        fi
    done

I think it's easy but I don't know how to do it ... What I want is to check if every $PROGRAM_NAME[X] (where X CAN range from 1 to 9) have an associated PID file. If not, start $PROGRAM_NAME[X].

So to do so, I think I must loop like Y time (where Y is the number of $PROGRAM_NAME[X] in DIRECTORY_NAME) and check them one by one...

For exemple, if I do ls $DIRECTORY_NAME, that would be like this :

  prog1
  prog1.pid
  prog2
  prog2.pid
  prog3
  prog4
  prog4.pid

So I would like to start prog 3 and not create prog5 since not all element have a existing pid file.

Could anyone explain me more about the while condition?

Is there some form of else that can be used inside of a switch-case? Java [duplicate]

This question already has an answer here:

Say you want to replace a long chain of if's with a switch-case, how do you handle a possible input that is not one of the cases that you have set. For example:

switch(medicalPlan) {
                    case 3: employeeList.add(new FullTime(inLast, inFirst, 
                            inSoc, inSal, NO_PREMIUM, NO_OFFICE, 
                            NO_HOSPITAL));
                    break;
                    case 2: employeeList.add(new FullTime(inLast, inFirst, 
                            inSoc, inSal, LOW_PREMIUM, LOW_OFFICE, 
                            LOW_HOSPITAL));
                    break;
                    case 1: employeeList.add(new FullTime(inLast, inFirst, 
                            inSoc, inSal, HIGH_PREMIUM, HIGH_OFFICE, 
                            HIGH_HOSPITAL));
                    break;
                }//end of switch case for medical plan

Is there some form of else that can be used inside of a switch-case?

Wrote a nested if else procedure that returns the answer AND "none". Why?

def is_friend (name): if name[0] == 'D': print 'yes' else: if name [0] == 'N': print 'yes' else: print 'no'

print is_friend ('Eric') no None

Column vector with for loop and if statement - IndexError: too many indices for array

I am trying to create a binary column vector (y3) based on a comparison of two lists. For each element of both list, if one is bigger than the other, 0, if not ,1. The result (ones and zeroes) being stored in y3.

t=5
list1 = data[:t,0]  # Extrated from data = np.array(list(...
list2 = data[:t,1]  # Same
for i in range(t):
    if list1[i]<=list2[i]:
        y3[i]=0
    else:
        y3[i]=1

I get an "IndexError: too many indices for array". What is wrong with the code? Thank you for your valuable help.

Java beginning if statement in for loop being skipped while others work

Back again with another problem that has stumped me completely and cannot for the life of me fix.

So I had previously posted a question about my Java game I am making for a class that with the help of @MadProgrammer was fixed...mostly. Now there is a new problem that needs a post all to it's own

Previous Post: EDITED: Rows and columns with multidimensional array java

Problem: In the code below I have it set up to loop through the variables x and y to make rows and columns on a jPanel. Each time it loops through it should randomly mark the "x,y" location with one of the "terrains" so that later it can "paint" that location with the appropriate colored 20x20 square.

The code runs great except for one thing, it looks like it skips the very first "if statement" that marks the "terran[0]" which is "floor". When the code is ran it "paints" the other three "terrains" and not a single "floor" "terrain".

I have looked for a solution on these posts but no success:
Java if statement is skipped
If statement being skipped during execution
Java - for loops being skipped
Java if-statement being skipped

Here is a working piece of code that results in the problem at hand:

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

public class gamePanel extends JPanel
{   

    public gamePanel()
    {
        setBounds(115,93,480,480);
    }

    private Random generator = new Random();    

    int floor = 0; //initializes the variable floor to zero for later use
    int dirt = 1;
    int stone = 2;
    int water = 3;

    int width = 24;
    int height = 24;    
    int x, y; // my x & y variables for coordinates

    int[][] coords = new int[width][height]; //my array that I want to store the coordinates for later use in painting


    int[] terrain = {floor, dirt, stone, water}; //my terrain that will determine the color of the paint

    public void mapGen() //what should mark/generate the JPanel
    {
        for(x = 0; x < width; x++)
        {

            for(y = 0; y < height; y++)
            {

                int z = generator.nextInt(20);// part of the randomization

                if(z <= 10)
                {
                    coords[x][y] = terrain[0]; //should mark the coordinates as floor

                }

                if(z == 11)
                {
                    coords[x][y] = terrain[3];//should mark the coordinates as water
                }

                if(z >= 12 && z <= 16)
                {
                    coords[x][y] = terrain[2];//should mark the coordinates as stone
                }

                if(z >= 17 && z <= 19)
                {
                    coords[x][y] = terrain[1];//should mark the coordinates as dirt
                }

                    coords[0][0] = terrain[0]; // sets coordinate 0,0 to floor //need to have these always be floor
                    coords[23][23] = terrain[0]; // sets coordinate 24,24 to floor //^^^^^^^^^^
            }
        }


    }   


    @Override
    public void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
    {
        super.paintComponent(g);

        for(int x = 0; x < width; x++)
        {
            for(int y = 0; y < height; y++)
            {
                mapGen();

                if(coords[x][y] == terrain[floor])//should paint the floor color at marked coordinates
                {
                    g.setColor(Color.white);
                    g.fillRect((x*20), (y*20), 20, 20); 

                }

                if(coords[x][y] == terrain[dirt]);//should paint the dirt color at marked coordinates
                {
                    g.setColor(new Color(135,102,31));
                    g.fillRect((x*20), (y*20), 20, 20);
                }

                if(coords[x][y] == terrain[stone])//should paint the stone color at marked coordinates
                {
                    g.setColor(new Color(196,196,196));
                    g.fillRect((x*20),(y*20),20,20);
                }

                if(coords[x][y] == terrain[water])//should paint the water color at marked coordinates
                {
                    g.setColor(new Color(85,199,237));
                    g.fillRect((x*20),(y*20),20,20);
                }
            }
        }

    }//end paintComponent

public static void main(String[] args)
{
    gamePanel panel = new gamePanel();
    JFrame frame = new JFrame();
    frame.setSize(500,550);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.setVisible(true);

}//end main

}// end gamePanel

Please keep in mind that I am a novice programmer and I am still learning. So anything that is not considered "basic" code please explain in detail.

Is if statement optimized to not call recursive functions if first condition is false?

Consider the scenario:

int fun(node* a, node* b){
    if(a == NULL && b == NULL) return 0;
    if( (a->data == b->data) && (fun(a->left) == fun(b->left)) && (fun(a->right) == fun(b->right)) return 1;
    return 0;
}

If we met a condition like if a->data != b->data, then will the recursive call be made to (fun(a->left) == fun(b->left)) and (fun(a->right) == fun(b->right)) or will it directly say false for the condition?

Javascript variable with InnerHtml not working

I'm coding a game and in the game when you die I want a specific game over text to be displayed according to the score using innerHTLM and if/else if

I followed some tuts but it doesn't seem to work and don't know why.

Here's the code :

<div id="game-over">
      <h3><font color="orange">Tu as courus <span id="score"></span> mètres.</font></h3>
      <font color="orange"><h1 id="customegotext">Error text not found</h1></font>
      <a href="javascript:void(0)" class="button restart">Ressayer ?</a>
    </div>
  </div>
  <script>
    var scoretext;
    if ("score" < 45) {
        scoretext = "Text1";
    } else if ("score" > 100 ) {
        scoretext = "Text2";
    } else if ("score" > 500 ) {
        scoretext = "Text3";
    } else if ("score" > 750 ) {
        scoretext = "Text4";
    }
    document.getElementById("customegotext").innerHTML = scoretext;
</script>

More details :

  • The variable "score" is calculater in a separate .js file specifed in the index.html ( file where the error is present ) by this line of code

<script type="text/javascript" src="ljdm.js"></script>

  • The game works perfectly ( .html, .js and .css are correctly related by code )

  • I'm a beginner into programming

Thanks for helping me !

Getting "syntax error near unexpected token `else’" in shell script

I’m using bash shell on Amazon Linux. When I run the below block of code

if [ $rc -eq 0 ] then
  passed=`tr ' ' '\n' < $TFILE | grep -c PASSED`
  error=`tr ' ' '\n' < $TFILE | grep -c ERROR`
  warning=`tr ' ' '\n' < $TFILE | grep -c WARNING`
  subject="Automated Results - $passed passed, $error errors, $warning warnings."
else
  subject="Failed to run any tests."
fi

I get the error, “syntax error near unexpected token `else’”. What do I need to do to write this if-then-else block correctly?

if else dividing in BASH [duplicate]

This question already has an answer here:

I am doing a school assignment in bash and got this code:

if a < 0
    a = a/b
else
    a = b/a
fi

The assignment says that we need to divide two number read from the keyboard, and check if the first number is larger than the number 0.

echo "Write two numbers, with a space, that need to be divided:"
read a b
  if a > 0
    a = $a / $b
  else
    a = $b / $a
fi

echo "$a"

What am I doing wrong here?

if(a = 1) is true [duplicate]

This question already has an answer here:

I don't know if it's possible duplicate. Testing my code, sometimes I was wrong with because I put = and not == or === in if conditions:

Consider this code :

var a = 0;
if(a = 1) console.log('true'); 

I don't know why this is not an error and why returns true the condition (a = 1) I guess that what it does is assign 1 to the a variable, but why this evaluates to true and there's no error?

How to modularise reactive output in Shiny (that includes if statement)?

Up until recently, I had been repeating the same reactive statements within each output of the server object.

server <- function(input, output) {
 output$MeanResult <- renderText({
   if(input$Posi != "All"){
     ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   mean(ProjDt[[input$Metric]])
 })
 output$hist <- renderPlot({
   if(input$Posi != "All"){
     ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   hist(ProjDt[[input$Metric]])
 })
} 

This seems to produce the desired result but I would like to avoid duplicating the reactive part of each output.

I therefore attempted to 'modularise' the reactive part of the code before passing it to the output statements such that:

server <- function(input, output) {
 ProjDt <- reactive({
   if(input$Posi != "All"){
      ProjDt <- ProjDt[ProjDt$Pos == input$Posi,]
   }
   ProjDt <- filter(ProjDt, TimeToKO < input$TimeKO)
   ProjDt <- ProjDt[[input$Metric]]
 })
 output$MeanResult <- renderText({
   mean(ProjDt())
 })
 output$hist <- renderPlot({
   hist(ProjDt())
 })
}

I've played around with it quite a lot but I can't get the desired result. The main error I get is that 'object of type 'closure' is not subsettable'.

I'm relatively new to Shiny so I feel like I'm missing something quite fundamental.

What do I need to do get the modularised reactive output to work?

Detect which condition is false in multiple if statement

I try to shorten my code, and so I come along to shorten the following type of if statement:

// a,b,c,d needed to run
if ( empty(a) ) {
    echo 'a is empty';
} elseif ( empty(b) ) {
    echo 'b is empty';
} elseif ( empty(c) ) {
    echo 'c is empty';
} elseif ( empty(d) ) {
    echo 'd is empty';
} else {
  // run code with a,b,c,d
}

Is there a way to detect which one of the conditions was false (is emtpy)?

if ( empty(a) || empty(b) || empty (c) || empty(d) ) {
     echo *statement n*.' is empty';
} else {
  // run code with a,b,c,d
}

I tought about a for loop, but that would need massive code changes. Maybe someone can point me to the right direction.

Thanks in advance :)

Jens

Excel VBA Copy one cell from some sheets and save on the another sheet

I have 5 sheets : graph, sheet1, sheet2, sheet3 and list. I have to copy the cell B3 from sheet1 and paste on graph in the cell C2, cell B3 from sheet2 to graph after B3 from sheet1 (cell C3) etc. But I can't touch the sheet list.

nbrows = Range("A" & rows.Count).End(xlUp).Row
For y = 2 To nbrows   
    Workbooks("JiraKPI.xlsm").Activate
    Worksheets(Worksheets("Sheet" & y).Range("B3").Copy
    Worksheets("Graph").Select
    If Range("C2") <> ("") Then
        Range("$D65536").End(xlUp).Offset(1, 0).Select
        Selection.PasteSpecial Paste:=xlPasteValues
    Else
        Range("C2").Select
        ActiveSheet.Paste
    End If
Next y

EditText checking

I'm trying to check an EditText value, but the application crashes.
How can I handle my EditText?

        String stra_txt = edit_1.getText().toString();
        boolean first = false;
        if (stra_txt.equals("1") || stra_txt.equals("0"))
            {
                first = true;
            }
        else
            {
                first = false;
            }

        if(first = true)
            zheg();
        else
        {System.exit(0);}

this code does not work too:

        String stra_txt = edit_1.getText().toString();

        if (stra_txt.equals("1") || stra_txt.equals("0"))
            {
                zheg();
            }
        else
            {
                System.exit(0);
            }

mardi 26 avril 2016

Using an if statement inside of a for loop

I have a form with two sets of radio buttons. I am trying to make it so that when a certain value is checked, a <p> element (with the Id descript) will update with the corresponding data.

Here is what I have, it isn't updating the element at all right now.

DEMO

function classStats() {
  classes = ['archer', 'mage', 'warrior'];
  classStats = ['HP: 20 Strength: 3 Intellect: 1 Speed: 5 Magic Defense: 1 Defense: 3', 'HP: 15 Strength: 1 Intellect: 6 Speed: 2 Magic Defense: 2 Defense: 1', 'HP: 30 Strength: 2 Intellect: 1 Speed: 1 Magic Defense: 3 Defense: 5'];
  classAdd = ['The archer also has a special passive for armor penetration.', 'The mage has a special passive for increased gold gain', 'The warrior has a special passive for percent damage mitigation.'];
  for (i = 0; i < 3; i++) {
    c = classes[i];
    e = classStats[i];
    f = classAdd[i];
    if ($('input[name=class]:checked').val() === c) {
      $('#descript').text(e + ' ' + f);
    }
  }
}
classStats();

mysql - [if / then] query, not function. Normally Query Execution

MSSQL : query analizer

if (1=1) begin
select 'ok'
select 'ok'
end

result : ---------------------
ok
ok

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

MYSQL : how? how? Looking for answers. It is difficult. Not a function!

If else javascript error

I'm attempting to make a simple code so when you insert your name, it inserts it into the text, but if you don't insert your name it asks you to insert your name. The code seems like it should work, but it doesn't. Can anyone help me?

<body>

<h3>Please enter your name</h3>

<input type="text" id="name" value="" placeholder="Please enter your name">

<p id="dolly"></p>

<button onclick="yourName()">Enter</button>


<script>
function yourName() {
var x = document.getElementById("name").value;
if (x == "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
</script>
</body>

Selecting Max Value - Adding Criteria

@ScottCraner provided the below formula to my question, where I wanted Column E of my dataset to read "Max" for the row where the ID contains the max probability for that state. If two IDs for the same State have the same probability, as in Maryland, I wanted "Max" to show for the ID with the nearest Date. If two IDs match on both Probability and Date, then I wanted "Max" to appear for only one ID within each group of States.

=IF(ROW(D2)=MIN(IF((ABS($C$2:$C$18-$H$1)=MIN(IF(($A$2:$A$18=A2)*($B$2:$B$18=MAX(IF(($A$2:$A$18=A2),$B$2:$B$18))),ABS($C$2:$C$18-$H$1))))*($A$2:$A$18=A2),ROW($D$2:$D$18))),"Max","")

Dataset

Column A       Column B     Column C    Column D    Column E
State        Probability       Date        ID       Formula Field
California        10%       12/31/2016    123   
California        20%       1/7/2017      129   
California        23%       1/14/2017     135       Max
Colorado          26%       1/21/2017     141   
Colorado          38%       12/31/2016    147       Max
Illinois          44%       1/14/2017     153       Max
Illinois          44%       1/14/2017     159   
Illinois          20%       1/21/2017     165   
Illinois          35%       1/28/2017     171   
Maryland          41%       2/4/2017      177   
Maryland          41%       12/31/2016    183       Max
Maryland          35%       1/7/2017      189   
Michigan          20%       1/14/2017     195   
Michigan          35%       1/21/2017     201   
Michigan          38%       1/28/2017     207       Max
West Virginia     41%       2/4/2017      213   
West Virginia     44%       2/11/2017     219       Max

The formula works just fine. Now I want add criteria such that if Probability = 100% then "Max" should be assigned to that record. This criteria is most important and ought to precede all other designations of "Max" as outlined in the formula above. Note that only one "Max" should appear for each group of states (e.g. only one record from California should have "Max" in column E.

if statements in while loop?

Hi I am just wondering how do if statements work in while (loop)? I want the page to display number through 1 to 10 and show special comment for number 1 and 2. Thanks so much!

<?php
$x=1;
while($x <= 10) {
echo "". $x . "<br />";
$x = $x + 1; }

if ($x = 1 ) {
echo "".$comment."";
    $comment = "this is one!";}     
elseif ($x = 2) {
echo "".$comment."";
    $comment = "this is two!";}

?>

Calculate total votes using data from files

I am a beginner coder and don't have much experience in java. I am confused about a program that I have to code using arrays, if-else statements, and loops.

The assignment prompt is, "Write a program that uses the file ElectionVotes.txt, which contains state names and electoral votes, and the file ElectionData.txt, which contains state names and total votes for each candidate, to calculate the number of electoral votes earned by Obama and Romney in the 2012 election. Your program should build a lookup table with the state names, another table with the associated electoral votes for that state. The output should show two numbers - the total electoral votes for each candidate."

I have tried to do it, but I don't know if this will work.

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

public class Electoral_Votes {

public static void main(String[] args) {


   String str, filename, filename2;
     double[] States = new double[51];
     int[] ObamaVote = new int[51];
     int[] RomneyVote = new int[51];
     int high, low, high2, low2, EV;
     double Total, sum = 0;
     int i = 0;
   Scanner keyboard = new Scanner (System.in);

    try{
         Scanner inputFile = new Scanner(new File("ElectionVotes.txt"));
         str = inputFile.nextLine();

         while (inputFile.hasNext())
         {
             str = inputFile.next();
             States[i] = inputFile.nextDouble();
             EV = inputFile.nextInt();


              for(i = 0; i <= 51; i++)
         {
             RomneyVote = getRomneyV();
             ObamaVote = getObamaV();
             if ( RomneyVote > ObamaVote )
             {
                RomneyVote[i]+=EV;



              }

         }
         }

     }catch (IOException e)
     {
         System.out.println("File not found");
     }


}


    public static double[] getElectionData ()        
    {
         double[] States = new double[51];
         int[] ObamaVote = new int[51];
         int[] RomneyVote = new int[51];
         int i = 0;
  try{

         Scanner inputFile = new Scanner(new File("ElectionData.txt"));
         String str = inputFile.nextLine();

         while (inputFile.hasNext())
         {
             str = inputFile.next();
             States[i] = inputFile.nextDouble();
             ObamaVote[i] = inputFile.nextInt();
             RomneyVote[i] = inputFile.nextInt();
         }
     }catch (IOException e)
     {
         System.out.println("File not found");
     }

return States;
}

public static int[] getRomneyV ()        
{
     double[] States = new double[51];
     int[] ObamaVote = new int[51];
     int[] RomneyVote = new int[51];
     int i = 0;
 try{

         Scanner inputFile = new Scanner(new File("ElectionData.txt"));
         String str = inputFile.nextLine();

         while (inputFile.hasNext())
         {
             str = inputFile.next();
             States[i] = inputFile.nextDouble();
             ObamaVote[i] = inputFile.nextInt();
             RomneyVote[i] = inputFile.nextInt();

         }
     }catch (IOException e)
     {
         System.out.println("File not found");
     }

return RomneyVote;

}

public static int[] getObamaV ()        
{
     double[] States = new double[51];
     int[] ObamaVote = new int[51];
     int[] RomneyVote = new int[51];
     int i = 0;
try{

         Scanner inputFile = new Scanner(new File("ElectionData.txt"));
         String str = inputFile.nextLine();

         while (inputFile.hasNext())
         {
             str = inputFile.next();
             States[i] = inputFile.nextDouble();
             ObamaVote[i] = inputFile.nextInt();
             RomneyVote[i] = inputFile.nextInt();
         }
     }catch (IOException e)
     {
         System.out.println("File not found");
     }

return ObamaVote;
}

}

coldfusion continue keyword within IF block in cfscript / Odd behaviour

Has anyone noticed this odd behaviour with the Continue word. It seems to kill all following code in the template when used within an If statement.

I tested this in CF and Lucee with http://cflive.net/

eg:

<cfscript>

writeoutput('test1, loop<br>');

for (x=0;x>5;x++){
    writeoutput(' gonna continue?');
    continue;
    writeoutput('continued within');
}

writeoutput('Out of loop..<br><br>');

writeoutput('test2, if<br>');

oURL    = true;
if(oURL) {
    writeoutput(' gonna continue?');
    continue; // seems to kill all following code
    writeoutput('continued within');
}

writeoutput(' out of If..');

writeoutput(' end');


for (x=0;x>5;x++){
  writeoutput('loop:' & x);
}


</cfscript>

if statements,lables and combo boxes

Ok my code has to pick route (check)display in label(check) have a return and single(check) need it to display text(check) my problem is it only prints text related to one of my statments hope come one can tell me how to fix my if statments. the lable changes on a button.It reads code by lable.

package learning;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList.*;
import java.util.Arrays.*;
import java.util.List.*;


@SuppressWarnings("unused")
public class test {

String[] items = {"Tipperary to cork ","Cork to Dublin","Limerick to Tipperary","Dublin to Cork"};
    JComboBox c = new JComboBox(items);
    JButton b = new JButton("From");
    JLabel l = new JLabel("route");

    String[] items2 = {"window","aisle"};
    JComboBox m = new JComboBox(items2); 
    JButton  n = new JButton("Seat");
    JLabel  o = new JLabel("choose seat");

    String[] items3 = {"Single","return"};
    JComboBox x = new JComboBox(items3); 
    JButton  y= new JButton("Ticket");
    JLabel  z = new JLabel("choose Ticket");

    String[] items4 = {"1","2","3","4","5","6","7","8","9","10"};
    JComboBox<?> xx = new JComboBox(items4); 
    JButton  yy = new JButton("seat");
    JLabel  zz = new JLabel("Choose a seat");
    JLabel  hh = new JLabel("cost");
    JButton  ccc = new JButton("comfirm");
    JLabel  hhh = new JLabel("");{

    }


    public test(){

        if(l.equals("Tipperary to cork")==(z.equals("single"))){
            ccc.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    hh.setText("15");                          //***only prints the text here and doesnt change to 20.

}});        
        if(l.equals("Tipperary to cork")==(z.equals("return"))){
            ccc.addActionListener(new ActionListener(){      
                public void actionPerformed(ActionEvent e){
                    hh.setText("20");                          //****

                }
            });     
        }}
    frame();

    }
     public void frame(){

    JFrame wolf = new JFrame();//frame
    wolf.setVisible(true);
    wolf.setSize(350,350);
    wolf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );

    JPanel p = new JPanel();


    p.add(hh);
    p.add(c);//
    p.add(b);//
    p.add(l);//lable1
    p.add(m);//
    p.add(n);//
    p.add(o);//lable 2
    p.add(x);//
    p.add(y);//
    p.add(z);//lable 2
    p.add(xx);//
    p.add(yy);//
    p.add(zz);//lable 2
    p.add(ccc);
    p.add(hhh);
    wolf.add(p);

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
    String s = c.getSelectedItem().toString();
        l.setText(s);
        }
    });


     n.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
        String s = m.getSelectedItem().toString();
            o.setText(s);
            }
        });

     y.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
        String s = x.getSelectedItem().toString();
            z.setText(s);
            }
        });
     yy.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
        String s = xx.getSelectedItem().toString();
            zz.setText(s);
            }
        });
     }
     {
     }
public static void main(String[]args){



    new test(); 
    }
}

(VBScript) If statement conditions not met, code still executing

So I've been searching for the better half of my work shift now, and I cannot seem to find the answers I need. I'm writing a VBScript that searches the Active Directory for a computer object. If the object does not exist or exists and is in the correct OU, then it should run a separate script that creates/joins the computer to the AD.

ObjExist_CorrectOU_7 = Null
ObjExist_CorrectOU_10 = Null

If compare = True Then
  Win7_OU = "OU=DisallowRDP,OU=64Bit,OU=Win8"
  Win10_OU = "OU=DisallowRDP,OU=64Bit,OU=Win10"

  For x = 16 to 46
    If Asc(Mid(objRS.Fields("distinguishedName"), x, 1)) = Asc(Mid(Win7_OU, (x - 15), 1)) Then
    ObjExist_CorrectOU_7 = True
    Else ObjExist_CorrectOU_7 = False
    End If

    Next

  For y = 16 to 46
    If Asc(Mid(objRS.Fields("distinguishedName"), y, 1)) = Asc(Mid(Win10_OU, (y - 15), 1)) Then
    ObjExist_CorrectOU_10 = True
    Else ObjExist_CorrectOU_10 = False
    End If

    Next

End If

If ObjExist_CorrectOU_7 = True Then
Wscript.Echo "TRUE"
End If

Dim objShell

Set objShell = Wscript.CreateObject("WScript.Shell")

filename = "C:\programdata\dell\kace\k2000_deployment_info.conf"
Win7_Deployment = "deployment_name=Windows 7 x64 with SP1, join AD"
Win10_Deployment = "deployment_name=Development Windows 10 (x64), join AD"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do While Not f.AtEndOfStream
  If ((f.ReadLine = Win7_Deployment) Or ((f.ReadLine = Win7_Deployment) And (ObjExist_CorrectOU_7 = True))) Then
  Wscript.Echo "IT WORKED!"
  'objShell.Run "JoinAD_Win7.vbs"
  Exit Do
  End If

  On Error Resume Next
Loop

f.Close
Set g = fso.OpenTextFile(filename)

Do While Not f.AtEndOfStream
  If ((g.ReadLine = Win10_Deployment) Or ((g.ReadLine = Win10_Deployment) And (ObjExist_CorrectOU_10 = True))) Then
  'objShell.Run "JoinAD_Win10.vbs"
  Wscript.Echo "IT WORKED AGAIN!"
  Exit Do
  End If

  On Error Resume Next
Loop

g.Close

Set objShell = Nothing

The problem I'm running into (as I am trying to learn VBS as I go) is that I most likely have a logic error that I do not know. The two If, Then statements execute every time when I know the conditions are absolutely NOT being met.

Does it have to do with my use of "Or" and "And"?

Please, any help would be great. Thanks!

builtins.TypeError: list indices must be integers, not list. line 10, in

My program is to Write a program that will simulate a network of computer that is infected with a virus at various spots.

Based off a list of random numbers 0 (healthy),1 (infected), and 2 (dead) my function needs to display a circle at the given position on the graphics window. Here is the code I have so far for the given function below.

def displaygen(generation,  win):        
    for row in generation:
        for col in row:
            position = Point(5,5)    
            if generation[row][col] == '0':
                circ = Circle(position,3)
                circ.setFill('green')
                circ.draw(win)
            elif generation[row][col] == '1':
                circ = Circle(position,3)
                circ.setFill('red')
            elif generation[row][col] == '2':
                circ = Circle(position,3)
                circ.setFill('black')                

ELIF statements

I have done the program, but I keep getting an invalid syntax at the close of main and cannot figure out what I am doing wrong. I am trying to get the elif to get the multiple of the larger number, and to indicate how many times the smaller integer divides into the larger. Also, on my else statement, the smaller integer is not a multiple of the larger one, the program would show the whole number quotient and remainder when the larger is divided by the smaller integer. Code below:

def main():
    num1 = int(input('Enter any numbers greater than 2:'))
    num2 = int(input('Enter any number less than num1:'))
    if num2 >= num1:
        print("Bad_Input.Try_Again")
    elif num1 % num2 == 0:
        quotient = num1 / num2
        print(quotient)
    else:
        print(num1 / num2)
        print(num1 % num2)
        print(num1,'divides by',num2,'=','and remainder',divmod(num1 / num2)

main()

Can anyone tell me why I keep getting an Invalid syntax error when trying to execute the program.

Searching within txt files using bash

I am looking trivial solution for the trivial task.

My bash script is looping several folders producing in which some log.txt file. If some operation in each case has performed successfully in each of the log the string with sentence "The unit is OK" should somewhere in the log.txt appeared, however its actual position (precise number of string) in each log.txt is differs! I need to put in my loop some condition (probably using IF ) to check whether that sentence is actually present somewhere in the log file and if so - to print "Everything is OK" within the terminal where my script is executed in moment of looping of particular folder, and otherwise (if the string is absent in the log) to print smth like "Bad news"! Will be thankful for the different solutions especially how to find the strings of selected phrases in the given log file.

Thanks!!

Gleb

Usage of semi colon for string matching in Ruby?

I am trying to understand if we can use ; inside string match ? Even though the below code doesn't seem to work ..but i am trying to understand what previous developer wanted to do.

if param.type == 'Team'
  search_url += '/type-Team'
elsif param.type == 'Agent;Team;Office'
  search_url += '/type-Agent;Team;Office'
end

Resources for Hyperion Interactive Reporting Studio V11

Does anyone know of resources that could help with Hyperion Interactive Reporting Studio V11? I need assistance with creating multiple if statements when creating computed items in the results section.

Thank you

visual basic excel if

Fishing Control want a program where the fishermen can enter the name of the fish and the size. The program shall tell the user if the fish is legal or not. Below min size is illegal.This is the fish names and sizes

I wrote the below code but it is not giving me a msgbox in result. after inputting values, there is not output. very frustrating. tried many things but no result. Also tell me a shorter way of doing this. I do confess that it is a bit lengthy

Sub FishControl()
    Dim dName As String
    Dim dSize As Integer
    dName = InputBox("Please enter the name of the fish")
    dSize = InputBox("Please enter the size of the fish")

    If ((dName = trout) And (dSize < 40)) Then
    MsgBox ("This fish is illegal to hunt")

    ElseIf ((dName = trout) And (dSize >= 40)) Then
    MsgBox ("This fish is legal to hunt")

    End If

End Sub