samedi 31 octobre 2015

How to do an IF statement in PLY?

I'm doing a compiler using PLY. I have successfully implemented arithmetic and logical operations, but I'm having trouble with the 'if statement'.

This is my current code:

-Lexer:

tokens = (
    'NAME','INT', 'DOUBLE', 'GREATER', 'LESS',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN', 'CHAR', 'TRUE', 'FALSE',
    'GREATEQ', 'LESSEQ', 'EQEQ', 'NOTEQ', 'AND',
    'OR', 'COLON', 'IF'
    )

# Reserved words
reserved = {
    'if' : 'IF'
}

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z][a-zA-Z0-9_]*'
t_CHAR    = r'\'[a-zA-Z0-9_+\*\- :,\s]*\''
t_TRUE    = r'\t'
t_FALSE   = r'\f'
t_GREATER = r'>'
t_LESS    = r'<'
t_GREATEQ = r'>='
t_LESSEQ  = r'<='
t_EQEQ    = r'=='
t_NOTEQ   = r'!='
t_AND     = r'&'
t_OR      = r'\|'
t_COLON   = r':'

def t_DOUBLE(t):
    r'[0-9]+\.[0-9]+'
    try:
        t.value = float(t.value)
    except ValueError:
        print("Integer value too large %d", t.value)
        t.value = 0
    return t

def t_INT(t):
    r'[0-9]+'
    try:
        t.value = int(t.value)
    except ValueError:
        print("Double value too large %d", t.value)
        t.value = 0
    return t

# Ignored characters
t_ignore = " \t"

def t_IF(t):
    r'if'
    return t

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lexer = lex.lex()

-Parser:

# Parsing rules

