lundi 30 avril 2018

How to change the color of two divs for a matching game?

I am working on an assignment where you create a Memory game with a 4x4 grid of divs to serve as cards. The end goal is a user selects two cards. If they are a match then remove them from the game (Change the colors to white so the card appears gone) and if they are not a match, turn them back into black. I am using console.logs as placeholders just to show that the functions run properly, but I am stuck on how to change the colors. Additionally, the original colors of the cards have to remain showing for two seconds before changing to white or black. I know that this requires the use of setInterval, but my main concern is changing the colors of the cards and having them change to the proper colors depending on if it is a match. This is what I have so far:

var elements = document.getElementsByClassName('grid-cell');
var i;
var picks = [];

//Event Listeners to respond to a click on the squares.
for (i = 0; i < elements.length; ++i) {
 elements[i].addEventListener('click', showColor);
}


function showColor(){
        this.style.backgroundColor = this.getAttribute('data-color');
        picks.push(this.getAttribute('data-color'));
        console.log(picks);
        if(picks.length === 2){
                checkMatch();
                picks = [];
        }
}

function checkMatch(){
        if(picks[0] === picks[1]){
                console.log("Match");
        }else{
                console.log("Not a match");
        }
}
.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 106.25px);
  grid-gap: 15px;
}

.grid-cell {
  height: 106.25px;
  border-radius: 3px;
  background: #000000;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Memory</title>
        <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>

        <div class="game-container">
  <div class="grid-container">
    <div class="grid-cell" data-color="red">
      <span></span>
    </div>
    <div class="grid-cell" data-color="blue">
      <span></span>
    </div>
    <div class="grid-cell" data-color="pink">
      <span></span>
    </div>
    <div class="grid-cell" data-color="orange">
      <span></span>
    </div>
    <div class="grid-cell" data-color="purple">
      <span></span>
    </div>
    <div class="grid-cell" data-color="green">
      <span></span>
    </div>
    <div class="grid-cell" data-color="yellow">
      <span></span>
    </div>
    <div class="grid-cell" data-color="grey">
      <span></span>
    </div>
    <div class="grid-cell" data-color="orange">
      <span></span>
    </div>
    <div class="grid-cell" data-color="red">
      <span></span>
    </div>
    <div class="grid-cell" data-color="green">
      <span></span>
    </div>
    <div class="grid-cell" data-color="pink">
      <span></span>
    </div>
    <div class="grid-cell" data-color="blue">
      <span></span>
    </div>
    <div class="grid-cell" data-color="grey">
      <span></span>
    </div>
    <div class="grid-cell" data-color="purple">
      <span></span>
    </div>
    <div class="grid-cell" data-color="yellow">
      <span></span>
    </div>
  </div>
</div>
        
        
        
        <script src="js/app.js"></script>
</body>
</html>

C++ - Display only last result in fum of series in for loop

I'm writing a code to sum a series of numbers but it keep showing all the results. I only need the last result that is the sum of numbers

My Code:

//Sum of numbrs which are divisible by either 3 or 5
cout << "\nSum of numbers: ";

for ( numbers = 1; numbers <= limit; numbers++ )
{
    if ( ( numbers%3 == 0 ) || ( numbers%5 == 0 ) )
    {
        if (  !( numbers%3 == 0 && numbers%5 == 0 )  )
        {
            sum += numbers; 
            cout << sum << " ";
        }
    }
}

Output:

Sum of numbers: 3 8 14 23 33 45 63 83 104

I only need the last value as 104 in the above example.

How to search for a particular word using regular expression in python?

I searched a lot but I was unable to find a solution to my problem which is I want to search for a particular word from the input (text). Though I only find the first letter. my code is as:

import re

regex = r"([a-zA-Z]+)"
datm = str(input('Enter  a passage to search for a word :'))
if re.search(regex, datm):

    match = re.search(regex, datm)

    print("Full match: %s" % (match.group(0)))

else:

    print("The regex pattern does not match. :(")

Thanks for the answer, you don't have to answer if you are going to give minus.

Ansible Pull mulptiple repo

I want to pull multiple repositories via ansible playbook but with if condition matches,

tasks: - name: pull from git abc/123 git: repo: git@gitlab.com:xyz.git dest: var/www/abc/123 update: yes version: $sprint_name

tasks: - name: pull from git abc/234 git: repo: git@gitlab.com:xyz.git dest: /var/www/234 update: yes version: $sprint_name

Now here i want to pass "123" or "234" as variable and if user want to pull only "123" or only "234" user should be able to do it

setting multiple if statements correctly

I have difficulty to set proper nested if stament in user defined function.

My sample data is like this

test = data.frame(x=rev(0:10),y=10:20)

if_state <- function(x,y){
  if(x==min(x)&&y==max(y)){
    "good"
    }
  else
  if(max(x)/2==y[which(y==15)]/3){  #to find when x=5 and y=5 condition if it is true set class to "y==5"
    "y==5"
  }
      NA

}

   > test
    x  y
1  10 10
2   9 11
3   8 12
4   7 13
5   6 14
6   5 15
7   4 16
8   3 17
9   2 18
10  1 19
11  0 20

library(dplyr)
test%>%
  mutate(class=if_state(x,y))


    x  y class
1  10 10    NA
2   9 11    NA
3   8 12    NA
4   7 13    NA
5   6 14    NA
6   5 15    NA
7   4 16    NA
8   3 17    NA
9   2 18    NA
10  1 19    NA
11  0 20    NA

I don't know why if statement is not working correctly ?

Knock knock conversation between server and client , it terminates the connection after I submit the UID

This is part of my code, the problem is while, and if loops. It is like a knock-knock conversation between a client and a server. the server receives the UID from the user to allow him to send knock-knock joke. if the client submits incorrect UID, there should be a loop to iterates until UID in the same form (G#########)is received.

  add( enterField, BorderLayout.NORTH );

  displayArea = new JTextArea(); // create displayArea
  add( new JScrollPane( displayArea ), BorderLayout.CENTER );

  setSize( 300, 150 ); // set size of window
  setVisible( true ); // show window
  } // end Server constructor

  // set up and run server
  public void runServer()
  {
  try // set up server to receive connections; process connections
  {
      server = new ServerSocket( 12345, 100 ); // create ServerSocket //change the addresses
  while ( true )
  {
  try
  {
  waitForConnection(); // wait for a connection
  getStreams(); // get input & output streams
  processConnection(); // process connection
  } // end try
  catch ( EOFException eofException )
  {
  displayMessage( "\nServer terminated connection" );
  } // end catch
  finally
  {
  closeConnection(); // close connection
  ++counter;
  } // end finally
  } // end while
  } // end try
  catch ( IOException ioException )
  {
  ioException.printStackTrace();
  } // end catch
  } // end method runServer

  // wait for connection to arrive, then display connection info
  private void waitForConnection() throws IOException
  {
 displayMessage( "Waiting for connection\n" );
  connection = server.accept(); // allow server to accept connection
  displayMessage( "Welcome to the Knock-Knock Server. Please submit your ID ");
 // &&&&&
  } // end method waitForConnection

           // get streams to send and receive data
           private void getStreams() throws IOException
           {
           // set up output stream for objects
               output = new ObjectOutputStream( connection.getOutputStream() );
               output.flush(); // flush output buffer to send header information
           // set up input stream for objects
               input = new ObjectInputStream( connection.getInputStream() );
           displayMessage( "\nGot I/O streams\n" );
           }

           // process connection with client
           private void processConnection() throws IOException
           {
               BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));  //receives from the client
                PrintWriter out = new PrintWriter(connection.getOutputStream(), true); //sends to the client 

           String message = "Welcome to the Knock-Knock Server. Please submit your UIDs";
           sendData( message ); // send connection successful message
           String  clientMessage = null;
           String  ServerMessage1 = null;
           // enable enterField so server user can send messages
           setTextFieldEditable( true );

           do // process messages sent from client
           {
           try // read message and display it
           {
             //  clientMessage = ( String ) input.readObject(); // read new message
             //displayMessage( "\n" + clientMessage ); // display message

                String GID= null;


               ServerMessage1 = "Please submit your G-number"; 
            sendData( ServerMessage1 );
            GID = input.readLine();

            String regex= "^[G-g]{1}[0-9]{8}$";

            while (!GID.matches(regex))
            {
            if (GID.equalsIgnoreCase("shutdown"))
            {closeConnection();
            }
        if (GID.isEmpty())
            { ServerMessage1 = "The field should not be Empty.";
            sendData( ServerMessage1 );}
        else 
        {ServerMessage1 = "Incorrect identifier; please submit again";
        sendData( ServerMessage1 );
         GID = (String) input.readLine();

        }

        }//end while 
        String ServerReply1 =  null;
        String Jokeinput ;
        Jokeinput = (String) input.readObject();
        while (!Jokeinput.equalsIgnoreCase("shutdown"))
        {
            if ( Jokeinput.equalsIgnoreCase("Knock Knock") || Jokeinput.equalsIgnoreCase("Knock, Knock") || Jokeinput.equalsIgnoreCase("Knock-Knock" ))
            {
                ServerReply1 = "Who's there?";
                        sendData( ServerReply1 );
                        Jokeinput = (String) input.readObject();
                        if (!Jokeinput.isEmpty())
                        {
                            ServerReply1= Jokeinput.concat("who?");
                                    sendData( ServerReply1 );
                                    Jokeinput = (String) input.readObject();
                                    if (!Jokeinput.isEmpty())
                                    { ServerReply1= "Nice Joke!";}      
                        }}
                        else
                        {
                            ServerReply1="unKnown response";
                            sendData( ServerReply1 );
                        }


            }}



           catch ( ClassNotFoundException classNotFoundException )
           {
           displayMessage( "\nUnknown object type received" );
           } // end catch

           } while ( !message.equals( "CLIENT>>> shutdown" ) );
           } // end method processConnection

           // close streams and socket



           private void closeConnection()
           {
           displayMessage( "\nTerminating connection\n" );
           setTextFieldEditable( false ); // disable enterField

           try
           {
               output.close(); // close output stream
               input.close(); // close input stream
               connection.close(); // close socket

           } // end try

           catch ( IOException ioException )
            {
            ioException.printStackTrace();
            } // end catch
            } // end method closeConnection




           private void sendData( String message )
            {
            try // send object to client
            {
                output.writeObject( "SERVER>>> " + message );
                output.flush(); // flush output to client

            displayMessage( "\nSERVER>>> " + message );
            } // end try
            catch ( IOException ioException )
            {
            displayArea.append( "\nError writing object" );
            } // end catch
            } // end method sendData

            // manipulates displayArea in the event-dispatch thread


           private void displayMessage( final String messageToDisplay )
            {
            SwingUtilities.invokeLater(
            new Runnable()
            {

Google Scripts to Telegram - if statement issues when comparing strings

function sendText(id,text) {
  if(text == "hiii"){
    var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + "sup?";
  } else{ 
    var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + "yo yo yo";
    var response = UrlFetchApp.fetch(url);
    Logger.log(response.getContentText());
  }
}

My issue is that in Google Scripts (back end to Google Sheets), I have this function that reads in a message from telegram and, if the message reads "hiii" it should respond "sup?". Currently my code does not do this and instead executes only the else statement.

If then else ambiguity in CUP

I am constructing a grammar in CUP, and I have ran into a roadblock on defining IF-THEN-ELSE statements.

My code looked like this:

start with statements;

/* Top level statements */
statements ::= statement | statement SEPARATOR statements ;
statement  ::= then_statement | block | while_statement | declaration | assignment ;
block        ::= START_BLOCK statements END_BLOCK ;

/* Control statements */
if_statement    ::= IF    expression THEN statement
                  | IF    expression THEN statement ELSE statement ;
while_statement ::= WHILE expression THEN statement ;

But the CUP tool complained about the ambiguity in the definition of the if_statement.

I found this article describing how to eliminate the ambiguity without introducing endif tokens.

So I tried adapting their solution:

start with statements;

statements ::= statement | statement SEPARATOR statements ;

statement  ::= IF expression THEN statement
             | IF expression THEN then_statement ELSE statement 
             | non_if_statement ;

then_statement ::= IF expression THEN then_statement ELSE then_statement
                 | non_if_statement ; 

// The statement vs then_statement is for disambiguation purposes
// Solution taken from http://goldparser.org/doc/grammars/example-if-then-else.htm

non_if_statement ::= START_BLOCK statements END_BLOCK  // code block
                   | WHILE expression statement        // while statement
                   | declaration | assignment ;

Sadly CUP is complaining as follows:

Warning : *** Reduce/Reduce conflict found in state #57
  between statement ::= non_if_statement (*) 
  and     then_statement ::= non_if_statement (*) 
  under symbols: {ELSE}
  Resolved in favor of the first production. 

Why is this not working? How do I fix it?

Print a new column with conditional contraints using if statement in MySql

I have a table 'actor' whose fields are 'pk','fname',lname. I want to print a column(lets call this name) where by default fname is printed but if fname is null then lname is printed.

The query that I used is:

select if(fname = null,lname,fname) as name from actor;

This however does not achieve the given task. It prints the fname even if the value is null.

if statement to color Datagridview rows binded to sql query

Alright, maybe i'm missing something simple but I can not get an if statement inside a for loop to color a datagridview row based on a cell's value. Maybe you guys can see something I can't. Here is my sql code

SELECT Part,
CASE WHEN missing = 1 or secondmissing = 1 then '1'
WHEN missing IS NULL AND secondMissing IS NULL then '0'
end as 'missing'
FROM TableA

This query returns a list of part numbers and if they have been marked as missing or not and appears to run fine.In my win forms application I have a For loop to check the datagridview loaded with the sql query above to color any rows yellow that have the missing marked as 1. However nothing I seem to try work for catching line items marked as 1. Here is my VB code.

For x as integer = 0 to DataGridView1.rows.count - 1
  With Datagridview1.rows(x)
    if .cells(1).value.tostring = "1" then *
       .DefaultCellStyle.Backcolor = Color.Yellow
   else
       .DefaultCellStyle.BackColor = Color.White
   End If
 End With
Next

Notice in the for loop I marked a line with an *. Here are all the things I have tried here.

if .cells("missing").value = True Then
if .cells(1).value.tostring = "1" Then
if CInt(.cells(1).value) = 1 Then
if CInt(.cells(1).value.tostring) = 1 Then

None of the above options seem to work. If I try and use the column name "missing" instead of the column integer of 1 it completley misses the code. Any help would be great.

EDIT: I guess I should note the sql column fields. Part is NvarChar(25) and both missing and secondmissing are bits.

2 similar foreach statements, 1 works other doesnt

i have a txt file that contains user info that is read to a list, i then have a foreach statements the first simply prints containtes of a list. i want the second foreach to check the contents of the list to a user input then use, and then only use the info from the list that matches the user input. my second foreach statement only seems to check the first variable within the list. how do i go about fixing this?

var fileLines = File.ReadAllLines("stylist.txt").Where(line => !string.IsNullOrEmpty(line)).ToList();

var stylists = new List<Stylist>();


for (int i = 0; i + 4 < fileLines.Count; i += 5)
{
    stylists.Add(new Stylist
    {
        FirstName = fileLines[i],
        LastName = fileLines[i + 1],
        Email = fileLines[i + 2],
        Phone = fileLines[i + 3],
        Rate = fileLines[i + 4]
     });
}


foreach (var i in stylists) // prints the stylists first and last names
{
    Console.WriteLine(i.FirstName + " " + i.LastName);
}

string stylistSelected = Console.ReadLine(); // user input


 //for (int z = 0; z < stylists.Count; z++)
 foreach (var z in stylists)
 {

     if (z.FirstName == stylistSelected)

i am also using a custom class, the code for this is below

public class Stylist // creates the stylist class and variables needed for each stylist
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Rate { get; set; }
}

my txt file looks like so

john
smith
js@123.456
123456789
123

jane
doe
jd@123.456
987654321
1456

bryan
smith
bs@123.987
147258369
321

I want to print a message only once if the input field is blank and user hits enter with blank input. where am I going wrong

form.addEventListener('submit', (e) => { //create new invitee name
let text = input.value; //collect text value from input field
let counter = 0;
if (text != "") {
    createLI(text); //executes function to add new invitee. 
} else {. /*if text field is blank error message to be printed only once regardless on multiple entries with blank input*/

    const errorText = document.getElementById('enterName');
    const label = document.createElement('label');
    label.textContent = "please enter your full name";
    label.setAttribute("style", "color: red");
    if (counter == 0) {
        errorText.appendChild(label);
        counter += 1;
    }
}
});

If statement as vector/subsetting in R

I have two datasets, example of those given below.

DF1
Level
 10
 20
 10
 34

DF2
LevelLow     LevelHigh    Speed
   0            10          24
   11           20          29
   21           30          31
   31           40          36

I want to be able to add a column in DF1 which holds the speed of the Level if it's between the LevelLow and LevelHigh boundary. An example of the final dataset (DF1) is given below.

DF1
Level    Speed
 10        24
 20        29
 10        24
 34        36

I think I know how to do this via an if statement but how would I go about doing this in another way? I believe that vectorisation speeds up the process? If any of you know of any other way to do this then please let me know :)

Java check if first number of int is 0

So the question is very simple. How to check in java if first number of an int is 0;

Say I have: int y = 0123; int n = 123;

Now I need an if statement that would return true for y and false for n.

Working of Nested IF-Else Without the Braces

Can someone please explain me the working of Nested If-Else Statements written WITHOUT the Curly Braces.
I want to understand why Below Programme isn't giving me any output.
I've checked for all the 4 possibilities. (Outer, Inner)::(True, True),(True, False),(False, True),(False, False).
I'm editing with CodeBlocks,using gcc compiler on Windows.

int main() 
{
  int n=0,m=0;
  if ( n = 0 )
       if ( m = 0 )
           printf("True");
       else printf("False");
  return 0;
}

Thank You.

if statement and --variable

I am working toward my C++ exam, and I am doing some past papers. Then I stumbeled over this code understanding task. And I am wondering, why does value change to 4 in this if statement?

int found = 0, value = 5;
if (!found || --value == 0) {
    cout << "danger";
}
cout << "value =" << value << endl;

Javascript: detect if browser is IE, then hide HTML

I want to create a JaveScript to hide the html if the visitor is using browser IE. I did some research in Stackover and the below is what I come up. It doesn't work at the end. Can anyone tell me what I did wrong? Thanks!'

HTML:

<div id="content">
Hello
</div>

JS:

var isIE = /*@cc_on!@*/false || !!document.documentMode;


if (isIE === 'true') {
  function display() {
    document.getElementById('content').style.display="none";
}
}

excel if function with date

i have two sheets(sheet1 & sheet2),Likewise Sheet1 A B C H C-1 Hall-1 ok 30-04-2018 c-2 Hall-2 ok c-3 Hall-3 ok

Sheet2 A B C 29-04-2018 Hall-1 ok 29-04-2018 Hall-2 ok 29-04-2018 Hall-3 ok 30-04-2018 Hall-1 ok 30-04-2018 Hall-2 ok 30-04-2018 Hall-3 ok 01-05-2018 Hall-1 ok 01-05-2018 Hall-2 ok 01-05-2018 Hall-3 ok

Sheet1 H1 cell value will change on daily basis, based on that value i want formula result.i tried it, but result not came, so please find the erroed formula and give your suggestion.

=IF($H$1=Sheet2!$B$4:$B$500,(VLOOKUP(Sheet1!$B7,Sheet2!$B$2:$C$500,2,FALSE)))

Regards Shcsam

How to stop a JavaScript code from reading all IFs if it matches one

whenever I have more than one if and it matches all of them it runs through all of the code that would run for other ones.

Structure of a conditional statement in Javascript

is it possible to have a conditional statement in Javascript that looks like the following?

if (condition === value || value) {}

Thanks in advance!

Why does an IF inside a FOR loop not work on a DataFrame? Python

I am looping over a DataFrame, using an if statement inside a for loop as follows. However, of all the elements i that enter the for loop, only the first one reaches the if statement. My code works correctly when I would pass lists to it, but not when I pass DataFrames. How to solves this? I have tried the solutions mentioned in Pythonic way to combine FOR loop and IF statement. But they do not work for my DataFrame.

DataFrame:

   'Sentence'                                   'First2'     
0  If this is a string what does it say?        what does    
1  And this a string, should it say more?       should it    
2  This is yet another string.          

My code looks as follows:

import pandas as pd    
a = df1['Sentence']
b = df2['First2'] 

def func(r):
    for i in b:
        if i in r:
            q = r[r.index(i):] #The code seems to loop over all r's but not over all i's. 
            return q
        else:
            return ''

df1['Clauses'] = a.apply(func)

This is the result:

what does it say?

This is correct but incomplete. The code seems to loop over all r's but not over all i's. How to get the desired result, as below?

what does it say?
should it say more?

IF Formula to return value only if A1=A2, B1=B2

I am trying to return the values of a formula only if, for example, A1=A2 and B1=B2.

The formula I currently have is:

=IF(OR('Tournament Sheet'!G95="",'Tournament Sheet'!I95=""),
    "", IF(AND('Tournament Sheet'!G95='Player Sheet'!G95,
    'Tournament Sheet'!I95='Player Sheet'!I95),5,
    IF(OR('Player Sheet'!G95-'Player Sheet'!I95='Tournament Sheet'!G95-'Tournament Sheet'!I95,
    AND('Player Sheet'!G95>'Player Sheet'!I95,
    'Tournament Sheet'!G95>'Tournament Sheet'!I95),
    AND('Player Sheet'!I95>'Player Sheet'!G95,
    'Tournament Sheet'!I95>'Tournament Sheet'!G95)),2,0)))

I have tried to add if(and(a1=a2,b1=b2) in different locations within the formula and it is just returning different values. The current formula works fine but I need this extra code to go in.

Any ideas? I'm fairly new to excel so your patience is appreciated.

dimanche 29 avril 2018

How to save a file on macos desktop using kml in python?

I have just read some of posts on how to save a kml file on macos desktop in Python but i couldn't find the answer.I try to locate the file path but it doesn't work. my code is:

import pathlib
import simplekml

longitude = input("Enter longitude: ")
latitude = input("Enter longitude: ")

kml = simplekml.Kml()
kml.newpoint(name="Sample", coords=[(longitude, latitude)])
kml.save("~/Desktop/bura/Points.kml")

The problem starts with kml.save("~/Desktop/bura/Points.kml") it doesn't find the path and doesn't save the file.

Why does my "if" statement not exit out when I use the "break" function?

This code is like a ticket box counter, where the user selects if they want a ticket based on the price, or the seat. I haven't gotten to the seat selection part of the code, but when I was making my price selection one, after it's done, it prints out the layout too many times (instead of one, how it should be). After the "if" is triggered the first time, it should print out the layout, and then break. Though, it doesn't do this, and instead keeps on printing out the layout and going through the if function many times. Please help me fix this. Thank you!

line1 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10]
line2 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10]
line3 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10]
line4 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10]
line5 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10]
line6 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10]
line7 = [20 , 20 , 30 , 30 , 40 , 40 , 30 , 30 , 20 , 20]
line8 = [20 , 30 , 30 , 40 , 50 , 50 , 40 , 30 , 30 , 20]
line9 = [30 , 40 , 50 , 50 , 50 , 50 , 50 , 50 , 40 , 30]
seats = [line1, line2 , line3 , line4 , line5 , line6 , line7 , line8 , line9]

