mardi 28 février 2017

How to make if statement true every four loops in Python

I am not sure on how to ask this question, i have searched but no results. Please help.

How can I make an if statement which will repeat itself every four times insede a for loop:

for x in range(0,20):
     print x
     if x >= 3:
         print ","

As you can see here I want the comma to reap evry four numbers and instead i get this:

0
1
2
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
,
11
.
. 
.

Since the numbers ahead of 3 are greater than 3. I am on python. Please help me.

How can if statements be executed after an else statement has met its requirements?

public static void main(String args[]) {
    Scanner keyboard = new Scanner(System.in);
    int hankees, socks;

    out.print("Hankees and Socks scores?  ");
    hankees = keyboard.nextInt();
    socks = keyboard.nextInt();
    out.println();

    if (hankees > socks) {
        out.println("Hankees win...");
        out.print("Hankees: ");
        out.println(hankees);
        out.print("Socks:   ");
        out.println(socks);
    } else {
        out.println("It's a tie...");
        out.print("Hankees: ");
        out.println(hankees);
        out.print("Socks:   ");
        out.println(socks);
    }  if (socks > hankees) {
        out.println("Socks win...");
        out.print("Socks:   ");
        out.println(socks);
        out.print("Hankees: ");
        out.println(hankees);
    } 

    keyboard.close();
}

}

I am very new to Java, but I have noticed that Java codes tend to be executed regardless of the codes that follow if the conditions are met. So here I expected the else code to be executed ( in the case of socks> hankees) but the if statement that follows is properly taken into account. I would very much appreciate it if someone could explain why.

The statement "if this OR that do X" won't work in PHP

I'm trying to show some information on screen only if a certain field is not null or if it doesn't say the word "null". I'm working with a PHP script.

For some reason I have a database that has some values set as null as a string, instead as a real NULL value. As there are many items and I still don't know what causes to set the field as "null" instead of NULL, it's going to be easier to just set that with an if statement for the time being.

But for some reason, this is not working:

if ($row['cronograma'] != NULL || $row['cronograma'] != 'null') {
echo 'This is my reply';
}

If the field is actually NULL, the echo won't show up. If the field has the string null in it it does show up.

Please note that the fields in question are either NULL or has the "null" string without any spaces.

If / Else / Switch returning the wrong results

I'm making a Rock-Paper-Scissors-Lizard-Spock (Big Bang Theory, the tv show) using ReactJS and i'm facing some kind of abstract issue.

switch (this.state.playerOnePick === 'Rock') {
    case((this.state.playerTwoPick === 'Scissors') || (this.state.playerTwoPick === 'Lizard')):
    return (
        <div>
            <h1>Player One wins !</h1>
            <h2>P1: {this.state.playerOnePick} P2: {this.state.playerTwoPick}</h2>
        </div>
    );
        break;
    case((this.state.playerTwoPick === 'Paper') || (this.state.playerTwoPick === 'Spock')):
        return (
            <div>
                <h1>Player Two wins !</h1>
                <h2>P1: {this.state.playerOnePick}
                    P2: {this.state.playerTwoPick}</h2>
            </div>
        );
        break;

}

switch (this.state.playerOnePick === 'Lizard') {
    case((this.state.playerTwoPick === 'Spock') || (this.state.playerTwoPick === 'Paper')):
        return (
            <div>
                <h1>Player One wins !</h1>
                <h2>P1: {this.state.playerOnePick} P2: {this.state.playerTwoPick}</h2>
            </div>

        );
        break;
    case((this.state.playerTwoPick === 'Scissors') || (this.state.playerTwoPick === 'Rock')):
        return (
            <div>
                <h1>Player Two wins !</h1>
                <h2>P1: {this.state.playerOnePick} P2: {this.state.playerTwoPick}</h2>
            </div>
        );
        break;

}

Rock vs Paper is returning the right results, no matter who's picking it, when P1: Rock, P2: Lizard, P1 wins as expected, but when P1: Lizard P2: Rock, it is returning that P1 wins..

What it returns me when P1:Lizard P2:Rock

There is nowhere where Lizard is supposed to win vs Rock...

(playerOnePick and playerTwoPick are correctly updated as the player pick a weapon)

how to set php variable to another variable when first one is empty then echo

I am trying to create a title from page variables using this.

<?php if $page_title = $page_title ?: $page_name'  - Blah.com'; { ?>
<?php } else { ?>
<?php echo $page_title . " - Blah.com" ; ?>
<?php } ?>

When added to page, all I get is a blank page once I open it in a browser. Not sure if I am doing this right.

I want it to use the page_title variable and some text after it but if page_title is empty I want it to use the page_name instead. Can this be done with shorter code?

Thanks for any help

JavaScript Guess the letter expected an identifier and instead saw else

I am doing one of the tutorials on http://ift.tt/2m4xWhB. I´ve done 1, 2 and 3, but I am getting: "expected an identifier and instead saw else" when I run the code.

My code is:

var solution = ["F", "O", "X"];
var guessed = ["_", "_", "_"];
var reward = 0;
var numberofGuess = 0;

function guessLetter(letter) {
  for (var i = 0; i < solution.length; i++) {
    if (solution[i] == letter) {
      guessed[i] = letter;
      numberofGuess++;
      reward += Math.floor((Math.random() * 100) + 1);
      console.log("Current guessed letters " + guessed + ". Congratulations on finding a letter.");
    }
    if (numberofGuess == solution.length) {
      console.log("You won the game!");
      console.log("Your final reward is: " + reward);
    }
  } else {
    console.log("Thats not right");
    reward -= Math.floor((Math.random() * 100) + 1);
  }

}

guessLetter("D");
guessLetter("F");
guessLetter("O");
guessLetter("X");

How to return 1 String in case there are multiple IF statements

How can I return 1 value, in case I have some IF statements?

For example, when I choose Shopify, it calls a new method that allows me to type into console some need credentials and then append all typied data into 1 String and return that String(test) to Main class. In case, I choose Bigcommerce, it calls pretty much the same method and append all needed credentials for Biggcomerce into 1 String(test2) as well. But in this case public String credentailsCollector() should return test2.

How can I do that? Thanks.

public class CartCredentialsCollector {
//it should return something like this: 
//store_url=https://test.myshopify.com&apiKey=myapikey&apiPassword=myapipassword

public String credentailsCollector() throws IOException {

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Do you want to connect a new shopping cart ('yes'/'no')");
    String newConnection = bufferedReader.readLine();
    if (newConnection.equals("no")) {
        bufferedReader.close();
    } else {
        System.out.println("Specify your shopping cart. It works with Shopify and Bigcommerce only");
        String newShoppingCart = bufferedReader.readLine();
        if (newShoppingCart.equals("Shopify")) {
            ShopifyCredentialsHandler sch = new ShopifyCredentialsHandler();
            String test = sch.shopifyCredentialsHandler();
        }
        else if (newShoppingCart.equals("Bigcommerce")) {
        BigcommerceCredentialsHandler bch = new BigcommerceCredentialsHandler();
        String test2 = bch.bigcommerceCredentialsHandler()
        }

        else {
            System.out.println("This method works with Shopify and Bigcommerce. Try to connect a Shopify or Bigcommerce store.");
            bufferedReader.close();
        }
    }
    // Here I need to return test (in case I choose "Shopify") or test2 (in case I choose "Bigcommerce"). How can I do that?
    }
}

Avoid branching in the following statement

I got the following computation:

if (x==0) x=1.0;
Y = x * A

Any idea how can i avoid the "if" branching above by using some math clamping/step functions.