precedence = (
    ('left','AND','OR'),
    ('left','GREATER','LESS', 'GREATEQ', 'LESSEQ', 'EQEQ', 'NOTEQ'),
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

# dictionary of names
names = { }

def p_statement_assign(t):
    'statement : NAME EQUALS expression'
    names[t[1]] = t[3]

def p_statement_expr(t):
    'statement : expression'
    print(t[1])

def p_statement_if(t):
    'statement : IF LPAREN expression RPAREN DP statement'  
    pass

def p_expression_ariop(t):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if t[2] == '+'  : t[0] = t[1] + t[3]
    elif t[2] == '-': t[0] = t[1] - t[3]
    elif t[2] == '*': t[0] = t[1] * t[3]
    elif t[2] == '/': t[0] = t[1] / t[3]

def p_expression_logop(t):
    '''expression : expression GREATER expression
                  | expression LESS expression
                  | expression GREATEQ expression
                  | expression LESSEQ expression
                  | expression EQEQ expression
                  | expression NOTEQ expression
                  | expression AND expression
                  | expression OR expression'''
    if t[2] == '>'  : t[0] = t[1] > t[3]
    elif t[2] == '<': t[0] = t[1] < t[3]
    elif t[2] == '>=': t[0] = t[1] >= t[3]
    elif t[2] == '<=': t[0] = t[1] <= t[3]
    elif t[2] == '==': t[0] = t[1] == t[3]
    elif t[2] == '!=': t[0] = t[1] != t[3]
    elif t[2] == '&': t[0] = t[1] and t[3]
    elif t[2] == '|': t[0] = t[1] or t[3]

def p_expression_uminus(t):
    'expression : MINUS expression %prec UMINUS'
    t[0] = -t[2]

def p_expression_group(t):
    'expression : LPAREN expression RPAREN'
    t[0] = t[2]

def p_expression_int(t):
    'expression : INT'
    t[0] = t[1]

def p_expression_double(t):
    'expression : DOUBLE'
    t[0] = t[1]

def p_expression_char(t):
    'expression : CHAR'
    t[0] = t[1]

def p_expression_name(t):
    'expression : NAME'
    try:
        t[0] = names[t[1]]
    except LookupError:
        print("Undefined name '%s'" % t[1])
        t[0] = 0

def p_expression_bool(t):
    'expression : bool'
    t[0] = t[1]

def p_true(t):
    'bool : TRUE'
    t[0] = True

def p_false(t):
    'bool : FALSE'
    t[0] = False

def p_error(t):
    print("Syntax error at '%s'" % t.value)

import ply.yacc as yacc
parser = yacc.yacc()

I have also try something like this in the parser:

def p_statement_if(t):
    'statement : IF expression COLON statement' 
    t[0] = ('if',t[2],t[4])

Whether the expression is true or false, my compiler always does the statement
What am I doing wrong?

Thanks

Bash If NOT OR With TWO Commands

I want to check that whether two programs exist or not.

if ! [ type gedit ] || ! [ type vim ]; then
    echo "Installing programs"
    #code
fi

#code needs to run when one of them is missing.

What is the true way of it?

VHDL - "Input is never used warning"

I've written a program in VHDL (for Xilinx Spartan-6) that increments a counter whilst a button is pressed and resets it to zero when another button is pressed.

However, my process throws the error WARNING:Xst:647 - Input is never used. This port will be preserved and left unconnected... for the reset variables - despite the fact that it is used both in the sensitivity of the process and as a condition (just as much as button, yet that doesn't get flagged!).

binary_proc : process(CLK_1Hz, button, reset) --include all inputs on sensitivity list
begin
    if rising_edge(CLK_1Hz) and button = '1' then
        binary <= binary + 1;
    else if reset = '1' then
            binary <= (others => '0');
        end if;
    end if;
end process;

More curiously though, I can fix this by simply using two if statements rather than just an if-else if statement, as shown below;

binary_proc : process(CLK_1Hz, button, reset) --include all inputs on sensitivity list
begin
    if rising_edge(CLK_1Hz) and button = '1' then
        binary <= binary + 1;
    end if;
    if reset = '1' then
        binary <= (others => '0');
    end if;
end process;

My question is: why is the reset variable optimized out of the circuit when an if-else statement is used but not when two if statements are used? What causes this and how can this sort of thing be avoided it?

Thanks very much!

NB: Full code of the program is below in case it helps!

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity button_press is
    port(
        CLK_200MHz : in  std_logic;
        button     : in  std_logic;
        reset      : in  std_logic;
        LED        : out std_logic_vector(3 downto 0) --array of LED's
    );

end button_press;

architecture Behavioral of button_press is
    signal CLK_1Hz : std_logic;         --input clock (think 200 MHz)
    signal counter : std_logic_vector(26 downto 0); --counter to turn 200 MHz clock to 1 Hz
    signal binary  : std_logic_vector(3 downto 0); --binary vector thats mapped to LED's
begin
    -----Create 1 Hz clock signal from 200 MHz system clock-------
    prescaler : process(CLK_200MHz)
    begin
        if rising_edge(CLK_200MHz) then
            if (counter < 2500000) then --possibly change to number in binary
                counter <= counter + 1;
            else
                CLK_1Hz <= not CLK_1Hz; --toggle 1 Hz clock
                counter <= (others => '0'); --reset counter to 0
            end if;
        end if;
    end process;
    ------ Increment binary number when on rising clock edge when button pressed -------
    binary_proc : process(CLK_1Hz, button, reset) --include all inputs on sensitivity list
    begin
        if rising_edge(CLK_1Hz) and button = '1' then
            binary <= binary + 1;
        end if;
        if reset = '1' then
            binary <= (others => '0');
        end if;
    end process;

    LED <= binary;                      --map binary number to LED's

end Behavioral;

Syntax error on the "N" on line 18

I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.

def triangle():
    N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
    if N == 1:
        a = int(input("What's one of the angles?"))
        b = int(input("What's the other angle in the triangle?"))
        c = a + b
        f = 180 - c
        print(f)
        print("If you'd like to continue, please type in triangle()")

    elif N == 2:
        a = int(input("What's the value of angle 1?"))
        b = 180 - a
        c = b /2
        print(c)
        print("If you'd like to continue, please type in triangle()")

    else N == 3:
        a = 180
        b = 180 / 3
        print(b)
        print("If you'd like to continue, please type in triangle()")

But I'm getting a syntax error returned on elif N == 3: Any tips would be great.

C# if statement with multiple or conditions not returning expected behavior

I have an if statement that will display a .CSHTML Layout under the following conditions:

    @if ((ViewBag.title != "Log in")
    || (ViewBag.title != "Register")
    || (ViewBag.title != "Confirm Email")
    || (ViewBag.title != "Login Failure")
    || (ViewBag.title != "Forgot your password?")
    || (ViewBag.title != "Forgot Password Confirmation")
    || (ViewBag.title != "Reset password")
    || (ViewBag.title != "Reset password confirmation")
    || (ViewBag.title != "Send")
    || (ViewBag.title != "Verify"))
{ Layout markup }

When I load the Log in page; however, the Layout template appears. Setting a breakpoint shows that the page title correctly corresponds to the != "Log in" condition and no exceptions are being thrown. Just to be sure, I checked my markup against the solution in this post and it appears to be fine... Have a screwed up my statement logic somehow and just don't see it?


Simple text based game

and i need help to this task. i am really stuck, i need help to move on

The Explorer’s backpack can contain up to 20 kg of small items. Large items cannot be carried in the explorer backpack (they cannot be picked up). Implement a method in the Explorer class that returns the total weight of all items in the backpack at a given moment.

An item can be picked up from the floor of the current room and added to the explorer’s backpack, or dropped on the floor (from the backpack).

In Explorer class implement the following method:

 public boolean pickup(Item someItem)

the method returns true if the item was picked up successfully, false otherwise (for example if the backpack was already full).

In Room class implement:

  public boolean drop(Explorer expl, String itemName)

the method returns true if the item is in the backpack and can be successfully dropped in the room, false otherwise.

Use these new methods in the Game class, by adding 2 new commands to the textual menu:

“Welcome to the BlaBlaBla game. Type: ‘a’ to add a random item to the room ‘r’ to remove the first item in the room’s item list ‘l’ to print a list of all items in the room ‘p’ to pick up an item from the room ‘d’ to drop an item from backpack to the room ‘q’ to quit the game.”

And make it so that at each turn, the Game class prints also the list of contents of the explorer’s backpack. When the player types ‘p’ the game should list the items in the room and ask the name of the item to pick up.

Beware: there could be 2 items with the same name, or none; please be sure that your pick up command works for both and eventually prints relevant messages to the player in both cases.

i can't show the output to the user

i wrote that code but every time i try to show the out put to the user by System.out.print statement something goes wrong. "the purpose of the code is to check if the array is “palindromic” "

import java.util.Scanner;
public class u {
public static void main(String[] args) {
    int [] arr = {1,2,3,4,5,2,1};
    int counter1 = 0,counter2 = arr.length-1;
    int x = arr.length/2;
    while (counter1 < x ) {
        if (arr[counter1] == arr [counter2]){
            counter1++;
            counter2--;
        } else break;

    } 


   }}

(JQUERY) check if input A OR input B has value

im trying to check if 1 of 2 inputs has a value as an IF statement. Here is the HTML:

                 <ul>
                    <li>
                        <label>Width</label>
                        <input type=text id="value1" />
                    </li>
                    <li>
                        <label>Height</label>
                        <input type=text id="value2" />
                    </li>
                </ul>

I want to check whether input#value1 OR input#value2 has a value...

Thanks in advance :)

Atomic Instructions: IFs and Loops

Are IF statements and loops such as while or do while atomic instructions in concurrent programming?

If not, is there a way to implement them atomically?

edit: Fixed some of my dodgy English.

two if inside an if inside a foreach not working properly

I have two ifs inside an if. They're not showing in the order that I want.

I want the if:

if(${'user'.$countCats}[$resp->getQuestionId()]...

shows first and then the if:

if($resp->getIdR()==${'bd'.$countCats}[$resp->getQuestionId()])....

If someone can help thank you!

Here's the code:

<?php
function afficheResultats(Array $user1,Array $user2,Array $user3,
                      Array $bd1,Array $bd2,Array $bd3,
                      $tableCats,$tableQ, $tableR)
{
echo "Évaluation: ";
$pourcTous=0;
$countCats=0;
foreach ($tableCats as $categ) 
    {
        $countGoods=0;
        $countBads=0;
        $countCats++;
        {                   
            echo " ".$categ." ";
            foreach ($tableQ as $quest) 
            {
                if($quest->getCatId()==$categ->getIdCat())
                {
                    echo $quest;                        
                    foreach ($tableR as $resp) 
                    {   

                        $contenu="";                        

                        if($resp->getQuestionId()==$quest->getIdQ()
                           &&$resp->getIdCat()==$categ->getIdCat())
                            {
                                $eval=false;

                                if($resp->getIdR()==${'user'.$countCats}[$resp->getQuestionId()])
                                {
                                    $contenu= "<p>Votre réponse: ".$resp->getNameR()."<p/> ";
                                    //$eval=false;
                                    if(${'user'.$countCats}[$resp->getQuestionId()]==${'bd'.$countCats}[$resp->getQuestionId()])
                                    {                                       
                                        $contenu.="<p>Correct!</p>";
                                        $eval=true;
                                        $countGoods++;                                          
                                    }
                                    else
                                    {
                                        $contenu.="<p>Incorrect.</p> ";
                                        $eval=false;
                                        $countBads++;
                                    }
                                }
                            }
                        if($resp->getQuestionId()==$quest->getIdQ()
                           &&$resp->getIdCat()==$categ->getIdCat())
                            {                               
                                if($resp->getIdR()==${'bd'.$countCats}[$resp->getQuestionId()])
                                {
                                    $contenu.="<p>Bonne réponse: ".$resp->getNameR()."<p/>";
                                }                                                                   
                            }   

                    }
                    echo $contenu;
                }
            }
            $pourcPartial=round($countGoods/($countGoods+$countBads)*100);
            echo "<p> Pourcentage pour cette parti: ".$pourcPartial."%</p>";
            $pourcTous+=$pourcPartial;              
        }           
    }       
    echo " <p>Pourcentage Total: ".round($pourcTous/$countCats)."%</p>";
}

issue in boolean variable in matlab

I have two vectors A and B of the same size.I have the following code.

 y1=[];y2=[];y3=[];y4=[];
 for i=1:length(A)
 for k=0:0.1:1
        for m=0:0.1:1
           h=k*m/(k+m-k*m);
           if(h==A(i))
                y1=[y1 k];
                y2=[y2 m];
           end
           if(h==B(i))
                y3=[y3 k];
                y4=[y4 m];
           end

        end
    end
    end

This code runs fine. But in this code say for example if h=A(i)=0.2 is true. Then y1 and y2 can only take the combinations [0,0.2],[0.2,0]

If h=B(i)=0.4 is true then y3 and y4 can take combinations[0,0.04],[0.02,0.02],[0.01,0.03] likewise. I want to group all the combinations of B for a particular A(i) and to know when A(i) takes a different value, and for that different A(i) the corresponding B(j)'s.

So I wrote the following code.

y1=[];y2=[];y3=[];y4=[];
for i=1:length(A)
    istrue=0; 
    for k=0:0.01:1
           for m=0:0.01:1
           h=k*m/(k+m-k*m);

       if(h==A(i))
            istrue=1;
            y1=[y1 k];
            y2=[y2 m];
       end

       if(istrue==1)

           if(h==B(i))

               y3=[y3 k];
               y4=[y4 m];
           end
       end
       istrue=0;

    end
end
end  

But the problem is this never executes the part

               if(h==B(i))

                   y3=[y3 k];
                   y4=[y4 m];
               end  

If I remove istrue variable and run as in the previous code it works.

if(h==A(i))
                    istrue=1;
                    y1=[y1 k];
                    y2=[y2 m];
               end

gets executed at least once. Yet the part

if(h==B(i))


                   y3=[y3 k];
                   y4=[y4 m];
               end `   

doesn't get executed.
What is wrong with my code?Is the issue with the istruevariable?

if else Error: unexpected '}' in "}" in R

The simplest script ever, so why do I get an error:

> x <- -5
> if(x > 0){
+     print("Non-negative number")
+ } 
> else{
Error: unexpected 'else' in "else"
>     print("Negative number")
[1] "Negative number"
> }
Error: unexpected '}' in "}"

If I simply put the else after } then there is no problem.

> x <- -5
> if(x > 0){
+     print("Non-negative number")
+ } else{
+     print("Negative number")
+ }
[1] "Negative number"

Thing is I have always written it the first way without problem; am I going crazy?

The name 'c' doesn't exist in current context [duplicate]

This question already has an answer here:

I've been writing this code to do the quadratic formula for me, but there's a problem found a problem right here:

        if (textBox2.Text != "")
        {
        string h = textBox2.Text;
        double c = double.Parse(h);
        }
        else if (textBox2.Text == "")
        {
        double c = 0;
        }
        // else error message

        //Delta
        double delta = (Math.Pow(b, 2)) - (4 * a * c);
        string dtxt = Convert.ToString(delta);

        label5.Text = dtxt;

The problem is, "The name 'c' doesn't exist in current context". That also happens with the values b, and a, which have the same conditions as c.

If statement does equalsIgnoreCase while not preffered - Java

If I use this code:

if(new File(inputNickname + ".acc").exists() == false) {
        System.out.println("[Login] This account does not exists!");
        exists = false;
    }

and I would make a text file called example.acc, it will say true if inputNickname = EXAMPLE or ExAmPle etc. But I only want that exists = true, when inputNickname is example and not EXAMPLE or ExAmPlE etc.

Thanks

Undefined operator for if function - Java

I am trying to write a simple if function that calculates if someone is eligible for a bonus or not. This is done in an "Employee" class that has fields:

  private int             id       = 0;
  private String          forename = null;
  private String          surname  = null;
  private Salary          salary;
  private CompanyPosition companyPosition;

Here is the IF :

public boolean eligibleForBonus(){

boolean isEligible = true;

if ( salary >= 40000) {
  isEligible = true;
  }
return isEligible
}

Salary is another class with a field

private double salary = 0.0;

(also has all getters and setters defined)

HOWEVER - i get an error on the line with the IF, that:

" The operator >= is undefined for the argument type Salary, int

Can someone help? Thank you

if and ifelse problems [duplicate]

This question already has an answer here:

I have a trouble with my code, in the structure when something hasn,t a condition get the value of second last else ('no') but it have to get the last else. I´ve cheked my code for a couple of hours and I didn´t see any problem . Some solution or other way for get the results that I hope.

for ($i=0; $i <sizeof($datos) ; $i++){
    if (empty($_POST[$datos[$i]])) {
        $err = "<div class='alert alert-danger'>Rellena el campo " .$datos[$i]."</div>";
    }elseif($datos[$i] == "numero"){
        $datos[1] = $_POST[$datos[1]];
        for ($i=0; $i < $datos[1] ; $i++) {
            if(isset($_POST[$secciones[$i]])){
                $definidas[$i] = $_POST[$secciones[$i]];
            }else {
                $err = "<div class='alert alert-danger'>Rellena todas las Secciones</div>";
            }
        }
    }elseif($datos[$i] == "facebook"||"twitter"||"google"||"instagram"||"correo"){
            if($_POST[$datos[$i]] == "si"){

                if (empty($_POST['di'.$datos[$i]])) {
                    $err = "<div class='alert alert-danger'>Rellena todas las casillas sociales</div>";
                }else{
                $datos[$i] = $_POST['di'.$datos[$i]];
                }

            }else{   
                $datos[$i] =  "no";
            }

    }else {
        $datos[$i] = $_POST[$datos[$i]];
    }
}

and this is my array

$datos = array ('web','numero','slider','vista','facebook','twitter','google','instagram','correo','admin','contrasena');

How do I return my string inside an if statement?

public static String  mixColors1(String x, String y)
{
    String red="red";
    String yellow="yellow";
    String blue="blue";
    String color = null;//this line... is an issue
    if(red == x && yellow == y || red == y && yellow == x)//if red&yellow selected
        color = "orange";//return orange

    else if(red == x && blue == y || red == y && blue == x)//if red&blue selected
        color = "purple";//return purple

    else if(yellow == x && blue == y || yellow == y && blue == x)//if blue&yellow selected
        color = "green";//return green

    return color;
}

The Ubiquitous: Application defined or object defined error

I wrote a little macro that enters transactions into our ERP system and things seem to get gummed up when it's determining whether or not the second location defined in the spreadsheet is greater than zero. Here is my code:

    Option Explicit

Sub DblChk()

If (MsgBox("Are you sure you are ready to append scrap data to QAD? This cannot be reversed.", vbOKCancel)) = 1 Then

Call Scrap

Else: Exit Sub

End If

End Sub

Sub Scrap()

On Error GoTo ErrorHelper

Sheets("Roundup").Select

Range("I2").Select

Call Shell("C:\Program Files\QAD\QAD Enterprise Applications 2.9.6\QAD.Applications.exe", vbNormalFocus)

'Sign in to QAD
Application.Wait (Now + TimeValue("0:00:05"))
SendKeys ("username")
SendKeys ("{TAB}")
SendKeys ("password")
SendKeys ("{ENTER}")

'Enter Scrap

Application.Wait (Now + TimeValue("0:00:15"))
SendKeys ("{TAB}")
Application.Wait (Now + TimeValue("0:00:01"))
SendKeys ("{TAB}")
Application.Wait (Now + TimeValue("0:00:01"))

'Scrap Loop

Do While Not IsEmpty(ActiveCell)

If ActiveCell.Value > 0 Then

ActiveCell.Offset(0, -8).Activate
SendKeys (ActiveCell.Value)
ActiveCell.Offset(0, 6).Activate
SendKeys ("{ENTER}")
SendKeys (ActiveCell.Value)
SendKeys ("{TAB}")
SendKeys ("{TAB}")
SendKeys ("{TAB}")
Application.Wait (Now + TimeValue("0:00:01"))
ActiveCell.Offset(0, -1).Activate
SendKeys (ActiveCell.Value)
SendKeys ("{ENTER}")
SendKeys ("{TAB}")
SendKeys ("{TAB}")
Application.Wait (Now + TimeValue("0:00:01"))
SendKeys ("SCRAP")
SendKeys ("{TAB}")
SendKeys ("{TAB}")
SendKeys ("{TAB}")
SendKeys ("{TAB}")
Application.Wait (Now + TimeValue("0:00:01"))
ActiveCell.Offset(0, 2).Activate
SendKeys (ActiveCell.Value)
SendKeys ("{TAB}")
ActiveCell.Offset(0, -4).Activate
SendKeys (ActiveCell.Value)
SendKeys ("{TAB}")
ActiveCell.Offset(0, 1).Activate
SendKeys (ActiveCell.Value)
SendKeys ("{ENTER}")
SendKeys ("{ENTER}")
ActiveCell.Offset(1, -4).Activate

Else

ActiveCell.Offset(1, 0).Activate

End If

Loop
ErrorHelper:
MsgBox Err.Description
End Sub

I've seen several references to this error on the internet but none that seem to apply to my specific situation. It seems to be going awry at the beginning of the If statement.

Any thoughts?

vendredi 30 octobre 2015

Javascript Conditionals not working

I'm sorry I didn't search for another topic I thought this was a bit too specfic, ok now that's out of the way!

When this is run missionButton.click(); is always ran, even though CheckHealth() is = to 0 it's like it's just skipping over the original if statement, is this normal for js (i'm used to other languages)

//__Action_Functions__

// When you're at zero health.
function Hospital(){     
    location.assign("http://ift.tt/1Nf3uIN");
    var HospitalUse = HospitalID;
    HospitalUse.click();

    setTimeout(location.assign("http://ift.tt/1NHgFR1"),5000);
}


//__Does Mission__
function start(){
    var missionButton = CrimeID; //CrimeID is the ButtonID from the /crimes page/ variables at the top of this script.  

    if(CheckHealth() === 0){Hospital();}
    else if (CheckStamina() > 0);{missionButton.click();}
}

There's no reason I can see this won't work

EXTRA

I'm using tampermonkey, if that makes any difference.

Javascript If/else style changing

i have a problem with simple if else statement that changes text color of a

element depending on a current color. I see why i get certain results but i can't seem to find a solution. Any help to newbie like me appreciated.

HTML <p id="demo">JavaScript can change the style of an HTML element.</p>

JS TRY 1

<script> 
var x = document.getElementById("demo");

    function one() {  

x.style.fontSize="16px";
x.style.color="black";}

function two() {

x.style.fontSize="16px";
x.style.color="red";}

function three(){

if(x.style.color="black") { two() }
else {one()
}
}
</script>` <button type="button" onclick="three()">Click Me!</button>

JS TRY 2

<script> 
var brojilo = 1 ;
function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

function one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (brojilo % 2 == 0)
{one()} 
else
{two()}

var brojilo = brojilo + 1 ;

}
</script><button type="button" onclick="three()">Click Me!</button>

JS TRY 3

<script> 
var b2 = 0 ;

function brojanje(){
var b2 = b2+1;}

function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

vfunction one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (b2 % 2 == 0)
{one()} 
else
{two()}
}
</script><button type="button" onclick="three(); brojanje ();">Click Me!</button>