for line in seats:
    print(line) 

seatFound = False

SorP = input("Would you like to select a seat based on the price (P) or seat (S)")

if SorP == "P":
    price = int(input("What price would you like?"))
    for line in seats:
        for seat in line:
        if seat == price:
            print("There is a seat available for that price")
            seatFound = True
            position = line.index(seat)
            line.remove(seat)
            line.insert(position , 0)
            for line in seats:
                print(line) 
            break
if seatFound != True:
    print("There is not a seat available for this price. Try again")

Rewriting multiple if statements

I am looking for best practice to write multiple if statements and making code more reusable. these are my if statements that i wuld like to change

    public DataSet getOrganizationDataSet(string organizationType, string 
    name, string state, string city, string county, string zip)
    {
        string search = "";

        if (organizationType != "")
        {
            search = search + "&type=" + organizationType;
        }
        if (name != "")
        {
            search += "&name=" + name;
        }
        if (city != "")
        {
            search = search + "&town=" + city;
        }
        if (zip != "")
        {
            search = search + "&zip=" + zip;
        }
        if (county != "")
        {
            search = search + "&county=" + county;
        }
        if (state != "")
        {
            search = search + "&state=" + state;
        }
}

i am thinking about writing code like this to make it more readable:

 public DataSet getOrgDataSet(string type, string name, string state, 
 string city, string county, string zip)
    {
        string search = "";

        if ((type ?? state ?? name ?? city ?? county ?? zip) != "") {

            search += "&type=" + type;
            search += "&name=" + name;
            search += "&town=" + city;
            search += "&county=" + county;
            search += "&zip=" + zip;
            search +=  "&state=" + state;

     }

I would like to know your opinion on this and best practices. Thanks in advance, and sorry for novice question, i am still learning c#

I having issues with this program. Anyone seeing what I am doing wrong? Fairly new to this

  `enter code here`main ()

enter code here{ enter code hereint adultTickets = 0, seniorTickets = 0, childTickets = 0, enter code hereinfantTickets = 0, baggage = 0, age = 0, passengerTotal = 0; enter code heredouble totalBaggagefee = 0.0, baggageFee1 = 20.00, baggageFee2 enter code here= 35.00, adultFee = 147.30, seniorFee = 137.75, childFee = enter code here110.25, infantFee = 0.0, totalTicket = 0.0, enter code heretotalwithCheckedbaggage = 0.0; enter code herechar reply; enter code herestring input; enter code herecin >> input; enter code herestring Yes = "YES"; enter code herestring No = "NO"; enter code herestring quit = "QUIT";

enter code herecout << "Enter your age. "; enter code herecin >> age; enter code hereif (age > 18); enter code here{ enter code herecout << "You are old enough to buy a ticket." << endl; enter code herecout << "Would you like to purchase a ticket now? "; enter code herecin >> reply;

    `enter code here`if (input == Yes);
    `enter code here`{
        `enter code here`cout << "How many Adult Tickets? "; 
        `enter code here`cin >> adultTickets;
        `enter code here`cout << "How many Senior Tickets? "; 
        `enter code here`cin >> seniorTickets;
        `enter code here`cout << "How many Child Tickets? "; 
        `enter code here`cin >> childTickets;
        `enter code here`cout << "How many Infant Tickets? "; 
       `enter code here` cin >> infantTickets;
       `enter code here` cout << "Number of checked baggage? "; 
        `enter code here`cin >> baggage;
        `enter code here`cout << endl;

            `enter code here`if (baggage <= passengerTotal);
               `enter code here` totalBaggagefee = 

enter code herepassengerTotalbaggageFee1; enter code heretotalTicket = (adultTicketsadultFee)+enter code here(seniorTicketsseniorFee)+(childTicketschildFee)+(infantTickets*infantFee); enter code heretotalwithCheckedbaggage = totalTicket+totalBaggagefee; enter code here{
enter code herecout << "Your total including check baggage is " << totalwithCheckedbaggage << "" << endl; enter code here }
enter code hereelse (baggage >= passengerTotal); enter code heretotalBaggagefee = passengerTotal * baggageFee1 + 1 * baggageFee2; enter code here totalTicket = (adultTicketsadultFee)+(seniorTicketsseniorFee)+(childTicketschildFee)+(infantTicketsinfantFee); enter code heretotalwithCheckedbaggage = totalTicket+totalBaggagefee; enter code here{
enter code herecout << "Your total including check baggage is " << totalwithCheckedbaggage << "" << endl; enter code here} enter code hereelse (input == No); enter code here{ enter code here cout << "You are a minor, have an adult purchase your ticket. "; enter code herecout << "Thank you." << endl; enter code here}
enter code herecout << "Type quit to end. "; enter code herecin >> reply; enter code herecout << endl; enter code hereexit(1); enter code here}
enter code hereelse if (age<18); enter code here{ enter code here cout << "You are too young, have an adult buy your ticket. " << endl; enter code here}

    `enter code here`return 0;

    `enter code here`}}

Syntax for ifelse() Function in R Please [duplicate]

I have a dataset called old_images

One of the columns in this dataset is called difference, which can take values between 1 and 1115.

I also have another column called Quarter, which I want to have values of 1, 2, 3, or 4 depending on what Quarter the difference value of that row is.

So the rules would be as follows:

If old_images$difference is between 1 and 279, then old_images$Quarter = 1

ELSE

If old_images$difference is between 280 and 558, then old_images$Quarter = 2

ELSE

If old_images$difference is between 559 and 837, then old_images$Quarter = 3

ELSE

If old_images$difference is between 838 and 1115, then old_images$Quarter = 4

Any help would be hugely appreciated, thank you very much!

How do I return an error message when the user inputs the wrong info? in Ruby

I'm very much a beginner, learning Ruby, and I'm stuck on how to insert an error message in the loop below when the user inputs the wrong info.

So far, the method works by displaying a numbered list and asking the user to input either a number or name from the list. The block loops until the user enters "exit," after which the program ends. I want to add a line or two that puts an error message like, "Sorry, I don't seem to understand your request" if the user inputs something that is not on the list (name/number) and is not the word "exit."

It seems like it should be simple to add in an error message, but I can't seem to figure it out. Any advice?

My current code below! Thanks in advance!

def start
  display_books
  input = nil
  while input != "exit"
    puts ""
    puts "What book would you more information on, by name or number?"
    puts ""
    puts "Enter list to see the books again."
    puts "Enter exit to end the program."
    puts ""
    input = gets.strip
    if input == "list"
      display_books
    elsif input.to_i == 0
      if book = Book.find_by_name(input)
        book_info(book)
      end
    elsif input.to_i > 0
      if book = Book.find(input.to_i)
        book_info(book)
      end
    end
  end
  puts "Goodbye!!!"
end

Getting the result of an if else statement out of scope in Javascript

In this code I currently have the value of the addToOutput variable trapped inside an if else statement in a way that I am unable to get that value of the variable outside to the statement. I wish to get this value out so that when the user enters a number (for example 930) the function will output 900+30+0. To compile the results I have the variable "output" but if its unable to get the value from addToOutput I will not be able to get the desired result how can I make it so the value of addToOutput will be in scope?

function expandedForm(num) {

  let stringOfNumber = num.toString();
    let numberArray = Array.from(stringOfNumber);
    let zero = "0";
    let output;
    let addToOutput;
    for (let i=0; i<numberArray.length; i){
       let firstNumber = numberArray.shift();
       let arraySize = numberArray.length;

       ifElse(arraySize, firstNumber,zero)

       output = output + addToOutput;
    }
}

function ifElse (arraySize, firstNumber, zero, addToOutput){
    if(arraySize > 0){
      let numberOfZeros = zero.repeat(arraySize);
      addToOutput=firstNumber+ numberOfZeros + " + ";

      return(addToOutput);
    }
    else{
      addToOutput = firstNumber;
      return(addToOutput);
    }
 }
expandedForm(930);

Use of if-then-else and facts in CLIPS

I want to order 4 letters, [a,b,c,d]. I'll ask some question to the user about some of the letters, and depending on his answers, I build the final order.

My problem is, if I had 2 rules that looked like this:

(defrule rule_1
    =>
(assert (1-a))
)

and

(defrule rule_2
    =>
(assert (2-a))
)

and I want to build an "if" statement where if "a" has to go first then the solution is [1-a, 2-b, 3-c, 4-d]; but if "a" is second, then the solution is [1-b, 2-a, 3-c, 4-d]. My rule is the following:

(defrule rule_3
    =>
    (if (1-a) 
    then (printout t "[1-a, 2-b, 3-c, 4-d]" crlf)
    else (printout t "[1-b, 2-a, 3-c, 4-d]" crlf)
))

The error I get is "Syntax Error", however I've searched through several manuals and I'm 100% sure the syntax follows like that, the difference with my code is that they use "if" on variables, and I want to use "if" as, If I have this fact -> do this. Is that possible?

Else if conditional executes although conditions are not true

I'm trying to track a reference in PLECS (power electronics simulation software) with this circuit. C-Script is where I have the code below which basically tells the IGBT devices to open (0) and close (1). However, I can't understand why I get "0" as output when it is clear that the voltage across the capacitor (VCS) is not even close to zero volts, as shows this figure.

int track(double ref, double isb, double vcs) {
    int out;

    if(ref > isb){
        out = 1;
    }
    else if(ref < isb && vcs == 0.0){
            out = 0;
        }

    return out;
}

In C-Script block, signal values may only be accessed by using macros, not by pointer arithmetic. For example, I declared Inputs and Output as follows:

#define REF Input(0) // Reference Current
#define ISB Input(1) // Snubber Output Current
#define VCS Input(2) // Capacitor Voltage
#define IGBT Output(0) // IGBT Firing

MySQL first condition match priority

I have this data

+----+--------+---------------------------------+
| id | fromid |            message              |
+----+--------+---------------------------------+
|  1 |  1213  | this is just an example         |
+----+--------+---------------------------------+
|  2 |  1992  | other random message            |
+----+--------+---------------------------------+
|  3 |  1364  | example number three            |
+----+--------+---------------------------------+

I need to search data where fromid='1992' or message LIKE '%example%'

if there is any result where fromid matches 1992 value, return this result, and ignore second condition

but if there is no result from first condition (fromid='1992'), return the result from second condition

can I do that on single query?

if file doesn't exits create and write in C

I want to create a file if it doesn't exist and write on it if it's already exists.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 30

int main() {
    FILE * shelfFile;
    //if file doesn't exist
    char start[MAX] = "NULL";
    if (!(shelfFile = fopen("shelf.txt", "r"))) {
        shelfFile = fopen("shelf.txt", "w");
        printf("In if block\n");
        fwrite(start, sizeof(char), MAX, shelfFile);
        fwrite("\n", sizeof(char), 1, shelfFile);
    }   
    fclose(shelfFile);

    system("PAUSE");
    return 0;
}

when I run this code, the file has not been created and printf doesn't work too. Shortly it doesn't enter in if code block. What is wrong with this?

if-statement with continue or break

I'm doing the simulation of Java OCA test. During my study with the book "OCA - Study Guide" (Sybex), at the second chapter there is the following (Table 2.5, page 91): if - allows break statement: NO if - allows continue statement: NO

But during the simulation of Java OCA test, did by Sybex (online book OCA), there is this question:

int  x= 5;
    while (x>=0) {
        int y = 3;
        while (y>0) {
            if (x<2)
                continue;
            x--; y--;
            System.out.println(x*y + " ");
        }
    }

My answer was: It doesn't compile But the correct answer is: 8 3 0 2

What is the correct information? What is right (book or simulation test)?

Thanks a lot!

Many else if statements in the code

I would like to ask if it is a good way to have many else if statements based on the boolean conditions like below?

public void borrowItem() throws IOException {

    boolean ableToBorrow = isUserAbleToBorrow(cardID);
    boolean isDemand = checkDemand(title, authorNumber);
    boolean userExists = checkIfUserExists(cardID);


    if(ableToBorrow && isDemand && userExists) {

           //lots of code....

    }else if(!ableToBorrow && isDemand && userExists) {
        System.out.println("User limit  exceeded");
    }else if(!ableToBorrow && !isDemand && userExists) {
        System.out.println("User limit  exceeded and no book demand");
    }else if(ableToBorrow && !isDemand && userExists) {
        System.out.println("No book demand");
    }else if(ableToBorrow && !isDemand && !userExists) {
        System.out.println("No book demand and user does not exists");
    }else if(ableToBorrow && isDemand && !userExists) {
        System.out.println("Unrecognized user!");
    }

}

Is it a good way or there is a better idea in java to do that?

Why is my sort shuffling the vector

typedef struct{
    long unsigned int line;
    long unsigned int column;
    double  value;
}sparse;



    void bubblec(int l, int r){
        int i,j, done;
        sparse t;
        for(i = l; i<r; i++){
            done = 1;
            for(j = r; j> i;j-- ){
                if(matrix[j].column < matrix[j-1].column){
                    t = matrix[j-1];
                    matrix[j-1] = matrix[j];
                    matrix[j] = t;
                    done = 0;
                }
            }
            if (done){
                break;
            }
        }
    }


void aux(int l, int r){
    int i;
    int auxx = 0;
    for(i = l; i<r; i++){
        if(matrix[i].line == matrix[i+1].line){auxx += 1;}
        else{
            if(auxx !=0){
            bubblec(auxx -i, i);
            auxx = 0;
            }
        }
    }   
}

aux(0, 7);

Guys I have this code that should sort my unidimensional vector that contains elements represented by sparse struct, first I sort by line ( tested it a million times and everything looked fine), after sorting by line I need to go to each line and sort it by column, My bubblec is bubble sort for the columns of the vector. Facing this problem i did an aux function to discover the position that lines are equal (after being sorted by lines) and sort that by columns.

The problem is that he doesn't sort it right, and shuffles my vector.

Imagine this matrix witch the first column are the lines of the struct and the second column are the columns of my struct

[0;3]
[0;1]
[2;2]
[2;0]   
[4;3]               <----- This is my input matrix,after sorted by lines I 
[4;1]                       Call the aux function with 0 (first element) 
[6;0]                       and 7 (the last element)

This is the matrix after i call the aux function that should sort each line by column

R Comparing the values of two factors in a data frame and getting the result in a third

i am trying to compare the values of two factors in a dataframe and getting the result in a third. I am trying to use a if statement.

Risk is the new column i'm trying to add.

 X = within(X, {
  Risk = if(X$Member == "Member" & X$Predict == "Non Member"){
    "Risk"
  } else{
    "No Risk"
  }  
})

Changing variables as a result of it statements? (Python)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); #sys.exit() if sys is imported
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                if aa != "-\o/-":
                    print("Ok, stupid, WORK!!!!!!!")
                    aa = "     "
                    ab = "-\o/-"
                else:
                    print(m)
                print(m)
            if event.key == pygame.K_a:
                if ab == "-\o/-":
                    print("Ok, stupid, WORK!!!!!!!")
                    ab = "YAY!!"
                    aa = "-\o/-"
                else:
                    print(m)