Using an =IF(ISNA(VLOOKUP formula

I am using an =IF(ISNA(VLOOKUP to check two columns for matching values on any line, returning a yes or no with a match.

Now each value has a simple date on the row also and I want to find the difference in days for the rows returning yes, my issue is I cannot pin point the relating dates as I cannot tell exactly where each yes answer is coming from as all I'm getting back from my first formula is yes/no.

any help would be appreciated

Edit -

=IF(ISNA(VLOOKUP(D2,'Completed installs'!D:D,1,0)),"No","Yes") Returns my yes/no value, I am looking to locate the date on the row of the 'completed installs' !D:D which returned my yes value, for this example the date column is B

Optimization - General rule - if condition into a loop breaks the pipeline

In the context of a job, I have to optimize a big code which has a lot of loops in its main structure.

Sometimes, there are into these loops (with big iterations) one or more "if then else" conditions. A colleague of mine told me to avoid these "if then else" conditions into loops because according to him, "this breaks the pipeline of execution".

But in some cases, I have not the choice to not use them unless modifying a lot of things (and I don't want to start by doing large modifications).

I think that for avoiding them, I need to pre-filter the indexes which check and replace the indexes selected by the "if then else" condition (in the current version) but this doesn't seem interesting from an optimization point of view because to pre-filter and find these valid indexes, I need also to use another loop before the existing loop.

From what I know, the "pipeline" is the capacity for a processor to fetch the next instruction before the current instruction to be finished.

So, I would like to have advices about this concept "Don't use "if then else" into loops because it breaks pipeline" : is this really the case or modern compiler and processor can overcome this algorithmic issue.

Any remark is welcome, thanks

php if && || OR statement returning nothing ... but does separately

I'm truly puzzled and need someone to shed some light on this matter for me please.

When I use those 2 statements separately they get results:

$ads->where('country_to', '=', $_COOKIE['country_from'])

$ads->where('country_from', '=', $_COOKIE['country_from']);

... but once I tried to use the OR statement then I get no results, just wondering why?

        $ads->where('country_to', '=', $_COOKIE['country_from']) || $ads->where('country_from', '=', $_COOKIE['country_from']);

I also tried this way, no results either:

    $ads->where('country_to', '=', $_COOKIE['country_from'] || 'country_from', '=', $_COOKIE['country_from']);

Can someone tell me what I'm doing wrong here? Thanks all ;-)

Adding an if statement to a while loop

The premise of this code is to ask for a name, with a maximum of 3 attempts.

password = 'correct'
attempts = 3
password = input ('Guess the password: ')
while password != 'correct' and attempts >= 2:
    input ('Try again: ')
    attempts = attempts-1
if password == 'correct':               #Where the problems begin
    print ('Well done')

I can only enter the right password for the first attempt to return 'well done.' On the other two attempts, it will return as 'try again.' How can I get it to return well done, if entered on any of the attempts?

Create column to flag rows within a date period in R

I need to create a "flag" column within my main data frame that flags rows where the date is within a specific time range. That time range comes from a second data frame. I think I'm just stuck on the ifelse (or if) statement because there are NA's in the flag column. Maybe ifelse isn't the way to go. Here's some sample data:

    # main data frame
date <- seq(as.Date("2014-07-21"), as.Date("2014-09-11"), by = "day") 
group <- letters[1:4]                           
datereps <- rep(date, length(group))                  
groupreps <- rep(group, each = length(date))    
value  <- rnorm(length(datereps))
df <- data.frame(Date = datereps, Group = groupreps, Value = value)  

# flag time period data frame
flag <- data.frame(Group = c("b", "d"), 
        start = c("2014-08-01", "2014-08-26"),
        end = c("2014-08-11", "2014-09-01"))

# Merge flag dates into main data frame
df2 <- merge(df, flag, by = "Group", all.x = T)

# Execute ifelse statement on each row
df2$flag <- "something"
df2$flag <- ifelse(df2$Date >= as.Date(df2$start) & df2$Date <= as.Date(df2$end), "flag", "other")

The result is that in rows where a "start" and "end" date are specified, "flag" and "other" are labeled, but where "start" and "end" are NA, I get Na values for df2$flag. This happens even when I initiate df2$flag with "something". I want "other" for all values that are not defined as "flag". Look at rows 50:68.

df2[50:68,]

else not executing in php

If I leave all the fields blank, the code blow is not showing the else message.

<form action="index.php" method="POST">
    <textarea name="input_area" rows="6" cols="20"></textarea><br/><br/>
    Search<input type="text" name="find"/><br/><br/>
    Replace<input type="text" name="replace" /><br/><br/>
    <input type="submit" value="Find and replace"/>
</form>

PHP

if(isset($_POST['input_area'])&&($_POST['find'])&&($_POST['replace']))
{
    $text=$_POST['input_area'];
    $find=$_POST['find'];
    $replace=$_POST['replace'];

    if(!empty($text)&&!empty($find)&&!empty($replace))
    {
        $new_str=str_replace($find,$replace,$text);
        echo $new_str;  
    }
    else
    {
        echo 'FILL ALL THE FIELDS';     
    }
}

How i can add values from multiple lists using a for and if loop in Python?

I am using 3 lists and want to add the lists values according to a special condition. For a range of 10 items i need to a. Add the values at lists A and B using the values with index 1,2,4,5,7,8,10 b. Add the values at list A,B and C using the values with index 3,6,9

The code i wrote is the following :

Create lists

a=[i for i in range(10)]
a_cost=[1000*i for i in a] 
b=[i for i in range(10)] 
b_cost=[100*i for i in b]
c=[i for i in range(10)]
c_cost=[50*i for i in c]

code to estimate costs

for i in range(1,11):
   for i in range(1,11,2):
      cost=[x1+x2+x3 for x1,x2,x3 in zip(a_cost,b_cost,c_cost)]
   else: cost=[x1+x2 for x1,x2 in zip(a_cost,b_cost)]

When i run the code i am getting this result

cost=[1100, 2200,3300,4400,5500,6600,7700,8800,9900,11000]

and i should be getting this result

cost=[1100, 2200,3450,4400,5500,6900,7700,8800,10350,11000]

I also used the for following loop but still get the same results

for i in range(1,11):
   if i==i+2:
      d=[x1+x2+x3 for x1,x2,x3 in zip(a_cost,b_cost,c_cost)]
   else: d=[x1+x2 for x1,x2 in zip(a_cost,b_cost)]

Can someone please provide an insight on that issue?

Simple If issue

I have a program which gets the time in millis. On a button click, I wish to have the text change and state the difference between the time saved (savetime) and the current time. I can get it to display in millis, seconds and minutes, but for some reason I just can't get it to display hours. I'm sure it is a simple issue and can easily be resolved, I just am frustrated and can't get it... this is my latest attempt. Thank you so much!

long count;
long seconds = 1000;
long minutes = 60;
long hours = 3600;
TextView diff = (TextView)findViewById(R.id.diff);
count = (currenttime-savetime)/seconds;
if (count>=60) {
    count = count/minutes;
    diff.setText(difference+count+" minutes.");
} else if (count>=3600) {
    count = count/hours;
    diff.setText(difference+count+" hours.");
} else {
    diff.setText(difference+count+" seconds.");
}

problems with ArrayList in if-statement and for-loop

I have a question regardig the for-loop and ArrayList. I have a HashMap with String and Integers, where the String represents a class, and the Integer represents the grade. They I have a collection of students in an ArrayList. So what I am trying to do is find the average of the grades of the students in the ArrayList. This is the code of that class:

import java.util.ArrayList;

public class Bachelorstudenter {

private ArrayList<Bachelorstudent> bs;

public Bachelorstudenter() {

    bs = new ArrayList<>();
}

public int bsGjennomsnitt() {

    int sum = 0;
    int gjennomsnitt = 0;
  if(!bs.isEmpty()){
        for(Bachelorstudent b : bs.values){
            sum += b.finnGjennomsnitt();
        }
    return gjennomsnitt;
  }else {

    return 6;
  }
} 
}

I know that the bs.values in the for-loop within the if-statement is wrong, but I've tried googleing what I should use instead, and neither .contains or .size works.

Oh, and I also have another class called Bachelorstudent, where I can create an object of the Bachelorstudent and it will be put in the ArrayList in Bachelorstudenter.

Does anyone know what I need to put there instead?

Python "In" Comparison with *$("!£*!'. characters

Seems while learning as I'm going with Python that I'm running into every little roadblock I can.

Even though this is a simply "if" I can't seem to get it to work, and i was wondering if its because my input (pgName) has full stops within the string. e.g com.android.driver.software.

In my example scenario, I will enter com.android.driver.software, what is listed within the Dict.value is com.android.driver.software.7 I thought using the comparison "in" would work in this instance, but it doesn't seem to be handling the logic at all.. What am i doing wrong?

pgName = raw_input("Please enter a package name e.g com.android.driver.software: ")

#while loop that checks user input from pgName to see if it matches any device
#listed in the JSON output and if so printing all the entires for that value.
while True:
    try:
        jdata = data["result"]["items"][y]["tagValues"]["IdDevicesMap"]["value"]
        for device in jdata.values():
            if pgName in device:
                print jdata[device]
                print " "
            else:
                print 'false'

When i run it everything is false.

SAS: How can you write an IF statement to categorize data before a certain date and after it

I have a table with a column named DATE1 with format YYYY-MM-DD, and I need to create another column to categorize data into two groups. How should I write the code? I think that the problem is with the date format, the syntax should change.

    Data Tabla1;
    set &tTable0; 

    if DATE1 < 2001-12-31 THEN DATE1_AUX = "<2001"; else
   DATE1_AUX = >2001;

    keep    Date1
            DATE1_AUX;

    run;

if this class contains, then hide other class content

<div class="product_discountprice" id="product_discountprice1">
    <font color="red">
        <b style="font-size: 20px; font-weight: bold;">VIP Price:
            <p class="listpriceonGrid">List Price</p>
        </b>
    </font>
    <font class="pricecolor colors_productprice">$63.00</font>
</div>

They have this code on the site. You may check the actual site here --> http://ift.tt/2m8HlVV You'll see that some items has VIP Price and List Price, and some items don't have VIP Price. What I would like to do is to hide the "List Price" text if there's a VIP Price on the item, but if there's no VIP Price text, the List Price should be there. Any idea, advices, and help will be much appreciated.

I'm not really good in javascript esp when it comes to if-else. I tried it earlier:

<script type="text/javascript">
$(window).load(function(){
    if ($('.product_discountprice font b:contains("VIP Price:")')) {
        $('.product_discountprice font b p').css("display","none");
    }
});
</script>

but it did not work. So please help.

If then logic with && ||

Can someone explain to me or point me to documentation as to why the following function doesn't work?

var x = 1;
var y = 2;
var z = 1;

function logicTest() {
    if ((x && y && z) === 1 ) {
        return true;
    } else {
        return false;
    }
}

I know that I can type it out the long way as follows:

function logicTest() {
    if (x === 1 && y === 1 && z === 1 ) {
        return true;
    } else {
        return false;
    }
}

But I'm really trying to understand why the first doesn't work and also if there is a better way of typing the second if/then statement or if that is just the way it will always have to be.

Thanks!

Why does negation comparison in IF statement invokes a method

I have following code

if ( !handleOptions(args) ) {
        return false;
    }

    if ( !initConfig() ) {
        logger.error("Error initializing configuration. Terminating");
        return false;
    }

And the code itself is self explaining until I noticed that there are no else statements and yet, methods handleOptions and initConfig are called and executed. How does that work? From what I know, the parameters of if clause (in this case) are either determined true and then exception is thrown, or, they are false in which case I would expect else, yet I dont see one and code is still executed.

How to extract #F-1 submatrices (dim VariableXN) from A MXN when the subset boundary values are stored in B (dimFXN)

I think the immage can describe easily my problem. enter image description here

I have a single *.txt file with multiple records, from an MPU6050 connected to Arduino.

I can recognize when a new record was made because the column time restart from a random value lower then the previous (is never 0).

The file is a nX7 which contains in order time, ax, ay, az, gx, gy, gz

I defined, thanks to stack, my B matrix, where are stored all the boundary values (FXM in my pic)

I am trying to extract the F-1 submatrices from the single matrix, but each submatrix has different row, that depends from the length of the time record (A-B number of rows is different from B-C, but they have the same number of columns)

I have studied the "Submatrix" function, but i don't know how to apply in my specific situation, and i am not pratical with "Indexing" but i am studing how it works

Here the code i wrote

%Open the file 
filename= uigetfile ('.txt');
fileID = fopen (filename);
logmpu6050 =csvread(filename);
fclose (fileID); 
n=length(logmpu6050);


%Save the position of every i raw every time happens time(i)>time(i+1)
rangematrix = logmpu6050(diff(logmpu6050(:,1)) < 0,:);
%The last value sampled is exctracted from the dataset, because the last value don't satisfy the condition t(i)>t(i+1)
%but is still a boundary value
endlog=logmpu6050(end,:);
%We need to take the last  
rangematrix = cat(1,rangematrix,endlog)
lengthrangematrix = length(rangematrix);

Here is were i am stuck

for i = 1: lengthrangematrix-1

submat(i)= submatrix(logmpu6050[rangematrix(i),:]);

Thanks, always, for your time.

I also read this question and documentation, but i still not able to find the solution :/

Matrix Indexing Create Function Handle

Function Handles

MATLAB: Extract multiple parts of a matrix without using loops

String matching in iOS returning 0x00000001?

i have a simple string checking code, which will check NSString which coming from my server to the NSString which i hard coded in my xcode.

Please check the code

if([[array valueForKey:@"type"] isEqualToString:@"type"]  ) {
//Failed
}

input values are these

[array valueForKey:@"type"] is a string from server  'type'

When i did this in xcode console

po [[array valueForKey:@"type"] isEqualToString:@"type"]

i got output as

0x00000001

Both strings are same but then what is this 0x00000001??

How to show a message on a certain number count using parseInt (javascript)?

Hello :) Using parseInt I made a function that counts how many times you've clicked a certain button. Now I want to adjust this function or create another function that will show a message at a certain amount of clicks. This is how I count the clicks:

var cnt=0;
function CountBats(){
 cnt=parseInt(cnt)+parseInt(1);
 var divData=document.getElementById("showBats");
 divData.innerHTML="Total number of bats: "+cnt +"";
};

This is what I thought would show a message, but it doesn't work:

var cn=0;
function Nice(){
    cn=parseInt(cn)+parseInt(1);
    var divNice=document.getElementById("Nice");
    if (cn = 1) { 
    divNice.style.animation="nice 2s ease-out alternate 2";
    divNice.innerHTML="Nice!";}};

It did work when I put the if statement inside the counting function, but the problem with that was that the counter stopped after the button had been clicked twice. Question is, how do I make this work? (NB: I would like to do this in javascript, not jquery) Thanks in advance :)

How do i use IF in C?

i am new :) I'm trying to make a program that calculates the sum of two integers, and i don't know how to use If. My intent was to print a message if one (or both) number is negative.

An error appears if i try to compile this, it says me: 'else without a previous if'

Here is the code.

#include <stdio.h>
main()
{
    int num1, num2, numf;
    printf("type a number ");
    scanf("%d", &num1);
    if (num1<0);
    printf("you must type only positive numbers");
    else
    printf("type a number ");
    scanf("%d", &num2);
    if (num2<0);
    printf("you must type only positive numbers");
    else
    numf=num1+num2;
    printf("%d + %d = %d", num1, num2, numf);
    system("PAUSE");
}

i know, it's kinda stupid, but i'm doing this to understand how to use properly if. What am i doing wrong? Is this a complete disaster?

Please help me ;(

looping a data frame while performing if statements

R newbie question. I have a data frame (wealth_df) with each row grouped into a quintile (1 to 4). I want to do loop on each row and find the number of observation each item has for each quintile and store them in a table.

    **   Car Bicycle Motorcycle Boat House Quintiles_Score**
     1   0.5   0.2     0.4       0.6  0.8    1
     2   0     0.2     0.4       0     0     2
     3   0.5   0       0.4       0.6   0     1
     4   0     0.2     0         0     0     3    
     5   0     0       0.4       0     0.8   4
     6   0     0       0         0     0     4

I have done the following but its too tedious since the data frame is big.

library(Tidyverse)
#owns a car and in quintile 1
Car_Q1 <- filter(wealth_df, wealth_df$car == 0.5 & wealth_df$Quintile == 1)
No_CarQ1 <- nrow(CarQ1)
print(No_CarQ1)

#owns a boat and in quintile 4
Boat_Q4 <- filter(wealth_df, wealth_df$Boat == 0.8 & wealth_df$Quintile == 4)
No_BoatQ4 <- nrow(BoatQ4)
print(No_BoatQ4)

etc

lundi 27 février 2017

If statement not reading char variable properly

When calling the programs starLeftTriangle & starRightTriangle, the if statements seem to ignore the variable choice and the program continuously runs as if the choice is 'l' or 'L'.

Any idea why the if statements are being ignored? I've omitted the actual code for the programs.

#include <iostream>
using namespace std;

void starLeftTriangle(int n);
void starRightTriangle(int n);


int main() {
int star;
char choice;
cout << "Input the number of stars you want to draw: \n";
cin >> star;
cout << "Would you like to draw a left triangle, right triangle, or quit?     \n";
cin >> choice;

cout << "The choice value is " << choice << endl;

system("pause");

while (choice != 'q' || 'Q'){
    if (choice == 'l' || 'L'){
        starLeftTriangle(star);
    }
    else if (choice == 'r' || 'R') {
        starRightTriangle(star);
    }
}
if (choice == 'q' || 'Q') {
    cout << "Quitting Program.";

}
else{
//throw error
}
return 0;

}

Can we use `if` or `guard` instead of `switch` on an enum to extract a value?

I defined an enum and I made a computed property to extract the value associated with one of the cases. I wrote this computation with a switch:

enum NetworkResult<T> {
    case json(T)
    case error(Error)

    var error: Error? {
        switch self {
        case .error(let error):
            return error
        default:
            return nil
        }
    }
}

Is it possible to achieve the same computed property without any switch keyword? (for instance, using an if let construct?)

what is the right way to use if statement in chef?

here the else part is not working I'm unable to figure out why , how do I execute this code successfully?

service 'McAfeeFramework' do
if{ supports :status =>true}
File.write('c:\chef-repo\n1.txt','running')
else
File.write('c:\chef-repo\n1.txt','not running')
end

How can the AVERAGEIFS function be translated into MATLAB?

I am working at moving my data over from Excel to Matlab. I have some data that I want to average based on multiple criteria. I can accomplish this by looping, but want to do it with matrix operations only, if possible.

Thus far, I have managed to do so with a single criterion, using accumarray as follows:

data=[
    1 3
    1 3
    1 3
    2 3
    2 6
    2 9];

accumarray(data(:,1),data(:,2))./accumarray(data(:,1),1);

Which returns:

3
6

Corresponding to the averages of items 1 and 2, respectively. I have at least three other columns that I need to include in this averaging but don't know how I can add that in. Any help is much appreciated.

GO / Golang (go1.7.5) - Material Design Lite: Remove Navbar & Footer from specific pages on Golang project

QUESTION: Remove Navbar & Footer from specific pages (landing/root) on Golang project

I am currently using Go v1.7.5 & Material Design Lite. I would like to remove the navbar and footer from the landing page.

I would like to achieve this organically (without frameworks, libraries, or other languages such as Javascript).

I assume an if statement of sorts would be the most simple solution. I am not sure on how to implement with Go best practices.

I appreciate all responses. Thanks

compare two integer column values in R and fill a new column

I am trying to fill new column values in R data frame based on a condition that compares values from two columns. Using for loop and if-else control statement.

Here's my sample dataset

Year1 | Year2 
----- | -----
1990  | 1990
1992  | 1992
1995  | 1998
1997  | 2000

I would like to do something like this:

for (i in 1:length(year1)
{
if (year 1 == year 2) 
   flag = 1 
else 
   flag = 2
}

This doesn't seem to be working. For some reason, all the conditions are evaluated as TRUE and flag is always 1.

Any suggestions would be much appreciated!

python pandas apply if statement and groupby only for one category

Piggy backing of this question python pandas flag if more than one unique row per value in column

I want to apply the following rule only to rows with Type X.

df['Test_flag'] = np.where(df.groupby('Category').Code.transform('nunique') > 1, 'T', '')

Dataframe df:

    Code      |  Type  | Category  |    Count
    code1          Y        A          89734
    code1          Y        A          239487
    code2          Z        B          298787
    code3          Z        B          87980
    code4          Y        C          098454
    code5          X        D          298787
    code6          X        D          87980

Expected result:

    Code      |  Type  | Category  |    Count  | Test Flag
    code1          Y        A          89734
    code1          Y        A          239487
    code2          Z        B          298787
    code3          Z        B          87980
    code4          Y        C          098454
    code5          X        D          298787       T
    code6          X        D          87980        T

I tried this

  df['Test_flag'] = np.where((df['Type'] == 'X') &df.groupby('Category').Code.transform('nunique') > 1, 'T', '')

and I get the following error:

ValueError: operands could not be broadcast together with shapes (1,2199) (7620,)

Creating new column in R based on data in spreadsheet, Using IF statement

Im working on a project regarding information about movies including their release date.

My professor wants us to add a new column reflecting the decade the movies were released in (1980s, 1990s, 2000s, or 2010s). In the original spreadsheet, we have a "Release" column in the format %Y-%m-%d. I have already changed it from a factor to date using the command:

df$Release<-as.Date(df$Release, format = "%Y-%m-%d")

Now, again, he wants a new column with just the decade as stated earlier. This is where I hit a wall. We have not learned much in this class, so I attempted to do so using an if statement like so:

if(df$Release == "198"){
  df$Decade<- "1980s"
}

While I'm aware this is wrong (I assume that its too specific) that was the idea I had. I have not learned enough to really do much else!

Here is a snapshot I took of my df so it may make more sense for you all

http://ift.tt/2m4nJ57

Thanks for any help!

What is there a difference between the following two uses of `putchar`?

So, I was writing some code where I was getting an unexpected output in one part of the program, which in turn disrupted the entire system.

The code can be simplified and shortened to:

char ch;

printf("Enter Number: ");

while ((ch = getchar()) != '\n') {

   if (ch >= 65 && ch <= 67)  {
         ch = 2;
   }

putchar(ch);
}

As per the code above, I am trying to print a character/integer sequence of the user's choice. The numbers should remain unchanged whereas if the user enters letter A, then this should print 2.

Expected Output

Enter Number: 23-AB
23-22

Actual Output

Enter Number: 23-AB
23-☺☺

Once confronted with this problem, I decided to tweak some things and came up with the following code which worked perfectly. Solution with the same approach however different output:

char input;

printf("\nEnter Number: ");

while ((ch = getchar()) != '\n') {  

    switch (toupper(ch)) {   //toupper function not really needed since I am expecting the user to enter upper-case letters ONLY
    case 'A': case 'B': case 'C':
        printf("2");
        break;
    default:
        putchar(ch);
    }
  }

Expected Output

Enter Number: 23-AB
23-22

Actual Output

Enter Number: 23-AB
23-22

I am unable to comprehend why I am failing to convert the ASCII value of the characters entered in the first code to a single integer. I would like to know what is the reason for this difference in the outputs? I have simply changed the type of controlling expression, from if-statement to a switch-statement (or so I think). How can I alter the first code to provide me with the same output as the second code. Any suggestions would be appreciated.

What is the most succinct way to use '!=' operator when comparing multiple values to the same variable?

EDIT: I did not mean efficiency as in the program running more efficiently, but I meant it as a quicker way to program the if statement.

I am trying to find a way to reduce my code for efficiency. For example: if(x!=10 && x!=20 && x!=30){} //etc`

I tried this, and I tried multiple other methods:

if(x!=(10 && 20 && 30){}

It does not work. Is there a way to reduce the size of this if statement?

Analogue of operand "pass" in Java

How to rewrite this code in Python:

if condition:
    do something
else:
   pass

Using Java? What is the analogue of "pass"?

Else do nothing SQL query

I have a field, froiexported, in DB table claim3 that is either set to one or zero. I want to run an update where if the criteria in the case statement is met the value in froiexported is set to 1 else do nothing. Below will make my results incorrect every day.

update claim3
set froiexpoted = 
CASE
     WHEN froimaintdate >= dateadd(day,datediff(day,1,GETDATE()),0)
     AND froimaintdate < dateadd(day,datediff(day,0,GETDATE()),0)
     and c1.jurst in ('AK', 'AL', 'CA', 'CO', 'FL', 'GA', 'IA', 'IN', 'KS',        'KY', 'LA', 'MA', 'ME', 'MN', 'MO', 'MS', 'NC', 'NE', 'NJ', 'PA', 'RI', 'SC', 'TN', 'TX', 'UT', 'VA', 'VT', 'WV') THEN '1'
    ELSE '0'
 END

Else If conditional with logical operators not working in Jquery

I'm having trouble setting animations when the browser window is a different size, in other words, making animations responsive.

In the code below, only the first If block works. The else If block doesn't work, there´s no syntax errors.

Thanks for the help.

$(window).scroll(function(){
var firstAnimation = function() {
  $('#in-view').delay(300).css("display","block").animate({          
      opacity:1,
      right: -150
  },'slow');
};

var h4Animation = function() {
$('#hr1').delay(500).animate({
    width: '60%'
},'200');
};


if ($(window).width() <= 768) {
   if ($(window).scrollTop() > 200 ) {
       h4Animation();
       firstAnimation();       
   } else if ($(window).width() >= 769) { 
       if ($(window).scrollTop() > 100) {
          h4Animation();
          firstAnimation();            
       }
   }
}   
});

App crashes repeatedly due to empty EditText

I have created a simple app to calculate the discount. it works fine when the values are provided, but keeps on crashing when calculation is done with empty text fields. thanks in advance..!!

public class Firstctivity extends AppCompatActivity {
   Button find;
   EditText ed1,ed2;
   TextView tv1;
   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_firstctivity);
    find=(Button)findViewById(R.id.button);
    tv1=(TextView)findViewById(R.id.text39);
    ed1=(EditText)findViewById(R.id.sai);
    ed2=(EditText)findViewById(R.id.editText);


    find.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {

            final double a =Double.parseDouble(String.valueOf(ed1.getText()));
            final double b =Double.parseDouble(String.valueOf(ed2.getText()));
            double results;
            double c;
           try {
               c = a * b;
               results = c / 100;
               String total2 = String.valueOf(results);
               // String total2="fuck u";
               tv1.setText("You have recieved Rs" + total2 + "/- concession.");
               tv1.setBackgroundColor(Color.parseColor("#4169E1"));
               }
          catch (NumberFormatException ex)

           {

           }


        }

    });


}

}

Nginx Check Upstream Server Status With If statement

So im trying to check my http_response code from my upstream server, and pass a default response code when the upstream is down; and when the upstream is up proxy all requests to it.

my nginx (NOT WORKING) config looks like this

server {
    listen 80;

    server_name auth.example.com;

    set $upstream 123.456.789.123:8080;


 location @active{
    proxy_pass_header Authorization;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;
    client_max_body_size 10M;
    proxy_read_timeout 36000s;
    proxy_redirect off;
    proxy_pass http://$upstream;
 }

location @outage {
   return 200 "yass!";

 }

location / {
    error_page 500 = @outage;
    set $200 @active;

    if ($http_status != 404){
    return 500;
    }
    if ($http_status = 200) {
      return 200;
    }

}

What i want to achieve is simple, if my upstream server is down return a default 200 response.

if my upstream server is available, proxy all requests to it.

how can i achieve this (a code example would be cool :-)) with nginx.

Ternary IF-check not working properly

I'm trying to print out a specific image based on a user's cookie.

The cookie can have either of the 2 values: en or es. First I'd like to check if that cookie exists in the first place. If it does, then print out its value. Else, it should print out en.

It's a language cookie. en = english, es = spanish. And I have two flags, one english flag and one spanish flag, in /img/flags/ folder, and they have the names en.gif and es.gif

Here is my code:

<img src="/img/flags/<?php (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en') ?>.gif">

Right now it just prints out an empty image (no file name) regardless if I have a cookie set or not: /img/flags/.gif

What am I doing wrong?

I'd rather use a ternary because it looks nicer. If I do a regular IF-check it works fine:

if (isset($_COOKIE['lang'])) {
  echo $_COOKIE['lang'];
} else {
  echo 'en';
}

Evaluating If condition in Jmeter based on values in CSV

Having massive problems with something that should be simple, due to my lack of understanding of jmeter.

I have a test consisting of:

CSV Data Set config
Http Request
If controller(containing Json Path extractor and an assertion)

I only want the contents of the If statement to execute if a particular variable in the CSV is set to 'Y'.

Variable name in CSV = Check_For_Selector The condition I've placed on the IF is "${Check_For_Selector}"="Y"

This doesn't work and I can't work out why.

Please note that I am using Jmeter 2.13 (forced to use this rather than 3.1).

What the heck am I doing wrong?

How to create a submatrix extracting each raw from a matrix that satisfy a logical condition?

I have a single *.txt file with multiple records, from an MPU6050 connected to Arduino.

I can recognize when a new record was made because the column time restart from a random value lower then the previous (is never 0).

The file is a nX7 which contains in order time, ax, ay, az, gx, gy, gz

I am trying to extract the m subrecords from the single matrix, so i defined a logical if.

  1. If time i > time i+1 keep track of the position from the original matrix and store in a submatrix (rangematrix) this boundary values.
  2. From the rangematrix create a set of submatrices (the total number of submatrices will be [size(rangematrix,1)-1] .

I have a civil engineer background and i am a noob with Matlab.
Thanks for your time, thanks for you patience.

I tried to solve this with the code below, but I think is only rubbish.

%Open the file 
filename= uigetfile ('.txt');
fileID = fopen (filename);
logmpu6050 =csvread(filename);
fclose (fileID); 
n=length(logmpu6050);
%Count every time i>i+1 where i is the i,1 element of my dataset
for i=1:n-1
%Save the data of the i raw every time happens i>i+1
if logmpu6050(i,1)>logmpu6050(i+1,1);
rangematrix(i,:)= logmpu6050(i,:);
end
end
% Create a new sets of matrices from boundary values

I also read a lot of questions on stack but i didn't find the solution:

MATLAB: extract every nth element of vector

Extract large Matlab dataset subsets

MATLAB: Extract multiple parts of a matrix without using loops

MATLAB: Extracting elements periodically

Extract data from MATLAB matrix without for-loop

How to extract a vector from a large matrix by index in MATLAB?

How to extract a part of a matrix with condition in Matlab

Append to array inside if statement Swift 3

I am trying to append to an array inside an if statement, I already declared the array outside of the if statement var AnArray = [String]() But when I try to append to the array inside an if statement: self.AnArray.append("hello") and then print it outside of the if statement, print (AnArray).However, when I print the array inside the if statement, it is able to append. How can I solve this? Thanks!

ref.observeSingleEvent(of: .value, with: { (FIRDataSnap) in
        for child in FIRDataSnap.children.allObjects {
            let key = (child as AnyObject).key as String
            self.myArray.append(key)
        }




        for (_, element) in self.myArray.enumerated() {

            self.ref.child(element).child("Players").observeSingleEvent(of: .value, with: { (Snap) in

                if Snap.childrenCount < 2 {
                    self.CanJoinArray.append("hello")

                }
                else {
                    print("Can't join lobby\(element)... Full!")

                }


            })



        }

       self.JoinSession()

    })




}

IF ELSE in sql query

I would like to know what's wrong in this query. In fact I have 3 tables and the idea is that I have 4 dates date_vesting_1 to date_vesting_4, and I should check the Last completed date to compere it with another date. So I used If ELSE in the query to start from date 4 to date 1 but it crashes every time I excute.

Thank you in advance.

   IF ( (SELECT (c.Date_vesting_4) FROM D_plan_characteristics AS c ) is NOT NULL) 
SELECT 
             e.emp_id, e.emp_lname, e.emp_fname, e.effective_date As eff_date
FROM 
             R_employee As e INNER JOIN 
                                                            (
                                                            D_plan_characteristics AS c INNER JOIN D_collaborator_plan As p 
                                                                                            ON c.charac_plan_id = p.charac_plan_id
                                                            ) 
                    ON e.emp_id = p.emp_id
WHERE 
             ( (c.date_cessibility) < (c.Date_vesting_4) )
    ELSE IF ( (SELECT (c.Date_vesting_3) FROM D_plan_characteristics As c ) is NOT NULL) 
SELECT 
             e.emp_id, e.emp_lname, e.emp_fname, e.effective_date As eff_date
FROM 
             R_employee As e INNER JOIN 
                                                            (
                                                            D_plan_characteristics AS c INNER JOIN D_collaborator_plan As p 
                                                                                            ON c.charac_plan_id = p.charac_plan_id
                                                            ) 
                    ON e.emp_id = p.emp_id
WHERE 
             ( (c.date_cessibility) < (c.Date_vesting_3) ) 
   ELSE IF ((SELECT (c.Date_vesting_2) FROM D_plan_characteristics As c ) is NOT NULL) 
SELECT 
             e.emp_id, e.emp_lname, e.emp_fname, e.effective_date As eff_date
FROM 
             R_employee As e INNER JOIN 
                                                            (
                                                            D_plan_characteristics AS c INNER JOIN D_collaborator_plan As p 
                                                                                            ON c.charac_plan_id = p.charac_plan_id
                                                            ) 
                    ON e.emp_id = p.emp_id
WHERE 
             ( (c.date_cessibility) < (c.Date_vesting_2) ) 
    ELSE IF ((SELECT (c.Date_vesting_1) FROM D_plan_characteristics As as c ) is NOT NULL) 
SELECT 
             e.emp_id, e.emp_lname, e.emp_fname, e.effective_date As eff_date
FROM 
             R_employee As e INNER JOIN 
                                                            (
                                                            D_plan_characteristics AS c INNER JOIN D_collaborator_plan As p 
                                                                                            ON c.charac_plan_id = p.charac_plan_id
                                                            ) 
                    ON e.emp_id = p.emp_id
WHERE 
             ( (c.date_cessibility) < (c.Date_vesting_1) );

Meteor / Mongo - Check if user has a verified email address and redirect him

I need to find out whether the user who triggers a click. event has a verified email. In case "true" he should be redirected to another page, where he can call a server side method. In case "false" he should be redirected to a page, where he can click a button to resent a new verification link to him.

I tried to use some functions I found in other questions, but it didn´t work... Here is my code for the click. event and if function which does not work out:

"click. event": function(e){
  e.preventDefault();
   if (this.userId && Meteor.user().emails[0].verified)
   {
    Router.go('LinkToCallTheMethod');
     }; else 
     {
    console.log('Please verify email first');
    Router.go('LinkToResentVerificationLink');
     }
   });

The problem is that nothing happens. The user is not redirected even when I change the boolean in the emails[0].verified field to 'true' or 'false' (doesn´t matter, nothing happens), but I also do not receive any error code.

Therefore I think the problem is in the if(...&& Meteor.user().emails[0].verified). Is there another way to find out whether a email is verified?

Would be happy if anyone could help out. Thanks!

Android JsonElement in if condition to check equalt to

I have a problrm with the JsonElement to chck one if condition in my project. How can i solve it ?

my string constants

public static final Integer RESULT_CODE_OK = 200;
public static final String RESULT_SUCCESS_OK = "true";
public static final String TAG_STATUS = "status";
public static final String TAG_SUCCESS = "success";

this is my constants file.

my json elements

JsonElement apiStatus=response.body().get(Constants.TAG_STATUS); 
JsonElement apiSuccess=response.body().get(Constants.TAG_SUCCESS);

I want to check below conditoin to do some task

 if ((apiStatus.equals(Constants.RESULT_CODE_OK)) &&
                        (apiSuccess.equals(Constants.RESULT_SUCCESS_OK)) ) { //data received successfully
    // some task 
}else{ //while retrieving data something went wrong.
// do some task for the else.
}

If done like this it is always goes else loop.

I have printed the above two variable on logcat. The value is absolutly fine for the if loop. Where i am doing wrong ?

There is something wrong with the if-statement in our setter

We are making a setter with the if-statement. We are trying to limit the approved values, and are using a print-method to print out the value that is set, or "wrong" if the value is not accepted.

This is the method:

public Sykkel(String colour)
{
    // initialise instance variables
    super(1, colour);
    this.height = height;
}

public void setHeight (int height) {
    if(height > 35 && height < 70){
        System.out.println("Sykkelen er " + height + " cm høy.");
    } else {
        System.out.println("Wrong");
    }
}

public int getHeight() {
    return height;
}

No matter what we set as the height it prints out "Wrong". Does anyone see the error in the code?

we've tried both this.height and just height, but the outcome is still the same.

Thanks in advance.

dimanche 26 février 2017

VB not showing error message in Else clause

I am trying to make a program that displays an error message in a StatusStrip control whenever the user doesn't enter a numeric value or a numeric value that falls within a certain range and gives the TextBox with aforementioned incorrect information focus after the user clicks the "Calculate" button. It displays the error message when the user fails to enter a numeric value in a TextBox but when the user enters a number outside the specified range it only gives focus to the TextBox and doesn't display the error message in the StatusStrip control. Please help.

Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    ' Variable declarations
    Dim dblWeek1 As Double          ' Week 1 Temperature
    Dim dblWeek2 As Double          ' Week 2 Temperature
    Dim dblWeek3 As Double          ' Week 3 Temperature
    Dim dblWeek4 As Double          ' Week 4 Temperature
    Dim dblWeek5 As Double          ' Week 5 Temperature
    Dim dblFiveWeekSum As Double    ' Sum of temperatures for five weeks
    Dim dblAverage As Double        ' Average of Temperatures

    ' Determine if there's a number in txtWeek1
    If IsNumeric(txtWeek1.Text) Then

        ' Determine if the value is > -50 and < +130
        If CDbl(txtWeek1.Text) > -50 And CDbl(txtWeek1.Text) < +130 Then

            ' Determine if there's a number in txtWeek2
            If IsNumeric(txtWeek2.Text) Then

                ' Convert the text to a number and place it in a variable
                dblWeek2 = CDbl(txtWeek2.Text)

                ' Determine if the value is > -50 and < +130
                If dblWeek2 > -50 And dblWeek2 < 130 Then

                    ' Display the temperature
                    txtWeek2.Text = dblWeek2.ToString()

                    ' Determine if there's a number in txtWeek3
                    If IsNumeric(txtWeek3.Text) Then

                        ' Convert the text to a number and place it in a variable
                        dblWeek3 = CDbl(txtWeek3.Text)

                        ' Determine if the value is > -50 and < +130
                        If dblWeek3 > -50 And dblWeek3 < 130 Then

                            ' Display the temperature
                            txtWeek3.Text = dblWeek3.ToString()

                            ' Determine if there's a number in txtWeek4
                            If IsNumeric(txtWeek4.Text) Then

                                ' Convert the text to a number and place it in a variable
                                dblWeek4 = CDbl(txtWeek4.Text)

                                ' Determine if the value is > -50 and < +130
                                If dblWeek4 > -50 And dblWeek4 < 130 Then

                                    ' Display the temperature
                                    txtWeek4.Text = dblWeek4.ToString()

                                    ' Determine if there's a number in txtWeek5
                                    If IsNumeric(txtWeek5.Text) Then

                                        ' Convert the text to a number and place it in a variable
                                        dblWeek5 = CDbl(txtWeek5.Text)

                                        ' Determine if the number is > -50 and < 130
                                        If dblWeek5 > -50 And dblWeek5 < 130 Then

                                            ' Display the temperature
                                            txtWeek5.Text = dblWeek5.ToString()

                                            ' Add the temperatures and store the answer in a variable
                                            dblFiveWeekSum = dblWeek1 + dblWeek2 + dblWeek3 + dblWeek4 + dblWeek5

                                            ' Calculate the average
                                            dblAverage = dblFiveWeekSum / 5

                                            ' Display the average
                                            lblAverage.Text = dblAverage.ToString()
                                        Else
                                            lblStatus.Text = "Error: The temperature for Week 5 must be between -50 and 130."
                                            txtWeek5.Focus()
                                        End If
                                    Else
                                        lblStatus.Text = "Error: The Week 5 field must contain a numeric value."
                                        txtWeek5.Focus()
                                    End If
                                Else
                                    lblStatus.Text = "Error: The temperature for Week 4 must be between -50 and 130."
                                    txtWeek4.Focus()
                                End If
                            Else
                                lblStatus.Text = "The Week 4 field must contain a numeric value."
                                txtWeek4.Focus()
                            End If
                        Else
                            lblStatus.Text = "Error: The temperature for Week 3 must be between -50 and 130."
                            txtWeek3.Focus()
                        End If
                    Else
                        lblStatus.Text = "Error: The Week 3 field must contain a numeric value."
                        txtWeek3.Focus()
                    End If
                Else
                    lblStatus.Text = "Error: The temperature for Week 2 must be between -50 and 130."
                    txtWeek2.Focus()
                End If
            Else
                lblStatus.Text = "Error: The Week 2 field must contain a numeric value."
                txtWeek2.Focus()
            End If
        Else
            lblStatus.Text = "Error: The temperature for Week 1 must be between -50 and 130."
            'MessageBox.Show("Error: The temperature for Week 1 must be between -50 and 130.")
            txtWeek1.Focus()
        End If
    Else
        lblStatus.Text = "Error: The Week 1 field must contain a numeric value."
        txtWeek1.Focus()
    End If
End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click

    ' Clear any error messages that may appear
    lblStatus.Text = String.Empty

    ' Clear all the TextBox controls and the Label control.
    txtWeek1.Clear()
    txtWeek2.Clear()
    txtWeek3.Clear()
    txtWeek4.Clear()
    txtWeek5.Clear()
    lblAverage.Text = String.Empty

    ' Give focus to txtWeek1
    txtWeek1.Focus()
End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    ' Close the form
    Me.Close()
End Sub
End Class

Excel unwanted behavior when using IF function

I'm lost on this one. My goal is to have a table conditionally fill itself out based on whether or not a certain cell has the letter "x" in it. Each remaining cell in the row contains one of three things: nothing, a "1", or a "0". When there is no "x" present in the designated cell, all 1's in that row become 0's. The blank spaces remain blank spaces. Here's what a given row looks like:

  A      B     C     D     E     F     G     H
Item 1   x     1           1     1           1
Item 2   x           1     1     1     1     
Item 3   x     1     1           1     1      

And here's what should happen if I get rid of the "x" for Item 1:

  A      B     C     D     E     F     G     H
Item 1         0           0     0           0
Item 2   x           1     1     1     1     
Item 3   x     1     1           1     1      

Unfortunately, I'm seeing some undefined behavior. If I remove one of the "x"s and press enter, the zeros populate in the right place and everything is fine. If I try adding that "x" back, however, the zeros turn back into ones AND some of the blank cells populate with ones. The weirdest thing is that not all of the blank cells populate with one, just seemingly random ones (though the same every time).

I checked those cells for any formulas, cleared the contents of those cells just to be safe, and I'm still seeing this behavior. Any ideas?

If/Else Statement Not Evaluating

I have a little helper function that is not evaluating on either the If or Else.

I know the function is being called because I have the nlapiLogExecution, which is how you debug in NetSuite. Notes on what is being logged are with the code.

How is this possible? I have tried to use == operator as well. I also tried to set it as a variable inside the function (which I don't think is necessary).

function convertUnit(unit, cubicMeters){
    nlapiLogExecution('DEBUG','convertUnitFunction',typeof(unit))
    // typeof is String
    nlapiLogExecution('DEBUG','convertUnitFunction',unit)
    // value is Each
    if (unit === 'Each'){
        return cubicMeters
        nlapiLogExecution('DEBUG','equals Each', cubicMeters)
        // does not log here
    }
    else {
        nlapiLogExecution('DEBUG','else statements', 'equals else')
        // Does not log here
    }
}

How to perform if statement for a certain timeperiod

I want to perform certain tasks in PHP between Monday 10:00am till Saturday 10:00am and I want to perform other tasks between Saturday 10:30am till Monday 10am. Every week.

I am sorry if that's a silly question. Any help would be highly appreciated.

How would I go about determining if an integer is a multiple of 2 but not a multiple of 3 print ‘

This is an example out put

How would I go about determining if an integer is a multiple of 2 but not a multiple of 3 print ‘ is a multiple of 2 only.’ ? Using python.

if myint % 2: print(str(myint), "is a multiple of 2 only")

How do I get it to output "but not a multiple of 3"

VBScript Number Guessing Game

I am at a complete loss here. I have been beating my head against a wall all weekend and I cannot for the life of me figure out how to make my program work. This is a college class assignment and it is my first programming assignment ever, so this is a real challenge for me. I have Googled until my fingers were bleeding (not really) and I have only come across marginally helpful information. Here is my assignment (I am deeply sorry if I get the formatting wrong):

'Initialization Section
Option Explicit
Const cGreetingMsg = "Pick a number between 1 - 100"
Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses
intNoGuesses = 0

'Main Processing Section
'Generate a random number
Randomize
intRandomNo = FormatNumber(Int((100 * Rnd) + 1))

'Loop until either the user guesses correctly or the user clicks on  Cancel
Do Until strOkToEnd = "yes"

  'Prompt user to pick a number
  intUserNumber = InputBox("Type your guess:",cGreetingMsg)
  intNoGuesses = intNoGuesses + 1

  'See if the user provided an answer
  If Len(intUserNumber) <> 0 Then

'Make sure that the player typed a number
If IsNumeric(intUserNumber) = True Then

  'Test to see if the user's guess was correct
  If FormatNumber(intUserNumber) = intRandomNo Then
    MsgBox "Congratulations! You guessed it. The number was " & _
      intUserNumber & "." & vbCrLf & vbCrLf & "You guessed it " & _
      "in " & intNoGuesses & " guesses.", ,cGreetingMsg
    strOkToEnd = "yes"
  End If

  'Test to see if the user's guess was too low
  'Assignment 3: Add another If/ElseIf/Else Condition to check for if the user is less than 
  '80,60,40,20,10 or farther from the correct guess, but still too low        
  If FormatNumber(intUserNumber) < intRandomNo Then 

  strOkToEnd = "no"
  End If

  'Test to see if the user's guess was too high
  'Assignment 3: Add another If/ElseIf/Else Condition to check for if the user is more than 
  '80,60,40,20,10 or closer to the correct guess, but still too high  
  If FormatNumber(intUserNumber) > intRandomNo Then

  strOkToEnd = "no"
  End If      

Else
  MsgBox "Sorry. You did not enter a number. Try again.", , cGreetingMsg
End If

  Else
    MsgBox "You either failed to type a value or you clicked on Cancel. " & _
      "Please play again soon!", , cGreetingMsg
    strOkToEnd = "yes"
  End If

Loop

This is blowing my mind. The only thing that has been remotely helpful has been this link: VBScript Guess a number and with that being said, I have no earthly idea how to even implement that code into my own. It looks like it would work, but whenever I try it VBScript throws tons of "expected end of statement" errors. My own code is near worthless in the effort, but here it is:

'Initialization Section

Option Explicit

Const cGreetingMsg = "Pick a number between 1 - 100"

Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses

intNoGuesses = 0

'Main Processing Section

'Generate a random number
Randomize
intRandomNo = FormatNumber(Int((100 * Rnd) + 1))

'Loop until either the user guesses correctly or the user clicks on Cancel
Do Until strOkToEnd = "yes"

'Prompt user to pick a number
intUserNumber = InputBox("Type your guess:",cGreetingMsg)
intNoGuesses = intNoGuesses + 1

'See if the user provided an answer
If Len(intUserNumber) <> 0 Then
'Make sure that the player typed a number
If IsNumeric(intUserNumber) = True Then

'Test to see if the user's guess was correct
If FormatNumber(intUserNumber) = intRandomNo Then
MsgBox "Congratulations! You guessed it. The number was " & _
intUserNumber & "." & vbCrLf & vbCrLf & "You guessed it " & _
 "in " & intNoGuesses & " guesses.", ,cGreetingMsg
strOkToEnd = "yes"
End If

'Test to see if the user's guess was too low
If FormatNumber(intUserNumber) < intRandomNo - 80 Then
    MsgBox "Your guess was too low by 80. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) < intRandomNo - 60 Then
    MsgBox "Your guess was too low by 60. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) < intRandomNo - 40 Then
    MsgBox "Your guess was too low by 40. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) < intRandomNo - 20 Then
    MsgBox "Your guess was too low by 20. Try again", ,cGreetingMsg
Elseif FormatNumber(intUserNumber) < intRandomNo - 10 Then
    MsgBox "Your guess was too low by 10. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) > intRandomNo Then
    MsgBox "Your guess was still too low. Try again, please", ,cGreetingMsg
    strOkToEnd = "no"
End If

'Test to see if the user's guess was too high
If FormatNumber(intUserNumber) > intRandomNo - 80 Then
    MsgBox "Your guess was too high by 80. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) > intRandomNo + 60 Then
    MsgBox "Your guess was too high by 60. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) > intRandomNo + 40 Then
    MsgBox "Your guess was too high by 40. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) > intRandomNo + 20 Then
    MsgBox "Your guess was too high by 20. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) > intRandomNo + 10 Then
    MsgBox "Your guess was too high by 10. Try again", ,cGreetingMsg
ElseIf FormatNumber(intUserNumber) < intRandomNo Then
    MsgBox "Your guess was still too low. Try again, please", ,cGreetingMsg
    strOkToEnd = "no"
End If

Else
    MsgBox "Sorry. You did not enter a number. Try again.", , cGreetingMsg
End If

Else
    MsgBox "You either failed to type a value or you clicked on Cancel. " & _
    "Please play again soon!", , cGreetingMsg
    strOkToEnd = "yes"
End If

Loop

Any and all help is greatly appreciated with this. Thank you.

Guarded Command Language- IF statement

I am new to Guarded command language. I have a program in Guarded command language. x and y are the variables

Do :: x>y) IF :: x-y =5 ) y:=y-1
              :: x<=0 ) x:=x-1
           FI
