mercredi 30 novembre 2016

Python - How to resample columns based based on another csv file

Looking at my example below, I want to resample my data to be hourly. I want to average the 'temperature' data over the hour and sum the 'rainfall data over the hour.

Snippet: F = F.csv

enter image description here

So far, my code that works, says:

F = F.resample('h').agg({'temperature':np.mean,'rainfall': np.sum})

But this code is very inefficient because I have over 100 columns to resample differently.

So if I create another csv, example below: G = G.csv

enter image description here

Does anyone have any suggestions on how to code:

When F.column = G.column, resample F.column based on G.row('resample')

Any help would be greatly appreciated.

if block returning the same value no matter what

When i run the following code it always returns a 1 even when the rand variable is greater than 80.

public static void give(int oSquareType){

int rand = (int)(Math.random()*100+1);
oSquareType = 1;
System.out.println(rand);


 if(oSquareType == 1){
  if(rand >= 0 || rand < 81){
    System.out.println(1);
  }else if(rand>=81 || rand <= 85){
    System.out.println(2);
  }else if(rand>=86 || rand <=90 ){
    System.out.println(3);
  }else if(rand>=91 || rand <= 95){
    System.out.println(4);
  }else if(rand>=96 || rand <= 100){
    System.out.println(5);
  }
  }
}
}

dont know why it is doing this, help is much appreciated as always friends.

P.S. this code is just for troubleshooting purposes for one of my methods for a project which is having the exact same error.

How do I select lists inside a list that have a specific length in Haskell?

In Haskell I have a list that looks like this:

[[["PersonA"],["AddressA"]],[["PersonB"],["AddressB"]],[["PersonC"]]]

and I need the lists within my list that have length=2, i.e. the people that I know the address of. In this case, I would want:

[["PersonA"],["Address"]]

and

[["PersonB"],["Address"]]

and I would not want PersonC because I don't have his address.

I was thinking about something like:

myList = [[["PersonA"],["123456789"]],[["PersonC"],["987654321"]],[["PersonE"]]]

main :: IO ()
main = do
  map (\x -> if length x == 2 print x else print "") myList

(print is just an example, I will need to work with them later)

But this returns a

Couldn't match expected type ‘IO ()’ with actual type ‘[IO ()]’

error on line 5.

Any idea how to do that?

Thanks

javascript: setting default value with IF statement instead of OR

I'm only sharing a small bit of code because there is so much going on, and I hope this is enough to answer my question.

I have some existing JS where a value is determined with an OR statement and I think I need to convert that to an IF statement. The final output is currently giving me both values if they both exist, and I only want "question" where both "question" and "name" values exist.

var question = new fq.Question(questionData.answerId, topicId,
        questionData['question'] || questionData['name'],
        questionData['text']);

Instead of using the OR operator (answerData['question'] || answerData['name']), I'd like to do something similar to the following:

if (questionData['question'] is undefined) {
  use questionData['question'];
} else { 
  use instead questionData['name'] 
}

But, I don't know how I might accomplish such a statement within the () in the existing code pasted above. The name variable/value is always present, so there's no risk in defaulting to that. Question is only defined some of the time. And I don't ever want both appearing.

This is probably outside of the scope of my query here, but to fill in a little more detail, this code eventually outputs JSON files for topics and questions. Topics only have names values, and questions have both names and questions, but I only want the questions json to include questions values, not names. I'm pretty sure this is the key part in all of the JS to determin

How do I end an R program?

I am very new to R programming. I understand it is more or less meant to be a statistics and number language, but I was thinking outside the box and wanted to make a password program. Where the user is asked for a password and if correct they can move on. If not, the program closes. Here is my code

print("Hello!")
   my.name <- readline(prompt="What is your name? ")
print(paste("Hello,", my.name))
x <- readline(prompt="What would be the password? ")
  if (x == 123) {
print("Correct!")
  } else {
print("Incorrect!")
}

I would like to know what to put in my ELSE spot to end the program. Thanks :D

Why doesn't the second part of this loop work?

The user should insert a name as an input and then confirm with a yes or no (or any of its derivatives) if the 3 worded name includes a middle name or not. So far, I've gotten the loop to work if the answer is yes; however it keeps looping the question if the answer is no.

The purpose: if the answer is yes, the program will understand its a 3 worded name with a middle name and therefore execute naming combinations with the middle name; if its no, the program will understand its a 3 worded name with a second last name instead of a middle name and therefore execute naming combinations accordingly.

Please note I have exluded a lot of the code for sharing purposes.

What I'm I doing wrong? My question is in regards to the elif part of the loop.

print ('enter name')
providedname = input ()
while providedname != 'quit':
  if len(providedname.split())==4:
    pass

  elif len(providedname.split())==3:
    print ('Does the name include a middle name or middle initial? Please type yes or no:)
    userinput = input()

    if userinput.startswith ('ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'):

    elif userinput.startswith ('no' or 'No' or 'NO' or 'na' or 'Na' or 'NA'):

    else:
      pass

  print ('enter name or type quit or q to exit')
  providedname=input()
  continue

Problems playing audio and using functions in python/Raspberry

I am trying to code a Q/A script for my raspberry using buttons and audio. But for some reason I am having problems with 'defs' or if statements. When I run my code, my first def doesn't read my button, so it doens't access other functions, and keeps repeating the first def only. Ps: my two buttons are fine, I've tried it before, and works fine.

import pygame.mixer
from time import sleep
import RPi.GPIO as GPIO
from sys import exit
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN)#YES
GPIO.setup(3, GPIO.IN)#NO

pygame.mixer.init()

sndA = pygame.mixer.Sound("audio.wav")#DO you want to eat?
sndB = pygame.mixer.Sound("audio2.wav")#Ok! lets GO!
sndC = pygame.mixer.Sound("audio3.wav")#Did you finish?
sndD = pygame.mixer.Sound("audio4.wav")#Great! 
sndE = pygame.mixer.Sound("audio5.wav")#No problems!
sndF = pygame.mixer.Sound("audio6.wav")#Oh dear! ok :(
soundChannelA = pygame.mixer.Channel(1)
soundChannelB = pygame.mixer.Channel(2)
soundChannelC = pygame.mixer.Channel(3)
soundChannelD = pygame.mixer.Channel(4)

def havealunch():
    time.sleep(5)
    soundChannelA.play(sndA)#Do you want to eat?
    if (GPIO.input(2) == False):#Yes
        wants()
    elif (GPIO.input(3) == False):#No
        doesntwants()   
    time.sleep(5)
def wants():
    soundChannelB.play(sndB)#Ok! Lets go!
    time.sleep(10)
    didyoufinish()

def doesntwants():
    soundChannelD.play(sndF)#Oh dear! Ok :(

def didyoufinish():
    soundChannelD.play(sndC)#Did you finish?
    if (GPIO.input(2) == False):#Yes!
        finished()
    if (GPIO.input(3) == False):#No
        didnt()

def finished(): 
    soundChannelD.play(sndD)#Great!


def didnt():
    soundChannelD.play(sndE)#No problems!   
    didyoufinish()  

print "Ready!!!"

while True: 
    havealunch()

I've tried to use only IF statements for this Q/A, but I had many problems, so this is my second plan, and now I have no idea about what to do. Any ideia?

Nested IF function in excel not working

I am trying to implement an IF function for a simple pricing database where if a cell is equal to one of 3 time durations, the cell automatically generates the correct price based on length of time. Here's what I have so far based on what other examples have of nested Excel functions:

=IF(F4=12;"$60";IF(F4=6;"$40";IF(F4=3,"$30")))

My primary issue is that the second condition has a red bracket, indicating an error. If I then swap the ";" for a ",", I have the same result.

As there are only 3 conditions, I have also tried the following:

=IF(F4=12;"$60",IF(F4=6;"$40","$30") 

But again I have the same issue with the bracket being red on the second condition.

Any ideas?

If statements and picture box values issue

i'm trying to create a snap game but when it comes to checking if the picture box contains the correct image, it simply just does not work, i've done a bit of research regarding this and implemented the ideas. it does not throw up any sort of error but i just do not receive a increased value when i should. Please have a look at this code and tell me if you know where i'm going wrong.

Attempt 1:

  Dim BirdPics() As Image = {My.Resources.Image_1}
If tbxAnimal_Group.Text = "Birds" And BirdPics.Contains(pbxPicture.Image) Then

    CurrentPoints += 1
    lblScore.Text = "Score:" & CurrentPoints
End If

Attempt 2

     Dim BirdPics() As Image = {My.Resources.Image_1}
If tbxAnimal_Group.Text = "Birds" And pbxPicture Is BirdPics Then

    CurrentPoints += 1
    lblScore.Text = "Score:" & CurrentPoints
End If

isset and !empty always returns true for login field

I'm trying to create a php file (login.php) that can check the login field and validate the username and password. At the moment, it's just checking username using regex. Below is my code. I can't trigger the second else clause, it seems that isset and !empty are always true, even when I can see that they're visually empty, like immediately after refreshing the page.

<?php 
if (isset($_POST['login']) && !empty($_POST['login'])) {
    if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST['username'])) {
        echo 'set';          
    }
    else {
        echo 'wrong';
    }
} else {
    echo 'required field';
}   
?>

<div id="login"> <!-- Login field with link to registration -->
    <form method="POST" action="login.php">
    <Legend>Login</Legend>
    Username <input type="text" name="username"/>
    Password <input type="password" name="password"/>
    <input type="submit" name="login">
        <div id="register">
            <a href="registration.html">Not a member? Click here to register!</a>
        </div>
    </form>     
</div>

How to change a parameter to false after the first time in python?

I'm working with python scripting in ArcGIS software. I have a problem with setting a parameter to false when it's true. The parameters[5] has a read only property "altered". When the code at the first time executed the first condition runs because the parameters[5] is not altered at the first time.But at the other times the parameter has been altered and the if condition not working. How to change the the parameter to false after the first execute of code ?

vtab = []
if parameters[4].altered and not parameters[5].altered:
                  with arcpy.da.SearchCursor(parameters[2].value,["Code1","Code2","Code3"],where_clause = sqlfinal) as curtable:                   
                    for rowt in curtable:
                       vtab.append([rowt[0],rowt[1],rowt[2]])
                       parameters[5].value = vtab

A while loop in my program has multiple ifs, but never reaches the bottom one?

I am in the middle of a really difficult to grasp assignment for school. I've been trying for a few days and I think I'm finally almost done, but... I'm stuck again and don't know why.