This is a code snippet from a game I am creating. When this line is true: if ab == "-\o/-":, it should print "Ok, stupid, WORK!!!!!!!", and reassign the two variables. However, the variables do not get reassigned. I have searched this site and the internet for an answer to this problem, but I cannot find one. I have also tried defining something that would do it, but still no luck. Any thoughts?

Issues with re-assigning text variables in IF statements? (Python)

My newest Python program is supposed to detect for a key press of WASD, and then move a five character sprite (-\o/-) over one in a large ASCII art board. Just for clarification, here are some code snippets (and then the full code at the end).

This is the model of the board as of right now. I will implement a new way of showing the board (right now it just prints it over and over, but I do want to have it clear every time it has to be loaded):

https://pastebin.com/z1fGLMYd (sorry, but formatting couldn't work out on here).

Then, pygame is initialized to connect to the keyboard:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
        pygame.quit(); #sys.exit() if sys is imported
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                doSkey()
                print(m)
            if event.key == pygame.K_w:
                doWkey()
                print(m)
            if event.key == pygame.K_d:
                doDkey()
                print(m)
            if event.key == pygame.K_a:
                doAkey()
                print(m)

Finally, we use if statements to connect the keyboard to the "v-board" (variable board, i.e everything stored in variable m):

def doAkey():
    if ab == "-\o/-":
        ab = "     "
        aa = "-\o/-"
    else:
        print(m)