Thanks in advance

Incompatible types: Card cannot be converted to java.lang.String

I keep getting this error with my code. I can't seem to find the problem.

I'm not sure what to do because I even looked in the text book and it gives me a similar method except with different variables.

I'm on BlueJ.

 public int findFirstOfPlayer(String searchString)
{
    int index = 0;
    boolean searching = true;
    while(index < cards.size() && searching) {
        String cardname = cards.get(index); // Error highlights index
        if(cardname.contains(searchString)) {
            searching = false;
        }
        else {
            index++;
        }
        if(searching) {
            return -1;
        }
        else {
            return index;
        }
    }
}

GAS Spreadsheet avoid getting duplicates by marking as "SENT", not working?

so I have this script in Google Spreadsheet and it fetches all the rows marked "READY" just fine, then it sets the value in column "W"(23) to "SENT", and then I am trying to avoid fetching duplicates, by marking the column as "SENT" but then when I run the code again, it ignores the "SENT" that it just pasted? What is wrong here?

var ss = SpreadsheetApp.openById("12y85GmJ94s6k3213j2nGK8rFr0GOfd_Emfk8WHu_MUQ");
var stitchSheet = ss.getSheetByName("Sheet8");
var orderSheet = ss.getSheetByName("Sheet1");

var SENT = "SENT";

function getOrders() {

var range  = orderSheet.getDataRange();
var orders  = range.getValues();  

for (var i = 1; i < orders.length; i++) {
var row = orders[i];
var status = row[1];
var order = row[4]; 
var name = row[5]; 
var system = row[22]; 

if(system != SENT){ 
  if(status.toString() === 'READY'){
orderSheet.getRange(i,23).setValue(SENT);
stitchSheet.appendRow([order,name]); 
}}
}
}

BigInteger's "&" Logical Operator Equivalent

I have this code:

if ((x & y)==0){ 
// do this... 
}