OD

The example selected here is x = 0 and y = -2. Both the statements in IF loop are satisfied, then how does the program work? Which statement(s) will be executed?

Regards, Riya208

Javascript condition operators not functioning how I thought they would

I'm trying to make my button change state depending on a boolean. This looks like it would work and I thought it would but it just changes to white. idek why. Please help.

function dropDown(){

var isClicked = false;
var button = document.getElementById("bigbutton");

if(isClicked == false){


    button.style.backgroundColor = "red";
    isClicked = true;
}

if(isClicked == true){

    button.style.backgroundColor = "white";
    isClicked = false;

}

}

python pandas flag if more than one unique row per value in column

In the following python pandas dataframe df, I have three columns:

   Code      |   Category  |    Count
     X               A          89734
     X               A          239487
     Y               B          298787
     Z               B          87980
     W               C          098454

I need to add a column, that if a category has more than one unique code (like B in the example above), it gets a flag denoting it as a test.

So the output I am looking for is this:

   Code      |   Category  |    Count    | Test_Flag
     X               A          89734       
     X               A          239487
     Y               B          298787         T
     Z               B          87980          T
     W               C          098454

Thank You.

Variables and IF/ELSE statements

I am trying to build an app that will alert users full name and age category from young, average, and old age but no matter which age i type in it says "You belong to young category". Please tell me what is wrong with my code. Here it is:

<script type="text/javascript"> 
    var godine = 25;
    var starost;
    if (godine < 30) {
        starost = " Vi pripadate u kategoriju mladih.";
    }
    if ((godine >= 30) && (godine < 70)) {
        starost = " Vi pripadate u kategoriju srednje starih.";
    }
    if (godine > 70) {
        starost = " Vi pripadate u kategoriju starih";
    }

    </script>
    <h1>Dobro dosli na kategorisanje starosti</h1>
    <form action="" name="frmLogin" onsubmit="alert('Korisnice: ' + ' ' + document.frmLogin.txtIme.value + ' ' + document.frmLogin.txtPrezime.value + document.frmLogin.txtStarost.value + starost)">
        Korisnicko ime: <input type="text" name="txtIme"/>
        <br>
        Korisnicko prezime: <input type="text" name="txtPrezime">
        <br>
        Godine: <input type="text" name="txtStarost">
        <br>
        <input type="submit" value="Pokreni program">
    </form>

Concatenate Multiple variables to a String in Java If Else Block

I need to create a string which becomes an input to a SHA 256 function to generate its hash equivalent. The string is created by concatenating several variables as below:

String strRequest = "";

            strRequest = request_passphrase.concat("access_code=").concat(access_code).concat("amount=").concat(amount).concat("command=").concat(mode).concat("currency=").concat(currency)
            .concat("merchant_identifier=").concat(merchant_identifier)
            .concat(request_passphrase);
        if(strRequest!="" || !strRequest.isEmpty())
        {
        signature = sha256(strRequest);
        }