def doDkey():
    if aa == "-\o/-":
        aa = "     "
        ab = "-\o/-"
    else:
        print(m)

What happens at this point is the program launches, and everything loads fine. But when the 'd' or 'a' keys are pressed, it just re-prints the board again, without making any change.

QUESTION:

Why doesn't the variable change in these 'if' statements? I have tried every possible solution I can find on the internet, but nothing works. I have also tried putting the code directly in the loop, but still nothing.

Any help would be greatly appreciated. Thanks!

Here is the full code, for anyone who wants it: https://pastebin.com/ay8MA0cm

how to set uneditable other EditTexts after type in one of them?

I have four EditTexts in my App and want to bocome uneditable all of other 3 edittexts as soon as we write in one of them ? how can I code it ?

Java, designing a game main menu

I am making a game menu which looks like this:

1: New game 2: Save Game 3: Load Game 4: Continue Game 5: Exit Game

I am using switch and case statements to navigate through the menu. However, when the user chooses to "Continue game" my play method (which starts the game) runs from the very beginning and not from the paused state. I am not sure how on earth I should direct it to the state they paused in.

I hope you guys can help! I look forward for you reply! Thanks!

samedi 28 avril 2018

If user's answer is NaN, alert NaN and ask again for a number

I'm writing a function that asks a user for a number and returns the sqrt of that number. If they don't provide a number I need to alert(NaN) and prompt for a number again. Not sure what I'm doing wrong here, it is returning the sqrt but I can't get the NaN part to work.