I would like to achieve the same effect but using BigInteger instead of int.

I tried this:

if ((x.compareTo(BigInteger.ZERO)==0)&&(y.compareTo(BigInteger.ZERO)==0)){ 
// do this...
}

Now, however, my program is never going inside this if statement. I would really appreciate your help.

Also, here's the entire code.

import java.math.*;

public class mew {

public static void main (String[] args) {

BigInteger two = BigInteger.valueOf(2);
BigInteger num = two.pow(100);
BigInteger i = BigInteger.valueOf(0);

while (i.compareTo(num) < 0){
    BigInteger mask = num;

    while (mask.compareTo(BigInteger.ZERO) > 0){
            if ((mask.compareTo(BigInteger.ZERO)==0)&&(i.compareTo(BigInteger.ZERO)==0)){
             System.out.print("0");
             }
            else {
             System.out.print("1");
                }
             mask = mask.shiftRight(1);
                }
     System.out.println();
     i = i.add(BigInteger.valueOf(1));
          }

    }
}

The purpose is to print all possible permutations of an n-long bit string. I ought to reference where I got the idea and the implementation: Java: How to output all possible binary combinations (256 different sequences)? see nikis post.

how to show added items in a new line when button is clicked

I'm new to android development I have been trying to create a Point Of Sale application Android Studio ..I'm trying to make the app show the items that the user clicked in a separate line instead of adding it to the same text view giving me the total of it.

Any other helpful tips to improve the app are also welcome

Thanks!

public class MainActivity extends AppCompatActivity {

TextView proutput, poutput, subtotal, totalitems, discounts, tax, total, qoutput;
ListView listView;
Button remove1;
double price = 0.00;
double pricef = 0.00;
double totalPrice = 0.00;
double taxes = 0.05;
int quantity = 0;
ButtonClickListener btnClick;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    poutput = (TextView) findViewById(R.id.POutput);
    qoutput = (TextView) findViewById(R.id.QOutput);
    proutput = (TextView) findViewById(R.id.PROutput);
    subtotal= (TextView) findViewById(R.id.STotal);
    totalitems = (TextView) findViewById(R.id.Total_Items);
    discounts = (TextView) findViewById(R.id.Discount);
    tax = (TextView) findViewById(R.id.Tax);
    total = (TextView) findViewById(R.id.FTotal);
    remove1 = (Button) findViewById(R.id.Remove1);




    btnClick= new ButtonClickListener();

    //array of id's
    int buttonid[]={ R.id.Remove1, R.id.Chicken, R.id.Beef,R.id.Pork, R.id.Fish,R.id.Milk,
            R.id.Eggs, R.id.Potato, R.id.Onions, R.id.Cereal, R.id.Chips,
            R.id.Tomato, R.id.Cookies, R.id.Hair_Gel, R.id.Shower_Gel, R.id.Soap,
            R.id.Apple, R.id.Avocado, R.id.Lettuce, R.id.Garlic, R.id.Banana,
            R.id.Total, R.id.Clear};

    for(int id:buttonid){
        View v= findViewById(id);
        v.setOnClickListener(btnClick);
    }
}