I am supposed to let the user fill in a number invoer (Dutch)/input. That number is supposed to be smaller than, or equal to 50. This number determines how many more inputs the user can do - these new inputs are test cases. Each test case should be a number larger than 0, but equal to, or lower than 100. It is not required to go very deep into handling bad input, so I only use some basic handling for that.

Then what needs to be tested for each test case, is what the smallest number is that is divisible by the test case, but the sum of the separate digits of that smallest number should equal your test case itself. So in the example they state: input = 1, (which means 1 test case, but they dont state that), input 2 = 10 (which means your only test case is the number 10, but they dont state that). What it sends out is the number 190 (this is because 190/10 = 19, so it's a correct outcome, but 1+9+0 = 10 as well, so it passes the second test, but again, they dont state that. I had to figure this all out myself, which is why the assigment takes me so long... the question itself is in Dutch and barely gives you any information at all).

So what my program DOES test, if I input number 25 as test case for example, that 25/25 = 1, so valid and 2+5 = 7. However, after calculating this number 7, it never seems to check the second condition. The sum of the digits needs to be 25, not 7. The program gets thrown in an infinite loop now and I don't see what is wrong.

I will post my code below. I apologize for the variable names and printed text, as they are in Dutch. I hope I explained the meaning of all this clearly enough.

import sys

invoer = int(input('Vul het aantal testgevallen in: '))
if invoer <= 50:
    invoer = invoer
else:
    print('Het getal moet groter kleiner dan of gelijk aan 50 zijn!!')
    sys.exit()

t = 0
testgevallen = []

while t < invoer:

    invoer2 = int(input('Vul een testgeval in groter dan 0 en kleiner of gelijk aan 100: '))
    if 0 < invoer2 <= 100:
        print('Testgeval ', t + 1, 'is: ', invoer2)
        testgevallen.append(invoer2)
        t += 1
        print('Array is ', testgevallen)
    else:
        print('Het getal moet groter zijn dan 0 en kleiner of gelijk aan 100!!')
        sys.exit()
t = 0

while t < invoer:
    print('Opgegeven nummer ', t + 1, ' is ', testgevallen[t])
    vermenigvuldiging = 1

    doorgaan = True

    while doorgaan == True:
        getal = testgevallen[t] * vermenigvuldiging

        if testgevallen[t] % getal == 0:
            print(getal, ' - Dit getal is deelbaar door ', testgevallen[t])

            som = sum(map(int, str(getal)))
            print(som)

            if som == testgevallen[t]:
                print('Output moet zijn: ', som)
                doorgaan = False

            else:
                doorgaan = True

        else:
            doorgaan = True
            vermenigvuldiging += 1

    t += 1
    doorgaan = doorgaan

I hope you guys can help me. Thanks a lot for you time in advance, I know it's quite the wall of text.

error with method not returning int - compiler error

when i try to compile its throwing error "method must return an int" any help is much obliged. also, will the rand variable reset to a different random value every time the method is called? thankyouthankyouthankyou

public static int giveType(int oSquareType, int x, int y){
int rand = (int)(Math.random()*100+1);
if(oSquareType == 1){
  if(rand>=0 || rand <= 80){
    return 1;
  }else if(rand>=81 || rand <= 85){
    return 2;
  }else if(rand>=86 || rand <=90 ){
    return 3;
  }else if(rand>=91 || rand <= 95){
    return 4;
  }else if(rand>=96 || rand <= 100){
    return 5;
    }
  }else if(oSquareType == 2){
    if(rand>=0 || rand <= 5){
      return 1;
    }else if(rand>=6 || rand <= 80){
      return 2;
    }else if(rand>=81 || rand <= 90){
      return 3;
    }else if(rand>=91 || rand <= 100){
      return 5;
    }

    }else if(oSquareType == 3){
      if(rand>=0 || rand <= 10){
        return 1;
      }else if(rand>=11 || rand <= 15){
        return 2;
      }else if(rand>=16 || rand <= 90){
        return 3;
      }else if(rand>=91 || rand <= 95){
        return 4;
      }else if(rand>=96 || rand <= 100){
        return 5;
        }


      }else if(oSquareType == 4){
        if(rand>=0 || rand <= 10){
          return 1;
        }else if(rand>=11 || rand <= 20){
          return 3;
        }else if(rand>=21 || rand <= 95){
          return 4;
        }else if(rand>=96 || rand <= 100){
          return 5;
          }


        }else if(oSquareType == 5){
          if(rand>=0 || rand <= 10){
            return 1;
          }else if(rand>=11 || rand <= 20){
            return 2;
          }else if(rand>=21 || rand <= 30){
            return 3;
          }else if(rand>=31 || rand <= 40){
            return 4;
          }else if(rand>=41 || rand <= 100){
            return 5;
            }
          }//end if block
        }//end method

Generating a price per item in an html table using a javascript

I have a javascript that is generating a table for me. The elements in the table are gathered in an array of arrays called sep. Sep contains 1152 sub arrays that are of the form:

Sep[0] //["316SS", "K", "-100 to 225°C", "Brass", "1/8", "4'", "4'", "8", "Ungrounded"]

So basically there are 1152 rows, each of which defines a products with 9 parameters. I want to make a for-loop that will create a price for each of the configurations. This is what I have so far:

//PART 1-------------WORKS FINE-----------------------------------
  var eopartprice2 = []; //matrix that I want to contain my prices

  for (var i = 0; i < sep.length; i++) {
  strnum1 = sep[i][5]; //parameter 5 is a length of material
  len1 = Number(strnum1.substr(0, strnum1.length - 1));

  strnum2 = sep[i][6]; //parameter 6 is another length of material
  len2 = Number(strnum2.substr(0, strnum2.length - 1));

  strnum3 = sep[i][7]; //parameter 7 is the number of units required
  condnum = Number(strnum3.substr(0, strnum3.length));

  feetOfMat = len1*len2*condnum; //The product of these is the total feet of req material

//PART 2------------PFCost always = 0.87--------------------------  
//Next i need to identify the cost of the material (to multiply by the total feet)

  var costOfMat = [0.87, 0.87, 1.77, 0.55] //different costs of the 4 materials
  if (sep[i][0] = "304SS") {
   var PFCost = costOfMat[0]; //304SS costs 0.87/foot
  } else if (sep[i][0] = "316SS") {
   var PFCost = costOfMat[1]; //316SS costs 0.87/foot
  } else if (sep[i][0] = "Inconel") {
   var PFCost = costOfMat[2]; //Inconel costs 1.77/foot
  } else if (sep[i][0] = "High Temp. Glass") {
   var PFCost = costOfMat[3]; //High Temp. Glass costs 0.55/foot
  }

  baseMatCost[i] = PFCost*feetOfMat; //I'd like to generate a matrix that
  //contains all of the base prices (1 for each row)

//PART 3---------------fitcost always = 36------------------------
//Trying to identify the cost of brass vs. stainless fittings
  if (sep[i][3] = "Brass") {
   fitcost = 36;
  } else if (sep[i][3] = "Stainless Steel") {
   fitcost = 37;
  }
}

My Problem so far is that I want the prices to be defined based off of whether or not the if statements are satisfied but in both cases (fitcost and PFCost) the values are simply the ones defined in the first if statement.

Lastly I'd like to generate my final price in the eopartprice2 matrix based off adding up the materials generated above + some cost of labor multiplied by some margin.

Also I'm concerned with the speed of how quickly this runs as it will be a live table in my website, and every time I add more to this I feel like it's taking longer and longer to generate. Here's a link to my w3 that I'm working in. http://ift.tt/2fRNQsj

Please, any help would be greatly appreciated :)

Why is my If block not working?

I have to check that the input date remains in a limit 0

import java.util.Scanner;
class Car{

     }


class CarRental{

            }
public class RentalManager {
public static void main (String args[])
{   Scanner sc = new Scanner(System.in);
System.out.println("Choose a car\n1. Porshe\n2. Ferrari");
String choice = sc.nextLine();

System.out.println("Start Date");
int date;
date = sc.nextInt();
if(date<0&&date>31)
{
System.out.println("Enter proper Date");
date = sc.nextInt();
}
System.out.println("Month");
int month = sc.nextInt();
if(month<0&&month>12)
{
System.out.println("Enter proper Month");
month = sc.nextInt();
}

System.out.println("Year");
int year = sc.nextInt();

System.out.println("Daily Rate");
int rate = sc.nextInt();
System.out.println("No of days for which you want to rent?");
int days = sc.nextInt();

System.out.println("You have entered the following information");

System.out.println("Daily Rate : "+rate+"\nRenting for : "+days+" days");
System.out.println("\nYour Bill will be : " + days*rate);





}
}

this is the output i am getting note : i have removed one print statement from the code so don't worry about the extra line in the output image. the two classes are empty right now, i intend to change that but first i need to get the date and month checking process right.

java looping in 2d array with if conditions statements

im trying to do a certain project and there is this part in which i want to loop in a 2d array and if the certain value of i & j then do something..

to be more specific my 2d array is defined for files and users and the attached photo might explain well, i want for example when index i=0 and j=0 equals 1 then print out that user 1 can write in file, i was able to iterate over the array and find the indexes where 1's occur in the array in the following code:

my 2d array defined

public class test {

public int counteri=0;
public int counterj=0;

 public void readpermission (int[][] array)
{
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<6; j++)
        {
            if(array[i][j]==1)
            {
                counterj = j;
                counteri=i;
                System.out.println("found 1's at index =" + counteri +" "+ counterj );


            }


            }


        }

    }



}

found 1's at index =0 0,

found 1's at index =0 1

found 1's at index =0 4

found 1's at index =1 1

found 1's at index =1 2

found 1's at index =1 3

found 1's at index =1 4

found 1's at index =1 5

when the first value is 0 0 i want an output that user 1 can write in file 1 and when th output is 0 1 i want an output stating that user 1 can read in file 1 and so on ...

C "if" structure

I am learning C and my question might be silly but im confused.In a function like:

  int afunction(somevariables)
    {
        if (someconditions)
        {
         do some stuff
         return 1;
        }
        raise_error("error happened")
        return 0;
    }

My question is,if the if statement isnt meeted(success),then it will go to the raise_error ? in other words,does the raise_errors position act like if it was in a else statement,or its because you have to return something at the end(return 0)?or would it need a proper else statement?Basically im confused on how to make a propre if condition--if this condition isnt meet--then call raise_error.

thank you!

If-Then clause using cells in Excel

My situation:

I have some colums in excel containing different values, for each row i want to check colum1,2,3,etc and then i need an if-then clause that works like this:

if (value in colum1=="something")
then 
fill cell x with "something else"

I'm not asking how to do it in details, but if you could tell me what excel functions i should look into to make it possible it'd be great. (I have never worked with excel before and i didnt find much googling)

php if else works except copying file

Hi I have a simple if else which works on both conditions, however if one condition involves copying a file then it is executed in either condition, can someone help?

<?php
if ($_GET["status"] <> "done") {
echo "match is in progress";
} else {
echo "match is ended";
copy("source.txt","target.txt");
}
?>

The echo function works correctly on a given "status" value, but copy("source.txt","target.txt"); still executes no matter what the status is given......

Code freezes on if statement

This if statement:

if (ButtonPress)
{
    Mix_PlayChannel(1, ButtonPress, 0);
}

works like this:

if (SelectButton)
{
    if (Press_Enter)
    {
        ButtonPress = true;
    }
}

However when the code reaches the if statement in question, the program entirely freezes and the code stops running. It might be worth noting that I'm using Visual Studio 2015 and SDL, also having made sure I've initialized everything beforehand. So why does the code freeze on this if statement?

Compare 2 strings even if capital letters are included

I have a question about an if statement.

if($_POST['billing_first_name'] == $tet['data']['0']['first_name']) {
} 
else 
{   
} 

This code compares a string that it gets from a form with an already existing string.

It works. But when i dont add a capital letter, it runs the code after all.

So for example if i compare String with String it doesnt run the code (which is what i want) But when i compare string with String it runs the code (which i dont want) Only because theres no capital letter included at the beginning. Is there a way to fix this?

Why is this "if" condition skipped?

I have an if condition (see below) which should be executing. I tried stepping through the the function step by step to see if I was getting wrong values but it seems it is correct (please, see the debugger image attached below). I am assuming that I simply made a syntax mistake in the condition but I am really unsure what the issue is.

if ((write_ind == 16)||((payload_ind == data_len[i])&&(i == last_wr)))
        {
            nt3h_eeprom_write_page(eeprom_address, write_buff);
            memset(write_buff, 0x00, sizeof(write_buff));
            if (write_ind == 16)
            {
                eeprom_address = nt3h_eeprom_increment_addr(eeprom_address);
                write_ind = 0;
            }
        }

enter image description here

As you can see, the right OR side should be true, but it is not the case. Thank you for the help.

implementation if and else in protractor

I have a scenario like this,when user select public there no problem but when selects a private,here modal should be popup and click on ok . HTML code:

<div ng-show="private" class="privateSetting">
      <h5>privacy Settings</h5>
      <div>
          <md-switch ng-model="privacySwitch" style="width:35%;" class="md-primary md-switch" ng-click="privacySettings()">
          </md-switch>
      </div>
      <p>privacy Msg</p>

    </div>

test code:

> element(by.css('aria-label=Private')).isDisplayed().then(function(result)
> {
>     if ( result ) {
>         element(by.css('[ng-click="privacySettings()"]')).click();
>         browser.sleep(5000);
>         element(by.className('btn btn-primary')).click();
>       browser.sleep(5000);
> 
>     } else {
>      
>         element(by.css('[ng-click="privacySettings()"]')).click();
>           browser.sleep(5000);
>     }

If Statement VBA

I am writing a script in Excel VBA with an If and an ElseIf statements for a database search. The search is conducted through a UserForm that has two fields, labelled as Country and Category and defined in the script as follows:

Dim country As String
Dim Category As String
country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value

The information is searched and presented in respect of the country searched and, as such, the minimum required for a search to run is the Country being provided by the user with a country that is in the database.

Taking the user-inputted criteria, the search runs through a table of data in a sheet called Database and pastes the results in another sheet called Results. Depending on the search criteria, the script will run several options prescribed by an If statement.

OPTION 1 - The user has provided a country and a category and:

  • The country exists in the database but;
  • The Category does not exist for the specific country.

In this case a MsgBox will pop up with saying that the specific combination of country and category provided by the user does not exist in the database. The message will ask the user if it would like to run a search just for all entries of the country provided, in this case. I have written the respective code as follows:

finalrow = Sheets("Database").Range("A200000").End(xlUp).Row

For i = 2 To finalrow

    If Sheets("Database").Cells(i, 1) = country And _
        (Category = "" Or Sheets("Database").Cells(i, 3) <> Category) Then
                Dim question As Integer
                question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you perhaps want to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")
                   If question = vbYes Then
                        Sheets("Results").Range("D6").ClearContents
                        Category = Sheets("Results").Range("D6").Value
                        boolRestart = True
                    Else
                        Sheets("Results").Range("D5").ClearContents
                        Sheets("Results").Range("D6").ClearContents
                        Me.Hide
                        WelcomeForm.Show
                        Exit Sub
                    End If

OPTION 2 - The user has provided a country and:

  • The country exists in the database and;
  • The user has also provided a Category that exists in the database for the specific country or;
  • The user has left the Category field empty.

In this case, the search will run. This is written in the script as follows:

ElseIf Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") Then

        'Copy the headers of the "Database" sheet
        With Sheets("Database")
            .Range("A1:I1").Copy
        End With
        Sheets("Results").Range("B10:J10").PasteSpecial

        'Copy the rows of the table that match the search query
        With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
        End With
        Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

    End If

I have tried to write the script in several different ways but the search engine keeps on not working as I want to. What is happening now is that when I input a Country that I know to be in the database, regardless of inputting a Category as well or not, OPTION 1 is always triggered. I have tried to take out OPTION 1 altogether and run just an If statement with OPTION 2 as is and the search runs fine with Country filled in and with both Country and Category filled in. However, as soon as OPTION 1 in in the code, this is always the option ran, regardless of what is inputted by the user.

The full code is here , for your reference:

Dim country As String 'Search query country, user-inputted
Dim Category As String 'Search query category user-inputted
Dim finalrow As Integer
Dim i As Integer 'row counter
Dim ws As Worksheet

Set ws = Sheets("Database")

country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
finalrow = Sheets("Database").Range("A200000").End(xlUp).Row

For i = 2 To finalrow

    If Sheets("Database").Cells(i, 1) = country And _
        (Category = "" Or Sheets("Database").Cells(i, 3) <> Category) Then
                Dim question As Integer
                question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you perhaps want to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")
                   If question = vbYes Then
                        Sheets("Results").Range("D6").ClearContents
                        Category = Sheets("Results").Range("D6").Value
                        boolRestart = True
                    Else
                        Sheets("Results").Range("D5").ClearContents
                        Sheets("Results").Range("D6").ClearContents
                        Me.Hide
                        WelcomeForm.Show
                        Exit Sub
                    End If

    ElseIf Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") Then

        'Copy the headers of the "Database" sheet
        With Sheets("Database")
            .Range("A1:I1").Copy
        End With
        Sheets("Results").Range("B10:J10").PasteSpecial

        'Copy the rows of the table that match the search query
        With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
        End With
        Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

    End If

Next I

Thank you very much for your help.

mardi 29 novembre 2016

Check Cell.Value for identical Value..IF Not Then

I am coding using VBA in Excel. My question is slightly complicated but the function is simple;

I am trying to make a cell follow a parent cell. Let me explain:

   1 A              B              C
   2 29/11/16      30/11/16        1/12/16
   3               30/11/16

Cells A2 thru C2 is the 'parent cell' Cells A3 thru C3 is the 'follower cell'

User will input a date in the 'follower cells' following the 'parent cell' The 'parent cell' is dynamic and will change its properties over time like so:

  1 A              B              C
  2 30/11/16       1/12/16         2/12/16
  3 30/11/16

My problem is that I need to have the 'follower cells' follow its 'parent cell' automatically, like what is shown above.

I have just started coding and I have tried designing various solutions using IF else statement, but that is as much as I know and its getting too complicated for me but I am learning from various sites and trying out codes.

I need help from the experts on this.

Thank you.

vigenere cipher c langauge

I am trying to make a vigenere cipher in C language. The input is only supposed to be alphabetical characters (a->z).

Currently my issue is the output only puts out 4 characters and outputs strange characters outside the alphabet. I have created the if statements to prevent this, but it seems they are not working. Any advice?

#include <stdio.h>


int main(){
    int i=0;
//Vigenere Cipher-- keyword is "apple"
//a = 1  value shift
//p = 16 value shift
//p = 16 value shift
//l = 17 value shift
//e = 5  value shift
 //cleaning out string array
 char guy[100];

printf("Enter the plain text: ");
fgets(guy, 100, stdin);//takes user's input

while (guy[i] != '\0'){ //while loop that runs until it reaches the end of the string

    if ((i%5==0) || i==0){ //checks to see which character it is in the string, for instance the numbers 0,5,10,15,20 should all be added by 1
    guy[i] = guy[i]+1;
    if (guy[i]>'z' && guy[i]<'A'){
            guy[i]-25;
    }
    if (guy[i]>'Z' && guy[i]>'A'){
        guy[i]-25;
    }
    }

    if (((i-1)%5==0) || i==1){ //all numbers that are second in the key word 'apple', such as 1,6,11,16
        guy[i]=guy[i]+16;
        if (guy[i]>'z' && guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z' && guy[i]>'A'){
            guy[i]-25;
        }
    }
    if (((i-2)%5==0) || i==2){// all numbers that are third to the key word 'apple' , such as 2,7,12,17,22
        guy[i]=guy[i]+16;
        if (guy[i]>'z'&& guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z'&& guy[i]>'A'){
            guy[i]-25;
        }
    }
    if(((i-3)%5==0) || i==3){// all numbers that are fourth to the key word 'apple', such as 3,8,13,18
        guy[i]=guy[i]+17;
        if (guy[i]>'z'&&guy[i]<'A'){//takes care of z
            guy[i]-25;
    }
        if (guy[i]>'Z' && guy[i]>'A'){//takes care of Z
            guy[i]-25;
        }
    }
    if(((i-4)%5==0) || i==4){// all numbers that are fifth in the key word 'apple', such as 4,9,14,19
        guy[i]=guy[i]+5;
        if (guy[i]>'z'&& guy[i]<'A'){
            guy[i]-25;
        }
        if (guy[i]>'Z' && guy[i]>'A'){
            guy[i]-25;
        }
    }
    else {
    i++;
    }
    }
printf("Encrypted text is: %s\n",guy);
}

Javascript if else condition for fields depending on values selected

I have a problem with a condition statement with 4 fields involved

  1. Issuing country select field [ Select field ]
  2. Currency of the amount to be paid [ Select Field ]
  3. Conversion of the amount entered [ Input Field ]

    //if "AUS" is selected auto-select AUD as currency and run the second function to the amt_input field
    
    
    
    <select name="issuing_country" id="issuing_country">
        <option value=""> -- Please Select --</option>
        <option id="ARG" value="ARG">Argentina</option>
        <option id="USA" value="ARM">Armenia</option>
        <option id="ABW" value="ABW">Aruba</option>
        <option id="AUS" value="AUS">Australia</option>
     <select> 
    
    
    
    //Select a currency:
    
    <tr class="shade">
       <td align="left">Currency: &nbsp;</td>
       <td>
          <select name="vpc_Currency">
             <option value="USD">USD</option>
             <option value ="AUD" selected>AUD</option>
          </select>
       </td>
    </tr>
    
    

    //where to enter the amount//

     <input type="text" name="amt" value="">
    
    

    //field that will reflect the computation//

      <input id="Total_Amount" name="vpc_Amount" value=""/>
    
    
    //Javascript//
    
    <script type="text/javascript">
    
       function ().call(){
    
             var amt;
                function.do{
    
    

    //if USD is selected to be converted to AUD in the amt field//

                    if (vpc_Currency = "USD")&&(AUS)
                    var amount = (usd * 1.36) * 1.023;
                    return amount;
    
    

    //if AUD currency and issuing bank is AUS//

             else if (vpc_Currency = "AUD")&&(loc='AUS')
                    var amount = [(aud * 1.023) * 1.1]
                    return amount; 
    
    

    //if different country and bank automatic select USD as currency//

                    else (aud * 1.023);
                    return amount;
                }
         }
    
    

C language-if statement issue

I've created the following program to make a Caesar and Vigenere cipher. I've gotten the Caesar cipher to work correctly, however I cannot get the Vigenere to work properly.

What I want to happen is have my if statements "catch" all the various numbers with an interval of 5. However whenever I run the program my Viegenere cipher outputs the exact same input. I believe this is because I'm making a mistake with my if statements, but i'm not sure what it is.

The beginning of the Viegenere cipher is commented in the code as //Vigenere Cipher-- keyword is "apple"

#include <stdio.h>


int main(){
int i=0;
 //setting the individual slot number for the array-- later used in the while loop
char guy[100];
printf("Enter the plain text:");
fgets(guy,100,stdin); //takes user's input-- such as "abc" and puts it into its respective slot in the array guy[10] r-right?

while (guy[i] != '\0'){ //while loop that runs until it reaches the end of the string


    if ((guy[i]) >= 'A' && (guy[i]<= 'Z')){ //moves capital letter values up 1
        if (guy[i]=='Z'){
            guy[i]=guy[i]-25;
        }
        else {
        guy[i]=guy[i]+1; //makes the current "slot" number go up 1 value. Example: a = 97 + 1 -> b = 98
        }
        }
    if ((guy[i]) >= 'a' && (guy[i]) <= 'z'){// moves lower case letter values up 1
        if (guy[i]=='z'){
            guy[i]=guy[i]-25;
        }
        else{
        guy[i]=guy[i]+1;
        }
    }
    i++; //moves the array's interval up to the next "slot"

}
printf("Encrypted text is: %s\n",guy);

//Vigenere Cipher-- keyword is "apple"
//a = 1  value shift
//p = 16 value shift
//p = 16 value shift
//l = 17 value shift
//e = 5  value shift

printf("Enter the plain text: ");
fgets(guy,100,stdin);//takes user's input

while (guy[i] != '\0'){ //while loop that runs until it reaches the end of the string

    if (i%5==0 || i==0){ //checks to see which character it is in the string, for instance the numbers 0,5,10,15,20 should all be added by 1
    guy[i] = guy[i]+1;
    }

    if ((i-1)%5==0 || i==1){ //all numbers that are second in the key word 'apple', such as 1,6,11,16
        guy[i]=guy[i]+16;
    }
    if ((i-2)%5==0 || i==2){// all numbers that are third to the key word 'apple' , such as 2,7,12,17,22
        guy[i]=guy[i]+16;
    }
    if((i-3)%5==0 || i==3){// all numbers that are fourth to the key word 'apple', such as 3,8,13,18
        guy[i]=guy[i]+17;
    }
    if((i-4)%5==0 || i==4){// all numbers that are fifth in the key word 'apple', such as 4,9,14,19
        guy[i]=guy[i]+5;
    }
    else {
    i++;
    }
    }
printf("Encrypted text is: %s\n",guy);
}

Equivalent of "case" for np.where

np.where lets you pick values to assign for a boolean type query, e.g.

test = [0,1,2]
np.where(test==0,'True','False')
print test
['True',1,2]

Which is basically an 'if' statement. Is there a pythonic way of having an 'if, else if, else' kind of statement (with different cases) for a numpy array?

This is my workaround:

color = [0,1,2]
color = np.where(color==0,'red',color)
color = np.where(color==1,'blue',color)
color = np.where(color==2,'green',color)
print color
['red','blue','green']

But I wonder if there's a better way of doing this.

Use if else to declar a `let` or `const` to use after the if/else?

I'm not sure why but it seems that I can't call the let or const variables if I declare them in an if/else statement

if (withBorder) {
  const classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
} else {
  const classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
}
return (
  <div className={classes}>
    {renderedResult}
  </div>
);

If I use this code it says that classes is not defined

But if I change the const to var classes is defined but I get a warning about classes used outside of binding contextand all var declarations must be at the top of the function scope

How could I fix this?

Refactor a multi-layered if-then

Looking for someone to proofread my logic. I inherited a method that contains this:

If (a || b)
{
   doTaskOne();
}
else
{
    if (c)
    {
        doTaskOne()
    }
    doTaskTwo()
}

Could this be simplified like this?

If ((a || b) || c))
{
   doTaskOne();
}
else
{
    doTaskTwo()
}

How to determine if an array index is even?

I am working on an assignment in which I must fill a two dimensional array row by row. If the row's index value is even (0, 2, 4, etc..) the row must fill from right to left. If the row's index value is uneven (1, 3, 5, etc...), then it must fill from left to right. What condition should I put in my if statement in order for the filling of rows to alternate in this way?

Thanks!

Query output not consistent to if condition

I am running into an issue I cannot figure out. I am doing a SELECT query to display users' friends. I am joining a users, friends, and profile_img table to get the user information, their profile image and the friend relationship.

In the friends table, if friend_one and friend_two have a status of 2, that means they are friends. This is what my query is checking for and then joining together the other tables to retrieve the other data, such as username and the image.

The query seems to be working fine. My output on the other hand is not what it should be though.

In my friends table, if you are looking at row 2 (see INSERT below), friend_one is 5 and friend_two is 1. My query gets the data for both of these users, however, when I attempt to output the friend list, I am only wanting to display the friend list associated with the user profile I am viewing. So if I am on friend 1's profile page, the data I want to show is only for friend 5.

CREATE TABLE `friends` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `friend_one` int(11) NOT NULL DEFAULT '0',
 `friend_two` int(11) NOT NULL DEFAULT '0',
 `status` enum('0','1','2') COLLATE utf8_unicode_ci DEFAULT '0',
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`),
 KEY `friend_two` (`friend_two`)
);

INSERT INTO `friends`
VALUES 
(1, 1, 2, 2, NOW()),
(2, 5, 1, 2, NOW())
;

I attempted an if statement to continue past the friend data in which matches the profile user's page I was on and it works for the friend_1 output...which would show 1, but it doesn't do it for the friend_img and friend_username.

Does anyone see why it is working for $friend_1, but not the rest of their data? The image and username are outputting the profile user's data, which it should be the opposite and just their friends data.

    $friend_status = 2;
    $friend_sql = "
    SELECT f.*,
        u1.*,
        u2.*,
        p1.*,
        p2.*,
        IFNULL(p1.img, 'profile_images/default.jpg') AS img1,
        IFNULL(p2.img, 'profile_images/default.jpg') AS img2
    FROM friends f
    LEFT JOIN users u1 ON u1.id = f.friend_one 
    LEFT JOIN users u2 ON u2.id = f.friend_two
    LEFT JOIN (
        SELECT user_id, max(id) as mid
        FROM profile_img
        GROUP BY user_id
    ) max1 ON u1.id = max1.user_id
    LEFT JOIN (
        SELECT user_id, max(id) as mid
        FROM profile_img
        GROUP BY user_id
    ) max2 ON u2.id = max2.user_id
    LEFT JOIN profile_img p1 ON p1.user_id = f.friend_one and p1.id = max1.mid
    LEFT JOIN profile_img p2 ON p2.user_id = f.friend_two and p2.id = max2.mid
    WHERE (friend_one = :profile_user or friend_two = :profile_user)
            AND status = :total_status
    ";
    $friend_stmt = $con->prepare($friend_sql);
    $friend_stmt->execute(array(':profile_user' => $profile_user, ':total_status' => $friend_status));
    $friend_total_rows = $friend_stmt->fetchAll(PDO::FETCH_ASSOC);
    $count_total_friend = $friend_stmt->rowCount();
?>  
            <div id="friend-list-container">
                <div id="friend-list-count">Friends <span class="light-gray"><?php echo $count_total_friend; ?></span></div>
                <div id="friend-list-image-container">
<?php
    foreach ($friend_total_rows as $friend_total_row) {
        $friend_1           = $friend_total_row['friend_one'];
        $friend_2           = $friend_total_row['friend_two'];
        $friend_img_src     = $friend_total_row['img'];
        $friend_img         = '<img src="'.$friend_img_src.'" alt="Friend Image">';
        $friend_username    = $friend_total_row['username'];
        if($friend_1 !== $profile_user) {
            echo '<div class="friend-list-block">
                    <div class="friend-list-block-img">' .
                    $friend_img .
                        '<div class="friend-list-block-details">'. $friend_1 . " "
                    . $friend_username .
                '</div></div></div>';

        }

Fiddle

A weird case of if else statement malfunction in PHP

I've been working over this question for a few hours and really hope im not missing anything basic. I know its mostly code but all the information is in comments within the code.

I have a function which i feed in my case: $db is array with access creds $uid is null in this case $email is a valid email address $companyid is a valid specific numeric value, which is irrelevant $fname, $lname, $mname, $role - valid strings

Now the function itself:

function hire_employee($db, $uid, $email, $companyid, $fname, $lname, $mname, $role){
    try{    
        $srvr = new PDO("mysql:host=".$db['server'].";dbname=".$db['db'], $db['mysql_login'], $db['mysql_pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
        $srvr->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        if (is_numeric($uid)){ //uid is null in our case, so we skip this piece of code
            echo "<br>trace 1";//does not output
            $set=$srvr->prepare("INSERT into roles (uid, companyid, role, assigned_date) VALUES ((SELECT uid FROM users WHERE uid=:uid and active=1), :companyid, :role, CURDATE());");
            $set->bindParam(":uid", $uid);
            $set->bindParam(":companyid", $companyid);
            $set->bindParam(":role", $role);
            if ($set->execute()){
                return true;
            }
        } elseif (isset($email)) {// this is our case, we have a valid email
            echo "<br>trace 2";//does output
            $email = filter_var($email, FILTER_SANITIZE_EMAIL);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                //is a valid email address
                //first trying to add existing user (if exists)
                echo "<br>trace 2.1";//does output
                $check=$srvr->prepare("INSERT into roles (uid, companyid, role, assigned_date) VALUES ((SELECT uid FROM users WHERE email=:email and active=1), :companyid, :role, CURDATE());");
                $check->bindParam(":companyid", $companyid);
                $check->bindParam(":role", $role);
                $check->bindParam(":email", $email);
                //NOW THE WEIRD PART!!!-----------------------
                if ($check->execute()){//checking if statement executes successfully and returns true
                    echo "<br>trace 2.1.1";//does not output, a proper thing in our case
                    return true;
                } else { //nope user does not exist, we need to create a user
                    echo "<br>trace 2.1.2";//this does not output either!!!
                    //dear stackoverflow member can skip the rest of the code below
                    echo "<br>traceYO!!! $uid, $email, $companyid, $fname, $lname, $mname, $role";
                    $newuserid=register_user($db, $fname, $mname, $lname, "NULL", "NULL", "NULL", "NULL", true, $email, "NULL");
                    echo $newuserid;
                    if (!is_numeric($newuserid) AND ($newuserif > 0)) {
                        echo "<br>trace 2.1.2.1";
                        return false;
                    } else {
                        echo "<br>trace 2.1.2.2";
                        $insert=$srvr->prepare("INSERT into roles (uid, companyid, role, assigned_date) VALUES (:uid, :companyid, :role, CURDATE());");
                        $insert->bindParam(":uid", $newuserid);
                        $insert->bindParam(":companyid", $companyid);
                        $insert->bindParam(":role", $role);
                        if ($insert->execute()){
                            echo "<br>trace 2.1.2.2.1";
                            return true;
                        }
                    }
                }
            } else {
                //is not a valid email address
                return false;
            }
        } else { 
            echo "<br>trace 3";
            return false;
        }

    }
    catch(PDOException $e) {
        report_error($db, $_SESSION['uid'], $companyid, 'hire_employee', "companyid: $companyid, fname: $fname, mname: $mname, lname: $lname, email: $email, uid: $uid, role:$role", $e->getMessage());
        return false;
    }
}

Now the only output I'm getting here:

trace 2 trace 2.1

Somehow it fails to trace 2.1.1 or 2.1.2.

Any help would be much appreciated.

Is omitting one of the operations in conditional ? : a good behavior? [on hold]

For instance: one way of doing conditional code is:

//set input to 100 when it is equal to 0. Do nothing when it is not valued as 0
int input = ifunction();
if(input == 0)
    input = 100;

Another way is:

input == 0 ? 100 : NULL;

It seems the second way is shorter and cleaner. How do you think? Which way is better?

Can I use Logical Operators && || with Strings?

For example, I was trying to create an if statement requiring both conditions entered in a scanner to be true. I know it's possible with numbers.

if(input2.equals("yes"))   
// and adding (input1.equals(chooseOpt[1])) to the same statement. 
// if this and that is true  all written in the same statement 
// then print out etc...etc... 

I'm on my way to becoming better at Java but I want to know, is this possible? And if so, how?

Need help connecting JavaScript code to button that is also connecting to html file on computer [on hold]

I'm using Expression Web 4, all my files are in a folder on the Desktop, but the page says the file can't be found. I am trying to host from my computer since I will only have this up for 1 day.

It would show up in the search bar like this:
file:///C:/UsersnameDesktopName_websiteWebsitePage.html

But I have the file path like this:
C:\Users\name\Desktop\Name_website\WebsitePage.html

The html code:(these are only a few of many)
All of the check boxes are in a tag,
Each checkbox resides in it's own tag,

<form action="">
<div class="course" id="crse">
<input type="checkbox" name="course" value="53" id="crse53" class="auto-style2" /><span class="auto-style2">BMT-1650 Customer Service - 3 credits</span><br class="auto-style2"/>
<input type="checkbox" name="course" value="54" id="crse54" class="auto-style2" /><span class="auto-style2">Cyber Law - 3 credits</span><br class="auto-style2"/>
<input type="checkbox" name="course" value="55" id="crse55" class="auto-style2" /><span class="auto-style2">BMT-2880 Emergency Management - 3 credits</span><br class="auto-style2"/>
</div>
</form>

<input id="clickme"type="button" value="Find my Certificate" onclick="doFunction();"/>

The javascript code: I'm trying to connect the if statement to the button which will lead the user to certain html page that is stored on my computer. The file is the same folder as the other html files.

var crse53 = document.getElementById('crse53').checked,   
crse54 = document.getElementById('crse54').checked,   
crse55 = document.getElementById('crse55').checked,    
crse56 = document.getElementById('crse56').checked,   
crse57 = document.getElementById('crse57').checked,   
crse58 = document.getElementById('crse58').checked;


if (crse53 == false && crse54 == false && crse57 == false && crse58 == false){

var myBtn = document.getElementById('clickme');

myBtn.addEventListener('click', function(event) {
    window.location.href='C:\Users\name\Desktop\Name_website\WebsitePage.html';});

document.getElementById("clickme").onclick = doFunction;

} else {
alert("try again");
};

I don't know whats wrong. Is it the file path or the something else? If there is a more efficient way of doing this please let me know!!

Use an if statement to make checking possible

I am a newbie to AngularJS so here is my question. I use the Ionic Framework and AngularJS and I want to use an if statement to check if a task is completed or not. I can do that but I want to use icons as well, an empty checkbox if it's not completed and a checked checkbox.

My code:

<ion-list>
  <ion-item ng-repeat="task in tasks" class="item-icon-right" ng-class="{complete: task.completed}"
            ng-click="task.completed = !task.completed">
    <i class="material-icons">check_box_outline_blank</i>
    <i class="material-icons">check_box</i>
    
    <ion-option-button class="button-assertive delete" ng-click="tasks.splice($index, 1)"><i class="material-icons">delete</i>
    </ion-option-button>
    <ion-option-button class="" ng-click="edit(task)"><i class="material-icons">mode_edit</i></ion-option-button>
  </ion-item>

</ion-list>

Break out from If statement in ActionScript3?

I try to write a small Android program, which tells me the distance from a fix point. When the distance of the device and the fix point is below 100meters, a phone plays a sound.

if (distance<100){mySound.Play()};

It's OK, the sound starts, but when the GPS send the new coordinates, and the distance is below 100meters again, the mySound starts again and again in each second. The Sound should be played only one, when the the distance decrase below 100metes at First time. Any advice? Thx!

What's wrong in my if statements logic?

In this little program I try to order 3 numbers in a descending order. But seems like the line in which has "// 3 2 1 - doesn't work" as a comment isn't working as expected. It seems like my logic is correct.

If the value hold on the integer numbThree is bigger than numbOne and if numbOne is NOT bigger than numbTwo (NOT == else) it should ouput numbThree, numbTwo and numbOne in this order, why doesn't it work?

#include <iostream>

int main() {
int numbOne = 0, numbTwo = 0, numbThree = 0;
std::cin >> numbOne >> numbTwo >> numbThree;

if (numbOne > numbTwo) {
    if (numbTwo > numbThree) {
        std::cout << numbOne << " " << numbTwo << " " << numbThree << std::endl; // 1 2 3
    }
    else {
        std::cout << numbOne << " " << numbThree << " " << numbTwo<< std::endl; // 1 3 2
    }
}
else if (numbTwo > numbOne) {
    if (numbOne > numbThree) {
        std::cout << numbTwo << " " << numbOne << " " << numbThree << std::endl; // 2 1 3 - works
    }
    else {
        std::cout << numbTwo << " " << numbThree << " " << numbOne << std::endl; // 2 3 1
    }
}
else if (numbThree > numbOne) {
    if (numbOne > numbTwo) {
        std::cout << numbThree << " " << numbOne << " " << numbTwo << std::endl; // 3 1 2
    }
    else {
        std::cout << numbThree << " " << numbTwo << " " << numbOne << std::endl; // 3 2 1 - doesn't work
    }
}

std::cin.get();
std::cin.ignore();
return 0;
}

Thanks in advance for helping me out.

Compare a varStatus with a number in

This question already has an answer here:

I have the following code snippet:

<c:if test="${ $(status.index) == 0 }"></c:if>

status is the varStatus of a surrouding c:forEach. I tried already several possibilities, but I couldn't find the correct way for comparing.

At the moment I am getting an javax.el.ELException (Function ':$' not found).

Does anybody may help?

What is good coding practice in BASH with regard to exiting

What is good practice when writing a BASH script with regards to exiting the script when using functions and if statements?

1)

functionONE(){
    some code here
    exit 0
}

functionTWO(){
    some code here
    exit 0
}

if [[ condition ]]; then
    functionONE
else
    functionTWO
fi

exit 1

2)

functionONE(){
    some code here
}

functionTWO(){
    some code here
}

if [[ condition ]]; then
    functionONE
    exit 0
else
    functionTWO
    exit 0
fi

exit 1

Or would scenario create an endless loop? (Would the exit 0 in the second scenario be executed after the functions have run or would it never be reached

Ideally the bottom line would never be reached.

lundi 28 novembre 2016

Defining variable in if [duplicate]

This question already has an answer here:

I am trying to call a function in an if, save the value in a variable and check if the value is equal to something. Have tried:

def funk():
    return ("Some text")

msg=""
if (msg=funk()) == "Some resut":
  print ("Result 1")

I am getting a syntax error. Can this be done?

I'm coming from C and I know that this can work:

#include <stdio.h>

char funk()
{
    return 'a';
}
int main()
{
    char a;
    if( a=funk() == 'a' )
        printf("Hello, World!\n");
    return 0;
}

Is this possible in python?

P.S. The functions are simple so it is easier to understand what I want. I will not use the some functions in my program. If you give me a MINUS please explain in comment so I can make better questions in the future

Replace a row with zeros if one of its elements is higher than a fix number

I am doing the pricing of a Barrier option (if the underlying asset goes above 120, it cease to exist) in R using MC simulation.

Basically, I have a matrix (10000X100) that can have values raning from around 30 to 200 and I would like that if a value in a row goes above 120, all the values in this row will be set to 0.

I think people do it like that in MatLab but I can't do it in R:

nbrsim = 10000;
nbr_step = 100;
S = zeros(nbrsim,nbre_step+1);
    for j = 1:nbrsim
    if min(S(j,:)) <= B
       l(j) = 0;
    else
        l(j) = 1;
    end
    vectpayoffs(j) = l(j)*max(ST(j) - K,0);
    end

I will be very glad if someone knows how to do this computation

Swift 3: How to know if a set certain amount of strings match in 2 arrays

I have a simple line of code with 2 String Arrays. They both contain the same strings inside both arrays and I have an if statement that will work if both arrays are the same. Like so:

var firstArray: [String] = ["Music", "Art", "Sports", "Movies"]
var secondArray: [String] = ["Music", "Art", "Sports", "Movies"]

if firstArray == secondArray {

   //they match...
}

However, I want to be able to add a few more strings to the first array so the 2 arrays aren't fully the same, which will cancel out the if statement above BUT I want to run the if statement if 4 or more strings are the same in the second array as they are in the first array. How do I do this? Thank you.

do-loop ignores if-statement in FORTRAN

i'm trying to use an if statement in a do loop which is supposed to generate prime numbers. For that i used modulo to sort out the numbers. After it found a prime number i want it to go a step further and add 1 so that the next prime number can be found and added to the array pzahl. My Problem is that the loop seems to ignore that it should go a step further with plauf after it found a prime number so that it just keeps going till infinity... I tried to rearrange the contents of the loop and if statement but it's just not working :/ Here the code:

PROGRAM Primzahlen

   IMPLICIT NONE

   INTEGER :: start, plauf, n, a
   INTEGER, ALLOCATABLE, DIMENSION(:) :: pzahlen !array into which the  prime numbers should be added
   INTEGER :: input
   INTEGER, DIMENSION(:), ALLOCATABLE :: alle 

   PRINT *, "How many prime numbers should be listed"
   READ (*,*) input
   ALLOCATE (pzahlen(input))
   pzahlen(1) = 1 
   start = 2
   plauf = 1

 loop1: DO 

   ALLOCATE(alle(start))

    loop2: DO n = 1,start
       alle(n)= MODULO(start,n)
    END DO loop2

   IF (minval(alle) /= 0) THEN  ! This is what it seems to ignore.
    plauf= plauf + 1 
    pzahlen(plauf) = start
    PRINT *, plauf
   END IF

  start = start + 1

 IF (plauf == eingabe) then
    EXIT
 END IF
 PRINT *,  alle
 DEALLOCATE(alle)

END DO loop1

PRINT *, "prime numbers:" , pzahlen(1:input)

END PROGRAM Primzahlen 

I use the gfortran Compiler and write it in emacs if that helps to know. Would be very thankful if somebody could give me a hint where my mistake is :)

I can´t figure out whats wrong with my if statement

I have a if statement, it should redirect visitors if they dont come from facebook, facebook mobile or instagram.

    $ref            =   $_SERVER['HTTP_REFERER'];
    $facebook       =   "http://ift.tt/g8FRpY";
    $facemob        =   "http://ift.tt/2fukxNO";
    $instagram      =   "http://ift.tt/1kwsCwF";

    if ($ref != $facebook or $ref != $facemob or $ref != $instagram) {
        echo "my header location here../ you are not welcome";
    } else{
     echo "Welcome!";
    }
    ?>

It works just fine if i only use if($ref != $facebook) {...ofcause only if i come from a facebook ref. :)

Flask, get value from checkbox and pass the result to another template

I am using Weasyprint, to display some jinja templates in a Flask Web App. I have this json.

value=["1","2","3","4"]

I have to pass 'value' to another jinja template in an if loop.


Liquid error: This liquid context does not allow includes.


But this shows the error,

TemplateSyntaxError: expected token ')', got '='

I thought I had to convert json to int in order to make the if loop work.

trying to the code below in JavaScript to take in age and restrict movie viewing

enter code herevar canIWatch = function(age) { enter code hereif(0 < age < 6) { enter code herereturn "You are not allowed to wantch Deadpool after 6.00pm."; enter code here} enter code hereelse if (6 <= age < 17) { enter code herereturn "You must be accompanied by a guardian who is 21 or enter code hereolder."; enter code here} enter code hereelse if (17 <= age < 25) { enter code herereturn "You are allowed to watch Deadpool, right after you enter code hereshow some ID."; enter code here} enter code hereelse if (age >= 25) { enter code herereturn "Yay! You can watch Deadpool with no strings enter code hereattached!"; enter code here} enter code hereelse { enter code herereturn "Invalid age"; enter code here} enter code here};

Convert If-Else statement to Switch Statement

I recently completed a problem in CodeWars using an if-else statement, but I wanted to retry it and use a switch statement instead. Too bad that it is not working the way that I thought it would!

The problem I am solving is to take in a distance(s) that an Ironman triathlon athlete has completed and return an object that shows a key based on whether the athlete should be Swimming, Biking or Running with a value of the length of the race to go.

My If-Else Solution:

function iTri(s) {  
  var triLength = 140.60;  
  var result = {};  
  var str = ' to go!';  
  var lengthLeft = (triLength - s).toFixed(2);  

  if (s === 0) {
    return 'Starting Line... Good Luck!';
  } else if (s <= 2.4) {
    result.Swim = lengthLeft + str;
  } else if (s <= 114.4) {
    result.Bike = lengthLeft + str;
  } else if (s < 130.60) {
    result.Run = lengthLeft + str;
  } else if (s < 140.60) {
    result.Run = 'Nearly there!';
  } else {
    return 'You\'re done! Stop running!';
  }
  return result;
  }

The (non-working) Switch statement:

function iTri(s){
  let tri = (2.4 + 112 + 26.2).toFixed(2);
  let left = tri - s;
  let str = ' to go!'
  let result = {};

  switch(s) {
    case (s === 0):
      return "Starting Line... Good Luck!";
      break;
    case (s <= 2.4):
      result.Swim = left + str;
      return result;
      break;
    case (s <= 114.4):
      result.Bike = left + str;
      return result;
      break;
    case (s <= 130.60):
      result.Run = left + str;
      return result;
      break;
    case (s < 140.60):
      result.Run = 'Nearly there!';
      return result;
      break;
    default:
      return 'You\'re done! Stop running!';
  }
}

These are the tests:

Test.describe("Example tests",_=>{
Test.assertSimilar(iTri(36),{'Bike':'104.60 to go!'});
Test.assertSimilar(iTri(103.5),{'Bike':'37.10 to go!'});
Test.assertSimilar(iTri(2),{'Swim':'138.60 to go!'});
});

And the Output:

✘ Expected: '{ Bike: \'104.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Bike: \'37.10 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Swim: \'138.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''  

Also is it worth it to convert it to a switch statement? What are benefits/drawbacks of doing it as if/else vs switch?

All help is appreciated!

What is wrong with my javascript functions logic? [duplicate]

This question already has an answer here:

I'm having a problem with my Javascript function, I'm not understanding something, just looking for some clarity.

I have a function:

function Test (array) {
    if (array === []) {
        return "the array is empty";
    } else {
    return array;
}

When I pass this function an empty array, it returns the empty array, completely skipping the first part of my if statement (this is the part I'm not understanding, why is it skipping that part? My understanding is that it would return my string statement at that point since the array I pass it, is in fact empty. If I remove the else statement, it returns "undefined".

NOTE! : I am aware that the solution to this problem is to set my "if" statement to compare the length of the array I pass it.

ex:

function Test (array) {
    if (array.length === 0) {
        return "the array is empty";
    } else {
    return array;
}

I'm just still not understanding why the first one doesn't work, and would really appreciate an explanation.

How to use break-continue inside for-loop when row/column values changes inside the database?

In the given data set I need to multiply values from different blocks with each other.

I want to inject break-continue within for loop but the examples I have looked so far isn't quite helping. Actually, this data is just a part of the big data so I need some explanation on how - why break-continue works.

So,for X(set) I have to multiply: 0.25*0.1*0.83 (since they belong to same block

block   X_set
2480    0.25
2480    0.1
2480    0.083
2651    0.43
2651    0.11
2651    0.23

My code is as follows:

test_q = open("test_question.txt", "r+")
header = test_q.readline()
data_q = test_q.read().rstrip("\n")

product=1.0
value_list = []

row = data_q.split("\n")

for line in row:
    block = line.split("\t")
    X_list = block[1].split()
    X_value = float(block[1])
    value_list = value_list + X_list
    product = product*X_value

print(value_list)
print(product)

The result is:

['0.25', '0.1', '0.083', '0.43', '0.11', '0.23']
2.2573925000000003e-05

But, in the print I want

['0.25', '0.1', '0.083']
0.0002075

['0.43', '0.11', '0.23']
0.010879

So, how to inject the break and continue function within this for-loop?

  • I don't want to use a fixed value for blocks since this is a long file and the block value will change.

  • Also, the row with same block values may not be next to each other.

  • Also, i don't need solution on pandas since this is just a part of big file which is exclusive mined using for-if-else loop.

Thanks much in advance !

Check if string contains more than one word reg exp javascript

i have a simple issue that i want to sort out. So basically i have a picture string that goes like this '10_aut_linen_male_less_student_work_yellow_n_cold.png' where

male = gender; n = weather ; cold = temperature.

Now i have those variables stored in a var. How do i check if ALL of those 3 variables are in the picture string?

C# Use returned value from Method in IF/ELSE Statement

I'm an Programmer Apprentice in Denmark. Right now i am working on a simple program, and this is a problem i've been thinking over many times. Many times i run my methods twice because of checking on the return value before running them, and i would like to know if there is a way i can prevent this, like using the returned value from the method i am checking against. It's quite hard to explain so here is a real life example from my program :-)

public class SFDBRepository
{
    public static Domain.SF.SFObject GetSFOrder(string WorkOrd)
    {
        //As you can see here i'm checking on the output of this method, before trying to return it.
        if (Domain.SF.SF.GetOrder(WorkOrd) != null)
        {
            //If the value is not null (My method returns null if no result), return the object
            return Domain.SF.SF.GetOrder(WorkOrd);
        }
        //Same thing happens here. My method runs twice every time almost. 
        else if(Domain.Building_DeliveryPerformance.Building_DeliveryPerformance.GetObject(WorkOrd) != null)
        {
            return Domain.Building_DeliveryPerformance.Building_DeliveryPerformance.GetObject(WorkOrd);
        }
        else
        {
            return null;
        }
    }

}

How to wait for a value until it performs the next syntax in VB.NET?

I am obtaining height data from my sensor and here is my code:

If Sensor1 = 5 Or Sensor1 = 6 Or Sensor1 = 7 Then
   If Sensor1 >= 13 Then
      flagCtr1 = 1
   End If
ElseIf Sensor1 = 8 Or Sensor1 = 9 Then
   If Sensor1 >= 13 Then
      flagCtr1 = 2
   EndIf
ElseIf Sensor1 = 10 Then
   If Sensor1 >= 13 Then
      flagCtr1 = 3
   End If
End If

Basically what I want to happen is, for example, when my sensor detected the height 7, it will wait for the value greater than or equal 13 before it performs the flagCtr = 1. I tested this code and nothing happens.

This is my dilemma. This is an example of how I read the height where 15 is the height where there is no object placed below the sensor

15
15
15
7 - object was placed
7
7
7
7
8 - object is being removed
15
15
15

everytime I will remove the object it goes to a certain number that is also in one of the conditions. My problem is the latest height data is being read not the data that was read at a time interval. So what I want to do is that I will wait for the sensor to go back to the value greater than or equal 13 before it performs the next instruction.

Sorry for a long post, I really need help, this is my thesis. Thank you so much

Simplifying conditional statement android

I have a method with few conditional statements. I have added the if conditions so I can avoid my NPE crash. Is there any way I can simplify the if conditions where I have added the non-null check?

 private void addComplementaryProductToBasket(String productId, String comboName) {
        Product product = ProductComboUtils.getProductById(productId);
        if (null == product) {
            LOG.info("Product does not exist in ProductComboUtils, fetching from DB");
            product = getProduct(productId);
        }
        if (product != null){
            product.setPrice(BigDecimal.ZERO);
            product.setCurrencyCode(currentBasket.getCurrencyCode());
            // Ensure to add comboName with purchase, this
            currentBasket.addToPurchase(product, comboName);
            int numberOfComplementaryProducts =
                    currentBasket.getPurchaseLineItemForProduct(product.getProductId()).getNumberOfComplementaryProducts();
            currentBasket.getPurchaseLineItemForProduct(product.getProductId()).setNumberOfComplementaryProducts(
                    ++numberOfComplementaryProducts);
        }else
        {
            CrashUtil.logNonFatalException("Product instance is null for productId: " + productId);
        }
    }

Comparing string with Optional to non Optional string

Are they both equal strings?

enter image description here

I tried printing them, following is the response:

enter image description here

When tried comparing them, it turns out to be false

enter image description here

I cannot understand, though they both letters are same in Arabic, but still it says, they aren't!

enter image description here Here is a more contextual picture of what's happening:

dimanche 27 novembre 2016

checking id to set value

I'm doing a jeopardy board, and I've given each div (each question square) an id in the index.html so when it's clicked, the correct question appears. I also wanted to set the point value for each div based on its id, so I used the jquery .is and this if/else statement. I've only done the code for A1 and A2, but while A2 should be worth $200, it's coming back worth $100. Why?

if ($('.well').is('#A1', '#B1', '#C1', '#D1', '#E1')) {
questionValue = 100;
}
else if ($('.well').is('#A2', '#B2', '#C2', '#D2', '#E2')) {
questionValue = 200;
}
else if ($('.well').is('#A3', '#B3', '#C3', '#D3', '#E3')) {
questionValue = 300;
}
else if ($('.well').is('#A4', '#B4', '#C4', '#D4', '#E4')) {
questionValue = 400;
}
else if ($('.well').is('#A5', '#B5', '#C5', '#D5', '#E5')) {
questionValue = 500;
}

Thank you in advance. Please let me know if I should include any more code. .well is the div class for the question squares.

Exiting loop when user clicks "cancel" or finishes number of allowed attempts

I want to code a loop that ends when the user has used up their three tries, clicks cancel or closes the window with the red x. The red x and using up the three tries portion work fine. But the cancel button is being useless and acting the same as the OK button.

I have written an if statement but it is ineffective. The window that prompts the user for a password continues to pop up until all allowed attempts are used up even when the user presses cancel. This is what I have so far:

    String[] options = new String[]{"OK", "Cancel"};

    int tries = 0;

    String passString = "";

    int option = JOptionPane.OK_OPTION;

    while (!isValidPassword(passString) && tries < 3) {

            option = JOptionPane.showOptionDialog(null, panel, "The title",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, options, options[1]);


            if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
                break;
            }

Simplification of successive if statements in Java

I have a series of if statements as shown below:

if (board[x+1][y]==true) {
    ar+=1;
}
if (board[x][y+1]==true) {
    ar+=1;
}
if (board[x-1][y]==true) {
    ar+=1;
}
if (board[x][y-1]==true) {
    ar+=1;
}
if (board[x+1][y+1]==true) {
    ar+=1;
}
if (board[x+1][y-1]==true) {
    ar+=1;
}
if (board[x-1][y+1]==true) {
    ar+=1;
}
if (board[x-1][y-1]==true) {
    ar+=1;
}

Is there a way to simplify/condense these statements with Java?

Any suggestions appreciated.

How to break-continue in for-loop (with if-else) when values changes in a row/column of a database?

In the given data set I need to multiply values from different blocks. In the original data I only had first 5 columns. I was able to update and add the last two columns using a for (with if-elif inside) loop. But, I also need to multiply the values from the different set (X and Y) based on their set status. But, the problem is I multiply values between rows.

So,for X(set) I have to multiply: 0.25*0.1*0.83 (since they belong to same block, set(index i.e before the pipe (|) sign, and group (X group)

X            value_X                Y             value_Y               block    set      X(set)       Y(set)
A,T,C        0.25,0.6,0.15          A,C,G         0.3,0.3,0.4           2480     A|C    0.25|0.15     0.3|0.3
G,T,C,A      0.25,0.15,0.1,0.5      G,T,C,A       0.21,0.3,0.19,0.3     2480     C|T    0.1|0.15      0.19|0.3
A,T,G        0.3,0.6,0.1            A,C,T         0.4,0.5,0.1           2480     C|T    0.083|0.6     0.5|0.1
C,A,T        0.26,0.31,0.43         C,T,G         0.39,0.43,0.18        2651     T|C    0.43|0.26     0.43|0.39
T,A,G        0.55,0.11,0.34         T,A,C,G       0.21,0.17,0.26,0.36   2651     A|C    0.11|0.083    0.17|0.26
G,A,C,T      0.23,0.23,0.34,0.2     A,T,C         0.21,0.36,0.43        2651     G|A    0.23|0.23     0.083|0.21

My syntax was as follows:

haplotype_freq = 1.0

haplotype_set_A = []

haplotype_set_B = []

hapA_freq_X = []

hapB_freq_X = []

hapA_freq_Y = []

hapB_freq_Y = []

test_data02 = open("multiply_test_level02.txt", "r+")
header = test_data02.readline()
#this separates the header (which is the very first line in the file)`

#load the rest of the data onto a variable called 'data'`
data = test_data02.read().rstrip("\n")
#rstrip removes the very last (\n) of the file`

lines = data.split("\n")

for each_line in lines:
    column = each_line.split("\t")

#Read different allele variables and frequency for both populations`
    X_list = column[0].split(","); X_values = column[1].split(",")
    Y_list = column[2].split(","); Y_values = column[3].split(",")


# Read the genotype of the phased haplotype in that line (position)
genotype = column[5]

#Read the first alleles from the genotype
allele01 = genotype[0]
allele02 = genotype[2]

# Analyzing allele01 from X_list
# check the index value of the first allele in X_list
# and its corresponding value_X based on index
if allele01 in X_list:
    allele01_index =  X_list.index(allele01)

    # now, find the value at that index position
    # at another column (value_X)
    allele01_value = value_X[allele01_index]

elif allele01 not in X_list:
    allele01_value = str((1/12).__round__(3))
    # This value (1/12) will be default if value for the matching set isn't found in the group (X or Y)

# Analyzing allele02 from X_list
if allele02 in X_list:
    allele02_index = X_list.index(allele02)
    allele02_value = value_X[allele02_index]

elif allele02 not in X_list:
    allele02_value = str((1/12).__round__(3))


## Repeat the above procedure for allele and frequency for group Y
    if allele01 in Y_list:
    allele01_index =  Y_list.index(allele01)

    # now, find the value at that index position
    # at another column (value_Y)
    allele01_value = value_Y[allele01_index]

elif allele01 not in Y_list:
    allele01_value = str((1/12).__round__(3))

# Analyzing allele02 from Y_list
if allele02 in Y_list:
    allele02_index = Y_list.index(allele02)
    allele02_value = value_Y[allele02_index]

elif allele02 not in Y_list:
    allele02_value = str((1/12).__round__(3))


# Generating the haplotype (i.e column 6 and 7)
# But, I am not showing the code to on how to generate 6 and 7

haplotype_set_A = haplotype_set_A + allele01.split()
haplotype_set_B = haplotype_set_B + allele02.split()
hapA_freq_X = hapA_freq_X + allele01_freq_My.split()
hapB_freq_X = hapB_freq_X + allele02_freq_My.split()
hapA_freq_Y = hapA_freq_Y + allele01_freq_Sp.split()
hapB_freq_Y = hapB_freq_Y + allele02_freq_Sp.split()

print(haplotype_set_A)

print(haplotype_set_B)

## and so on for frequency........

So, how to inject the break and continue function to generate separate haplotype and, or frequency when block value changes in the for loop? I tried to look through examples but it isn't helping. Also, i don't need solution on pandas since my find and matching of allele, allele index and then frequency based on this index is best done using if-else.

Thanks much in advance !

Using if inside of fold

I need to count the length of a vector of (bool, i32) where if the bool is true I increment count. I'm using fold to do this:

fn foo(& self) -> f64 {
    -&self.current_domain.iter()
        .fold(0, |count, &(exists, _)| if exists {count + 1}) as f64
}

The compiler complained saying:

.fold(0, |count, &(exists, _)| if exists {count + 1}) as f64
                               ^^^^^^^^^^^^^^^^^^^^^ expected (), found integral variable

So I added a ; and got this:

.fold(0, |count, &(exists, _)| if exists {count + 1;}) as f64
                               ^^^^^^^^^^^^^^^^^^^^^^ expected integral variable, found ()

How do you correctly use an if statement inside of fold?

My if else is not working

If-Else Write a program that gets three integers and prints the smallest one out. I did it but is not working good

#include <stdio.h>
 void main (void)
 {
double num1,num2,num3;


printf("This program will get three integers and prints the smallest one       \n");
printf("Enter Three integers please \n");
scanf("%lf",&num1);
scanf("%lf",&num2);
scanf("%lf",&num3);
printf("Your entered integers are %lf and %lf and %lf \n",num1,num2,num3);

if (num1 < num2 && num1< num3 )
printf("%lf",num1);
else if ( num2 < num1 && num2 < num3)
printf("%lf",num2);
else (num3 < num2 && num3 < num1);
printf("%lf",num3);
}

Java Testing if a variable equals a value in the array if not print -1

I need to see when a given variable value in an array is first occurred and once occurred change that variable to the number when it first occurs, and if it does not occur than change the value to -1. For example 32 appears first in the array so it should print 1 but 100 never appears in the array so it should print -1 but how do I make a second if statement in my loop so that the variable will be -1 but it test the original value to find it appears. Sorry if I did not explain it well enough.

here is the code for the loop and the first if statement

  public static int occurrence(int[] a) {
    Scanner scnr = new Scanner(System.in);
    int occurrence = scnr.nextInt();

    for (int i = 0; i < a.length; i++)
        if (a[i] == occurrence)
            occurrence = i + 1;

    return occurrence; 

Quit recursive function when a dynamic condition is met

Using the function from Generate all sequences of bits within hamming distance t:

void magic(char* str, int i, int changesLeft) {
        if (changesLeft == 0) {
                printf("%s\n", str);
                return;
        }
        if (i < 0) return;
        // flip current bit
        str[i] = str[i] == '0' ? '1' : '0';
        magic(str, i-1, changesLeft-1);
        // or don't flip it (flip it again to undo)
        str[i] = str[i] == '0' ? '1' : '0';
        magic(str, i-1, changesLeft);
}

I would like to quit the recursive function and return to the caller function when a certain condition occurs (if it does). So it's like my recursive function is hearing voices that might tell her to quit!

It only happens after str is printed, here:

if (changesLeft == 0) {
    printf("%s\n", str);
    if quit_now = voices();
    return;
}

How to do this (stop unfolding the recursion and return to the function caller)?


Attempt:

if (i < 0 || quit_now == 1) return;

just seems to block the execution and never end!

PS - I am interested even in old methodologies.

Wrapping a function within an if statement in MS Excel?

I have a function that removes part of a string after a comma, eg:

=LEFT(B3,FIND(",",B3)-1)

Eg: 123 West St, Sydney becomes 123 West St.

This works fine, but some of my cells don't have commas and so I get the #VALUE! error on these.

I've Googled and found 'IF(ISNUMBER)` and have made:

=IF(ISNUMBER(SEARCH(",",B3)),LEFT(B3,FIND(",",B3)-1))

but this just returns 'FALSE' on cells with no comma.

Is there a way to wrap this in an 'if' statement? Something like

if (B3 contains ','){=LEFT(B3,FIND(",",B3)-1)}

very basic programme using while loop and if statement compiles but does not work-i think its all correct?

The programme should repeatedly ask the user which and how many of a bird he/she has seen until they say end, it should store the most numerous bird seen then output which bird was seen the most.

When run, the program asks the questions, then when end is typed the output is always "You saw 0 ; It was the most common bird seen at one time in your garden." even when the while loop has run several times which means the second if statment is not being executed-but why?

import java.util.Scanner;

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

        questions();

    }// end main method

    public static void questions() {

        while (true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Which bird have you seen?");
            String answerBird = scanner.nextLine();

            int largest = 0;
            String popularBird = "";

            if (answerBird.equalsIgnoreCase("end")) {
                System.out.println("You saw " + largest + " " + popularBird);
                System.out.println("It was the most common bird seen at one time in your garden.");
                break;
            }//end if statement

        Scanner scanner1 = new Scanner(System.in);
        System.out.println("How many were in your graden at once?");            
        int answerNumber = scanner1.nextInt();

        if(largest < answerNumber) {
            largest = answerNumber;
            answerBird = popularBird;
        }



        }//end while loop

    return;
    }// end method questions

}// end class bird

Inaccessible returned Strings in Java

I keep getting the error that the Strings cannot be passed from method to method and I need to do that. The goal of the program is to return two Strings and an integer to the main to access another method that will randomly generate a name based off of the given factors. NameGenerator.java:12: error: cannot find symbol String rappername = rappername(firstname, lastname, color); symbol: variable firstname location: class NameGenerator 1 error

import java.util.*; public class NameGenerator{

  public static void main(String[] args) {
  Scanner console= new Scanner(System.in);
  firstname(console);
  lastname(console);
  color(console);
  String firtname = firstname(console);
  String lastname = lastname(console);     
  int color = color(console);
  String rappername = rappername(firstname, lastname, color);
  }

  public static String firstname(Scanner console) {
  System.out.println("Welcome to my Program!");
  System.out.println("I'm going to tell you your rapper name.");
  System.out.println("What is your first name? (Type stop to quit) ");
  String firstname;
   firstname = console.nextLine();
  if (firstname.equals("stop")) {
     System.exit(0);
  }
  else {
  return firstname;
    }
 }

 public static String lastname(Scanner console) {
  String lastname;
  System.out.println("What is your last name? ");
   lastname = console.nextLine();
  return lastname;
  }

  public static int color(Scanner console) {
  int color;
  System.out.println("Pick the number to your color of choice");
  System.out.println("Blue (1)");
  System.out.println("Red (2)");
  System.out.println("Purple (3)");
  color = console.nextInt();
  return color; 
  }

public static String rappername(String firstname, String lastname, int color)  `       {    
  System.out.println(firstname+lastname+color);
  }  
  }

if variable might not have been initialized [duplicate]

This question already has an answer here:

it's give me error on netbeans

could anyone help me. thanks.

double d;
double v;
double p;
String input;

input = JOptionPane.showInputDialog("Please enter the value : ");
v = Double.parseDouble(input);

if (v > 99){
    if(v < 200){
        d = v * 0.05;
        p = v - d;
    } else if (v < 300){
        d = v * 0.10;
        p = v - d;
    } else if (v < 400){
        d = v * 0.15;
        p = v - d;
    } else if (v < 500){
        d = v * 0.20;
        p = v - d;            
    } else if (v > 499){
        d = v * 0.25;
        p = v - d;            
    }

    JOptionPane.showMessageDialog(null , "you\'r discount is : " + d + "\n you have to pay : " + p );

} else{
    // zero 
    JOptionPane.showMessageDialog(null, "there is no discount. ");
}

Use of the if statement

I'm beginner in Java, and I'm learning the if statement without else, can please the community check my code to improve?

/* Code made by edu.

In this code we use only the if statement to practice. Here you need to enter your age to enter to the bar with hot girls, if your age is above to 18, you can enter. if it is below 18 you can't enter.

*/

import java.util.Scanner;

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

    Scanner input = new Scanner(System.in);

    int age;

    // Ask the age
    System.out.println("Please write your age to enter to the bar:");
    age = input.nextInt();

    // Equal to
    if(age == 18){
        System.out.println("Your age " + age + " it's equal to 18, you can enter");
    }

    // Not equal to
    if(age != 18){
        System.out.println("Your age " + age + " it's not equal to 18");
    }

    // Greater than
    if(age > 18){
        System.out.println("Your age " + age +  " " + "is greater than 18, you can enter");
    }

    // Less than
    if(age < 18){
        System.out.println("Your age " + age + " " + "is less than 18, you can't enter");
    }

    // Greater than or equal to
    if(age >= 18){
        System.out.println("Your age " + age + " is greater than or equal to 18, you can enter");
    }
    // Less than or equal to
    if(age <= 18){
        System.out.println("Your age " + age + " is less than or equal to 18, you can't enter");
    }
}

}