function sqrtUserNum() {
  let userNum = parseFloat(prompt("Give me a number and I'll tell you it's square-root."));
  if (isNaN(userNum)) {
    alert(NaN)
    prompt(userNum)
  }
  if (!isNaN(userNum)); {
    alert(Math.sqrt(userNum))
  }
}
sqrtUserNum()

Python: if elif loop [duplicate]

This question already has an answer here:

I am trying to do a sentiment analysis with twitter data. I know that the tokens in my POStagged_tweets_lines.json file are 90% neutral. My loop:

pos = "pos"
neg = "neg"
neu = "neu"
negative = 0
positive = 0
neutral = 0

if classification is neu:
    neutral += 1
elif classification is pos:
    positive += 1
elif classification is neg:
    negative += 1
print(negative, positive, neutral)

Should be counting the sentiments of the tweets in the json file. So, at the end I should be getting an output such as 5, 12, 100; but Instead I am getting 0 0 1 and I don't even know where is it coming from.

My if statement always does the not equal, even if the answer is equal

It always turn out to print out "Sorry", even if the number is the same. Why doesn't this if statement work?

    import random

    high_number = input("What is the maximum number?\nExample(20): ")  
    print('0-{}'.format(high_number))  

    guess = input("Guess the number: ")  
    high_number = int(high_number)  

    value = random.randint(0, high_number)  

    if value != guess:  
       print("Sorry.")  
    elif value == guess:  
       print("Hurray!")  

syntax error in if...else condition

I'm learning programming in Python and I'm stuck with a syntax error in the line 8 in the following code

x = int(input('Add x:\n'))
y = int(input('Add y:\n'))
if x == y :
    print('x and y are equal')
else :
    if x < y :
        print('x is less than y')
    else x > y :
        print('x is greater than y')

I just don't see what's wrong there.

The full error is:

Traceback (most recent call last):
  File "compare.py", line 8
    else x > y :
         ^
SyntaxError: invalid syntax

How to create array from certain elements in another array? (python)

I have an array with 7 columns, 52 rows. I want to create an array of just the 4th column but only based a 1 or 0 value from the 7th column. Can someone help?

Checking the condition of clicking on the checkbox

I have 3 checkboxes on my activity. I need to check status of checkbox(clicked/unclecked), and do specific action based on this result. My logic in this work like:

if(Check1,isCheked) {
//some action
} else if(Check2.isCheked) {
//some action
} else if (Check3.isCheked) {
//some action
} else if ((Check1.isCheked) && (Check2.isCheked)) {
//some action
} else if ((Check1.isCheked) && (Check3.isCheked)) {
//some action
} // etc.

If there are some more rational approach of this, because i, for example, have 9 checkboxes and for their verification, I need 509 conditions?

why the outputs are different in the while loop

while($car_result1 = mysqli_fetch_object($car_connect1)){

<div class="portfolio all" data-cat="all">

<? echo $car_result1->car_gear; ?>  // output is stick

<img alt="Ay <?php if($car_result1->car_gear='auto'){ echo "Auto"; } else { echo "Stick"; };  ?> ">

<? echo $car_result1->car_gear; ?> // Output is Auto 

}

car_gear field is filled as "stick" in the database. after the image tag, car_gear output changed as "Auto"

Why the result $car_result1->car_gear; change from "stick" to "Auto" ?

'if' used in Javascript

var myGlobal = 10;
function fun1(){
oopsGlobal = 5; 
}
function fun2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}
fun1();
fun2();

Console shows the results: 'myGlobal: 10,oopsGlobal: 5',but when I moved all '+' away the result changed into 'oopsGlobal: 5',I tried my best but still not know why this happen,thanks a lot!

if two cell values match the formula should return data from third cell as my answer

I manage accounts of my company and have many debit credit entries which are entered into various columns categorically

I am using if else conditions and whenever the data that needs to be shifted is numerical it works but when shifting data after comparing numerical values the formula results in inconsistent formula

A B C D E 12 12 CASH SALE CASH SALE 12 THIS IS WHAT I WANT THAT IF COLUMN A=B THEN DATA OF COLUMN A SHOULD GO TO E AND NOTES MADE IN C SHOULD MOVE TO D.

vendredi 27 avril 2018

SQL SELECT depending on value

I need advise or an idea how to solve my problem. I have select based on few joins. One of the selected value is ex. CA.PADDING_ZERO_FLAG which is '0' or '1'.

Based on this, I want to get other values in select statement.

Pseudocode:

Select if(CA.PADDING_ZERO_FLAG = '1') then LPAD(ZR.START_ZIP_CODE, 5, '0'),
    LPAD(ZR.END_ZIP_CODE, 5, '0') else ZR.START_ZIP_CODE, ZR.END_ZIP_CODE

Is it possible to do?

Thanks in advance

Finding two specific numbers in a list using string tokenizer

I'm trying to find two specific numbers (25,55) in a input list by converting them to tokens. e.g. below - string list = (52 98 55 86 42 25 87 566 56 843). Just for context, the numbers are prices for books bought in a week for a library.

If they are both in a line only then I want to know (print "both"). If only one of them is in the line or something like 5562 or 3259 (part of another number), i want a return of "no". I guess that's why I'm converting them to tokens.

This code below is not working unless i remove the else statement and even when i do remove it, it prints out "both" no matter what I numbers i put in, even if there's no 25 or 55. Sorry if this seems like a dumb question, pretty new to coding.

package part;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
public class part 
{
public static void main(String[] args) throws Exception
{


String list = "52 98 55 86 42 25 87 566 56 843";

StringTokenizer tokenizer = new StringTokenizer(list);


String rp = tokenizer.nextToken();
    if (rp.equals("25") && rp.equals ("55"));
      {
          System.out.println("both");   
   }

      else


      { System.out.println("no");}


}
}

Optimize the if condition

I want to simplify this condition where a and b are booleans

!((a && b) || (!a && !b))

I have tried using the truth table generator, but I am not able to figure out the simplified version.

Integer not working with an if statement

I am making a text based game, and I am experimenting with different ways of making the storyline of the game progress. (Im sorry if this is semi-hard to follow, I am new to this website, and still fairly new to Java, I'm making this for a class project)

One of the ways I am trying is by increasing a value (In this case LevelNum) by one, and whenever a number not equal to zero is displayed it will set the text of jLabel1 to whatever the text is.

I am trying to do this by using an if statement as shown here:

if(LevelNum == 0) {
                jLabel1.setText(StoryData.LevelOne);
            }

The increase of LevelNum is done like this:

public void actionPerformed(ActionEvent e) {
                    LevelNum += 1;
                    System.out.println(LevelNum);

            }

(The System.out was just to check to see if it was increasing the number)

The problem I am running into is that no matter what the value of jLabel1 is, the text never changes, and I dont know why.

The whole code can be found here: https://pastebin.com/JSX6urFT

The StoryData is a seperate class within in my text document, and the individual strings look like this: static String LevelOne = "Level one test";

Play and pause buttons are working... but how do I reset button to show the play symbol once audio is over?

I've coded a button to display the "play" symbol (triangle). When you click the button, the selected audio plays and the button displays a "pause" symbol instead. If you click pause, the audio pauses and the button switches back to the play symbol. So far, so good. When the audio is OVER, however, the button keeps displaying the "pause" symbol. You can press the button again and the audio will play again, but the image does not return to the play triangle. Any advice for a newbie?

<script>
var loopA = document.getElementById('playA');

function playAudioA() {
    if (loopA.paused) {
        loopA.play();
        pButtonA.className = "";
        pButtonA.className = "fa fa-pause";
    } else { 
        loopA.pause();
        pButtonA.className = "";
        pButtonA.className = "fa fa-play";
        loopA.currentTime = 0
    }
} 
</script>

Skipping lines in VBA (Loop/If Statements) - Chart Axis Boundaries changes

I have a loop that goes through data and puts it in another sheet to produce a chart. However, because I have a wide range of data I want the vertical axis' boundaries to change according to what the cell value is. I tried creating a section of the code to follow it. However, in this section only 3 lines are being read, the other lines get skipped. I ran the code then I stepped into it and that's when I noticed. Can anyone help me figure out why these lines are getting skipped?

The lines that are being skipped are:

cht.Axes(xlValue).MinimumScale = 10
ElseIf cell.Value >= 40 Then
cht.Axes(xlValue).MinimumScale = 20
ElseIf cell.Value >= 60 Then
cht.Axes(xlValue).MinimumScale = 40

Here's the full code:

Sub Loop()

   Range("E2").Select
    ActiveCell.Range("D1:E1").Select

Dim myPDF As String
Dim i As Long

    For counter = 5 To 21
        Sheets("Lang").Select
        Range("'Lang'!$E$" & counter & ":$F$" & counter).Select 'numbers
        Selection.Copy
        Sheets("Lang-Chart").Select
        Range("B1:C1").Select
        ActiveSheet.Paste
        Sheets("Lang").Select
        Range("'Lang'!$G$" & counter & ":$I$" & counter).Select 'labels
        Selection.Copy
        Sheets("Lang-Chart").Select
        Range("A2:C2").Select
        ActiveSheet.Paste

       Dim cht As Chart
Set cht = Worksheets("Lang-Chart").ChartObjects("Chart 2").Chart
For Each cell In Range("B1:C2")

    If cell.Value >= 10 Then
        cht.Axes(xlValue).MinimumScale = 10
    ElseIf cell.Value < 10 Then
        cht.Axes(xlValue).MinimumScale = 0
    ElseIf cell.Value >= 40 Then
        cht.Axes(xlValue).MinimumScale = 20
    ElseIf cell.Value >= 60 Then
        cht.Axes(xlValue).MinimumScale = 40
   End If
    Next cell


       ActiveSheet.ChartObjects("Chart 2").Activate
       ActiveChart.ChartArea.Select
       myPDF = "\\stchsfs\arboari$\Profile-Data\Desktop\Sample 20\c3-" & Sheets("Lang").Range("D" & i + 2).Value2 & ".pdf"
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myPDF, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
        i = i + 1
     Next counter

End Sub

Thanks!

How to use if_else with sql query in RODBC package R

I am using the RODBC package in R to run a SQL query. I'd like to add a simple condition to run this query. I am able to get results from the below query

library(RODBC)
database1 <- odbcConnect(dsn = "<database_name>")
sqlQuery(database1, "SELECT * FROM TABLE")

But when I add an ifelse() statement to it, then it doesn't work

ifelse(1<2, sqlQuery(database1, "SELECT * FROM TABLE"), "")

What really went wrong here?

Unfortunately, I cannot produce a reproducible example as the question needs a database connection.

Thanks!

Why is this Java code always giving me "False" statement? [duplicate]

This question already has an answer here:

When I type the same password (jalalkay) it gives me "False" answer!

import java.util.Scanner;

public class password2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner pass = new Scanner(System.in);


        System.out.println("Type a password");
        String ps = pass.nextLine();

        if(ps == "jalalkay"){
            System.out.println("true");

        }else{
            System.out.println("false");
        }

    }

}