What should be the best way to create an if-else to drop concatenation for a variable which is null. For ex. if access_code is Null or empty, then the string will be request_passphrase.concat("amount=").concat(amount). and so on.

Paste corresponding cell value using Nested If

Following is my data structure

A          B      C                       D                  E            

Company Name|Year|First Trading (Year)|Suspended From (Year)|Suspended Till (Year)| and F Year of Delisting|

I need to have corresponding values of A in column G, where if the year (column B) matches First Trading (Column C) and if it is true then any value of B would not be between column D and E. Moreover, if values of B are greater than values of F then it would return 0 in column G.

I had used " If (B2>=C2,if(B2e2),a2),0),0),0) in cell G2 but still no help?

It would be great help to me if anybody can rectify my statement or tell me a way to do it.

Many Thanks,

Sagnik

can't go back into the if loop even the value of q is not zero

The program flow goes out of the loop even value of q is not zero.

i=5;
q=1;
    if (q!=0)
{
    r = i%2;
    q = i/2;
    [arr addObject:[NSNumber numberWithInt:q]];
    i=q;
}

}

Are all brackets for if-statements and loops in Swift optional?

I'm new to swift and heard that you may put brackets but you don't have to use them in if-statements and loops.

for eachView in allSubViews {
    if (eachView is UILabel) {
        // code
    }
}