public class ButtonClickListener implements OnClickListener{
    public void onClick(View v){

        switch(v.getId()) {

            case R.id.Chicken:

                remove1.setText("X");
                poutput.setText("Chicken");
                ++quantity;
                pricef = 10.25;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Beef:

                remove1.setText("X");
                poutput.setText("Beef");
                ++quantity;
                pricef = 12.45;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Pork:

                remove1.setText("X");
                poutput.setText("Pork");
                ++quantity;
                pricef = 8.35;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Fish:

                remove1.setText("X");
                poutput.setText("Fish");
                ++quantity;
                pricef = 14.15;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Apple:

                remove1.setText("X");
                poutput.setText("Apple");
                ++quantity;
                pricef = 1.23;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Tomato:

                remove1.setText("X");
                poutput.setText("Tomato");
                ++quantity;
                pricef = 1.53;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Onions:

                remove1.setText("X");
                poutput.setText("Onions");
                ++quantity;
                pricef = 0.85;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Garlic:

                remove1.setText("X");
                poutput.setText("Garlic");
                ++quantity;
                pricef = 0.54;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Avocado:

                remove1.setText("X");
                poutput.setText("Avocado");
                ++quantity;
                pricef = 3.25;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Lettuce:

                remove1.setText("X");
                poutput.setText("Lettuce");
                ++quantity;
                pricef = 2.35;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Banana:

                remove1.setText("X");
                poutput.setText("Banana");
                ++quantity;
                pricef = 2.05;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Cereal:

                remove1.setText("X");
                poutput.setText("Cereal");
                ++quantity;
                pricef =  8.10;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Cookies:

                remove1.setText("X");
                poutput.setText("Cookies");
                ++quantity;
                pricef = 4.99;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Chips:

                remove1.setText("X");
                poutput.setText("Chips");
                ++quantity;
                pricef = 1.85;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Milk:

                remove1.setText("X");
                poutput.setText("Milk");
                ++quantity;
                pricef = 2.75;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Eggs:

                remove1.setText("X");
                poutput.setText("Eggs");
                ++quantity;
                pricef = 4.25;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Hair_Gel:

                remove1.setText("X");
                poutput.setText("Hair Gel");
                ++quantity;
                pricef = 5.34;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Shower_Gel:

                remove1.setText("X");
                poutput.setText("Shower Gel");
                ++quantity;
                pricef = 4.88;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Soap:

                remove1.setText("X");
                poutput.setText("Soap");
                ++quantity;
                pricef = 3.85;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;

            case R.id.Potato:

                remove1.setText("X");
                poutput.setText("Potato");
                ++quantity;
                pricef = 2.55;
                price = quantity * pricef;
                qoutput.setText(String.valueOf(quantity));
                proutput.setText(String.format("%.2f", price));
                break;




            case R.id.Clear:
                quantity = 0;
                taxes = 0.0;
                totalPrice = 0.0;
                price = 0;
                remove1.setText("");
                poutput.setText("");
                qoutput.setText("");
                proutput.setText("");
                subtotal.setText("Sub Total  ");
                totalitems.setText("Total Items  ");
                discounts.setText("Discount  ");
                total.setText("Total  ");
                tax.setText("Tax(%5)  ");
                break;

            case R.id.Total:
                //taxes prices incremented error
                double tax2 = 0.05;
                taxes = tax2 * price;
                totalPrice = tax2 + price;
                subtotal.setText(String.format( "    Sub Total  %.2f", price ));
                totalitems.setText("Total Items  " + String.valueOf(quantity));
                discounts.setText("Discount  ");
                tax.setText(String.format( "Tax(%%5) %.2f", taxes));
                total.setText(String.format( "Total  %.2f", totalPrice ));
                break;

            case R.id.Remove1:
                --quantity;
                if (quantity <= 0)
                {
                    quantity = 0;
                    remove1.setText("");
                    poutput.setText("");
                    qoutput.setText("");
                    proutput.setText("");
                }
                else
                {
                    price =  pricef * quantity;
                    qoutput.setText(String.valueOf(quantity));
                    proutput.setText(String.format("%.2f", price));
                }
                break;

        }
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="horizontal"
android:weightSum="2"
android:background="#43378dff">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="20"
    android:layout_weight="1">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:weightSum="5">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product1"
            android:id="@+id/Chicken"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#90ff2030" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product5"
            android:id="@+id/Milk"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#92fffa34" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product9"
            android:id="@+id/Apple"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product13"
            android:id="@+id/Avocado"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product17"
            android:id="@+id/Cereal"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#9bffb103" />

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:weightSum="5">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product2"
            android:id="@+id/Beef"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#90ff2030" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product6"
            android:id="@+id/Eggs"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#92fffa34" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product10"
            android:id="@+id/Lettuce"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product14"
            android:id="@+id/Potato"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product18"
            android:id="@+id/Soap"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#4eff00dc" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:weightSum="5">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product3"
            android:id="@+id/Pork"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#90ff2030" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product7"
            android:id="@+id/Tomato"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product11"
            android:id="@+id/Onions"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product15"
            android:id="@+id/Chips"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#9bffb103" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product19"
            android:id="@+id/Shower_Gel"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#4eff00dc" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:weightSum="5">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product4"
            android:id="@+id/Fish"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#90ff2030" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product8"
            android:id="@+id/Banana"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product12"
            android:id="@+id/Garlic"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#622aff00" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product16"
            android:id="@+id/Cookies"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#9bffb103" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Product20"
            android:id="@+id/Hair_Gel"
            android:layout_weight="1"
            android:textSize="9sp"
            android:textStyle="bold|italic"
            android:background="#4eff00dc" />
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:layout_marginLeft="10dp"
    android:weightSum="8">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:weightSum="4"
        android:background="#fffc84">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="        X"
            android:id="@+id/Remove"
            android:layout_weight="1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Product"
            android:id="@+id/Product"
            android:layout_weight="1"
            android:layout_marginLeft="5dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Quantity"
            android:id="@+id/Quantity"
            android:layout_weight="1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Price "
            android:id="@+id/Price"
            android:layout_weight="1" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="6"
        android:background="#ffffff">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/Remove1"
            android:background="#ffffff"
            android:layout_weight="1"
            android:textStyle="bold" />
    </ScrollView>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:weightSum="2"
        android:background="#49ffff07">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Total Items"
            android:id="@+id/Total_Items"
            android:layout_weight="1"
            android:layout_marginLeft="6dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sub Total"
            android:id="@+id/STotal"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:weightSum="2"
        android:background="#49ffff07">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Discount"
            android:id="@+id/Discount"
            android:layout_weight="1"
            android:layout_marginLeft="6dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tax(%5)"
            android:id="@+id/Tax"
            android:layout_weight="1"
            android:layout_marginLeft="10dp" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:weightSum="1"
        android:background="#49ffff07">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Total"
            android:id="@+id/FTotal"
            android:layout_weight="1"
            android:layout_marginLeft="6dp" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:layout_weight=".5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Clear"
            android:id="@+id/Clear"
            android:layout_weight="1"
            android:textStyle="bold|italic"
            android:background="#dfff000d" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Total_Result"
            android:id="@+id/Total"
            android:layout_weight="1"
            android:textStyle="bold|italic"
            android:background="#bc38ff00" />

    </LinearLayout>

</LinearLayout>

Multiple If and Then Statements

Here is a the VBA code that I have, and the only thing that works is the first and last if and then statements. But the two on the middle don't. What I want to happen is if a Username opens the workbook, excel will only show the worksheet that is intended for that person. That workbook will basically have different worksheet for different people and it will be shared. Does anyone have an idea how to fix the code?

Private Sub Workbook_Open()
On Error Resume Next

If VBA.Environ("username") = "Joseph" Then
     Worksheets("Joseph").Visible = xlSheetVisible ' First sheet to be made visible
     Worksheets("Mark").Visible = xlSheetVeryHidden
     Worksheets("Joel").Visible = xlSheetVeryHidden
     Worksheets("Ed").Visible = xlSheetVeryHidden

Else

If VBA.Environ("username") = "Mark" Then
     Worksheets("Mark").Visible = xlSheetVisible ' First sheet to be made visible
     Worksheets("Joseph").Visible = xlSheetVeryHidden
     Worksheets("Joel").Visible = xlSheetVeryHidden
     Worksheets("Ed").Visible = xlSheetVeryHidden

Else

If VBA.Environ("username") = "Joel" Then
     Worksheets("Joel").Visible = xlSheetVisible ' First sheet to be made visible
     Worksheets("Ed").Visible = xlSheetVeryHidden
     Worksheets("Joseph").Visible = xlSheetVeryHidden
     Worksheets("Mark").Visible = xlSheetVeryHidden

Else

If VBA.Environ("username") = "Ed" Then
     Worksheets("Ed").Visible = xlSheetVisible ' First sheet to be made visible
     Worksheets("Joseph").Visible = xlSheetVeryHidden
     Worksheets("Mark").Visible = xlSheetVeryHidden
     Worksheets("Joel").Visible = xlSheetVeryHidden

End If
End If
End If
End If

End Sub

How to handle if/else scope issue for variables set in "if condition" (Destroying GameObject in C#)

I'm using Unity and making a program that makes spheres appear once an object is clicked and then I want to delete the spheres when it is clicked again.

The problem is that on the initial run through the spheres are not defined since they are only created if the object is has not been clicked (!isSelected). I create them as an array of GameObjects but when I enter the else condition I receive the error NullReferenceException: Object Reference not set to an instance of an object Cube.OnMouseDown( ). I think this is because I originally set GameObject[] Spheres = null in the beginning. How should I initialize this variable so that I don't receive this error?

Also in general what's the best practice for using a variable that is defined in an if statement and modified in an else statement?

using UnityEngine;
using System.Collections;
using System.Linq;

public class Cube : MonoBehaviour {

    bool isSelected = false;

    void OnMouseDown() {
        Renderer rend = GetComponent<Renderer>();
        GameObject[] Spheres = null;

        if (!isSelected) {
            isSelected = true;
            rend.material.color = Color.blue; //#588c7e
            Vector3[] vertices = GetComponent<MeshFilter>().mesh.vertices;
            Vector3[] verts = removeDuplicates(vertices);
            Spheres = drawSpheres(verts);
        } else {
            rend.material.color = Color.white;
            print("destroy verts");
            for (int i=0; i<Spheres.Length; i++) {
                Destroy(Spheres[i]);
            }
            isSelected = false;
        }

    }
   GameObject[] drawSpheres(Vector3[] verts) {
        GameObject[] Spheres = new GameObject[verts.Length];
        for (int i = 0; i < verts.Length; i++) {
            Spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            Spheres[i].transform.position = verts[i];
            Spheres[i].transform.localScale -= new Vector3(0.8F, 0.8F, 0.8F);
            Spheres[i].AddComponent<VertClicked>();
        }
        return Spheres;
    }

} 

NOTE: I removed the removeDuplicates(), Start() and Update() functions from this class as I didn't think they contributed to the question.

How would I go about looping an if statement back to a certain part of the program? I already have a do-while that works for another issue

The gross pay cannot be less than the withholdings. My goal is to set that back up where the "do" is

#include <iostream>
using namespace std;

int main ()
{
    double userChoice, employeeNumber, grossPay, stateTax, federalTax, ficaWithholdings,
    netPay, totalGrossPay, totalStateTax, totalFederalTax, totalFicaWithholdings, totalNetPay; //Declares variables
    cout<<"\t\tMENU\n"; //Menus screen
    cout<<"----------------------------------------------\n";
    cout<<"1) Payroll Report \n";
    cout<<"2) Salesbar Chart \n";
    cout<<"3) Quit\n";
    cout<<endl;
    cout<<"Enter choice: ";
    cin>>userChoice;
    cout<<endl;
    while(userChoice == 1) //Executing payroll report
    {


        cout<<"Enter the employee number (0 to quit): ";
        cin>>employeeNumber;
        if (employeeNumber == 0)
        {
            cout<<"Program terminated";
            return 0;
        }
        while(employeeNumber < 0)
        {
            cout<<"Error, number can't be negative. \n"; //input validation
            cout<<"Enter the employee number: ";
            cin>>employeeNumber;
            cout<<"\n";
        }
        //-------------------------------------------------
        do {
        cout<<"Enter the gross pay: $"; //Gets gross pay
        cin>>grossPay;
        while(grossPay < 0)
        {
            cout<<"Error, number can't be negative. \n"; //Input validation
            cout<<"Enter the gross pay: $";
            cin>>grossPay;
        }
        //------------------------------------------------
        cout<<"Enter the state tax: $";
        cin>>stateTax; //gets state tax
        while(stateTax < 0 || stateTax > grossPay) //Input Validation
        {
            cout<<"Error, number can't be negative, or greater than gross pay \n";
            cout<<"Enter the state tax: $";
            cin>>stateTax;
            //while(stateTax > grossPay)
            /*{
                cout<<"Error, number can't be greater than the gross pay. \n";
                cout<<"Enter the state tax: $";
                cin>>stateTax;
            }*/                                                                      //documented out because was causing errorsin code
        }
        //----------------------------------------------    
        cout<<"Enter the federal tax: $";
        cin>>federalTax; //gets federal tax
        while(federalTax < 0 || federalTax > grossPay) //Input valdation for federal tax
        {
            cout<<"Error, number can't be negative, or greater than gross pay \n";
            cout<<"Enter the federal tax: $";
            cin>>federalTax;
            /*while(federalTax > grossPay)
            {
                cout<<"Error, number can't be greater than the gross pay. \n";
                cout<<"Enter the federal tax: $";
                cin>>federalTax;
            }*/
        }
        //-----------------------------------------------
        cout<<"Enter the FICA witholdings: $";
        cin>>ficaWithholdings; //gets fica
        while(ficaWithholdings < 0 || ficaWithholdings > grossPay) //input validation for fica
        {
            cout<<"Error, number can't be negative, or greater than gross pay \n";
            cout<<"Enter the FICA Withholdings: $";
            cin>>ficaWithholdings;
            //while(ficaWithholdings > grossPay)
            /*
            {
                cout<<"Error, number can't be greater than gross pay. \n";
                cout<<"Enter the FICA Withholdings: $";
                cin>>ficaWithholdings;
            }*/
        }
        cout<<endl;
        //------------------------------------------------
        netPay = grossPay - (stateTax + ficaWithholdings + federalTax);
        **if ((stateTax + ficaWithholdings + federalTax) > grossPay) //Gross pay cannot be less than taxes combined
        {
            cout<<"Error, witholdings cannot exceed gross pay.\n"; //*******Where I'm having trouble******
            cout<<"Reenter data: \n";
            cout<<"Enter the employee number (0 to quit): ";
            cin>>employeeNumber;

        }**
        totalGrossPay = totalGrossPay + grossPay; //Calculations
        totalStateTax = totalStateTax + stateTax;
        totalFederalTax = totalFederalTax + federalTax;
        totalNetPay = totalNetPay + netPay;
        totalFicaWithholdings = totalFicaWithholdings + ficaWithholdings;
        cout<<"Enter the employee number (0 to quit): "; //Asks for employee number to loop again
        cin>>employeeNumber;        
        }

        while(employeeNumber > 1);      //end of do-while

C# console app: How can I continue returning an error message until user enters valid data?

I'm building a method to calculate shipping cost. I've already validated the data type to an integer. As long as the integer entered is greater than 0, the logic works correctly. When the number entered is less than one, an error message is generated and repeats the request for a larger whole integer. Okay so far.

However, after the error message asks for a valid integer, the data entered is ignored and the calculation is incorrect. How can I repeat the request until the user enters a number greater than 0 and then perform the desired calculation with it? Thanks!

        static double CalculateShipping(int items, double shippingCharge)
        {
        if (items == 1)
            shippingCharge = 2.99;
        else if (items > 1 && items < 6)
            shippingCharge = 2.99 + 1.99 * (items - 1);
        else if (items > 5 && items < 15)
            shippingCharge = 10.95 + 1.49 * (items - 5);
        else if (items > 14)
            shippingCharge = 24.36 + 0.99 * (items - 14);
        else
        {
            Console.WriteLine("You must order at least 1 item.");
            Console.WriteLine();
            Console.Write("Please enter a whole number greater than  zero: ");
            items = Console.Read();
        }
        return shippingCharge;
    }

If Loop in Java till condition is no longer valid then continue with script

I am trying to delete every (visible) row in a table untill there are none left, only then do I want to continue with the rest of my test case. For this reason I'm using an if/else statement. As part of this statement I need to select the first row, click the delete button and then confirm my action by clicking OK. Then I want to go back and check if there is still a first row, if so then repeat till there are no more rows. If not, then press other button. This is what I've got so far:

if(driver.findElement(By.xpath("//div[@id='ext-gen445']/div/table/tbody/tr/td[2]/div")) != null) //to determine if there is a first row present
        {
            driver.findElement(By.xpath("//div[@id='ext-gen445']/div/table/tbody/tr/td[2]/div")).click(); // select first row
            driver.findElement(By.xpath("//*[@type='button' and text()='Delete']")).click(); //click delete
            wait.until(ExpectedConditions.elementToBeClickable(By.id("ext-gen483")));

            /** as there is more then one OK button I need the following code to find and click the correct OK button to confirm deleting the row */
            List<WebElement> listOfOKbut = driver.findElements(By.xpath("//*[@class=' x-btn-text' and text()='OK']"));
            if(listOfOKbut.size() >= 2) {
                listOfOKbut.get(1).click(); //click OK button to delete
        } Now I need to back to see if there is a first row again and repeat this till there are no more rows
else{
Only when there are no more rows do I want to continue

Problem now is that when it deletes the first row it skips the else statement and continues with the test script after the else statement, even though there are more rows present.

Also, when I change the first line so that the element cannot be found the script stops completely with a NoSuchElementException. Seems this bit of code is also incorrect.

As some of you may have noticed, I ask a lot of questions. I have not had any Java training (yet) but love what I can do with test automation using this stuff.

Thanks!

Why is this if statement returning false every time?

I have a piece of code. It is returning false every time, despite the fact that condition is true. Where am I wrong?

$a = 5;
$b = 10;
$c = 15;

if( ($c > $b) > $a){
    echo "yes";
} else {
    echo "no";
}

if statement not working correctly - java

I have this code with "if" statement :

    if(svc.bfi==0){changeBackgroundOnHoverUsingEvents(fi, svc.bfi);}
    if(svc.bcr==0){changeBackgroundOnHoverUsingEvents(cr, svc.bcr);}
    if(svc.brf==0){changeBackgroundOnHoverUsingEvents(rf, svc.brf);}
    if(svc.bmo==0){changeBackgroundOnHoverUsingEvents(mo, svc.bmo);}
    if(svc.bev==0){changeBackgroundOnHoverUsingEvents(ev, svc.bev);}

In here, even if svc.bfi = 1, still the function changeBackgroundOnHoverUsingEvents(fi, svc.bfi); is being executed & displaying the results, and this applies to all other variables - bcr, brf, bmo & bev.

is my if statement incorrect?

Here is the svc class :

class setValClick{
public byte bfi = 0;
public byte bcr = 0;
public byte brf = 0;
public byte bmo = 0;
public byte bev = 0;

public void display(){
    System.out.println(bfi + " " + bcr + " " + brf + " " + bmo + " " + bev);
}

}

and the function I'm calling changeBackgroundOnHoverUsingEvents(fi, svc.bfi); is displaying the desired changes, i.e, it is displaying that svc.bfi = 1, but is still being executed.

use self with if condition before super.init(nibName:)

I would like to use self with an if condition in init() method... (before the super.init()).

Here is my example I can't use (self before super.init) :

init()
{
    if #available(iOS 8.0, *) {
        if self.traitCollection.horizontalSizeClass == .Regular
        {
            super.init(nibName: ProductDetailsIdentifier, bundle: NSBundle.mainBundle())
        }
        else
        {
            super.init(nibName: ProductDetailsIdentifierIphone, bundle: NSBundle.mainBundle())
        }
    }
}

required init?(coder aDecoder: NSCoder)
{
    super.init(coder : aDecoder)
}

Can't pass an int from button if / else case to media player

how are you supposed to let the mediaplayer know what it is supposed to play?

wholeTextPlayer = MediaPlayer.create(Lesson1Reading.this, engAu);

It works fine if I declare the file in the top:

MediaPlayer wholeTextPlayer;
private int engAu = R.raw.l1r_en_l10;
Button btn_default_acc_whole;

It doesn't work from within a button click if / else statement wherever I try to put it with the following combination:

MediaPlayer wholeTextPlayer;
private int engAu;
Button btn_default_acc_whole;

The button click:

final Button btn_default_acc_whole = (Button) findViewById(R.id.btn_default_acc_whole);
    btn_default_acc_whole.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            if (wholeTextPlayer.isPlaying()) {
                wholeTextPlayer.pause();

            } else {
                wholeTextPlayer.start();
                startPlayProgressUpdater();
            }
            setEngAu(R.raw.l1r_en_l10); //this line doesn't want to fit anywhere
        }
    });

The setter:

public void setEngAu(int engAu) {
        this.engAu = engAu;
    }

Of course they are separately placed in the activity, I just copied and pasted the relevant bits from it.

Thanks guys.

jeudi 29 octobre 2015

Java restart program and keep count number of tries within the run

I created a quiz program that keeps track of students score. What I am trying to do is if the student received 100% then they get a message that their score is 100%. If the the score is less than 100 then the program should restart and keep the counter of up to 5 tries in the counter integer.

Once the counter reaches int of 5 with the score of less than 3 than break the program and display message "take a quiz later"

What is working right now: I am able to keep track of the "score" int variable and its working if you get 100% or less than 100%.

What I am trying to get working: Get the "counter" int variable working to keep the record of the number of tries so the user gets up to 5 tries and restart the whole console program while maintaining the score on the "counter" variable. for instance:

counter < 5 - try again 
     counter++
counter >= 5 - end the program.

Here is the end of the program. Maybe I should somehow place it in the method and recall it in my public void run but I was unable to accomplish that and keep record of scores. I have many loops so it would be unrealistic to write the whole program in loop one big loop.

Thanks!

   public void run()
    {
        if (score >= 3) 
            {
            println("You have passed the exam with 100%");
            }   
                else if (counter<5) 
                {
                counter++;
                println("You're score is less than 100%.");
                println(" ");
                println("Try Again!");
                //restart the questions until you're out of 5 attempts
                } 
                    else if (counter==5)
                    {
                        println("You're out of your 5 attempts");
                    }
    }

how to get a sum of the value which i get in the if condition

first of all i am new in this programming area so i don't know how to do this?

have a database table "video_master" in that i have "ID, REC_ID, VIDEO_DATE, VIDEO_COUNT, IS_REDIM, field in it. now i want a count of that amount. i use if and get a amount as video but now i don't know how to take a that amount sum. total amount. here i give what i done.

<?php

            // If user not logged in then show login message
            if (!isset($_SESSION['userid'])) {

                ?><div class="message">
                    To access this page, you must be logged.<br />
                    <a href="connexion.php">Log in</a>
                </div><?php
            }
            else{

                //Video count values of the database
                if(isset($_REQUEST['date1']) && isset($_REQUEST['date2'])){
                    $dnn = mysqli_query($conn, 'select video_date,video_count from video_master where  rec_id="'.$_SESSION['userid'].'" and video_date >= "' . $_REQUEST['date1'] . '" and video_date <= "' . $_REQUEST['date2'] . '"');
                }
                else{
                    $dnn = mysqli_query($conn, 'select id,video_date,video_count,is_redim from video_master where  rec_id="'.$_SESSION['userid'].'"');

                 }


                if(mysqli_num_rows($dnn)>0)
                {



                    ?><table>
    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Date</th>
                            <th>Video Count</th>

                            <th>Total Amount</th>
                            <th>Is Redim ?</th>
                        </tr></thead><?php

                        while($rowData = mysqli_fetch_array($dnn)){
                            //$video_date = date("Y-m-d","d-m-Y",$rowData['video_date']);
                            $video_date = $rowData['video_date'];
                            $video_count = $rowData['video_count'];

                            ?><tbody><tr>
                                <td><?php echo $rowData['id']; ?></td>
                                <td><?php print($video_date); ?></td>
                                <td><?php print($video_count); ?></td>
                                <td><?php //echo $rowData['video_count'];

                                    if($rowData['video_count'] < 250){
                          $amount1 = $rowData['video_count']*0;
                          echo $amount1;            
                } 
                else{
                            if($rowData['video_count'] <= 500){
                            $amount1 = $rowData['video_count']*0.25;
                            echo $amount1;            
                            } else
                            {
                                if($rowData['video_count'] <= 750){
                                $amount1 = $rowData['video_count']*0.50;
                                echo $amount1;            
                                } else
                                {
                                    if($rowData['video_count'] <= 1000){
                                    $amount1 = $rowData['video_count']*0.75;
                                    echo $amount1;            
                                    } else
                                    {
                                            if($rowData['video_count'] <= 1250){
                                            $amount1 = $rowData['video_count']*1;
                                            echo $amount1;            
                                            } else
                                            {

                                                if($rowData['video_count'] < 1500){
                                                $amount1 = $rowData['video_count']*1.50;
                                                echo $amount1;            
                                                } else
                                                {



                                                }        


                                            }        

                                    }


                                }                      

                            } 

                    } 


                                 ?></td>
                                <td><?php echo $rowData['is_redim'];  ?></td>
                            </tr></tbody><?php

                        }
                    ?></table><?php
                }   



                ?>
            <?php

            }


    ?>

i get a "$amount" as a video but now i want to calculate the total of that $amount. amount field is not in the database. i get the amount from video_count.

How can i get an element from QUEUE

int get(){
        if (head == 0) { 
            return -999; 
        }
        else {
            int v = head->item; 
            link t = head->next;
            delete head; head = t; 
            return v;
        }           
    }

Here is my switch case to call get function

if (q.get() != -999) {
    cout << q.get() << " element removed from Queue" << endl;
} 
else {
   cout << "nothing to get; queue is empty" << endl;
}

when i get an element like 1 from get function, im getting "nothing to get; queue is empty"message.

but i am able to get a correct element from the queue, but getting a wrong message. What is wrong in my code?

Android - possible way to notify other i chatted using If statement passing in a user?

I wonder how to make an if statement in android studio like if you click the send button it will notify the one i contacted. would that possible in if else? i am creating chat app and i am using firebase as the storage of messages.do you think this would be possible?

if (view == button){
  //number of message
   numMessage++

}
else{

 "notification builder code?"
}

ugh i dunno if what would be the best possible way to notify the other i contacted . because if you set an intent in your send button it will just notify the emulator not the one you send a message. give an idea or any suggestion.

trying to figure out how to "save" console inputs

I'm creating a java code that compares the ACT, SAT, and GPA scores of two applicants and determines which one would be the better applicant. I have all the math and everything figured out and basically my code calls on a method that uses an if/else statement to determine whether it's ACT or SAT scores then it goes to another method that asks about GPA and then it goes back and does both again but I'm having trouble figuring out how to get it to remember the first applicants scores and then remember the second so I can compare the two in the last method. Obviously once it goes and calls on the methods again for the second applicant it's going to replace the previous console inputs with the new ones.

Missing Return Statement within While Loop w/no exits

Long time reader, first time poster. I appreciate how helpful this community has been to me before, and I hope I can find an answer to my question!

I have a java method that is "missing a return statement." I have looked into this heavily, and know that the problem is most likely that the compiler found a path within an 'if' function which doesn't offer a return statement. However, my while loop should be set up so that when a path within an 'if' function reaches an endpoint where it doesn't return anything, it ends up looping the entire method.

The overall goal of the method is for the user to type in a file that they want to output to, but if they choose one that exists and then choose not to overwrite it, the initial question asking for a new file name is reexecuted, until a new file is entered or an existing file is entered and the user agrees to overwrite it.

Here is my code, does anyone know how to fix it? Thank you very much

    public static PrintStream getOutputPrintStream(Scanner console){
    boolean done = false;
    while (done = false) {
        System.out.print("Enter output file: ");
        File outFile = new File(console.next());

        if (outFile.exists()) {
            System.out.print("The file " + outFile + " already exists, would you like to overwrite it? (y/n): ");
            String overwrite = console.next();
            overwrite = overwrite.toLowerCase();
            char decision = overwrite.charAt(0);
            if (decision == 'y') {
                    try {
                        PrintStream output = new PrintStream(outFile);
                        done = true;
                        return output;
                    } catch (FileNotFoundException e){
                        System.exit(1);
                    }
            }
        } else {
            try {
                PrintStream output = new PrintStream(outFile);
                done = true;
                return output;
            } catch (FileNotFoundException e){
                        System.exit(1);
                    }
        }


    } 

}

Java loop run only for the max tries

I had created an if statement while its true to keep on asking question until you get it right. However that is not an option in my case. I have implemented a counter with the max tries, if the loop runs 3 times and you still got it wrong then print "you got it wrong" and go to the next question. If they get it right within 3 tries, "go to the next question" the score++ is just there to keep track of the score. score++ must keep the score only for the correct answer that is why its under while (true). If someone could help me out, that would be awesome. I am open to different ways I can improve my loop. Thank you!

Here's the loop:

int count = 0;
int maxTries = 3;

do {
    println(q1.PrintQuestion());
    yourAnswer = readLine("Your answer: ");
    if ((q1.IsAnswerCorrect(yourAnswer)) && (count < maxTries))
        break;
    else
        println("You got it wrong! \n");

} while (true);
count++;
score++; 
println("You got it right! \n");

Detect and print the multiples of a specific integer in Perl

I am trying to write a script that will detect the multiples of an integer that a user entered and is in the range of 200-100. I think I am missing something in my if statement because its not detecting any results for me.

use strict;

use warnings;

print "Enter an integer: ";

my $integer = ;

chomp $integer;

my @nums = (200..100);

my $i = 200;

while($i < $#nums) {

print "$nums[$i]  ";

++$i;

}

if ($i % $integer == 0){

print "$i\n";

}

Conditional statement issue [duplicate]

This question already has an answer here:

Hello stackoverflow community!

I'm having an issue trying to figure out why my do while loop continues to loop even when I am entering the correct condition to break it?

For an example when entering "rock" it still asks me to enter in a valid choice...

Here is my code:

  boolean isRight = false;

  System.out.println( "Enter Your Name");
            Scanner sc = new Scanner(System.in);
            String playerName = sc.nextLine();

          String UserChoice;

            do{
                System.out.println("Enter in rock, paper or scissors:");
                 Scanner user = new Scanner(System.in);
             UserChoice = user.nextLine();


                if( UserChoice != "rock" || UserChoice != "paper" || UserChoice != "scissors"){
                    System.out.println("You must enter either rock, paper or scissors. Try again: ");

                }else{
                 isRight = true;
                }

            }while(isRight==false);

I would really appreciate the help!

Dynamically create IF in PHP from database

I store dynamic conditions in Mysql in order to create conditions; I would need to create those conditions in PHP in order to accept if not the form.

Example: Database:

===============================
COND1  |  COND2  |  COND3  |
1      |  4      |         |
       |  4      |  3      |

I would like to make a loop inside BDD a create conditions:

if (($_POST[1]=="1") and ($_POST[2]=="4"){echo "ERROR";}
if ($_POST[2]=="4"){echo "ERROR";}
if (($_POST[2]=="4") and ($_POST[3]=="3"){echo "ERROR";}

Because conditions are dynamics I cannot create the IF statements

Id tried something like that but not working

if ($cond1!=""){$req0=" and (".$_POST['v1']." ==\"$cond1\")";}
if ($conf2!=""){$req1=" and (".$_POST['v2']." ==\"$cond2\")";}
if ($cond3!=""){$req2=" and (".$_POST['v3']." ==\"$cond3\")";}

if ("".$req0." ".$req1." ".$req2.""){//echo "ERREUR";}

I don't know how to generate if conditions in PHP :-(

batch multi-condition if else ==batch==

I would like to know how to use multicondition if else. For example I am looking if the folder (A) exists then move it to another folder (B) else if the folder (B) exists then move it to another folder (A) else msg * no such directry

code:

if exist ( C:\Users\%username%\AppData\ABC\
taskkill /f /im File.exe 
move C:\Users\%username%\ABC C:\Windows\system\ABC2\
msg * Move 
exit
 ) else if exist ( C:\Windows\system\Cool\
taskkill /f /im Viber.exe
move C:\Windows\system\Cool C:\Users\%username%\AppData\Roaming\ViberPC\
msg * You will active your viber thank you Enjoy it baby. i love you all 
exit
 ) else ( 
msg * This account (number) does not exist please singup on your smartphone to get acces thank you ... have a nice day
 ) )
pause

Short Circuiting: How would I write if then else with short-circuiting?

Is it possible to write a one-line if then else statement in a language that supports short-circuiting? It doesn't have to be language specific, just pseudocode.

In case you didn't know, short-circuiting means that a language will evaluate exp1 || exp2 || exp3 || exp4... (|| is the or operator) by first executing exp 1, then if it returns true, execute exp 2, and so on... However, the moment exp n returns false, it does not continue evaluating exp n+1 and anything after that.

Trying PHP IF Else Statements for the first time

I'm just learning PHP and I'm trying to understand the if else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age

Here is my code so far:

my .html file

<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>

my php file

<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";

if ($age == 25){
    echo "$yes";
}else{
 echo "$no";
}
?>

Thank you in advance for your time.

Excel: IF statement, Number less than X but greater than Y

Within my program I have a column(H) specifying hours (24.2, 23.5, 21.5, 25.0, 28.3, 23.1, 22.5, 17.9, 22.1, 16.2, 24.3, 23.8)this continues for 600 or so more rows.
Max hours = 36.88348 Min hours = 16.15569.
I'm trying to categorise the hours into 4 different numbers to later use for more accurate data than averages:
0 = 16-20, 1 = 21-25, 2 = 26-30, 3 = 31>.
So far I have came to this solution: =IF($H4>=31,3,IF($H4<=20,0,IF($H4>=21<=25,1,IF($H4>=26,2))))
This works apart from the 21-25($H4>=21<=25,1)
If anybody could assist me, i believe it's something basic as my syntax. Thanks much appreciated.

If / else statement in wordpress to change uploaded image to default

I have some trouble with changing image on default one when the image field is empty. Here the two different images. I want to combine them and if get_field('author_photo') is empty then upload the second one.

  <?php 
       $image = get_field('author_photo');
       if( !empty($image) ): 
  ?>

  <img src="<?php echo $image['url']; ?>" height="80" id="img-sp" alt="<?php echo $image['alt']; ?>" />

  <?php endif; ?>              

  <? if (get_user_featured_image_id('mentor','user_'.get_the_author_ID())){ ?>
  <?php $image = p_get_attachment_image_src(get_field('user_featured_image', 'user_'.get_the_author_ID()),'small-profile-thumbnail'); 
  ?>

  <img src="<?php echo @$image[0]; ?>" height="80"  alt="" id="img-sp"/>

Thanks in advance!

Why or condition is working differently compare with Java and SQL

In Java,

int a = 10, b = 10;

if (a == 10 || b==10)
{
// first condition (a==10) is true, so it wont check further
}

But, in SQL,

select * from my table where a = 10 or b = 10;

--As per my understanding, It should return data only based on a.
--But it returns both entries. 

Why is that?

IF statement with logical OR

Maybe one of you young gentlemen or ladies can help me with something.

if(1 == 2 || 4)
{
cout<<"True";
}
else
{
cout<<"False";
}

This is how I read the above. If 1 is equal to 2 or 4, then print true. Otherwise, print false. When this is executed though... true is printed. Obviously I'm misunderstanding something here. 1 is not equal to 2 or 4. Wouldn't that make it false?

Thank you and sorry for the stupid question.

Java nested if to switch statement

I'm having trouble transforming the following nested if statement below, into an equivalent switch statement. If anyone can give me some advice, it would be appreciated.

if (num1 == 5)
    myChar = ‘A’;
else
if (num1 == 6 )
    myChar = ‘B’;
else
if (num1 = 7)
    myChar = ‘C’;
else
    myChar = ‘D’;

How to check if a date cell in Excel is empty?

If feels like this should be really easy but I dont get it to work without retrieving the value of the cell again.

To start with, I have 2 date cells:

Dim agreedDate As Date
Dim completedDate As Date

THIS WORKS .. (but looks messy)

agreedDate = Worksheets("Data").Cells(Counter, 7).Value
completedDate = Worksheets("Data").Cells(Counter, 9).Value

If (IsEmpty(Worksheets("Data").Cells(Counter, 7).Value) = True) Or (IsEmpty(Worksheets("Data").Cells(Counter, 9).Value) = True) Then

[.. do stuff]
End If

THIS DOES NOT WORK - WHY NOT?!

agreedDate = Worksheets("Data").Cells(Counter, 7).Value
completedDate = Worksheets("Data").Cells(Counter, 9).Value

If (IsEmpty(agreedDate) = True) Or IsEmpty(completedDate) = True) Then

[.. do stuff]
End If

Is there a way to write the if statement in a clean and easy way?

if-else statement in conky not working properly

my if-elseif-else construct in conky is not working properly. It should display "wireless" when I am connect to a wifi, "wired" when I am connected to a wired lan and "no network", when I have no network connection. This is my conky-code which is not working properly:

${if_existing /proc/net/route wlan0}${color grey}wireless\
${else}\
${if_existing /proc/net/route eth0}${color grey}wired\
${else}\
${color grey}no network\
${endif}

The problem is that if I do have a wireless connection, nothing from my conkyrc after the lines written above is executed. If there is no network connection, it is working.

What is working though, is if I only use one if-else construct:

${if_existing /proc/net/route wlan0}${color grey}wireless\
${else}\
${color grey}no network\
${endif}

What am I doing wrong in the first snippet?

How to rewrite code for a (too) big IF statement?

I have a project with some UIbuttons with different UIimages displayed in it. Through user interaction, there could be any of the UIimages in the UIButtons. There are like around 1000 images in the project. I have initialised a variable named 'i'. And a IBAction named buttonTapped on all the buttons. Now I want to update variable 'i' and use the value of 'i' for every different possible `UIImage'. I can do this with an IF statement as shown here:

@IBAction func buttonTapped(sender: UIButton) {

if sender.currentImage == UIImage(named: "image1") {

    i = 1

    print(i)
    // use the value of i

} else if sender.currentImage == UIImage(named: "image2") {

    i = 2

    print(i)
    // use the value of i

} else if sender.currentImage == UIImage(named: "image3") {

    i = 3

    print(i)
    // use the value of i

     } else if // and so on

But I would like a better solution then an IF statement with around 1000 else if(s). I have tried, but I am not able to rewrite the code in a concise matter. What could I use instead of the IF statement? Some kind of loop?

Splitting String into characters and matching with users input in Java

I am working on very simple program to split characters from the word and ask user to input character. IF user input character match the characters array then display "YES" if not then display "NO". I used .ToCharArray method and loop to split each character from word and assign it to character array. Then I used for loop with IF statement to check the condition and display the result. But it matches with only one character from character array and ignores other.

public class test {


public static void main(String[] args) {

    // Declaring variables
    String[] wordsList= {"java"};
    char[] wChar = wordsList[0].toCharArray();
    char wCharLetter = 0;
    char inputChar;

    Scanner input = new Scanner (System.in);

    for (int i = 0; i < wordsList[0].length(); i++){
        wCharLetter = wChar[i];
    }

    for (int i = 0; i < wordsList[0].length(); i++){
        inputChar = input.next().charAt(0);
        if (inputChar==wCharLetter){
            System.out.println("YES");
        }
        else{
            System.out.println("NO");
        }
    }       

} }

According to my understanding; technically the wCharLetter variable should store all the characters, and it does when I print wCharLetter but doesn't work in matching.

How to formulate on specific dates

Lets say I have 5 invoices each having a total of 100 4 of the invoices are in the month of Jan and 1 in the month of Feb I would like to sum ONLY the 4 invoices of Jan thereby giving me a total of 400

I would expect to write a formula such as if invoice.date in period 01.01.2015 to 31.01.2015 then sum invoice.total

however when I try this, the result is 500 as it's totalling all invoices and note only the 4 in the period.

Java= arbitrary placement of if statement gives different output? [duplicate]

I am goofing around in CodingBat with Java Strings warm-ups.

The prompt was:

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).

last2("hixxhi") → 1

last2("xaxxaxaxx") → 1

last2("axxxaaxx") → 2

My first attempt was:

public int last2(String str) {

   String last = str.substring(str.length()-2);
   int count = 0;

   if (str.length() < 2){
      return 0;
   }


   for (int i = 0; i <str.length()-2; i++){
      String sub = str.substring(i,i+2);

      if (sub.equals(last)){
         count++;
      }
    }

return count;

}

This code produced the correct output for all tests except when the input string had a length less than 2 (output = Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:3), etc.), meaning the if statement was ignored.

enter image description here

However, simply moving the if statement above the variable declarations in the beginning of the method made the code correctly pass all tests (even strings with length less than two):

public int last2(String str) {

   if (str.length() < 2){
     return 0;
   }

  String last = str.substring(str.length()-2);
  int count = 0;

  for (int i = 0; i <str.length()-2; i++){
      String sub = str.substring(i,i+2);

      if (sub.equals(last)){
        count++;
       }
    }

    return count;

  }

Output for attempt 1

I feel like the variable declarations shouldn't have any impact on the functionality of the if statement... what is keeping my first coding attempt from working?