How to display a block of code at the end of a foreach loop only once

Below, I have the following foreach statement with an if statement nested inside of it. I am running into an issue that I cannot figure out.

I am wanting the following code to be included in the else-statement, but not be in the foreach loop. I have tried the break function, but it breaks the loop, which I do not want. I also tried changing the structure of the loop to include a endforeach before the end bracket for the else-statement, but this just broke the code.

Essentially, I am just wanting my foreach loop to run normal, but then for the else-statement to populate the moreEventsContainer. I can't think of a way to do it.

Does anyone have any ideas?

  echo '<div class="moreEventsContainer">
          <div id="moreEventsWrap" class="total-center">
           <span class="moreEventsLink">SEE ALL EVENTS</span>
           <div class="rightArrow"></div>
         </div>
       </div>'

;

This is what I am wanting to output:

enter image description here

Without the break, it does this:

enter image description here

With the break, I only get this:

enter image description here

Full Code:

foreach ($event_rows as $event_row) {
    $event_name = $event_row['event_name'];
    $display_date = $event_row['display_date'];
    $event_description = $event_row['small_desc'];
    $end_date = new DateTime($event_row['end_date']);
    $date = new DateTime('now');
    if ($date >= $end_date) {
        //$noEvents = 'No events are scheduled yet.';
        $noEvents = '
        <div id="noEvents">
        </div>
        ';
    } else {
        echo '<div class="eventBlock">';
        echo '<div class="total-center eventBlockWrap">';
        echo '<span class="displayDate">'. $display_date .'</span>';
        echo '<span class="eventName">'. $event_name .'</span>';
        echo '<p class="dGsmall margNone">'. $event_description .'</p>';
        echo '</div>';
        echo '</div>';
        break;
        echo '<div class="moreEventsContainer">
                <div id="moreEventsWrap" class="total-center">
                    <span class="moreEventsLink">SEE ALL EVENTS</span>
                    <div class="rightArrow"></div>
                </div>
            </div>'
        ;

} }

I have error Parse error: syntax error, unexpected '{' in C:\xampp\htdoc [duplicate]

This question already has an answer here:

Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\ons.php on line 69

if ($result2 = mysql_query($sql2))

                {
                    while($row2 = mysql_fetch_assoc($result2)) {

if ($row["id"] == $image['id'] ){$vi = 'background: #2b1644;';};

            echo '<div class="col-md-2" style="'.$vi.' ;"> </div>';
             }

                    mysql_free_result($result2);

                }

Nested IF Statements for batch

I am currently trying to get a list of items saved from a profile on an old machine and then sent to the new machine and profile. Being that the profile is the same. In windows 7 there is the location "%userprofile%\AppData\Roaming\Microsoft\Sticky Notes\" that stores the .snt for sticky notes. That location exists natively all the way to Windows 10 1511. In Windows 10 1607 it has been moved to "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\" and changed to "plum.sqlite.

If you upgraded from anything earlier than windows 10 1607 it will have made a "Legacy folder" with "ThresholdNotes.snt" in it and that will convert over to the "plum.sqlite"

I am writing a nested .bat that will: if old sticky notes location on the new computer exists, then check for pulled .snt file, then copy over ELSE

if new sticky notes location exists, check for pulled .snt file, if new legacy location not exist, then create and then copy and rename .snt to convert, else copy,rename

if old sticky notes location not exist, then check for new .sqlite file, if exist then copy new file to new location ELSE

otherwise say there are none detected.

But it seems I may be writing it wrong or something because I have placed a pause in the .bat but it just closes immediately when ran.

Here is the current Pull part where it retrieves the .snt or .sqlite. Variables first and then the actual action part.

REM Saves Users Sticky Notes
Set StickyNotes="%userprofile%\AppData\Roaming\Microsoft\Sticky Notes\StickyNotes.snt"
Set FlashStickyNotes="%~dp0%USERNAME%\StickyNotes"

REM Saves Users Sticky Notes From Win 10 1607+
Set StickyNotesWin10="%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite"
Set FlashStickyNotesWin10="%~dp0%USERNAME%\StickyNotesWin10"


Title Pulling StickyNotes
if exist %StickyNotes% ( xcopy %StickyNotes% %FlashStickyNotes% /f /y ) ELSE if exist %StickyNotesWin10% ( 
xcopy %StickyNotesWin10% %FlashStickyNotesWin10% /f /y ) else Echo "No Sticky Notes Detected"

^^This part seems to work just fine and not have any problems

Here's the Push part and this is where I seem to have trouble but maybe its formatting? Variables first and then the actual action part.

REM Saves Users Sticky Notes
Set StickyNotes="%userprofile%\AppData\Roaming\Microsoft\Sticky Notes\"
Set FlashStickyNotes="%~dp0%USERNAME%\StickyNotes\StickyNotes.snt"

REM Saves Users Sticky Notes From Win 10 1607+
Set StickyNotesWin10="%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\"
Set FlashStickyNotesWin10="%~dp0%USERNAME%\StickyNotesWin10\plum.sqlite"

Title Pushing StickyNotes
REM if old sticky notes location on the new computer exists, then check for pulled .snt file, then copy over ELSE
REM if new sticky notes location exists, check for pulled .snt file, if new legacy location not exist, then create and then copy and rename .snt to convert, else copy,rename
REM if old sticky notes location not exist, then check for new .sqlite file, if exist then copy new file to new location ELSE
REM otherwise say there are none detected
IF exist "%userprofile%\AppData\Roaming\Microsoft\Sticky Notes\"( IF exist "%FlashStickyNotes%"( xcopy %FlashStickyNotes% %StickyNotes% /F /Y ) 
IF exist "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\"(
    IF exist "%FlashStickyNotes%"(
        IF not exist "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\Legacy"(
            mkdir "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\Legacy"
            xcopy %FlashStickyNotes% "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\Legacy\ThresholdNotes.snt" /F /Y
        ) else IF exist "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\Legacy"((
            xcopy %FlashStickyNotes% "%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\Legacy\ThresholdNotes.snt" /F /Y
        )
    )
) else IF not exist "%StickyNotes%" (
    IF exist %FlashStickyNotesWin10% (
    copy %FlashStickyNotesWin10% %StickyNotesWin10% /Y
    )
)
) ELSE Echo "No Sticky Notes Detected" 
    REM Saves Users Sticky Notes From Win 10 1607+
    Set StickyNotesWin10="%userprofile%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\"
    Set FlashStickyNotesWin10="%~dp0%USERNAME%\StickyNotesWin10\plum.sqlite"

C++: Is it worth using static_cast to avoid if conditions which compare numbers?

I try to make very time efficient code in C++. I was told that I should avoid if conditions whenever possible. So I was thinking that type conversion could do the job. The code with if condition would look like this:

double a = .512;  // some real number
double x = 1.1;  // a coordinate that gets changed when if condition is true
a *= a;  // a squared
if(a >= 1){x += .1;}

I would avoid the if condition in the following way.

double a = .512;  // some real number
double x = 1.1;  // a coordinate that gets changed when if condition is true
a *= a;  // a squared
x += static_cast<bool>(static_cast<int>(a)) * .1

This first converts a into an int. This gives 0 for a<1 and a non-zero int for a>1. The second conversion then converts all non-zero ints to true. But is it really faster? Are there any problems I could run into using this method?

Usage of "If any ()" not producing desired results

I have a list of words in a csv file (in column A). I also have a file filled with 1 sentence per line (row, column A).

I need to iterate through each sentence and only keep the sentences that do contain any of the words in "list of words" csv file.

I was very sure that i had the right code, but for some reason, it just keeps writing every single sentence. Can you please have a look to see what part of my code is incorrect? I suspect that my usage of "If any()" may be incorrect.

bad_words = r'C:\Users\.spyder-py3\words.csv'

with open(r'C:\Users\.spyder-py3\newdata.csv') as oldfile, open('newfile.csv', 'w') as newfile:
    for line in oldfile:
        if any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

Getting "undefined" result when using the logical operator "&&" in a JavaScript If..Else statement

The code is for selecting the federal poverty level (var fpl) percentage category base on the income (var income). When I run this script, my result is "undefined" when I use the && logic operator. If I use the || logic operator, I get the wrong and same answer - "101-185%" - no matter what number I use for var income.

<p id="demo"></p>