why does the order of my if statement affect what gets printed? python [duplicate]

This question already has an answer here:

I am new to programming and i have come across this when i have been trying to make a simple game. You have to guess a letter and if it is in the word it should response with that letter is in the word and if it isn't then it should say it isn't. Instead is just prints the first if statement result no matter what the input is. i switched the if and elif order around and it still only printed the first if statement result. How do i fix this? Here is my code:

    response2 = input("What is your first letter or guess at the word?")
    b = str(response2)
    if b != "s" or "n" or "a" or "k" or "e":
        print("That letter is not present. You have 6 lives remaining.")
        lives -= 1
    elif b == "s" or "n" or "a" or "k" or "e":
        print("That letter is in the word!")
    elif b == "snake":
        print("You won! That was quick!") 

No matter what the input is here is prints "That letter is not present." swapping the order meant that what ever the input it said "That letter is present" even when it didn't fix the if statement.

(Java) Read list of int values, (sentinel -1), print only occurrences of 2 followed by 3

I need to write a program that reads the input from the user of a list of integers and prints only occurrences of 2 followed by 3, using while loop and if statements.

Thank you!

Convert values to a number using excel vba if statement

I have a column in excel that has two values "Disqualified" and "Open".

I want to use an If Statement using VBA to change the disqualified values to 0 and the Open values to 1.

Here is the excel formula that shows what I want to do

=IF(H:H="Disqualified","0","1")

I think I need a for loop to loop through all the values in column H but can't seem to get this to work. Thanks

IF OR Function in jQuery on a PHP site

Can anyone tell me what's wrong and how to fix this bit of code...

I am trying to bring up a message and not go to the next page, if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).

This is the bit of code I am having issues with:

 if (country == '0' || country == "Send From...") {
                error = 1;
                jQuery('.msg').text("Please Select A Country.");
            }

I think I have an issue with the OR function as it works without the || country == "Send From...". Thanks

<script>
    jQuery(document).ready(function(){
        jQuery('.submit').click(function() {

            var error = 0;
            var country = jQuery('#send_country').val();
            var countrys = jQuery('#delv_country').val();
            var idsa = jQuery('.size').val();

            if (country == '0' || country == "Send From...") {
                error = 1;
                jQuery('.msg').text("Select A Country.");
            }
            if (countrys == '0') {
                error = 1;
                jQuery('.msg').text("Select A Country.");
            }

            if (error) {
                return false;
            } else {
                return true;
            }

        });

    });
    </script>