If i put brackets around the "eachView in allSubViews", my Xcode complains about it and i have to remove them :O Why? in the if-statement, it's ok with or without brackets.

Multiple IF statements in ajaxSuccess giving the same result

Very simply put, in the ajaxSuccess part, of my GET method, for retrieving data, I have 12 ifs like so(part of the code):

 success: function (result) {
                if ((result.AppTime = "9:00") && (result.AppWithYritys = "Laakkonen")) {
                    document.getElementById("A9").style.background = "red";
                }
                if ((result.AppTime = "9:30") && (result.AppWithYritys = "Laakkonen")) {
                    document.getElementById("A930").style.background = "red";
                }
                if ((result.AppTime = "10:00") && (result.AppWithYritys = "Laakkonen")) {
                    document.getElementById("A930").style.background = "red";
                }
                if ((result.AppTime = "10:30") && (result.AppWithYritys = "Laakkonen")) {
                    document.getElementById("A930").style.background = "red";
                }
                if ((result.AppTime = "11:00") && (result.AppWithYritys = "Laakkonen")) {
                    document.getElementById("A930").style.background = "red";
                }

depending on the data retrieved from the database, it should color the appropriate div, as You can see, but it is coloring all of the divs and I know that the only thing that exists in the database and can be retrieved is the first if, only the first if is true. Am I doing something wrong?

Comparing two ints and using the diffrence for a calculation

i have set a personal socre to a player in the game that i am making. i want to update this score if the player wins, but the amount it raises or drops is depending on the diffrence in personal score.

public int editScore(int personalScore){

if(endOfGame().getResult().equals("win")){

now i want to get both players their personal score and compare them to determine how much points will be asigned

        if(this.getPersonalScore.compareTo(partner.getPersonalScore))

how will i make this work? i will need a return of the diffrence between the two.

Javascript function if statement not excuted right

I have this little piece of code that is supposed to do something if some "if" conditions are met. It does not work as it should and I could not figure out why.The code is a bit lengthy please bear with me.Any kind of help is really appreciated!

First I have a button in my html,when it is click it will trigger function

function coverCard() {
if (2>1) {
GodAn();
}
else  {
if (bbbbb===0) {   do something
}
else
{    do sth 
}
}
}

This function will lead to GodAn function shown as follow

function GodAn() {
var a = 1
 if (a<2) {
 document.getElementById("coverCard").onclick =Alert.render("do option 1  please")
 bbbbb=0;
 }
 else
 {  
 document.getElementById("coverCard").onclick =Alert.render("do option 2  please")
 bbbbb=2;
 }
 }

Finally following is the function defining what is shown in the dialog box and what will happen when its"ok"button is clicked

 function CustomAlert(){
 this.render = function(dialog){
 document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">ok</button>';
}


     if  (bbbbb===0) {
this.ok = function() {
    alert("do option1")
    console.log(bbbbb)
     }
    }
    else this.ok = function() {

    alert("do option 2")
    console.log(bbbbb)
    }
    }   
    var Alert = new CustomAlert();

**what I expect to happen is when the html button is clicked, the dialog box will show "do option 1 please",(which it always does) and then alert "do option1". However sometimes in the CustomAlert function the "do option 2" alert will be wrongly triggered,even when the global var bbbbb is reset to 0.(console.log also confirms bbbbb is 0). I have uploaded the original html file and the link is here:*

http://ift.tt/2myFbvb This really drives me crazy so somebody please shed some light here please?

Strange (for me) Syntax Error with If|Elif|Else Statements [on hold]

I am programming a little Python 3.5 program in Spyder3 on Ubuntu 16.10 that can calculate vertexes and so on of parabolas ... The code ...

# Enter the code of enter
entercodeinput = input("Enter the code of enter of the formula: ")
entercode = int(entercodeinput)

# Entercode 1 , Roots and y-intercept
if 1 == entercode:
    print("1: Roots and y-intercept")

    inputa = input("a = ")
    a = int(inputa)

    inputb = input("b= ")
    b = int(inputb)

    inputc = input("c= ")
    c = int(inputc)

    xrealminus = -2*c / b - math.sqrt(b**2 - 4*a*c)
    xrealplus = -2*c / b + math.sqrt(b**2 - 4*a*c)
    ximagminus = -2*c / b - cmath.sqrt(b**2 - 4*a*c)
    ximagplus = -2*c / b + cmath.sqrt(b**2 - 4*a*c)
    print("Real minus solution: ",      xrealminus)
    print("Real plus solution: ",      xrealplus)
    print("Imaginary minus solution:", ximagminus)
    print("Imaginary plus solution:", ximagplus)

# Entercode 2 , Vertex
if 2 == entercode:
    print("2: Vertex")

    inputa = input("a = ")
    a = int(inputa)

    inputb = input("b= ")
    b = int(inputb)

    inputc = input("c= ")
    c = int(inputc)

    x = -b / 2*a
    y = -1*(b**2 - 4*a*c)/4*a

    print("x-component of vertex: " , x)
    print("y-component of vertex: " , y)    

# Entercode 3 , Axis of symmetry
if 3 == entercode:
    print("3: Axis of symmetry")

    inputa = input("a = ")
    a = int(inputa)

    inputb = input("b= ")
    b = int(inputb)

    x = -b / 2*a

    print("Solution", x)

# Entercode 4 , Focus  
if 4 == entercode:
    print("4: Focus")

    inputa = input("a = ")
    a = int(inputa)

    inputb = input("b= ")
    b = int(inputb)

    inputc = input("c= ")
    c = int(inputc)

    x = -b / 2*a
    y = 1--1(b**2 - 4*a*c)/4*a

    print("x-component of vertex: ", x)
    print("y-component of vertex: ", y

# Entercode 5 , Directrix    
if 5 == entercode:
    print("5: Directrix")

    inputa = input("a = ")
    a = int(inputa)

    inputb = input("b= ")
    b = int(inputb)

    inputc = input("c= ")
    c = int(inputc)

    y = -1 * -1*(b**2 - 4*a*c) / 4*a
    print("Solution:", y)

# 42
if 42 == entercode:
    print("""The answer of the life, the universe and everything ...
... is here not needed! ;-""")

# No right input
entercodes = (1,2,3,4,5,42)

if not entercode in entercodes:
    print("Invalid input! Please run QPyES again!")

In line 136 or if 5 == entercode: Spyder3 is showing me there should be an error ... I didnt´t know why, because the if-Statements before are errorless ... When I comment the full 5th if-Statement, the error go to if 42 == entercode: and so on ...

Can you please help me? I don´t know next ... I tried to run it errorless with replacing if 1 == entercode: and elif 2 == entercode: and so on until else: but thats not made it ...

Thank you very much!

Jakob Krieger

samedi 25 février 2017

Conditional value assignment to multiple columns based on some other column value

I have been stuck with this problem and I am sure for some of you this will not be too hard to solve. I've had no success in finding the answer in this forum.

The company I work at has a rotational program in which employees spend some time in multiple divisions and, at the end of some period, they get evaluated for a more senior division (promotion). Most will finish their program in 3 years, then a few more in the 4th and 5th. A small percentage (around 15%) does not complete the program. The dataset is fairly large and goes back more than 30 years. Some data is entered manually and is prone to data entry mistakes. The columns cont1, cont2,...,cont7 flags whether the individual is still in the rotational program. The columns prom3, prom4 and prom5 has a 'Y' if the employee has successfully completed the program in 3, 4 and 5 years respectively. So a 'Y' in prom3 means that there will also be an 'Y' in prom4 and prom5, and consequently a NA in cont3,...,cont7 because the person is no longer in the rotational program. If an individual is not promoted in year 3 but, instead, do it in year 4, then prom4 is 'Y' and cont4,...,cont7 is NA. By now you see the problem. The issue is that I have more years. I understand I can use ifelse() but the code gets quite messy and long. I would like to find a solution to do this in a more elegant way, dynamically.

I need to find a way to dynamically program if prom3 has a 'Y' then cont2 is 'Y' and cont3,...,cont7 is NA. If id has 'Y' in prom4 then cont4,...,cont7 is NA and cont2 and cont3 is 'Y' and so on. Something like:

contYears <- seq(2,7, by=1)

promYears <- seq(3,5, by=1)

if (paste0("prom",promYears)=='Y'){
is.na(paste0("cont",contYears)) while contYears >= promYears)}
else paste0("cont",contYears)=='Y'

Sorry for the not so elegant try above!

Thank you for your help!!! Below a toy df:

set.seed(123)
df <- tibble::data_frame(id = seq(1,100, by=1),
                     cont2 = sample(c('Y', NA), 100, replace=T, prob = c(0.9, 0.1)),
                     cont3 = sample(c('Y', NA), 100, replace=T, prob = c(0.8, 0.2)),
                     cont4 = sample(c('Y', NA), 100, replace=T, prob = c(0.5, 0.5)),
                     cont5 = sample(c('Y', NA), 100, replace=T, prob = c(0.25,0.75)),
                     cont6 = sample(c('Y', NA), 100, replace=T, prob = c(0.15,0.85)),
                     cont7 = sample(c('Y', NA), 100, replace=T, prob = c(0.10,0.9)),
                     prom3 = sample(c('Y', NA), 100, replace=T, prob = c(0.5,0.5)),
                     prom4 = sample(c('Y', NA), 100, replace=T, prob = c(0.75,0.25)),
                     prom5 = sample(c('Y', NA), 100, replace=T, prob = c(0.85,0.15)))

head(df) 

id cont2 cont3 cont4 cont5 cont6 cont7 prom3 prom4 prom5
1     Y     Y     Y     Y     Y  <NA>  <NA>  <NA>     Y
2     Y     Y     Y     Y  <NA>  <NA>     Y     Y     Y
3     Y     Y     Y  <NA>     Y  <NA>  <NA>     Y     Y
4     Y     Y     Y  <NA>  <NA>  <NA>  <NA>  <NA>     Y
5     Y     Y     Y  <NA>  <NA>  <NA>  <NA>     Y     Y
6  <NA>     Y  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>

If command doesnt work

there might be something wrong with my code below:

 $tal1 and $tal2 are randomised.

if ($_POST['matte'] != $tal1 + $tal2){
$ok = false;
$message6 = 'You must be able to count...!<br />';
}

somehow when I enter the correct amount the variable $ok is still false? If someone can help me I would really appreciate it.

If statement for a centain amount of time?

I haven't been using C++ as much recently, however I have came upon a small issue upon re-visiting it! If possible, could someone please give an explanation (and example) of how I could use an if statement in this manner:

If (photocellReading > 350 for 350 ms) {
do action

I hope this makes sense...

How do the logic operators work in an if statement with Python?

if "link?" or "Link?" in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():
        print ("Link String found " + comment.id)
        print(comment.body)
        #comment.reply("Here you go!")
        print ("Replied to comment ")
        #time.sleep(600)

When I run the code it skips through the first "link", or rather it runs the code inside the if statement whether or not "link?" is found in comment.body. I'm trying to run the code as:

if (a or b) and c and d

Where it's searching for either the string "link?" or the string "Link?" in the comment body. If either one is found, it will run the code in the for loop. It currently works if I have:

if "link?" in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():

So I know that it's the "or" operator that is wrong. It's just that I'm used to coding with Java where operators can be held in brackets.

Terraform conditional block based on environment

I'm looking at using the new conditionals in Terraform to basically turn a config block on or off depending on the evnironment.

Here's the block that I'd like to make into a conditional, if, for example I have a variable to turn on for production.

access_logs {
    bucket = "my-bucket"
    prefix = "${var.environment_name}-alb"
}

I think I have the logic for checking the environment conditional, but I don't know how to stick the above configuration into the logic.

"${var.environment_name == "production" ? 1 : 0 }"

Is it possible to turn the access_logs block on and off via the environment_name variable? If this is not possible, is there a workaround?

Comparing using a percentage sign? % JavaScript

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

Large files and multiple if statement Issues in Python

I am having speed issues using multiple "if/elif statements" when trying to read through and print a large file. When timing my code it took almost 10 mins to read through and replace 2MB file lol. The sample file I used had roughly 8 characters on a line. Example (ABAABAA, AAAAA, BAABABAB)

with open("text2.txt","r") as File1:
        for line in File1:
                    W = 'A'
                    Z = 'B'
                    counting1 = line.count(W)
                    counting2 = line.count(Z)
                    if counting1 == 1:
                        removeW = line.replace(W,'C')
                        removeZ = line.replace(Z,'D')
                        print (removeW)
                        print (removeZ)
                        if counting2 == 2:
                            removeW = line.replace(W,'E')
                            removeZ = line.replace(Z,'F')
                            print (removeW)
                            print (removeZ)
                    elif counting1 == 2:
                        removeW = line.replace(W,'G')
                        removeZ = line.replace(Z,'H')
                        if counting2 == 3:
                            removeW = line.replace(W,'E')
                            removeZ = line.replace(Z,'F')
                            print (removeW)
                            print (removeZ)
                    elif counting1 == 3:
                        removeW = line.replace(W,'I')
                        removeZ = line.replace(Z,'J')
                        print (removeW)
                        print (removeZ)

I have a decent computer, because I'm so new at coding can someone assist me with cleaning that up and/or teach me just a better process for speed purposes. I have 2 nested if statements and because of the different possibilities not sure a better way.

I need some help creating an AND system for when a complex network is connected

I currently have an if statement so that two agents i and j are considered to be connected if their beliefs lie within tol of each other. Here is the relevant code for this

for i=1:1:n
   for j=i:1:n
    if abs(beliefs(i) -beliefs(j))< tol
        A(j,i)=1;
        A(i,j)=1;
    end
   end
end

Now I want them to be connected if that condition is true AND they are connected in the complex network, which will be an adjacency matrix produced by a function called random_graph.

Is it possible to only draw a line on a canvas in Tkinter after a condition is met?

Whenever I put a line similiar to c.create_line(50,50, 50,250) under an if statement, the canvas seems to disapear from the window, even when the if condition is true.

if string not in line

I have a list with a bunch of lines (created from a 'show cdp neighbors detail from a Cisco switch or router).

I want to perform some processing but only on lines that contain one of the following four strings:

important = (
        "show cdp neighbors detail",
        "Device ID: ",
        "IP address: ",
        "Platform: " 
)

Right now my iterations work but I am processing over a large number of lines that end up doing nothing. I simply want to skip over the unimportant lines and do my processing over the four lines lines that contain the data that I need.

What I want to do (in English) is:

for line in cdp_data_line:
if any of the lines in 'cdp_data_line' does not contain one of the four strings in 'important', then continue (skip over the line).

After skipping the unwanted lines, then I can test to see which of the four lines I have left and process accordingly: 

if all of the four strings in 'important' is not found in any line of cdp_data_line, the continue

if any of those four strings is found in a line,then process:
elif 'show cdp neighbors detail' in line:
    do something
elif 'Device ID: ' in line:
    do something
elif 'IP address: ' in line:
    do something
elif 'Platform: ' in line:
    do something                   
else:
    sys.exit("Invalid prompt for local hostname - exiting")

I am trying to do it like this: if any(s in line for line in cdp_data_line for s not in important): continue

PyCharm says it doesn't know what 's' is, even though I found code snippets using this technique that work in PyCharm. Not sure why mine is failing.

There has got to be a succinct way of saying: If string1 or string 2 or string 3 or string 4 is not in cdp_data_line, then skip (continue), otherwise if I find any of those four strings, do something.

Any help would be greatly appreciated.

using string in one way selection (if statement)

please help me to know how to use the string s1, to print success when StdMark>50 in this code. Thank you

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    int StdMark;
    string s1;
    s1="succuss";
    cout <<"Enter The grade:"<<endl;
    cin >>StdMark;
    s
    if(StdMark<50)
    {
    cout<<"fail";
}
    return 0;
}

Can you use a logical operator when evaluating the streamReader.Peek method?

I am filling an array from a file and evaluating whether I am at the end of the file or I have reached the length of my array[100]:

//fill array from file, checking for errors (strings, blanks)
int i = 0;
while (inputFile.Peek() != -1 || i < originalData.Length)
{
    item = inputFile.ReadLine();
    if (!double.TryParse(item, out z)) errors++;
    else originalData[i++] = Convert.ToDouble(item);
}

Results: This is evaluating TRUE every time. If my file has <100 numbers, I get pulled into an infinite loop. Once I've read the last number in my file, it begins to increase my errors counter. If my file has >100 numbers, I get an outOfIndex exception.

I have fixed this problem by breaking up the evaluation:

while (inputFile.Peek() != -1)
{
    if (i < originalData.Length)
    {
        item = inputFile.ReadLine();
        if (!double.TryParse(item, out z)) errors++;
        else originalData[i++] = Convert.ToDouble(item);
    } else break;

Are you not able to use logical operators while evaluating peek? I have also tried:

 !inputfile.EndOfStream()

with the same results.

My program needs to be able to evaluate files of any sizes. Here are two examples of files I am testing with:

Marks.txt - total 106 lines Marks 87.5 54.3 95.0 33.3 76.1 65.9 17.2 83.8 71.0 66.6

90.0 72.2 73.9 69.1

test.txt - total 6 lines title 123 45 6 78 9

If/ Else in Javascript doesn't work [on hold]

I wanted to make a javascript if else. I don't know why, but it always takes the if value = 2. Because of the alert, I can see, that the value is the right one. So no matter what value the variable value has, it always does the value = 2 thing.

    function luftfeuchtigkeit(value) {
    alert(value);
    if (value = 0) {
        $.ajax({
            type: 'GET',
            url: 'cgi-bin/luftfeuchtigkeit0.py'
        }).done(function (data) {

            window.open("luftfeuchtigkeit0.html", "_self");
        });
    } else {
        if (value = 1) {
            $.ajax({
                type: 'GET',
                url: 'cgi-bin/luftfeuchtigkeit1.py'
            }).done(function (data) {

                window.open("luftfeuchtigkeit1.html", "_self");
            });
        } else {
            if (value = 2) {
                $.ajax({
                    type: 'GET',
                    url: 'cgi-bin/luftfeuchtigkeit2.py'
                }).done(function (data) {

                    window.open("luftfeuchtigkeit2.html", "_self");
                });
            } else {
                $.ajax({
                    type: 'GET',
                    url: 'cgi-bin/luftfeuchtigkeit3.py'
                }).done(function (data) {

                    window.open("luftfeuchtigkeit3.html", "_self");
                });
            }
        }
    }
}

Using OR operator in an if statement [duplicate]

This question already has an answer here:

In the initial string, passed as an argument to the rot 13 function, the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.

I am trying to decode it by iterating through the string and using if else conditional statements. However, it seems that the OR(||) operator is not working properly.

" " has the value 32, so it should stay unchanged, but the result for this charater returns 19,(so 13 was still subtracted from 32).

Where is my mistake?

function rot13(str) { 
  var x="";
  var y = String.fromCharCode(x);
  for(i =0; i < str.length; i++) {
     if(str.charCodeAt(i) > 65 || str.charCodeAt(i) < 78){
        x+= str.charCodeAt(i) - 13 + ",";
      } else if(str.charCodeAt(i) > 78 || str.charCodeAt(i) < 91) {
       x+= str.charCodeAt(i) + 13 + ",";

     }
     else {x+= str.charCodeAt(i) + ",";}


  }

return x; 
//returns '70,56,69,69,19,67,53,68,69,19,67,65,77,54,'
}


rot13("SERR PBQR PNZC");

Check entire array for single if operation

I have this code to check some input fields. However input_28 is a list field that is sent as an array. Is there a shortcut to check the array for the filter? I dont care what it wrong or which line does not match. I just need to know if any line does not match the filter.

if($_POST['input_28'] != filter_var($_POST['input_28'], FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=> "/(\d\d\d\d-\d\d\d\d)|()/" )))){

How to properly use if/else/return-statements?

Suppose the following function:

int foo(int a){
  if(a == 1)
    return a;
  if(a%2 == 0)
    return a/2;
  else
    return a+1;
}

What are the dis-/advantages of leaving the else-keyword away?

In general is there any dis-/advantage of leaving the else-keyword away if we checked for certain conditions, that would have caused the function to terminate. Such that the code remaining code will only be executed if all of them have been false.

->I guess a if/else-if/else block would have been best in this situation, but it's meant to serve as an example.

vendredi 24 février 2017

If statement not checking string condition [duplicate]

This question already has an answer here:

I'm writing a very basic stock market game. Here's the code I'm having trouble with.

if(yn == "y"){
    System.out.println("\nYour starting money is $" + df.format(usernum) +  "\nType \"quit\" to quit anytime\nEnter how many days you want to simulate: ");
    sim = input.nextInt();

I'm not done so far, but I was testing it out, and it seems that at the very first if statement, it doesn't check the scanner for entered strings. it skips another if else statement I have, and then it just goes to the else statement

else System.out.println("I said enter y or n!!!");

I tried

yn = input.nextLine();

just to make sure it wasn't a mistake. Is there something I'm missing? Can Strings even be checked in if statements? I'm guessing if it doesn't work now, then the ones in the first while loop will probably not work either. Any help is appreciated, and hopefully it's not a stupid mistake. I'm a beginner in Java. Below is the full code if needed.

import java.util.Scanner;
import java.util.Random;
import java.text.DecimalFormat;
public class StocksSim {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat("#.##");
    Random rand = new Random();

    int sim;
    double apple = (500)*rand.nextDouble() + 1;
    double cocacola = (500)*rand.nextDouble() + 1;
    double google = (500)*rand.nextDouble() + 1;
    double yahoo = (500)*rand.nextDouble() + 1;
    double tmobile = (500)*rand.nextDouble() + 1;
    double nike = (500)*rand.nextDouble() + 1;
    double usernum = 1000;
    int numofdays = 0;
    int waiting = 0;
    int quantity;
    String stockname;
    String quit = "quit";
    String yn;
    boolean start = true;
    boolean over = false;

    System.out.println("Welcome to the Stocks game.\nRemember you can only simulate 10 days maximum.\nCareful simulating too many days. You might miss the stock of your life!\nContinue?(y/n)");
    yn = input.next();

    if(yn == "y"){
        System.out.println("\nYour starting money is $" + df.format(usernum) +  "\nType \"quit\" to quit anytime\nEnter how many days you want to simulate: ");
        sim = input.nextInt();

    while(start && !over && sim > 0 && sim<=10){

            numofdays = (sim + numofdays);
            System.out.print("Simulating " + sim + " day(s)");
            while(waiting <= 2){
            try{
                Thread.sleep(800);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.print(".");
            waiting++;
            }
            System.out.println("\nToday's stock prices are \n\nApple at  $" + df.format(apple) + " per share");
            try{
                Thread.sleep(800);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("\n\nCocaCola at  $" + df.format(cocacola) + " per share");
            try{
                Thread.sleep(800);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("\n\nGoogle at  $" + df.format(google) + " per share");
            try{
                Thread.sleep(500);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("\n\nYahoo at  $" + df.format(yahoo) + " per share");
            try{
                Thread.sleep(500);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("\n\nNike at  $" + df.format(nike) + " per share");
            try{
                Thread.sleep(500);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("\n\nNike at  $" + df.format(tmobile) + " per share");
            try{
                Thread.sleep(500);
            } catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("Enter the name of the stock you want to buy. (Enter the name exactly as written)\n");
            stockname = input.nextLine();
            if(stockname == "Apple"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(apple*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " Apple share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else if(stockname == "CocaCola"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(cocacola*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " CocaCola share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else if(stockname == "Google"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(google*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " Google share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else if(stockname == "Yahoo"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(yahoo*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " Yahoo share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else if(stockname == "Nike"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(nike*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " Nike share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else if(stockname == "T-Mobile"){
                System.out.println("How many shares do you want to buy?");
                quantity = input.nextInt();
                usernum = (usernum-(tmobile*quantity));
                if(usernum >= 0){
                    System.out.println("You bought " + quantity + " T-Mobile share(s). \nYour remaining balance is now " + df.format(usernum));
                }
                else if(usernum < 0){
                    System.out.println("You can't make that transaction. Not enough money");
                }
            }
            else System.out.println("Please enter the correct name!");

        }

    }
        else if(yn == "n"){
            System.out.println("Game over. Come back next time!");
        }
        else System.out.println("I said enter y or n!!!");










}

}