<script>
  function FPL() {   

    var income = '4200.00';
    var fs = '1';

        var fpl;  
        if(fs == '1') {
            if(income < '1022.00')
               fpl = "0-100%";  
            if (income > '1022.00' && income < '1882.00') 
               fpl = "101-185%";   
            if (result3 > '1882.00' && income < '2033.00') 
               fpl = "186%-200%";
            if (income < '2033.00')
               fpl ="'201% & Over";

            return fpl;                

        }             

        result6 = 'Federal Poverty Level: ' + fpl;

        document.getElementById("demo").innerHTML = result6;
 }   

</script>

Are the logic operators in an Else..If statement used differently in JavasScript?

set visibility trough property not working

This is my first post.

if (condition) {
    trace("called");
    p[1].visible = false;
    j[1].visible = false;
}

With the code above "called" was printed in console but the both objects (buttons) still visible. Then when I try to put the set visibility (p[1].visible = false; and j[1].visible = false;) out from condition, it's work well.

How can I do set visibility with some condition?

Writing to file and using if statments with loops

I am creating a simple system for people to enter there basic details, have them printed on the screen and once confirmed writen to a text file, is the info is wrong the user enters edit ot be looped back to the beginning of the report and if another input is ented it asks the question again. Im a struggling to get the print to file to work and the two end loops.

#include <stdio.h>
#include <string.h>

int get_line(const char *prompt, char *dest, size_t size) {
  printf("%s", prompt);
  fflush(stdout);
  if (fgets(dest, size, stdin) == NULL) {
    dest[0] = '\0';
    return 0;
  }
  dest[strcspn(dest, "\n")] = '\0';  // Lop off potential trailing '\n'
  return 1;
}

int main(void) 
{
    char first_name[20], surname[20], street_no[10], street_name[40], postcode[10], contact_no[20], save_edit_qu[10];
    int dd, mm, yy;
    get_line(" Enter first name:\n", first_name, sizeof first_name);
    get_line(" Enter surname:\n", surname, sizeof surname);
    get_line(" Contact Number\n", contact_no, sizeof contact_no);
    get_line(" Street Number\n", street_no, sizeof street_no);
    get_line(" Street Name\n", street_name, sizeof street_name);
    get_line(" Postcode\n", postcode, sizeof postcode);

    printf(" First Name : %s\n", first_name);
    printf(" Surname    : %s\n", surname);
    printf(" Contact No.: %s\n", contact_no);
    printf(" Street No. : %s\n", street_no);
    printf(" Stret Name : %s\n", street_name);
    printf(" Postcode   : %s\n", postcode);


    get_line(" If the informations above is correct please enter SAVE/if you wish to change any informations please enter edit", save_edit_qu, sizeof save_edit_qu);
    if (save_edit_qu[0] == 'SAVE' || save_edit_qu[0] == 'save') {
    //write info to file
    }
    if (save_edit_qu[0] == 'EDIT' || save_edit_qu[0] == 'edit') {
    //loop back to beginning of report
    }
    else if ()//loop to beginning of SAVE/EDIT QU

    return 0;
}

Meaning of !! and how to use it [duplicate]

I am writing a code using webstorm IDE, and i wrote an

if statement

in a method like this::

createEvent():boolean {
return this.http.post('/event', { params: {name , location} }).map(res => res.json()).map(res => {
if(event && event.success){
return true;
}
return false;
});
}

Then the IDE suggest i rewrite(simplify) the if statement this way:

createEvent():boolean {
    return this.http.post('/event', { params: {name , location} }).map(res => res.json()).map(res => {
   return !!(event && event.success);
    });
    }

I find it confusing while the system uses a double NOT sign.
Please i need some explanation.

Two "if" conditions in the same time

I am writing a script to bring me data from other nodes via ssh in a multi selection choice menu, and i want to display a message according to this data.

    if [[ "$option" == "1" ]]
 then
ssh skyusr@<IP> "export JAVA_HOME=/opt/mesosphere && /var/lib/mesos/slave/slaves/*/frameworks/*/executors/*/runs/latest/apache-cassandra-3.0.10/bin/nodetool -p 7199 status" | sed -n '6,10p' | awk '{print $1,$2}' | grep DN > $file_name
        if [ -s $file_name ]
        then
        echo "All Cassandra Nodes are UP !"
        else cat "$file_name"
        fi
fi

When i execute the script, i see it does not see the second if condition to display the message .

What is the correct syntax ?

Multiple conditions and MySQLConnections issue in C#

I have a button click event that checks conditions within multiple input elements on a form. Textboxes, radio, combo buttons, etc.

In addition, the method check whether a text entry for username is unique or already existent in the database. If the user meets all conditions, than with the else statement is activated and the entries are stored in the database.

