dimanche 30 avril 2017

Number Guessing Program issue Java

I'm having trouble with this assignment that I have been given(High School). It's a number guessing game and I have already gotten most of it down, but he wants us to put a range of numbers on the console. An example output would be:

Enter lower limit: 4

Enter Upper limit: 10

Etc, basically choose the specific range of numbers you want the computer to choose from. I have only been able to code in a set range(1-1000) since I can't figure out how to do what he wants. Here is my code:

import java.util.Scanner;


public class Game {
  public static void main(String[] args) {
        int randomNumber;
        randomNumber = (int) (Math.random() * 999 + 1);           
        Scanner keyboard = new Scanner(System.in);
        int guess;
 do {
            System.out.print("Enter a guess (1-1000): ");
            guess = keyboard.nextInt();

    if (guess == randomNumber)
  System.out.println("Your guess is correct. Congratulations!");
    else if (guess < randomNumber)
       System.out.println("Your guess is smaller than the secret number.");
  else if (guess > randomNumber)
 System.out.println("Your guess is greater than the secret number.");
        } while (guess != randomNumber);
  }

}

If you try it it is also really hard to play anyway. I would appreciate some help, thanks!

Effeciently test ifany three of four numbers are equal?

I am trying to determine a quick way to select sets of numbers (they'll be in arrays). I only need to keep sets where two or more of the numbers are greater than zero; therefore, sets that include zero three times can be discarded. I have come up with the following code but it doesn't have the expected outcomes, any advice would be greatly appreciated.

<?php
function testFour($a, $b, $c, $d)
{
  if(($a + $b + $c + $d) == ($a || $b || $c || $d)) {
      echo $a.", ".$b.", ".$c.", ".$d." => exclude<br>";
    } else {
      echo $a.", ".$b.", ".$c.", ".$d." => keep<br>";
    }
}
echo "<pre>";
testFour(0,0,0,5); // true
testFour(1,0,0,5); // false
testFour(0,4,2,0); // false
testFour(1,1,0,5); // false
testFour(0,2,0,0); // true
testFour(2,3,0,0); // false
echo "</pre>";

When using an if else statement, program goes straight to else

So after not coding in C for a while I wanted to make a simple test program where I would ask whether I liked a certain theme or not in Sublime Text

Here is the Code:

#include <stdio.h>

int main ( void )  {
    char A [ 2 ];
    printf ( "Do you like this theme? Answer Y or N: " );
    scanf ( "%d", A );

    if ( A == "Y" ) {
        printf ( "Good.\n" );
    } else {
        printf ( "Why not?\n" );
    }

    return 0;
}

I write an if else statement in which I tell the program if the input is "Y" then print Good. Makes sense right, well every time I run the program it goes straight to the else statement which asks Why not?

Here is the output:

C:\Users\           \Desktop>a
Do you like this theme? Answer Y or N: Y
Why not?

C:\Users\           \Desktop>

Not sure what the issue is been looking for a way to fix it for a while not but nothings seems to work. Any help would be great. And if you know a place to learn C, rather than reading a book, that would be really helpful as well.

PHP if statement inside HTML

I am checking if the value stored in my variable is equal to 0 or 1.
Depending on the value, I want to display some text inside my html form.
The value that I have inside $details['status'] is 0 of type int.

When I print_r() outside of the if-else structure, the result is 0.
However, if I print_r() inside the if statements, I get nothing back.

<form class="form-horizontal" action="/MVC/teacher/becomeTeacher" method="post">
    <?php print_r($details['status'])?> <!-- Gives me 0 -->

    <?php if($details['status'] === 1): ?>
        This will show if the status value is 1.
    <? elseif ($details['status'] === 0): ?>
        Otherwise this will show.
    <?php endif; ?>
</form>

If statement function is executing at a delay

I have an if statement that is measuring the microphone detection and triggering an animation. The issue I am having is that the animation begins 1/2 seconds after the user has stopped blowing. This is the code I have:

@interface ViewController ()
@property (nonatomic, strong) SecondViewController *secondVC;
@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[AVAudioSession sharedInstance]
 setCategory: AVAudioSessionCategoryRecord error:nil];

NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];

NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithFloat:44100.0],
                          AVSampleRateKey,
                          [NSNumber numberWithInt: kAudioFormatAppleLossless],
                          AVFormatIDKey,
                          [NSNumber numberWithInt: 1],
                          AVNumberOfChannelsKey,
                          [NSNumber numberWithInt: AVAudioQualityMax],
                          AVEncoderAudioQualityKey, nil];

NSError *error;

recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];

if (recorder) {
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    [recorder record];
    levelTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(levelTimerCallBack:) userInfo:nil repeats:YES];
} else
    NSLog(@"%@", [error description]);
}

- (IBAction)loadsecondVC:(id)sender {
    _secondVC = [[SecondViewController alloc] init];
    _secondVC.view.backgroundColor = [UIColor purpleColor];
    [self presentViewController:_secondVC animated:YES completion:nil];
}

- (void)levelTimerCallBack:(NSTimer *)timer {
    [recorder updateMeters];

    const double ALPHA = 0.5;
    double peakPowerForChannel = pow(10, (0.5 * [recorder peakPowerForChannel:0]));
    lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;

     if (lowPassResults > 0.5){
        NSLog(@"Mic blow detected");
        NSArray *animationArray = [NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"dandelion0001.png"],
                                   [UIImage imageNamed:@"dandelion0002.png"],
                                   [UIImage imageNamed:@"dandelion0003.png"],
                                   [UIImage imageNamed:@"dandelion0004.png"],
                                   [UIImage imageNamed:@"dandelion0005.png"],
                                   [UIImage imageNamed:@"dandelion0006.png"],
                                   [UIImage imageNamed:@"dandelion0007.png"],
                                   [UIImage imageNamed:@"dandelion0008.png"],
                                   [UIImage imageNamed:@"dandelion0009.png"],
                                   [UIImage imageNamed:@"dandelion0010.png"],
                                   [UIImage imageNamed:@"dandelion0011.png"],
                                   [UIImage imageNamed:@"dandelion0012.png"],
                                   [UIImage imageNamed:@"dandelion0013.png"],
                                   [UIImage imageNamed:@"dandelion0014.png"],
                                   [UIImage imageNamed:@"dandelion0015.png"],
                                   [UIImage imageNamed:@"dandelion0016.png"],
                                   [UIImage imageNamed:@"dandelion0017.png"],
                                   [UIImage imageNamed:@"dandelion0018.png"],
                                   [UIImage imageNamed:@"dandelion0019.png"],
                                   [UIImage imageNamed:@"dandelion0020.png"],
                                   nil];
        UIImageView *animationView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 375, 667)];
        animationView.animationImages      = animationArray;
        animationView.animationRepeatCount = 1;
        [animationView startAnimating];
        [self.view addSubview:animationView];
     }

        else if (lowPassResults < 0.5) {
        UIImageView *animationView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 375, 667)];
        [self.view addSubview:animationView];
        [animationView stopAnimating];
    }
}

@end

So the detection registers in the NSLog and when it stops, the animation plays. Do I have something in here that is delaying the animation? Or is an if statement the wrong thing to use here if I want it to happen at the same time. I have thought about using a 'while' statement but I got error messages when I did this.

I also need the animation to pause when the user stops blowing and proceed when they blow again so if anyone could help me out with the else statement I have at the bottom that would be really helpful as I know it is wrong.

Thanks in advance!

Matlab executes the first statement even if is false

I have the following function in matlab. I am trying to shuffle a matrix. But somehow matlab keeps executing the code from if even if the statement should go to else. And when it comes to else I have to put some aditional code, even if all it does is **i+1. It is normal for matlab or am I missing something?

function magic_matrix = magicsquare1(matrix,n)
magic_matrix=ones(n,n)*(-1);
i=3-1;
j=4+1;

for ki=1:n
for kj=1:n
    if(i<1)
        i=n;
    end
    if(j>n)
        j=1;
    end
    if magic_matrix(i,j) == -1

        magic_matrix(i,j)=matrix(ki,kj);
        %X = sprintf('i=%d j=%d',i,j);
        %disp(X)
        i=i-1;
        j=j+1;
    else
        i=i+2;
        j=j-1;
        if(i>n)
            i=1;
        end
        if(j<1)
            j=n;
        end
        magic_matrix(i,j)=matrix(ki,kj);
       % X = sprintf('i=%d / j=%d',i,j);
        %disp(X)
        i=i-1;
        j=j+1;
    end
end
end

An Python version of an R ifelse statement

I am trying to learn Python after learning R and an simple ifelse statement.

In R I have:

df$X <- if(df$A == "-1"){-df$X}else{df$X}

But I am unsure how to implement it in Python, I have tried:

df['X'][df['A'] <1] = -[df['X']
df['X'][df['A'] >1] = [df['X']

But this leads to errors, would appreciate some help.

How to add a logic statement to an object entering a moving area

I am trying to make a game. The object of the game is to move the square across the screen without hitting a raindrop falling from the roof. How do i make it so that if one of the raindrops enters the square, the square returns to the beginning of the canvas or x =0. Here is the code:

var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');

var WIDTH = 1000;
var HEIGHT = 700;
var x = 0;
var y = HEIGHT-20;
var xPos = [0];
var yPos = [0];
var speed = [1];
var rainDrops = 50;
var rectWidth = 20;
var rectHeight = 20;






for (var i = 0; i < rainDrops; i++) {
    xPos.push(Math.random()* WIDTH);
    yPos.push(0);
    speed.push(Math.random() * 5);

    }



function rainFall () {

    window.requestAnimationFrame(rainFall);
    ctx.clearRect(0, 0, WIDTH, HEIGHT);



    for (var i = 0; i <rainDrops; i++) {
    //Rain
    ctx.beginPath();
    ctx.arc(xPos[i], yPos[i], 3, 0, 2 * Math.PI);
    ctx.fillStyle = 'blue';
    ctx.fill();

    //Rain movement
    yPos[i]+=speed[i];

    //Box

        ctx.fillStyle = 'red';
        ctx.fillRect(x, y, rectWidth, rectWidth);

    if (yPos[i] > HEIGHT) {
        yPos[i]= 0;
        yPos[i]+=speed[0];
        }
    //This is the part where I need the Help!!!!!!!!!
    if (){
        x = 0;
    }

    }


};



//Move Object

function move (e) {
    if (e.keyCode === 37) {
        ctx.clearRect (0, 0, WIDTH, HEIGHT);
        x -=10;
    }
    if (e.keyCode === 39) {
        ctx.clearRect (0, 0, WIDTH, HEIGHT);
        x+=10;
    }
    canvas.width=canvas.width

}




//Lockl Screen

window.addEventListener("keydown", function(e) {
    // Lock arrow keys
    if( [37,39,].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);


rainFall(); 
document.onkeydown = move;
window.addEventListener("load", doFirst, false);

I'm having trouble with this code, the image names are correct; what do I do? How can I solve this Traffic Light Sequence?

I have been trying to create a JavaScript traffic light sequence as an experiment. The code seems right but for some reason, it's not working. Can someone please help?

<!DOCTYPE html> 
<html>

<body>

  <h1>Traffic Lights Task 3 JavaScript Controlled Assesment 2017</h1> 

  <img id="Traffic_Lights" src="RED.png">
  <button type="button" onclick="changeLights()">Change Lights</button>   

<script>

    var image = ["RED.png","AMBERRED.png","GREEN.png","AMBER.png"];

    function changeLights() {

      if (Traffic_Lights.src == "RED.png") {
      Traffic_Lights.src = image[1];
    } else if (Traffic_Lights.src == "AMBERRED.png") { 
      Traffic_Lights.src = image[2];
    } else if (Traffic_Light_Sequence.src == "GREEN.png") { 
      Traffic_Lights.src = image[3];
    } else {
      Traffic_Lights.src = image[0]

    }

      var Traffic_Light_Sequence = document.getElementById('Traffic_Lights');

    } 

  </script>  
</body> 

Swap words in sentence with String Buffer

Im having trouble with an application I have to build for college.

Develop an app that accepts following sentence from a user “Hickory Dickory, Ben. The mouse ran up the clock”. The app should change to word Ben with the word Dock. The app should then return the sentence “Hickory Dickory, Dock. The mouse ran up the clock”.

Some tips we were given are: 1. if there is space 2. if there is a char in the string at index 1 with a D 3. if there is a char in the string at index 2 with a O 4. if there is a char in the string at index 3 with a C 5. if there is a char in the string at index 4 with a K 6. if there is a space

This what I have tried but it doesnt work:

public void compute(){
  for(int i=0;i<sentence.length();i++){
     if(sentence.charAt(i)==' ')
        strBuff.append(' ')&&
        sentence.charAt(i)=='B'
           strBuff.append('D')&&
           sentence.charAt(i)=='e'
              strBuff.append('O')&&
              sentence.charAt(i)=='n'
                 strBuff.append('C')&&
                 sentence.charAt(i)==' '
                    strBuff.append('K');

     }
     else{
        error="Sorry please try again";
     }

  }
  newWord=stringBuff.toString();
}

We are to use string buffers, if statements and loops to swap the words. I just need help with the compute part. Please help.

How to code if else based on decision tree

I have a decision tree with Yes/No questions that includes the output. How can i implement such code using if else statement with yes/no button in Android Studio? Please help me with some code.

my decision tree

Yacc NULL in OCaml?

I am implementing the following grammar in OCamlyacc and OCamllex:

The OCaml type declaration for my IF-ELSE clauses is as such:

(* Some code not shown *)
and stmt  = ASSIGN of lv * exp
      | IF of exp * stmt * stmt 
      | WHILE of exp * stmt
      | DOWHILE of stmt * exp
      | READ of id
      | PRINT of exp 
      | BLOCK of block
(* Some code not shown *)

I can define the IF-ELSE portion in OCamlyacc as such:

stmt:
   |    IF LPAREN e RPAREN stmt                 { S.IF ($3, $5, ???) } /*line 1*/
   |    IF LPAREN e RPAREN stmt ELSE stmt       { S.IF ($3, $5, $7) }  /*line 2*/

But, how can I put "NULL" for a statement type ("stmt"), where the question marks are for the IF-Statement that does not have an ELSE (line 1)? I do not have access to a statement type that only has an expression ("exp") and only one statement.

I thought about putting a "while(0){print(0)}" statement there, but that is not how you are suppose to do it, especially because it will parse in a while-statement when it shouldn't.

Condition not passing into if statement

I'm trying to increase the count each time the function is run, it seems as though count is being reset each time the function is run. I think the count in the if statement may not be the same one that's passed as a condition. Thanks

def check_solution(user_solution, solution, count):

if user_solution == solution:
        count =+1
        print(count)
        return count
else:
    print("Incorrect")

how to use single delete page for deleting data from mulltiple pages in php using sql

<?php
 include('connect.php');
  if(empty($_REQUEST['b-id']))
 {
$id=$_REQUEST['id'];
$query="delete from contact where id='$id'";
$data=mysqli_query($con,$query);
    if($data>=1)
    {
        echo "<script>
        alert('Data Deleted Suceefully');
        window.location.href='user-queries.php';
        </script>";
    }
    else
    {
        echo "<script>
        alert('Process Failed');
        window.location.href='user-queries.php';
        </script>";
    }
}
 elseif(empty($_REQUEST['id']))
   {
   $bid=$_REQUEST['b-id'];
   $query1="delete from registration where id='$bid'";
   $data1=mysqli_query($con,$query1);
    if($data>=1)
    {
        echo "<script>
        alert('Data Deleted Suceefully');
        window.location.href='all-builders.php';
        </script>";
    }
    else
    {
        echo "<script>
        alert('Process Failed');
        window.location.href='all-builders.php';
        </script>";
    }
}

?>

In this, i am trying to delete rows from multiple pages by redirecting then on a single page.. but the problem is that when it redirects it deletes the data but also shows an error while it is not getting the another data.. if condition is also not working.. what to do and how to.

samedi 29 avril 2017

Not getting output in javascript

<script type="text/javascript">
    var score=1;
    if (score==1) {
    document.write("<a class="next" onclick="plusSlides(1)">&#10095;</a>");
    }
</script>

my javascript output is not coming, my IDE is telling that there is an unexpected token

How to call the next line during enumerate when using if-and-if statement

I am working on the code below where AnalyteName_user_input is a list of strings as seen in the image below.

AnalyteName_user_input

Occasionally there is an instance where the value of index seven is 'W' rather than 'W2'. The current goal is to create a new list which would be AnalyteRatio_user_input. This would contain the values of a ratio evaluation between float values from the MeanResponse_list list. I believe the current issue lies in line 3 where I am attempting to use an if-in-and-if-in statement. I believe the issue is that I am trying to call the next line in the enumeration but line+1 is the 'W' value from the AnalyteName_user_input list. How would I remedy this to call the next line in the list rather than the string and then adding some int value?

AnalyteRatio_user_input = []
for i, line in enumerate(AnalyteName_user_input):
    if 'W' in line and 'W2' in line+1: # need a way to define the next line. Unsure about this.
    AnalyteRatio_user_input.append(MeanResponse_list[i]/MeanResponse_list[i+5])
    AnalyteRatio_user_input.append(MeanResponse_list[i+1]/MeanResponse_list[i+5])
    AnalyteRatio_user_input.append(MeanResponse_list[i+2]/MeanResponse_list[i+5])
    AnalyteRatio_user_input.append(MeanResponse_list[i+3]/MeanResponse_list[i+5])
    AnalyteRatio_user_input.append(MeanResponse_list[i+4]/MeanResponse_list[i+5])
    AnalyteRatio_user_input.append(MeanResponse_list[i+5]/MeanResponse_list[i+5])
else:
    AnalyteRatio_user_input.append('N/A') 

If Statement Firing Regardless of Conditions, Variable not Aggregating Past One

Please see my comments. They explain my problems. I have an if statement that is firing no matter what and a variable that is not aggregating properly and I don't know why. Thanks in advance. (The following is a hangman program currently in development. printBody() will eventually print out the whole man.)

import random

words = []

lettersGuessed = []

isGuessed = 0



wordFile = open(r'C:\Users\Sarah\PycharmProjects\hangman\words.txt')

for word in wordFile:
    words.append(word.strip())

limbCount = 0

def printBody(limbCount):
    limbCount += 1

    if limbCount == 1:
        print("\n0")
    elif limbCount == 2:
        print("\n0")
        print("\n |")

    return limbCount

mysteryWord = random.choice(words)

while len(mysteryWord) <= 1:
    mysteryWord = random.choice(words)

for letter in mysteryWord:
    print("?", end = "")
print("\n")

def isWon(mysteryWord, lettersGuessed):
    #win conditions
    count = 0
    for letter in mysteryWord:
        if letter in lettersGuessed:
            count += 1

        if count == len(mysteryWord):
            isGuessed = 1
            return isGuessed



count = 0
victory = 0
while not victory:



    guess = input("Guess a letter \n")

    if guess.upper() or guess.lower() in mysteryWord:
        lettersGuessed.append(guess)
        for letter in mysteryWord:
            if letter in lettersGuessed:
                print(letter, end ='')
            else:

                print("?", end = '')

    #this statement is firing no matter what and I don't know why
    if guess.upper() or guess.lower() not in mysteryWord:
        #when I call printBody() limbCount increases to one but then stays there. It won't go up to two or three.
        printBody(limbCount)



    print("\n")
    count = 0
    victory = isWon(mysteryWord, lettersGuessed)


print("Congratulations, you correctly guessed ", mysteryWord)

elfi statement won't run in Python

This is my code. The last ELIF statement it keeps saying is wrong when ran from codeacademy labs - BATTLESHIP GAME EXERCISE!

from random import randint

    board = []

# All code functions here

    for x in range(0, 5):
        board.append(["O"] * 5)

    def print_board(board):
        for row in board:
            print " ".join(row)

    print_board(board)

    def random_row(board):
        return randint(0, len(board) - 1)

    def random_col(board):
        return randint(0, len(board[0]) - 1)

# All game variables for row and col guessing

    ship_row = random_row(board)
    ship_col = random_col(board)
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

# Prints the variable chosen randomly
    print ship_row
    print ship_col


    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sank my battleship!"

# THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT 
# RUNS
# WHAT'S WRONG WITH IT?

    elif guess_row not in range(0, len(board)-1) or guess_col not in        
        range(0, len(board)-1):
         print "Oops, that's not even in the ocean"

# final else statement. Prints missed battleship msg
else: print "You missed my battleship!" board[guess_row][guess_col]="X" print_board(board)

IF, ELIF, ELSE and OR with Python, not working

I´m trying to make this simple project work but is not working at all, i don´t know the if statement with the: if name == " Cher " or name == " Madonna ": print ("May I have your autograph please?"), is not working. I tried a lot of combinations and when I digit Jansen as the name it goes to the correct print, and also another name not listed, but when I put Cher or Madonna it goes to the print of the Else statement. Could someone help me to see what is wrong? I´m using the Python IDLE and Python Shell to run it. Thanks in advance.

password = input("Digit the password: ")

while password != "hello":
   password = input("Digit the password: ")

if password =="hello":
   print ("Welcome to the second half of the program!")
   name = input("What is your name?")

   if name == " Cher " or name == " Madonna ":
         print ("May I have your autograph please?")

   elif name == "Jansen":
         print ("What a Great Name")

   else :
        print (name, "that's a nice name.")

BASH IF statement with Y/N

I have this code below which is part of a much longer script I'm working on to help automate some sysadmin tasks on fresh servers but I can't seem to get the logic working for this IF statement.

apt-get -y install ${CORE_TOOLS[*]}

printf "\nWould you like to install some \033[0;32moptional\033[0m tools in addition to the core build toolkit? [Y/N]\n"
read -r -p answer
if [[ $answer = "Y" ]] ; then
    apt-get -y install ${EXTRA_TOOLS[*]}
fi

........

Once the user types Y and hits enter it's supposed to execute the statement with apt-get, but simply does nothing and continues to execute the rest of the script without throwing any errors.

Processing triggers for ca-certificates (20141019+deb8u2) ...
Updating certificates in /etc/ssl/certs... 174 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d....done.

Would you like to install some optional tools in addition to the core build toolkit? [Y/N]
answerY
Cloning into 'testcookie-nginx-module'...
remote: Counting objects: 294, done.
remote: Total 294 (delta 0), reused 0 (delta 0), pack-reused 294
Receiving objects: 100% (294/294), 253.53 KiB | 0 bytes/s, done.

Any idea why this might be?

In a swift Project, can I have an if else function that sends you to certain view controllers depending on the user input?

I'm very new to coding and have only been doing it for a few months. I'm building a choose your own adventure, and I wanted to know if in a playground I could take user input from a UITextField and run it through an if else function, so that for example they input a number and that number is divisible by 5 then it will send them to a new view controller where it says they have died. Otherwise it sends them to a different page with a different outcome.

Creating an if statement in Joomla

I've built a website using a purchased template and Joomla. I have a corporate logo which shows up perfectly on desktop. It comes up way too big on mobile. This is the following code I have entered.

How would I write an if statement so that logo/picture only shows up on desktops and not mobile? Or perhaps to make the logo appear, just smaller?

else condition is always executed even if the if statement is true

I am trying forever to fix this code: i have a list and i am searching through the list to find students. Once i don't find a student, an error message should appear. At the moment i have a function who searches the student based on text match. I have an if statement inside the function. When the match is found show student and when not, hide all the students. I created a variable 'found' set to 'true' when the student is found. if this is false the message should be appended.

The problem is that both conditions are being executed it seems so if i put found as being false inside the second condition the error message will display every time.

At the moment i have another if which checks if found was false. the problem is it doesn't recognise that it is false...so confusing. Please see screenshot with the console where you can see that although the student is found, the second condition is executed each time... screenshot with the console - second condition is always executed

First condition doesn't execute unless it's true.

Please help as I am trying to investigate this forever and I asked lots of questions here around this issue but with no big results.

Thanks so much, Alina

//add search bar 
$( ".page-header" ).append('<div class="student-search"></div>');
$( ".student-search" ).append('<input id="input-search" placeholder="Search for students..."/><button id="search">Search</button>');

// append to the .page the container div for the error message
$('.page').append('<div class="error"></div>'); 
// append to the error div a p with the error message if student is not found

var found = true;


//myFunction
function myFunction() {  
    var input = document.getElementById("input-search");
    var filter = input.value.toUpperCase();
    for (var i = 0; i < li.length; i+=1) {  
        var h = li[i].getElementsByTagName("h3")[0];
        if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
            li[i].style.display = ""; 
            console.log('yey found it');
            found = true;
        } else {
            li[i].style.display = "none";   
            console.log('condtion 2');
        }      
      } 
      if (found===false) {
         $('.error').append('<p>"student not found!"</p>');  
      }
    $('.pagination').hide();
}

//myFunction end
$('#search').on('click', function(){
      myFunction();         
});

// when the input is empty return to page 1, empty the error div, show pagination, 

$('#input-search').on('keyup', function() {
 if($(this).val() === '') {
   go_to_page(0);
   $('.pagination').show();
  }
});

PHP Foreach in Foreach with if statement

I am writing a web and i got stuck. PHP is not my language of choice, so I'm not that used to it. But lets look at the problem:

$i = 1;
$n = 0;
<div class="hs_client_logo_slider">
<?php
foreach ($hashone_client_logo_image as $hashone_client_logo_image_single) {
  foreach ($hashone_logo_list as $hashone_logo_url) {       
    if ($i > $n) {
      ?>
      <a target="_blank" href="<?php echo esc_url($hashone_logo_url) ?>"> 
        <img alt="<?php _e('logo','hashone') ?>" src="<?php echo esc_url(wp_get_attachment_url($hashone_client_logo_image_single)); ?>">
      </a>
      <?php
      $n = $n + 1;
      continue 2;
    } else {
        $i = $i + 1;
        continue 1;

Basically I am trying to do:

Foreach (x as y) && Foreach (a as b) {
  /* Magic happens here */

In the first foreach I have images and in the second one links. And for the first image I need the first link stored in logo_list, for the second image I need second link and so on... So I tried If statement that could take care of it, but for some reason it doesn't work.

Now it gives me first image with first link, but every image after that is stuck with second link. Do you have any idea what to do?

I'm glad for everyone who tries to help me out. Thank you very much.

what does this do??? /[\\/]electron-prebuilt[\\/]/.test()

I cloned a Electron React Boilerplate repo and in the main.js saw this in the code:

if ( process.defaultApp || /[\\/]electron-prebuilt[\\/]/.test(process.execPath)

What is this called and what does it do? /[\\/]

I have never seen this. I also do not have a keyword to search Google because I have no reference term to search.

Laravel API give json response when got error This action is unauthorized

I newbie in Laravel API. I do the update function. User can update the only their own post and cant update other people post. It worked. When user try to update other user's post, it will show the error response. But now it just show error like image below.

error diplay like this

I want show error like this

{
"status": "error",
"message": "This action is unauthorized",
}

This is my code for PostController.

public function update(Request $request, Post $post)
{

    $this->authorize('update', $post);    
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json) 


    $post->content = $request->get('content', $post->content);
    $post->save();

    return fractal()
        ->item($post)
        ->transformWith(new PostTransformer)
        ->toArray();

}

This code for PostPolicy

public function update(User $user, Post $post)
 {
    return $user->ownsPost($post);
 }

This is code for User model

public function ownsPost(Post $post)
{
    return Auth::user()->id === $post->user->id;
}

This code for AuthServiceProvider

 protected $policies = [
        'App\Post' => 'App\Policies\PostPolicy',
];

matlab vectorization if statement

Can someone please tell me the vectorized implementation of following matlab code. Predicted is an array containing either of the two values "pos" or "neg". I have to copy the values when condition comes true.

    p = 1;
    box = zeros(size(bbox));


   for k = 1: size(predicted)
        if predicted(k) == 'pos'
            box(p,:) = bbox(k,:);
            p = p + 1;
        end
   end

Using WordPress filter multiple times

I am not able to run two functions at the same time while using a filter that one of my plugins allow me. Actually I am trying to charge users as per checkboxes selection. But with my code, as given bellow, I am only able to process one payment (woo-commerce product) at a time.

PS: To understand the question more clearly, I am using toolset types plugin for custom fields, cred form & cred commerce plugins to charge for posting ads and woocommerce to process the payment. In my form, I have 2 addons as checkboxes that if users click when posting are charged accordingly.

// Function for urgent-banner
add_action ('cred_commerce_add_product_to_cart','my_hook',10,3);
function my_hook($product_id, $form_id, $post_id)

{
// product id is the current associated product ID
// form_id is the cred commerce form id
// post id is the post created or edited with the current form

if (get_post_meta(get_the_ID(), 'wpcf-urgent-ad', true)) {
$product_id = 687;
//$product_id = 209;
}

return $product_id; 
}

//Another function for Home page slider carousel

add_action ('cred_commerce_add_product_to_cart','my_hookc',9,3);
function my_hookc($product_id, $form_id, $post_id)

{
// product id is the current associated product ID
// form_id is the cred commerce form id
// post id is the post created or edited with the current form

if (get_post_meta(get_the_ID(), 'wpcf-home-page-carousel', true)) {
$product_id = 209;
}

return $product_id; 
}

How To Write To Txt File Using If Else Statement Within a Button

I am trying to find a way to write information gathered via scenebuilder into a .txt file. I managed to use if else statements to produce the desired results within the output window. Sadly, I am unable to find a way to save the file. I need a way to save and restore the information. Please help.

/*
* To change this license header, choose License Headers in Project 
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javafxapplication1;

import java.awt.Checkbox;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;


/**
*
* @author cwcis
*/
public class FXMLDocumentController implements Initializable {

private Label label;
@FXML
private Button save;
@FXML
private Button restore;
@FXML
private Button calculate;
@FXML
private TextField textcalccost;
@FXML 
private RadioButton vanilla;
@FXML 
private RadioButton chocolate;
@FXML 
private RadioButton strawberry;
@FXML
private CheckBox nuts;
@FXML
private CheckBox cherries;
@FXML 
private ToggleGroup IceCream;

@FXML
private void handleButtonSaving(ActionEvent event) {
if(vanilla.isSelected()) {
System.out.println("Vanilla");
}
if(chocolate.isSelected()) {
System.out.println("Chocolate");
}
if(strawberry.isSelected()) {
System.out.println("Strawberry");
}
if(nuts.isSelected()) {
System.out.println("With_Nuts");
}
else {
System.out.println("Without_Nuts");
}
if(cherries.isSelected()) {
System.out.println("With_Cherries");
}
else {
System.out.println("Without_Cherries");
}
}

@FXML
private void handleButtonRestore(ActionEvent event) {  
}

@FXML
private void handleButtonCalculateCost(ActionEvent event) {
double myTotal = 0.0;

myTotal += retrieveIceCreamCost();
myTotal += retrieveToppingsCost();
myTotal += retrieveTaxCost();

showAlert(myTotal);
}

private void showAlert(double theTotal) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Ice Cream Shop");
alert.setHeaderText("Order Confirmation");
alert.setContentText("Order: " + (retrieveIceCreamCost() + 
retrieveToppingsCost()) 
+ "\nTax: " + retrieveTaxCost() + "\nTotal: " + theTotal);
alert.showAndWait();
}

private double retrieveIceCreamCost() {
double iceCreamCost = 0.0;

if(vanilla.isSelected()) {
iceCreamCost = 2.25;
}
if(chocolate.isSelected()) {
iceCreamCost = 2.25;
}
if(strawberry.isSelected()) {
iceCreamCost = 2.25;
}
return iceCreamCost;
}

private double retrieveToppingsCost() {
double toppingsCost = 0.0;

if(cherries.isSelected()) {
toppingsCost += 0.50;
}
if(nuts.isSelected()) {
toppingsCost += 0.50;
}
return toppingsCost;
}    

private double retrieveTaxCost() {
double taxCost = 0.0;

if(cherries.isSelected()) {
taxCost += .03;
}
if(nuts.isSelected()) {
taxCost += .03;
}
if(vanilla.isSelected()) {
taxCost += .14;
}
if(chocolate.isSelected()) {
taxCost += .14;
}
if(strawberry.isSelected()) {
taxCost += .14;
}
return taxCost; 
}

public FXMLDocumentController() {
}

@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}    

}

MySQL if exists update values else insert

I am creating an application that stores a students attendance.

I am creating the database that will store this attendance and I am stuck on the mySQL query.

I want the query to search for the 'lecture name' and the 'user_id' (foreign key from other database) and if that exists increment the students attendance to the lecture (attended++ and total++)

So far I have this:

    INSERT INTO `attendance`(`attendance_id`, `module_code`, `lecture_name`, 
`attended`, `total`, `user_id`) VALUES ("null","test","TEST",1,1,1)
   ON DUPLICATE KEY UPDATE 
 attended = attended+1,total = total+1                                                                                              

This will insert a new row but for the ON DUPLICATE, there is no way to pass the primary key in to check for a 'duplicate'

I was wondering if there is another way to do this in MySQL other than ON DUPLICATE KEY, or if anyone can help me out.

Here is a screenshot of the database. For example see the 'Operations Research' was created when it should of incrememented the values. This is because I have no way of adding the primary key into the SQL query.

I would appreciate any help towards this, Thanks.

screenshot of the database

How to exit a while loop that uses numbers with a character that doesn't mess up the math

I have a script to write that is able to take user input of however many numbers they want until they press "q". Now I have it working, but it takes q and uses it in the math that the other numbers should be being used in. It also uses it to show what is the highest or lowest number.

total=0
count=0
largest=num
smallest=num
while [ "$num" != "q"
do
      echo "Enter your numbers when you are done enter q"
      read num
      total=`expr $total + $sum`
      count=`expr $count + 1`
      if [ "$num" > "$largest" ]
            then
                   largest=$num
      fi
      if [ "$num" < "$smallest" ]
      then
                   smallest=$num
      fi
done
avg=`expr $total / $count`
echo "The largest number is: $largest"
echo "The smallest number is: $smallest"
echo "The sum of the numbers is: $total"
echo "The average of the numbers is: $avg"

How to ensure only 2 divs are selected in javascript

I've done quite a bit of searching around and can't seem to find what I'm looking for so hoooopefully this isn't super repetitive. I'm making a pretty simple memory game in vanilla javascript (trying to stay away from jquery so I can get the basics of JS down)

Here's a link to the fiddle so you can see the whole works as well as the function I think is giving me the trouble: http://ift.tt/2pvCKyk

var showTile = function() {
var tile = document.getElementsByClassName('tile');
var tilesChosen = 0;
console.log(this.style.backgroundColor);
console.log(this);

if (tilesChosen < 2) {
    this.classList.remove('card-back');
    tilesChosen = tilesChosen + 1;
    console.log('under 2');
    console.log(tilesChosen);
}
else if (tilesChosen == 2) {
    tile.removeEventListener('click', function() {
        console.log('hit the max');
    })
}

};

and my problem here is that I can click on a tile, the card-back class is removed revealing the color but I can't figure out how to limit that to only 2 tiles.

My current train of thought goes something like this:

tilesChosen is set to zero
if statement checks if tilesChosen is < 2
if so, increment tilesChosen by 1
else, if tilesChosen == 2, then remove the event handlers on all the classes which I would think would stop anyone from overturning more than 2 tiles.

but so far I'm not even entering into the elseIf regardless of how many tiles you click. also, tilesChosen isn't incrementing beyond 1 so its like I'm stuck in the if part of the statement. I've also put this if/else inside for and while loops hoping to force it to loop through and test tilesChosen for its value but its the same thing.

any advice you guys have would be much appreciated!

getting image with if condition in laravel 5.4

I try to print uploaded image by user in Laravel 5.4 with if condition and if user does not uploaded any image to show default image but my code prints nothing somehow, this the code i use:

@if (File::exists($post->image))
    {
        echo "<img src="" alt="" />";
    } else {
        echo "<img src="" alt="" />";
    }
@endif

Read each individual word in string per 'if'

Hi is there a way to make Java read each individual word per 'if' in string? I will try my best to explain this...

public class test{
    public static void main(String[] args){
        String sentence = "testing1 testing2 testing3 testing4"

        //Scan first word \/ 
        if(sentence.equals("testing1"){
            //scan second word \/
            if(sentence.equals("testing2"){
                //scan third word \/
                if(sentence.equals("testing3"){
                    System.out.println("Works good!")
                }
            }
        }
    }
}   

If you can help me I would really appreciate it. ~Keion Vergara

Python for loop ignoring if statement

For some reason python is ignoring my if statement, even if the str(search) is in lista it still prints the elif statement regardless, am i doing something wrong?

    search = input("what would you like to search for?:")
    for n in range(len(lista)):
         if str(search) in lista[n]:
             print(lista[n])
         elif str(search) not in lista[n]:
             print("search not found in list")
             break 

Nested if using lambda in Python

I have a dataset like this:

Build_year Max_cnt_year   b1920  b1945 b1975 b1995 
NaN        120            120    35    45    70    
0          67             35     67    21    34    
1921       145            39     67    22    145   
...

Desired output:

Build_year Max_cnt_year   b1920  b1945 b1975 b1995 year_build1
NaN        120            120    35    45    70    1920
0          67             35     67    21    34    1945
1921       145            39     67    22    145   1921
...

I want to compare the max_cnt_year against the values of b1920, b1945, b1975, b1995 and want to assign the values accordingly if it matches to that year ,conditional on Build_year>1500

I am trying this code unsuccessfully:

df_all['build_year1'] = df_all.map( lambda x: df_all['build_year'] if df_all['build_year']>1500 
      else( 
      '1920' if df_all['max_cnt_year']==df_all['b1920'] 
      else(
            '1945' if df_all['max_cnt_year']==df_all['b1945']  
      else(
            '1975' if df_all['max_cnt_year']==df_all['b1975']
      else(
            '1995' if df_all['max_cnt_year']==df_all['b1995']
      else '2005'
          ))))

Change variable to trigger function 1 time only

I am having problems turning a function on and off based on a variable's value.

Even after I change the variables value to false, it appears to still run the function multiple times.

I am saying by default vibrateToggle = true and if the users mouse is over a certain element and if vibrateToggle = true then run navigator.vibrate(15); function, but after that set vibrateToggle = false so it doesn't keep running in the parent if statement.

Then when the mouse is off the element, set vibrateToggle = true again so that when the mouse is over the element in the future it can trigger vibrateToggle 1 time again.

But it isn't working like that, the navigator.vibrate(15); function is running as if the value if vibrateToggle is always true.

(I am simplified the code to try and make what I am trying to achieve clearer. That is why the first if statement is written like that)

//set variable to true
var vibrateToggle = true;
if (Mouse is over a certain element) {
  //If vibrateToggle is true 
  if (vibrateToggle === true) {
    //trigger vibrate
    navigator.vibrate(15);
    console.log("Vibrate: triggered");
    //After vibrate has been trigger, set vibrateToggle to false to turn it off
    vibrateToggle = false;
    console.log("Vibrate: false. VibrateToggle: " + vibrateToggle);
  }
} else {
  // Turn vibrateToggle back on
  var vibrateToggle = true;
  console.log("Vibrate: true. VibrateToggle: " + vibrateToggle);
}

vendredi 28 avril 2017

Why use : instead of { in if statements

Why do people use

if(condition) :
    /*do something*/
else:
    /*do something else*/
endif;

instead of

if(condition) 
{
    /*do something*/
} 
else
{
    /*do something else*/
}

Is one better than the other in any way? What should i get use to too?

Using if else and xargs to pipe into gnu parallel

Using if else and xargs to pipe into gnu parallel (open to other suggestions, find…)

In short am trying to write a script to check for existing folders and run a command (script for the non-existing folders/files) in gnu parallel (open to other suggestions)

I will be running the script for a list of subjects/files and they will be distributed over several compute nodes on a server, so it is important that the command does not write over the existing folders again as the same script will be run on different nodes and all of them point to the same directories. So far, my idea is the following:

For simplicity

SUBJ_LIST=(a text file with list of subjects/files to be executed .txt)
SUBJ_EXIST=(folder that the program outputs to)
SUBJ_tp_do= (hopefully only subjects/files that have not been done)

cat ${SUBJ_LIST} | xargs -I{} -n 1 if [ -d ${SUBJ_EXIST}/{} ]
then
   echo "folder exists"
else
   SUBJ_tp_do={}
fi

parallel -j8 command {}  ::: ${SUBJ_to_do}

as you can tell this script does not work

Apologies in advance for my rudimentary knowledge in scripting, any help/input is really appreciated.

I'm writing a very simple letter grading system, are if statements the most efficient?

Code example:

question:
cout << "Enter the grade % you scored on the test: ";
cin >> userScore;

if (userScore == 100) {
    cout << "You got a perfect score!" << endl;
}   
else if (userScore >= 90 && userScore < 100) {
    cout << "You scored an A." << endl;
}
else if (userScore >= 80 && userScore < 89) {
    cout << "You scored a B." << endl;
}
//... and so on...
else if (userScore >= 0 && userScore < 59) {
    cout << "You scored an F." << endl;
}
goto question;

This code has a total of 6 if statements, and it looks very.. cookie-cutter-ish.. I guess? Is there a more efficient/optimal way to write this?

I looked up some example beginner projects for C++ and found this grading one, and it said knowledge of switch statements would be useful. I looked into that and my understanding is that, in this case, switch statements would effectively work the same way as if statements.

How can I access variables outside of loop in Java?

So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this?

//all my imports here

public class ExchangeApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300,400);
        frame.setTitle("Exchange App");
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(8, 2, 5, 3));
        //GUI Elements
        JLabel toLabel = new JLabel("To");
        JTextField CurrencyTo = new JTextField(20);
        JLabel fromLabel = new JLabel("From");
        JTextField CurrencyFrom = new JTextField(20);
        JLabel amountLabel = new JLabel("Amount");
        JTextField AmountText = new JTextField(20);
        JLabel displayLabel = new JLabel();
        JLabel updateLabel = new JLabel();
        JButton Calculate = new JButton("Calculate");
        JButton Clear = new JButton("Clear");
        //Add elements to panel
        panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        panel.add(fromLabel);
        panel.add(CurrencyFrom);
        panel.add(toLabel);
        panel.add(CurrencyTo);
        panel.add(amountLabel);
        panel.add(AmountText);
        panel.add(Calculate);
        panel.add(Clear);
        panel.add(displayLabel);
        panel.add(updateLabel);
        //make visible
        frame.add(panel);
        frame.setVisible(true);

    class calculateListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent event){
            if(event.getSource()==Calculate){
                String line, from, to;
                String fromString = CurrencyFrom.getText();
                String toString = CurrencyTo.getText();
                double amount = Double.parseDouble(AmountText.getText());
                try{
                      //import text file
                      File inputFile = new File("currency.txt");
                      //create file scanner
                      Scanner input = new Scanner(inputFile);
                    try{
                      //skip first line
                      input.nextLine();
                      //while has next line
                      while(input.hasNextLine()){
                          //set line equal to entire line
                          line = input.nextLine();
                          String[] countryArray = line.split("\t");
                          //search for from
                          if(fromString.equals(countryArray[0])){
                              //set 'from' equal to that country code
                              from = countryArray[2];
                              //testing
                              System.out.println(from);
                          }
                          //search for to
                          if(toString.equals(countryArray[0])){
                              //set 'to' equal to that country code
                              to = countryArray[2];
                              System.out.println(to);
                          }
                          else{
                              displayLabel.setText("To country not found");
                          }
                      }//while loop
                  }//2nd try
                    finally{input.close();}
                }//1st try
                  catch(IOException exception){
                      System.out.println(exception);
                  }//catch bracket
        }//if bracket                                                              ****these 2 variables****
            String address = "http://ift.tt/1FxDXqE" + from + to;
    }//action bracket 
}//class implements action listener bracket
    ActionListener listener = new calculateListener();
    Calculate.addActionListener(listener);
}//main bracket
}//class bracket

What's wrong with my Vector stopping all of a sudden?

I just made an account but I got frustrated and ended up making a profile. Anyways, I'm getting an error after it loops to element 4096. For some reason it stops there and just causes error. Have no idea. If you need more info, let me know. Any help will be appreciated

if(myFile.is_open()){

    while(getline(myFile, linePerLine) && cacheSizeVector.size() <= userInputCacheSize){

        cacheSizeVector.push_back(linePerLine);

        if (find(cacheSizeVector.begin(), cacheSizeVector.end(), linePerLine) != cacheSizeVector.end()){
            for(int i = 0; i <= userInputCacheSize; i++){
                if(cacheSizeVector[i] == linePerLine){    <<<<LINE OF ERROR!
                    lruCounter[i] = lruCounter[i] + 1;
                    cout << lruCounter[i] << endl;
                    cout << cacheSizeVector[i] << " HIT!" << endl;
                    cout << cacheSizeVector.size() << endl << endl;
                }
            }

        }
        else{
            std::cout << "Element not found in myvector\n";
        }

Some error that were initialized:

"{return __is_long() ? __get_long_size() : __get_short_size();}" << EXC_BAD_ACCESS

go: or inside condition

I have this code:

if ev, ok := evt.(*ATypeEvent); ok {
   //process ATypeEvent
} else if ev, ok := evt.(*BTypeEvent); ok {
   //process BTypeEvent
} else if ev, ok := evt.(*CTypeEvent); ok {
   //process CTypeEvent
}

It so now happens that I have 3 more event types, which all fit into one of the other 3 - I'd think I need a an OR.

But after several tries, I haven't been able to figure how to do it. This doesn't work:

if ev, ok := evt.(*ATypeEvent) || evt.(*XTypeEvent); ok {
   //process ATypeEvent and X
} else if ev, ok := evt.(*BTypeEvent)  || evt.(*YTypeEvent); ok {
   //process BTypeEvent and Y
} else if ev, ok := evt.(*CTypeEvent)  || evt.(*ZTypeEvent); ok {
   //process CTypeEvent and Z
}

nor something like

if ev, ok := evt.(*ATypeEvent) || ev, ok := evt.(*XTypeEvent); ok {

nor

if ev, ok := (evt.(*ATypeEvent) || evt.(*XTypeEvent ) ); ok {

How can this be done correctly?

EXCEL IF then AVERAGE

I have conducted a Likert Scale survey in which the responses were recorded in Excel. Each answer corresponds with a number. Never(1), Rarely(2), Sometimes(3), Often(4), Always (5).

The respondents also entered their gender and age. I have conducted mean scores for all the questions but I now want to go further into my analysis and see whether age has an impact on the answers given. Meaning that I want to find the average score (answer) for a certain age group.

The formula should follow this logic:

IF(B3:B93 <30), then AVERAGE(E3:E93) <--average the corresponding cells

B3:B93 contains the ages of respondents and E3:E93 contains the scores (answers) to each question.

Can anyone shed a light on how this is done.

Thanks

Last item in for loop executes multiple times in Javascript

I'm making a JavaScript/jQuery version of a dice game my buddies and I play. Here's a 3 player version of the game:

http://ift.tt/2oUsBI8

I'm trying to make a version of the game where the user can select how many players are playing, and have the game function in the same way:

http://ift.tt/2oGzl0s

Every time the "Go" button is pressed, it's supposed to move on to the next person's turn, and I use a modular operator if condition in a for loop to check whose turn it is, so i can perform a specific action on their turn.

var turn = 0;

$(".goButton").click(function() {
  turn = turn + 1;
  var playerCount = $('#input-number').val();  

  for (i=1;i <= playerCount;i++){
    if (turn % playerCount == i) {
    $(".player" + i + "dollars").append("Hi!");
    }
  }
});

This works great for every player I've created, except the last one (player# playerCount). This is because playerCount % playerCount = 0, and i is never 0, so the last player is always skipped.

I tried to work around this with an else statement for when turn % playerCount = 0 :

var turn = 0;

$(".goButton").click(function() {
  turn = turn + 1;
  var playerCount = $('#input-number').val();  

  for (i=1;i <= playerCount;i++){
    if (turn % playerCount == i) {
    $(".player" + i + "dollars").append("Hi!");
    } else if (turn % playerCount == 0) {
    $(".player" + playerCount + "dollars").append("Hi!");
    }
  }
});

However, when I reach player# playerCount's turn, I get playerCount times "hi!" appended. For example, for 5 players, this is the output in browser:

Player 1
$3Hi!

Player 2
$3Hi!

Player 3
$3Hi!

Player 4
$3Hi!

Player 5
$3Hi!Hi!Hi!Hi!Hi!

Is this a classic "off by 1" error on my part? Or is my else statement flawed in some way?

Using ifelse on list

I've just transitioned to using R from SAS and I'm working with a very large data set (half a million observations and 20 thousand variables) that needs quite a bit of recoding. I imagine this is a pretty basic question, but I'm still learning so I'd really appreciate any guidance!

Many of the variables have three instances and each instance has multiple arrays. For this problem, I am using the "History of Father's Illness." There are many illnesses included, but I am primarily interested in CAD (coded as "1").

An example of how the data looks:

n_20107_0_0   n_20107_0_1     n_20107_0_2
    NA             NA              NA
    7             1                8
    4             6                1             

I've only included 3 arrays here, but in reality there are close to 20. I did a bit of research and determined that the most efficient way to do this would be to create a list with the variables and then use lapply. This is what I have attempted:

 FatherDisease1 <- paste("n_20107_0_", 0:3, sep = "")
lapply(FatherDisease1, transform, FatherCAD_0_0 = ifelse(FatherDisease1 == 1, 1, 0))

I don't quite get the results I am looking for when I do this.

 n_20107_0_0   n_20107_0_1     n_20107_0_2  FatherCAD_0_0
   NA             NA              NA             0
    7             1                8             0
    4             6                1             0

What I would like to do is go through all of the 3 instances and if the person had answered 1, then for "FatherCAD_0_0" to equal 1, if not then "FatherCAD_0_0" equals 0, but I only ever end up with 0's. As for the NA's I would like for them to stay as NAs. This is what I would like it to look like:

n_20107_0_0   n_20107_0_1     n_20107_0_2  FatherCAD_0_0
   NA             NA              NA            NA
    7             1                8             1
    4             6                1             1

I've figured out how to do this the "long" way (30+ lines of code -_-) but am trying to get better at writing more elegant and efficient code. Any help would be greatly appreciated!!

how to add flag to prevent app from crashing (swift3)

I have a button that saves a photo. The problem is a photo has to be in imageView for the save function to work. How can I add a flag in this code. So if the image view is blank. Just an error message will pop up and my app will not crash.

    @IBAction func Saverton(_ sender: Any) {

        guard let croppedImage = cropImageIntoQuarterSquare(image: image2!),
            let combinedImage = saveImage(image1: image1!, image2: croppedImage, image3: croppedImage) else {
                // handle the error
                return
        }

        UIImageWriteToSavedPhotosAlbum(combinedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)

             }

How to get if-loop to start once conditions are met, without a submit button

I'd like to execute an if-loop where the values within the two fields are compared to the table bestilling within the connected database and then, if there are values within the database that are the same as the ones within the field, will the submit button at the bottom be enabled. However I'm not sure how to get the if-loop to start once the two fields are filled out, help?

<li>Hva er deres Kundenummer?
<input type="text" name="KundeID"> </li>
<li>Hva er deres Passord?
<input type="text" name="password"> </li><br>
<?php
$tjener = "localhost";
$brukernavn = "root";
$passord = "";
$database = "gyldentag takeaway";

$kobling = new mysqli($tjener, $brukernavn, $passord, $database);

function login ($KundeID, $password) {
$result = mysqli_query($con, "SELECT * FROM kunder WHERE KundeID='$KundeID' AND password='$password'");
while($row = mysqli_fetch_array($result)) {
    $success = true;
}
if($success == true) {
    echo 'document.getElementById("Button").disabled = false;';
} else {
    echo '<div class="alert alert-danger">Brukernavn eller Passord er ukorrekt venligst prøv igjen</div>';
}
}
?>

How to call a string array in a if/else statement in Javascript

I'm a beginner in javascript and I trying to call a string array in an if/else statement. This is what I have. Which works fine, but is there a shorter way to execute this. I don't want to use any other method. I just want to stick to if/else statement.

enter code here

    var welcomeMessage = prompt("what is your name?").toLowerCase();
    var names = ["brad", "elena", "simon", "stella", "stasia", "sylvester", "sinclare"];

    if(welcomeMessage === names[0] || welcomeMessage === names[1] || welcomeMessage === names[2] || welcomeMessage === names[3] || welcomeMessage === names[4] || welcomeMessage === names[5] || welcomeMessage === names[6]) {
    alert("Your Authorized!");
  } else {
    alert("Signup for free!");
}

Peg Solitaire buttons in Java

I'm very new to coding, and struggling with a part of my final project. The project is very open ended: make a graphical java application. I've chosen a peg solitaire game, which as you'll see from the image below:

http://ift.tt/2oQgfRF

Incorporates a similar concept of 'jumping' pieces that a game like checkers uses. This is what I made so far, a board made up of a 7x7 grid of jbuttons, each uses a square pic to represent a part of the board; though I've left buttons intentionally blank in place of the spaces that would be on a normal board.

The problem I've run into is the next step, the game logic itself; I'm trying to figure out how to implement a system where I can click on a peg, and then click on an empty space to 'move' the peg (Which in this instance, would just be switching the jbutton image to the 'slotted' square). However, the game has to recognize whether or not the space clicked on is filled, whether or not the second space clicked is empty, and whether or not the space BETWEEN these two spaces is filled - because in this game, pegs can only move over another peg, and only into a space that is empty.

The pegs cannot move diagonally, only on the four compass directions. I put together this with my instructor's help:

I tried to add to it and figure out how to implement what I described above but I just can't really grasp it. I know what I need to do, but struggling on how to execute it. This code allows me to click on the identified square and 'empty' it, and also allows me to click on the empty space to remove the peg from the square between this and the first square.

But I don't know what the code for identifying when a space is filled or not, or the code for even differing between the empty space and filled space. I assume it's some kind of if statement and the name of the space and tied to which picture is being currently used (if it's the empty hole pic or the filled slotted pic). And then an else statement and...

Well, like I said, I'm very new to all this, and google searching on the subject isn't helping me because I only half understand it, and don't know how to translate the information given to the project I have.

    private class ButtonHandler implements ActionListener

    {
        public void actionPerformed(ActionEvent event)

    {

        if(event.getSource() == boxEleven)
        boxEleven.setIcon(holePic);

        if(event.getSource() == boxTwentyFive)
{
    boxTwentyFive.setIcon(peggedHolePic);
    boxEighteen.setIcon(holePic);
}

    else if(event.getSource() == boxEleven)
    boxEleven.setIcon(


    }

}

jQuery - animating div with if statement not working

What I am trying to accomplish is a simple div animation, where the div expands for 200px each time someone clicks on it. I have created a variable sizeCounter, which would grow for 200 each time the div is clicked. When the sizeCounter reaches 700, I want the div to change it's background-color property to green. However, it's not working. What is wrong with my code?

$(document).ready(function() {

  var sizeCounter = 100;

  $(".box").click(function() {
    $(".box").animate({
      height: "+=200px",
      width: "+=200px"
    }, 1000);

    sizeCounter += 200;

    $(".text").animate({
      opacity: "0.5",
      top: "+=60px"
    });
  });

  if (sizeCounter === 700) {
    $(".box").click(function() {
      $(".box").css({
        "background-color": "green"
      });
    });
  }


});
.box {
  height: 100px;
  width: 100px;
  background-color: darkblue;
  position: relative;
}

.text {
  color: #fff;
  text-align: center;
}
<script src="http://ift.tt/1oMJErh"></script>
<div class="box">
  <p class="text">Click me!</p>
</div>

Powershell - check if three variables match two specific strings

I have to check if the variables $var1, $var2, $var3 contain "172.20.110." or "172.20.111.". Is there a way to this with an IF statement (not a beautiful solution) or is there a better way to that. For Example: Can I create a "network object" with 172.20.110.0/23 (255.255.254) and check the variables against it?

Why does flask-wtf not enter if statement?

I'm building a random-question quiz using Flask and flask-wtf. My quiz questions/answers are saved as the dict 'OceaniaQuestions' and a question is chosen at random to be entered into a form; its answer is paired by using the get function to get the answer from the dict.

def OceaniaQuiz():
print("Quiz loaded")

#Quiz dict and quiz properties
OceaniaQuestions = {'What is the name of the desert at 30-degrees South?':'Great Victoria Desert',
                    'What is the name of the island to the south east of Australia that is home to small "devils"?':'Tasmania',
                    'Which island nation is home to the Southern Alps?':'New Zealand',
                    'Which type of island chain contains a lagoon in the interior space between all of the individual islands?':'Atoll',
                    'Which type of island has rich soil for growing crops due to nutrients being brought to the surface of the Earth?':'Volcanic'}

question = random.choice(list(OceaniaQuestions.keys()))
correct_answer = OceaniaQuestions.get(question)

question_total = 0
quiz_length = len(OceaniaQuestions)

#Quiz form
class OceaniaContentForm(FlaskForm): 
    answer = StringField(question)
    correct_answer = OceaniaQuestions.get(question)

#Call form
form = OceaniaContentForm(question)
print("Question: {} | Answer: {}".format(question, correct_answer))
add_xp()
#response = make_response(render_template('OceaniaQuiz.html', form=form))

if form.validate_on_submit():
    print('At least got to the beginning of if-statement')
    user_answer = request.form.get('answer')
    #answer is incorrect
    if user_answer != correct_answer:
        #flash('Wrong!', 'error')
        return '<h1>Wrong!</h1>'
    else:
        #answer is correct
        OceaniaQuestions.pop(question)
        #question = random.choice(list(OceaniaQuestions.keys()))
        #correct_answer = OceaniaQuestions.get(question)
        return render_template('OceaniaQuiz.html', form=form)

return render_template('OceaniaQuiz.html', form=form)

Using the print functions, I know the code up until the 'if' statement is functioning properly, as the question and correct answer are returned to the terminal.

Why is the program not entering the 'if' statement and using its logic? When I enter the answer (both correct and incorrect) to a question, the program simply reloads a new random question and ignores the 'if' statement.

Thanks in advance for any help!

syntax error python introduction if elif else

what's wrong with this code? I wrote this in python 3.6 IDLE. i get a syntax error.

>>> age = int(input("How old are you: "))

>>> if age <= 18:
    print("Thanks for shopping!")
elif age in range(16, 18):
    print("I'm not allowed to sell you strong alholic beverages!")
else:
    print("I'm not allowed to sell you alcohol, nor cigarettes")

When I make conditions within properties, Do I have to make same conditions in Custom constructor again?

My full question is:
When I make conditions within properties, Do I have to make same conditions in Custom constructor again or I can somehow use Property Custom constructor?

If i have code like this:

class Program
{
    struct Student
    {
        private int _id;
        private string _name;
        private int _age;

        public int ID // Property
        {
            get
            {
                return _id;
            }
            set
            {
                if (value <= 0)
                {
                    Console.WriteLine("You cannot assign id less then 1");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
                else
                {
                    _id = value;
                }
            }
        }

        public string NAME // Property
        {
            get
            {
                return _name;
            }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    _name = "No Name";
                }
                else
                {
                    _name = value;
                }
            }
        }

        public int AGE // Property
        {
            get
            {
                return _age;
            }
            set
            {
                if(value <= 0)
                {
                    Console.WriteLine("Your age cannot be less then 1 year.");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
                else
                {
                    _age = value;
                }
            }
        }

        public Student(int initID, string initName, int initAge) // Defining custom constructor
        {
            if (initID <= 0)
            {
                Console.WriteLine("You cannot assign id less then 1");
                Console.ReadLine();
                Environment.Exit(0);
            }
            if (String.IsNullOrEmpty(initName))
            {
                _name = "No Name";
            }

            if (initAge <= 0)
            {
                Console.WriteLine("Your age cannot be less then 1 year.");
                Console.ReadLine();
                Environment.Exit(0);
            }
            _id = initID;
            _name = initName;
            _age = initAge;
        }

        public void Status() // struct member - method
        {
            Console.WriteLine("ID: {0}", _id);
            Console.WriteLine($"Name: {_name}");
            Console.WriteLine($"Age: {_age}\n");
        }


    }

    static void Main(string[] args)
    {
        Student s1 = new Student(1, "James", 10);
        s1.Status(); 
        Console.ReadLine();
    }
}

As you can see I set some conditions within property like ID cannot be 0 and less then 0, but when I want to use Custom constructor, I have to make this condition again. It is only way how to do this? or is some another way?

Are even custom constructors used with encapsulation and when you have properties?

Thank you for your answers. :)

javascript function dodging the if statement and going straight for the gold

I have an if statement that I am trying to use to attack a problem with async functions, everything works great when it works however that take multiple refreshes. The page errors out several times then finally displays the color i need. Below is just an example but on the server side once the client connects, the server is dodging my if statement and goes straight for function current(). Here is example of what its doing. I'd like to update the clients color based on colors from the server so if they chose the color green their choice comes back to the server, goes through a function and spits out a different color which then is sent back over to them, when it works. My issue is, Im completely dodging the if statement.

function ijoined() {
do this();
do that();
after doing this and that();
decide();
}

Decideds what color to display 
function decide() {
  if (yellow !== null) {
     start();
    console.log('I started');
  } else {
    current();
    console.log('I already started');
  }
} 

First color displayed for client
function start() {
      yellow = '545';
 }

Current color
function current() {
    var color id = clients color;
    var time = current time;
  }

Need some help: Passing variables in functions and printing them

'new to programming' post I have an issue with my code.

    def function_test(valid_employee,employee_number):
        print """ valid_employee : %d \n employee_number: %d""" %.     (valid_employee,employee_number)
if employee_number == valid_employee:              # my if statement seems to be wrong:
        print " EMPLOYEE NUMBER RECOGNISED, WELCOME %d " %(employee_number)
else:
        print "EMPLOYEE NOT RECOGNISED"

     print "Please enter your employee_number "
     employee_number = int (raw_input())
     test_function = function_test(030532,employee_number)

I'm trying to pass 030532 (the valid_employee) but everytime time I print it, in the function(function_test) I get the value '12634' when it should be '030532'. I am using an if statement to check both employee_number and valid_employee within the function to confirm if the employee is valid.. that being valid_employee (should be 030532) is the same as employee_number. I think there seems to be a problem with me passing variables

employee_number seems to be printing fine, I get the value I want 030532 or should I say '30532'. I pass '030532' to the test_function as the first argument, but it doesn't seem to pass to the function when I print valid_employee is keep getting 12634?

anyway guys sorry if I am not explaining this coherently, I appreciate your input thanks guys.

Perl: Can not compare two strings if one of them is with special chars

I am new to Perl. Trying to check whether an existing variable $file_path is equal to a specific path or not in if condition.

my $PRODPATH = '/path/to/prod';
if ( $file_path eq "$PRODPATH/specific/path/to/file" )
{
  print "File is same as earlier \n\n";
}
else
{
  print "File is not same as earlier \n\n";
}

But the flow is not going to any of the conditions because of the special character $ in the string which I am comparing with $file_path. Is these / in the path are also creating any issues?

Using IF statement on Delta value in R

Can anyone please let me know how to make a IF loop on a Delta value? For Example; giving a Delta value = 2, works as below; Check IF (output is between in +2 and -2) and i also want to include 2 and -2 in a check. If condition fulfills, save it in a vector else discard it. I am using below mentioned data.

 longitude <- round(c(48.7188021250007,
                 48.7188133749999,
                 48.7188291249998,
                 48.7188336250004, 
                 48.7188291250005, 
                 48.7188291250085
                 ), 8);

 Latitude <- round(c (2.39514523661229,
                 2.39512477447308, 
                 2.39472235230961,
                 2.39467460730213,
                 2.39467460730313, 
                 2.4), 8);

Thanks

Can someone explain why elif is being ignored?

I'm very new to programming can't wrap my head around why my elif statements are being ignored. Can anyone help?

prompt = ("Enter your age to buy a ticket ")
prompt += ("or type 'quit' to end the program:")

while True:
    age = raw_input(prompt)

    if age == 'quit':
        break
    elif age < 3:
        print "Free ticket."
    elif age < 12:
        print "$10 ticket."
    else:
        print"$15 ticket."

Python "if all in for in"

I am developing a part for a router which receives data and sends it wireless. Someone already made a huge part, but it doesn't work at all after I debugged by logging steps.

Code:

class TimerEvent(threading.Thread):
    def __init__(self):
        super(TimerEvent, self).__init__()
        self.daemon = True
        self.event = threading.Event()
    def run(self):
        while True:
            time.sleep(0.2)
            self.event.set()
    self.timerevent = TimerEvent()
    self.timerevent.start()

functions = {
        0x01: self.msg_0x01,
        0x02: self.msg_0x02
    }

while True:
    if self.timerevent.event.isSet():
        split_data = can.split()
    if all(k in self.msg for k in (0x01, 0x02)):
        if self.status:
            "other code"

So the issue here is:

if self.timerevent.event.isSet():

This doesn't work

if all(k in self.msg for k in (0x01, 0x02)):

this neither. here, it actually "skips" the if statement while it shouldn't skip it.

Applying polymorhism in PHP to remove if-else statement

Reading about PHP, OOP and polymorphism, i have seen many discussions about if-else replacement with polymorphism. In this question Deserializing from JSON into PHP, with casting?, the highest voted answer has the following code:

class User
{
   public $username;
   public $nestedObj; //another class that has a constructor for handling json
   ...

   // This could be make private if the factories below are used exclusively
   // and then make more sane constructors like:
   //     __construct($username, $password)
   public function __construct($mixed)
   {
       if (is_object($mixed)) {
           if (isset($mixed->username))
               $this->username = $mixed->username;
           if (isset($mixed->nestedObj) &&     is_object($mixed->nestedObj))
           $this->nestedObj = new NestedObject($mixed->nestedObj);
       ...
       } else if (is_array($mixed)) {
           if (isset($mixed['username']))
               $this->username = $mixed['username'];
           if (isset($mixed['nestedObj']) && is_array($mixed['nestedObj']))
               $this->nestedObj = new NestedObj($mixed['nestedObj']);
           ...
       }
   }
   ...

   public static fromJSON_by_obj($json)
   {
       return new self(json_decode($json));
   }

   public static fromJSON_by_ary($json)
   {
       return new self(json_decode($json, TRUE)); 
   }
}

My question is nothing related to the mentioned question or the code. What I want to know is, in the above class, instead of using if else in the constructor, can we apply polymorphism to remove the if else. I don't want to know whether it is efficient or good practice. I just want to see how it is done.

Date range in "if" statement

I have this piece of code:

function auto_select_param_call_time() {
    if (today() == date("02.01.2017") || today() == date("03.01.2017")) {
        auto_click_param("call_time", "Non-working day");
    } else {
        //Do something else
    }
}

As you can see, it checks if it's any holidays today. Now there are around 8 new holidays I need to add to this 'If'. If just write them all down like "today() == date("02.01.2017")" it will turn really ugly and big really fast.

Is there any way I can write a range of dates? For example, "if it between 06.05.2017 and 9.05.2017, then...", WITHOUT using a switch?

Or any other way?

jeudi 27 avril 2017

Javascript - if boolean true not working

So, i created the following function to check the file uploaded by user is 1) Image only 2) Size less than maxSize KBs 3) Dimensions less than maxWidth and maxHeight

All else is working fine except that the condition where I check dimensions. The value in dimensions is indeed the correct value but the condition if(dimensions) doesn't run even when dimensions=true.

Is there something I am doing wrong?

var maxThumbnailWidth = '1050';
var maxThumbnailHeight = '700';

function imageFileChecks(file, type) // type here refers to either Image or Banner or Thumbnail
{
  var maxSize;
  var maxWidth;
  var maxHeight;
  var dimensions = false;
  if (type == 'image') {
    maxSize = maxImageSize;
    maxWidth = maxImageWidth;
    maxHeight = maxImageHeight;
  }
  if (type == 'banner') {
    maxSize = maxBannerSize;
    maxWidth = maxBannerWidth;
    maxHeight = maxBannerHeight;
  }
  if (type == 'thumbnail') {
    maxSize = maxThumbnailSize;
    maxWidth = maxThumbnailWidth;
    maxHeight = maxThumbnailHeight;
  }

  //First check file type.. Allow only images

  if (file.type.match('image.*')) {
    var size = (file.size / 1024).toFixed(0);
    size = parseInt(size);
    console.log('size is ' + size + ' and max size is ' + maxSize);
    if (size <= maxSize) {

      var img = new Image();
      img.onload = function() {
        var sizes = {
          width: this.width,
          height: this.height
        };
        URL.revokeObjectURL(this.src);

        //console.log('onload sizes', sizes);
        console.log('onload width sizes', sizes.width);
        console.log('onload height sizes', sizes.height);
        var width = parseInt(sizes.width);
        var height = parseInt(sizes.height);
        if (width <= maxWidth && height <= maxHeight) {
          dimensions = true;
          console.log('dimensions = ', dimensions);
        }

      }

      var objectURL = URL.createObjectURL(file);
      img.src = objectURL;

      if (dimensions) {
        alert('here in dimensions true');
        sign_request(file, function(response) {
          upload(file, response.signed_request, response.url, function() {
            imageURL = response.url;
            alert('all went well and image uploaded!');
            return imageURL;
          })
        })
      } else {
        return errorMsg = 'Image dimensions not correct!';
      }


    } else {
      return errorMsg = 'Image size not correct!';
    }

  } else {
    return errorMsg = 'Image Type not correct!';
  }
}

php if statement not working with or on stripos

Probably something simple, but I can't find the same thing on SO...

I have an php file that creates an html email, and I need to check for two (or more) pieces of text in a string.

When I just do a normal if, it executes:

if (stripos($Q5Answer, '2')  !== false) {
  message .= "<tr style='background: #eee;'><td> </td><td>". $Q5 ."</td>
</tr>"; 
}

But using an OR (using "OR" or "||"), it no longer displays

if (stripos($Q5Answer, '2') || stripos($Q5Answer, '1')  !== false) {
  message .= "<tr style='background: #eee;'><td> </td><td>". $Q5 ."</td>
</tr>"; 
}                   

What am I doing wrong?

How to update input text with save button

I'm trying to create two buttons: an edit and a save button. I have already figured out the edit one, but I need help on the save button. When the user clicks 'save', whatever text they inputted will save to the database. How can I get this to work? All help is appreciated!

CODE:

function setBindings() {
    $(".account").click(function (e) {
        var ui = DATA.getUserInfo();
        if($.isEmptyObject(ui)){
            swal("Oops...", "You need to sign in!", "error");
        }else{
            $(".home").html('<label>Name:</label><input id="editInput" onClick="check()" disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
            $(".edit").click(function (e) {
                //here is where you want to change the disable to true
                $("#editInput").prop('disabled',false);
            });

            $(".save").click(function (e) {
               //here is where you will update the user information in the database

                function check() {
                    document.getElementById('editInput').value = '';
                }

            })
        }

how to get if stamens to check for multiple values in array

Im having some trouble with this

$AuthUserIDs = array('299816740352593','1783393008638862');

foreach($AuthUserIDs as $AuthUserID){
  if($userID == $AuthUserID){
   //DO SOMETHING
   }
}

I can't seem to figure out what to say in the if statement to check for the multiple id's from the array?

Python if statement not functioning

print ("Hello World")
    myName = input("What is your name?")
    myVar = input("Enter a number:")
    if(myName == "MZ" or myVar != 0):
        print ("MZ is great")
    elif(myName == "MV"):
        print ("MV is ok")
    else:
        print ("Hello World")

No matter what I input as name (myName) or number (myVar), it always prints - MZ is great.

Please help. Thanks

jquery else condition inside onscroll function

Hello guys this is my first question and i hope to get help.

I have a problem in animation in onscroll event.

The if condition work very well when i scroll down and div shows without any problem, but when i scroll up the else condition does not work so the div doesn't hide and it still shown

This is the code:

$(function () {

'use strict';

var myDiv1 = $('div'),
    div1Top = (myDiv1.offset().top) / 2;

$(window).on('scroll', function () {

    var docScrollTop = document.documentElement.scrollTop;

    if (docScrollTop >= div1Top) {

        $('div').animate({opacity: '1'}, 800);

    } else {

        $('div').css('opacity', '0');
    }
});

});

mysql if statement and where

I'm trying to get this code to work. As of now I'm getting all sorts of syntax errors. When I don't get syntax errors, the code does not do what I want it to. I'm new to sql and I'm not sure entirely what is wrong with it.

I'm specifically trying to do 2 things.

  1. Make the Tables Join only if the variable $category exists. Because not all of my Styles are linked into the category table yet.

  2. I'm trying to get a result based on only the 3 or less variables I've used. For Example, if I use all 3 variables $divisionof, $mill, and $category, I want to pull all of the products that fit into those criteria. If I only use $mill, I want to find styles that fit into only that 1 criteria. So on and so forth.

      <?php $divisionof='Mohawk'; $mill='Aladdin'; $category='Commercial Cut  Pile';
    
    

    $order = mysqli_query($con, " SELECT DivisionOf, Manufacturer, Style, Price, ShowPrice, Include, Fiber, Width, Backing

    FROM CarpetInfo

    SELECT IF ('$divisionof'=DivisionOf, JOIN CarpetCategorySort USING (ProductID) JOIN CarpetCategories USING (CategoryID),WHERE (('$divisionof'=DivisionOf) AND ('$mill'=Manufacturer) AND ('$category'=Category)), '')

    WHERE (('$divisionof'=DivisionOf) AND ('$mill'=Manufacturer) AND ('$category'=Category)) OR (('$divisionof'=DivisionOf) AND ('$category'=Category)) OR (('$mill'=Manufacturer) AND ('$category'=Category)) OR ('$category'=Category),

    WHERE (('$divisionof'=DivisionOf) AND ('$mill'=Manufacturer)) OR ('$divisionof'=DivisionOf) OR ('$mill'=Manufacturer) )

    GROUP BY ProductID

    ORDER BY CASE WHEN ((Price <= '0.00') OR (Price >= '49.95') OR (ShowPrice!='Yes')) THEN Style ELSE 0 END asc, CASE WHEN (Price > '0.00') AND (Price <= '49.95') AND (ShowPrice='Yes') THEN Price ELSE 0 END asc, CASE WHEN (Price > '0.00') AND (Price <= '49.95') AND (ShowPrice='Yes') THEN Style ELSE Manufacturer END asc, CASE WHEN (Price > '0.00') AND (Price <= '49.95') AND (ShowPrice='Yes') THEN Manufacturer END asc;

    "); $result = mysqli_fetch_row($order);

    // Gather data from database mysqli_data_seek($order, 0); while($info = mysqli_fetch_array( $order ))

    include($_SERVER['DOCUMENT_ROOT'].$info['Include']);?>

Trigger after insert with condition in oracle

I have an error with my trigger. it show

LINE/COL ERROR


2/2 PL/SQL: SQL Statement ignored

2/6 PL/SQL: ORA-00922: missing or invalid option

I want this trigger run if the customertype is member.

Here are my table TABLE CUSTOMER

CREATE TABLE CUSTOMER 
(CUSTOMERID VARCHAR2(100) primary key,
CUSTOMERNAME VARCHAR2(50), 
CUSTOMERADDRESS VARCHAR2(100), 
CUSTOMERPHONE VARCHAR2(15), 
CUSTOMEREMAIL VARCHAR2(50), 
CUSTOMERTYPE VARCHAR2(15)
)

TABLE MEMBER

CREATE TABLE MEMBER
(MEMBERID VARCHAR2(100), 
USERNAME VARCHAR2(25), 
PASSWORD VARCHAR2(10), 
CUSTOMERID VARCHAR2(100),
CONSTRAINT FK_Member Foreign Key (CustomerId)
REFERENCES Customer(CustomerId)
);

This is my trigger

CREATE or replace TRIGGER insertMember
after insert ON CUSTOMER
for each row
BEGIN
SET NOCOUNT ON
If (select customertype from customer) = 'member'
begin
  INSERT INTO MEMBER (customerid ) values
  (:new.customerid);

END insertMember;
/

Why does this error occur when it shouldn't?

I've been writing a script that will check for reflective XSS vulnerabilities. I'm having an error on a part that checks if you have "http://" or "https://" in your URL and '*' in the place of queries. However, when I put https://google.com/#q=*", it results inERROR! MISSING 'http://', OR 'https://'!`. Here's my code:

<!DOCTYPE html>

<html>

  <head>

    <title>Slingshot.XSS</title>

  </head>

  <body style="font-family:monospace;" align="center">

    <h2>Slingshot.XSS</h2>
    <h3>Slingshot.XSS is a script that launches pre-loaded XSS payloads at a target to test its vulnerabilities.</h3>
    <h4>Please report all issues to <a href="http://ift.tt/2qk9t6X"></a> or contact me at keeganjkuhn@gmail.com.</h4>
    <a href="http://ift.tt/2pr7PD9" style="font-family:monospace" align="center">Source Code / Learn More</a>
    <br />

    <h4>Enter a URL with <b>*</b> in the place of query.</h4>
    <h5>Example: http://ift.tt/2qk2TgO;
    <input type="text" id="myText" placeholder="Enter a URL"> <button onclick="myFunction()">Submit</button>

    <p id="demo">No Submitted URL</p>

    <script>

      function myFunction() {

        var x = document.getElementById("myText").value;

        // Error check
        if ( !x.includes("*") && ( !x.includes("http://") || !x.includes("https://") ) ) {

            document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY, \'http://\', AND \'https://\'!";
            x = false;
            return 0;

        }

        if ( !x.includes("*") ) {

            document.getElementById("demo").innerHTML = "ERROR! MISSING \'*\' IN PLACE OF QUERY!";
            x = false;
            return 0;

        }

        if ( !x.includes("http://") || !x.includes("https://") ) {

            document.getElementById("demo").innerHTML = "ERROR! MISSING \'http://\', OR \'https://\'!";
            x = false;
            return 0;

        }

        document.getElementById("demo").innerHTML = x;

      }

    </script>

  </body>

</html>

What am I doing wrong?

How to return Yes or No in SQL without if/case flows

Apart from the IFs and the CASEs from SQL, is there another way to return a table of "Yes"/"No" (in SQL)?

How to use 'if' to condition and ignore a word in a particular sentence?

How can I construct a condition that if a phrase has the name "x" is ignored when the phrase is displayed?

Exemple:

if(item.contains("Text"))
{
    Then ignore "Text" And display the remaining mill
}

multiple if statement conditions vba

I'm very new to VBA so need a little help. I have a macro (BEM) that is dependent on the value of two cells. I want to be able to run the macro if either of those values is changed. If either of them is blank, I need the code to do nothing until a value is inputted in both cells.

Here's what I have so far but it doesn't seem to work:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$3" Or Target.Address = "$B$4" And (IsEmpty(Range("B3").Value) Or IsEmpty(Range("B4").Value)) Then
        Exit Sub
    Else
        BEM
    End If
End Sub

How to open a file in C++ and read it

I'm trying to open up a file in c++ and I understand that I need to #include , but I don't know what to do in main. What I want to do is to read the file line by line. I can't make it a stream because the lines I'm reading are numbers.

5000
2015
5000
8200
9012
4018
2016
1017
3015
2017
1016
9003
1017
6000
7000
0
0
0
1

These are the numbers that are inside the file. I want to read it line be line. I know I probably need to do a while statement in order for this to work, but I also want to put if else statements inside the while loop. Because I need to take the first number of each line. (Example 5000 is 5, 2015 is 2) I'd like to accomplish that by doing division with integers because it'll just get me the whole number. Basically the biggest question I have is what am I missing to read each line without making them strings.

Conditioning in R

I would like to implement a different counters based on different values of a certain variable:

Let's assume, I have a variable:

Age 

Now, I want to update different counters based on the value of 'Age'.

So, I can use the following code:

    if ( age<15) {
         count1<-count1+1
    } else if ( age<30) {
         count2<-count2+1
    } else if ( age<45) {
         count3<-count3 +1
    } else
         count4+1

Is there a nicer way to do it in R?

"If" command goes to random section if entered value isn't an option

If I use the if command but enter a value that isn't an option it goes to a random section, for example:

set /p test

if %test% == x goto home

if %test% == y goto home2

:home echo hi pause

:home2 echo how are you pause

:pie echo want some pie?

if I enter x, it goes to home but if I enter c or w it goes to pie or home2, how do I fix that?

What would the correct formula be in excel?

The IF function should first determine if the staff member’s Service Years is greater than 3 OR if the staff member’s college graduate status is “Yes”. Remember to use a structured reference to the Service Years ([Service Years]) and the College Graduate columns ([College Graduate]). If a staff member meets one or both of those criteria, the function should return the text Yes (using “Yes” for the value_if_true argument). If a staff member meets neither of those criteria, the function should return the text No (using “No” for the value_if_false argument).

Ive tried plenty formualas and it's not accepting them on my mac. please help.

Populating a table on R

I have the following tab delimited file (read into my code under variable name "data"):

Species Salt    Inhibited
C. violaceum    Cadmium nitrate 1
C. violaceum    Cadmium chloride    1
C. violaceum    Cobalt chloride 1
C. violaceum    Cobalt nitrate  1
C. violaceum    Iron (III) chloride 0
C. violaceum    Iron (III) sulfate  0
C. violaceum    Iron (II) sulfate   0
C. violaceum    Manganese chloride  0
C. violaceum    Manganese sulfate   0
C. violaceum    Nickel chloride 0
P. aeruginosa   Cadmium nitrate 1
P. aeruginosa   Cadmium chloride    1
P. aeruginosa   Cobalt chloride 1
P. aeruginosa   Cobalt nitrate  1
P. aeruginosa   Iron (III) chloride 0
P. aeruginosa   Iron (III) sulfate  0
P. aeruginosa   Iron (II) sulfate   0
P. aeruginosa   Manganese chloride  0
P. aeruginosa   Manganese sulfate   0
P. aeruginosa   Nickel chloride 1
S. marcescens   Cadmium nitrate 1
S. marcescens   Cadmium chloride    1
S. marcescens   Cobalt chloride 1
S. marcescens   Cobalt nitrate  1
S. marcescens   Iron (III) chloride 0
S. marcescens   Iron (III) sulfate  0
S. marcescens   Iron (II) sulfate   0
S. marcescens   Manganese chloride  0
S. marcescens   Manganese sulfate   0
S. marcescens   Nickel chloride 1

I would like it to be put into a table in the format:

Salt    No.Inhibited    Species.Inhibited
Cadmium nitrate    3    C. violaceum, P. aeruginosa, S. marcescens
Iron (III) chloride     0    None
Nickel chloride    2    P. aeruginosa, S. marcescens

Etc. (I would like all the data included but only typed a short amount here) So far I have managed to make a table that shows The Salt in the first column and the No. Inhibited in the second column using the following code:

data <- read.delim("tabledata.txt", header=TRUE, sep="\t")
data1 <- aggregate(Inhibited~Salt, data=data, FUN = sum)

But I can't get the species that were inhibited to show up in a third column. I've tried using a for loop with an ifelse statement:

for(Species1 in data$Inhibited)
 ifelse (data$Inhibited == 1,yes=data$Species, no="None")
data3 <- cbind.data.frame(data1, Species1)

but this only creates a third column with the value "1" in each row. My professor suggested I use dcast (from the reshape2 package) to try to make this work, but I can't figure that out either. Can someone give me some direction on creating this third column?