This is the method below:

    private void button2_Click_2(object sender, EventArgs e)
    {

        int Vid_Smetka;

        if (radioNewAdmin.Checked)
        {
            Vid_Smetka = 1;
        }
        else
        {
            Vid_Smetka = 0;
        }


        if (txtNewUser.Text == String.Empty)
        {
            MessageBox.Show("Корисничкото име е празно. Ве молиме пополнете го полето.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewFullname.Text == String.Empty)
        {
            MessageBox.Show("Ве молиме пополнете го полето за целосно име и презиме.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewEmail.Text == String.Empty || !txtNewEmail.Text.Contains('@'))
        {
            MessageBox.Show("Ве молиме пополнете го полето за email. Користете валидна e-mail адреса.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewPassword.Text.Length < 6)
        {
            MessageBox.Show("Ве молиме внесете најмалку 6 карактери во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (!txtNewPassword.Text.Any(x => char.IsUpper(x)))
        {
            MessageBox.Show("Ве молиме внесете барем една голема буква во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (!txtNewPassword.Text.Any(x => char.IsLower(x)))
        {
            MessageBox.Show("Ве молиме внесете барем една мала буква во лозинката.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else if (txtNewPassword.Text != txtNewRepeatPassword.Text)
        {
            MessageBox.Show("Лозинките не се совпаѓаат. Ве молиме обидете се повторно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (!radioNewAdmin.Checked && !radioNewUser.Checked)
        {
            MessageBox.Show("Ве молиме селектирајте тип на сметка.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (string.IsNullOrEmpty(comboNewFunction.Text))
        {
            MessageBox.Show("Ве молиме функција на корисникот на сметката во училиштето.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
        else if (txtNewUser.Text != String.Empty)
        {

            MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["#.Properties.Settings.ConnectionString"].ConnectionString);

            conn.Open(); //Try to open the connection to the MySql database

            //Check if there is a row with credentials entered in the form
            MySqlDataAdapter sda = new MySqlDataAdapter("SELECT Count(*) FROM #.# WHERE Korisnik = '" + txtNewUser.Text + "'", conn);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            //Initiate a new connection string

            if (dt.Rows[0][0].ToString() != "0")
            {
                MessageBox.Show("Корисничкото име е зафатено. Ве молиме обидете внесете уникатно.", "Потсетник", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            conn.Close();
        }
        else
        {

            var sqlCommand = "INSERT INTO #.#" +
            "(Korisnik, Lozinka, Vid_Smetka, email, user_function, full_name) " +
            "VALUES ('" + this.txtNewUser.Text + "', '" + this.txtNewPassword.Text + "', '" + Vid_Smetka + "', " +
            "'" + this.txtNewEmail.Text + "', '" + this.comboNewFunction.Text + "', '" + this.txtNewFullname.Text + "');";

            //Initiate a new connection string

            try
            {
                using (MySqlConnection con = new MySqlConnection(conString))
                {
                    MySqlCommand cmdDatabase = new MySqlCommand(sqlCommand, con);
                    con.Open();
                    MySqlDataReader myReader;
                    myReader = cmdDatabase.ExecuteReader();
                    dataGridView1.DataSource = loadData().Tables[0];

                    MessageBox.Show("Зачувано.", "Известување", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    panelNew.Visible = false;

                }
            }
            catch (Exception ex)

            {
                MessageBox.Show(ex.Message);
            }


        } 
    }

This is obviously quite simple. But, for a certain reason the else statement is not executing when all other conditions are met.

I am making a mistake with the MySQLConnection? Any hints where I might be getting it wrong?

Node-red:node-function - missing "null" value in if condition

I'm using Node-Red and in node function I have:

  ...  
  res = dataTransform.transform();  
  //critic case: res = [{"pressure":null}];  
  key = Object.keys(res[0]);  
  if(res[0][[key]]!=null)  
  {  
   ...   
   console.log("res:   ", [key]+":"+res[0][[key]]);  
  }  

on console.log I have always:

res: 0:[object Object]

And it enters in if-statement always (also when the "res[0][[key]]" is null).

What was I mistake?

jeudi 26 avril 2018

Python Tkinter Button with If Else statements

i want to bind the 'Start Button' with 2 possible functions. If 'Choise 1 Button' is clicked and then the 'Start Button', the 'Start Button should call Function 1. But when the user clicks 'Choice 2 Button' then the same 'Start Button' should call Function 2.

Anyone a idea? Thanks prevardly!

Excel multiple variable lookup then output a given value

I have two sheets in excel. The first sheet1 has 3 given values (E, fy, f'c), the second sheet2 has all of those same values with corresponding p (rho) values. I'm trying to write a code such as vlookup or similar that first checks for the fy column, then the f'c, then E, and then provides the p value at the intersection of those values. Any suggestions would be greatly appreciated.

Basically I should be able to input E = .0075, fy = 60000, f'c = 4000. Then the code should search Sheet2 and find the corresponding rho p value to be = .0138 (Column D, Row 16)

I've attached a google spreadsheet with the example. spreadsheet example

Breaking out of a foreach within a nested if statement

I am having a difficult time figuring out how to break a section out of a an else-statement that is nested within a foreach loop.

The section I want to break out of the foreach loop is :

echo '
  <div class="moreEventsContainer">
  <div id="moreEventsWrap" class="total-center">
  <span class="moreEventsLink">SEE ALL EVENTS</span>
  <div class="rightArrow"></div>
  </div>
  </div>'
;

The thing is that it is part of the else statement, but leaving it in the loop just makes it duplicate itself over and over when I just want it to appear once.

Does anyone see how I can do this?

I tried doing the alternative endforeach nested before the end of the else statement, but it just broke the code.

Any ideas?

foreach ($event_rows as $event_row) {
        $event_name = $event_row['event_name'];
        $display_date = $event_row['display_date'];
        $event_description = $event_row['small_desc'];
        $end_date = new DateTime($event_row['end_date']);
        $date = new DateTime('now');
        if ($date >= $end_date) {
            //$noEvents = 'No events are scheduled yet.';
            $noEvents = '
            <div id="noEvents">
            </div>
            ';
        } else {
            echo '<div class="eventBlock">';
            echo '<div class="total-center eventBlockWrap">';
            echo '<span class="displayDate">'. $display_date .'</span>';
            echo '<span class="eventName">'. $event_name .'</span>';
            echo '<p class="dGsmall margNone">'. $event_description .'</p>';
            echo '</div>';
            echo '</div>';
            echo '<div class="moreEventsContainer">
                    <div id="moreEventsWrap" class="total-center">
                        <span class="moreEventsLink">SEE ALL EVENTS</span>
                        <div class="rightArrow"></div>
                    </div>
                </div>'
            ;
        }
    }
    if ($noEvents != NULL) {
        echo $noEvents;
    } else {

    }

IF statement ignoring keyboard input

I have been trying to run a program using keyboard input to decide whether or not to run the program and the if statement is ignoring the input and always defaults to the else statement. Here is my code.

import random
import time
import sys

print("Do you want to run the program? Yes/No")
ans = sys.stdin.readline()

time.sleep(1)

if ans == "Yes" or ans == "yes":

    '''Body of IF statement'''

else:
    print("Alright, have a great day!")

Bash if/else statement is not piping output correctly

I have a script that is querying AWS regions for specified subnet masks. In AWS, the default VPC CIDR block is 172.31.0.0/16, so I wrote an if/else statement to pipe that output to /dev/null and then write all other CIDR blocks to a text file. For some reason, the 172.31.0.0/16 block is still being written to the text file.

Code:

#!/bin/bash

get_cidrs() {
for region in `aws ec2 describe-regions --output text | cut -f3`
do
    echo -e "\nGetting subnets in region:'$region'..."
    describe_cidr=`aws ec2 describe-vpcs --region $region | grep '\Block":' | awk 'NR%2==0' | sed 's/CidrBlock": "//g'`

    echo "$describe_cidr"
    if [[ "$describe_cidr"  == "172.31.0.0/16," ]]; then
        echo "$describe_cidr" > /dev/null 2>&1
    else
        echo "$describe_cidr" >> cidr_blocks.txt
    fi
done
}

get_cidrs

Output:

Getting subnets in region:'eu-central-1'...
                    "172.31.0.0/16",

Getting subnets in IX region:'us-east-1'...
                    "10.247.92.0/23",
                    "10.247.90.0/23",

Text file:

cat cidr_blocks.txt
"172.31.0.0/16",
"10.247.92.0/23",
"10.247.90.0/23",

The goal is to not have any of the "172.31.0.0/16", ranges in the text file.

Using dateTime function in a foreach loop to check is set date is greater than current date

I am attempting to use the dateTime function against a date/time field I have in my database to check against each other as to whether it is greater than or less than each other.

The issue I am running into is that if I set the condition to if ($date >= $end_date), then I only get the $noEvents to output, even though there are end_date fields that are actually greater than the $date (current dateTime). Then the same happens if I change the condition to if ($date <= $end_date), except vise versa.

It seems as if this if statement is only reading once and not looping through each record.

Here is what is in my database. The first two records have dates greater than today. The third record has a day less than or previous of today.

If the condition is : if ($date >= $end_date)

I only get $noEvents.

If the condition is: if ($date <= $end_date)

I get all of the three database records displaying, even though the record titled "Test" should not be displaying.

Does anyone know why this isn't working correctly?

enter image description here

if ($date <= $end_date) {
                $noEvents = 'No events are scheduled yet.';
            } else {

events  CREATE TABLE `events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_name` text NOT NULL,
  `display_date` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `event_img` text NOT NULL,
  `end_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 


try {   
    $con = new PDO('mysql:host='.$servername.';dbname=name', $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql_events = "
        SELECT *
        FROM events
        ORDER BY end_date ASC
        LIMIT 3
    ";
    if ($event_stmt = $con->prepare($sql_events)) {
        $event_stmt->execute();
        $event_rows = $event_stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($event_rows as $event_row) {
            $event_name = $event_row['event_name'];
            $display_date = $event_row['display_date'];
            $event_description = $event_row['description'];
            $end_date = $event_row['end_date'];
            $date = new DateTime("now");
            if ($date <= $end_date) {
                $noEvents = 'No events are scheduled yet.';
            } else {
                echo '<div class="eventBlock">';
                echo '<span class="hGc">'. $display_date .'</span>';
                echo '<a href="#" class="hLink">'. $event_name .'</a>';
                echo '<p class="dG margBot40">'. $event_description .'</p>';
                echo '</div>';

            }
        }
        if (isset($noEvents)) {
            echo $noEvents;
        }
    }
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

How to apply a "for loop" in all columns in R?

I have this data and a for that I created to convert all the elements in a column, based on condition (if). (I know that there are more ways to do that...)

Here it is:

S1 <- c(0,1,1,0,0,2,2,1,1,1,1,1,0)
S2 <- c(2,1,0,1,0,2,1,1,0,1,2,2,1)
S3 <- c(0,1,0,0,1,2,0,1,2,1,2,0,2)
S4 <- c(2,1,0,2,1,2,2,1,2,1,2,2,0)

df <- data.frame(S1,S2,S3,S4)

for (i in 1:nrow(df)){
  if(df[i,1] == 0){
    df[i,1] <- "A/A"
  }
  if(df[i,1] == 1){
    df[i,1] <- "A/T"
  }
  if(df[i,1] == 2){
    df[i,1] <- "T/T"
  }
  if(df[i,1] == "NaN"){
    df[i,1] <- 0
  }
}

This is the actual:

S1  S2  S3  S4
0   2   0   2
1   1   1   1
1   0   0   0

When I run the for it works for the first column only, since I described the df[i,1]. The question is, how can I do this for all columns simultaneously? Is there a way I could solve this problem?

Thanks

Using averageifs function for time point

I'm stuck with an AVERAGEIFS function in excel and I'm hoping to get some input here. I'm working with data on sleep and have multiple entries per person. I want to know what the average midsleep (the time you go to bed + sleep duration/2) on free days is for one person in week 1 and week 2. So basically just a time point in hh:mm. I already have calculated midsleep for each data point.

What I already did and has worked for sleep duration, e.g. =AVERAGEIFS(BZ2:BZ266, B2:B266, "8469", CC2:CC266, "1", CG2:CG266, "1") the average sleep duration for person 8469 in week 1 on work days (1).

For midsleep it also has worked, but not always. I think there must be going on something with how time works in excel. For example I get 17:49 as person 8470's average midsleep in week 2, but the average sum is 11:39. If I then divide 11:39 into two, it's 17:49 again.

I used the same formula here: =AVERAGEIFS(CB2:CB266,C2:C266,"8470",CG2:CG266,"2",CH2:CH266,"2") - the midlsleep point in week 2 on free days (2).

Do you have any idea what's happening here? It seems to be a time issue. My columns are formatted as hh:mm.

Let me know if you need more information.

All the best, Anita

if statement activates even if conditions are not met [on hold]

light = int(input("Please enter a number for light x:")), int(input("Please enter a number for light y:"))

thor = int(input("Please enter a number for thor x:")), int(input("Please enter a number for thor y:"))

longitude, latitude = thor
longitudel, latitudel = light
e = (1,0)
s = (0,1)
n = (0,-1)
w = (-1,0)
se = (1,1)
nw = (-1,-1)
ne = (1,-1)
sw = (-1,1)

while thor != light:
    if thor > (40,40) or thor < (-40,-40):
        break
    elif longitude > longitudel and latitude == latitudel: #e
        thor = tuple(sum(x) for x in zip(e + thor))
    elif latitude > latitudel and longitude == longitudel:#s
        thor = tuple (sum(x) for x in zip(s + thor))
    elif latitude < latitudel and longitude == longitudel:#n
        thor = tuple(sum(x)for x in zip(n + thor))
    elif longitude < longitudel and latitude == latitudel:#w
        thor = tuple(sum(x)for x in zip(w , thor))
    elif longitude and latitude < longitudel and latitudel:#se
        thor = tuple(sum(x)for x in zip(se , thor))
    elif longitude and latitude > longitudel and latitudel:#nw
        thor = tuple(sum(x)for x in zip(nw , thor))
    elif longitude > longitudel and latitude < latitudel:#ne
        thor = tuple(sum(x)for x in zip(ne , thor))
    elif longitude < longitudel and latitude > latitudel:  # sw
        thor = tuple(sum(x)for x in zip(sw , thor))
    print (thor)

I don't understand why the elif statements activate even if conditions are not met and its normally the se, nw, etc conditions rather then n, e, w. Can someone please explain what im doing wrong ?

Excel VBA: Optimal use of DateValue in VBA (or other method to compare dates)

I've written a VBA macro in Access that's creating a new excel file basing on a few different ones. I'm unable to change the way the source files are formatting the data, and I want to write a simple IF statement (if date X is past date Y, delete entire row). The problem is that the dates have different format. The way I'm able to do it is create a new column:

=IF(DATEVALUE(A2)>DATEVALUE(H2),TRUE,FALSE)

And then go from that and at the end delete the column. That doesn't feel right though and I believe there's a better solution. I've been trying to do something like

 If ifDelete = vbYes And .Cells(Lrow, 19).Value Like "*timing*" And DateValue(.Cells(Lrow, 1).Value) > DateValue(.Cells(Lrow, 8).Value) Then
      .Cells(Lrow, 19).EntireRow.Delete
 End If

But it obviously doesn't work. I also tried working with formatting the date columns prior to running that IF statement, but still, no luck. If that helps, dates are formatted in a way MM/DD/YYYY and M/D/YYYY. For some reason going with .NumberFormat = "MM/DD/YYYY" on the 2nd or both fields doesn't work too.

Kind regards, heaton124.