samedi 30 septembre 2017

Both if else statements executing togetther qt c++

I have written a function to search words in qtable widget(which has 10 rows) and display the relevant word on the the 1st row if the word in the table widget.

But unforutnately when I enter a word in the tablewidget and click the button the message box in the else statement executes 1st and then the word is shown on the 1st row!

void MainWindow::on_pushButton_clicked()
{

  QString Line = ui->lineEdit->text();
  for(int i = 0; i < 10; ++i)
  {
      if(ui->tableWidget->item(i, 0)->text() == Line)
      {

          ui->tableWidget->clear();
          ui->tableWidget->setItem(0,0,new QTableWidgetItem(Line));
          break;
      }
      else{

          QMessageBox::information(this,"Word not found","The word you are searching is not in the list");
          break;

      }
  }

How can I correct this?

Excel nested if. If cell A2 do this, if cell B2 do this, if cell b3 do that

Ok im a little rusty on my excel. I have data currently on a sheet that are in 3 tables basically the first one asks them to put in a value and the next 3 columnns return values. So they put in a state and the metro areas are returned in one cell, cities in the next, and streets in the last. I also created a table under it that does basically the same except they enter the metro it will then display states next to it. cities to the right of that and then streets to the right of that. finally one more for table that they put in the city and streets are returned next to it. I would like to combine these by having 3 columns up top and they enter one particular area to one of those cells. So it would be

State | Metro |City ------ | ------ |----- Cell | Cell |Cell

in the cell field they would fill in the lets say the city. Below I have the table with the cells that would determine which cell had text and return the appropiate data. so there would be 3-4 cells for the Metro, Cities, Streets, States. If i put a city in the first 3 cells wouldnt return a value but streets would return the streets for that city. If i put a state in it would retrun the Metro areas, cities, and streets. I basically just need formula to check which cell has data to run the particular formula i have to return that data.

Below is what i want it to look like. and what it currently is.

http://ift.tt/2xKvPDv

http://ift.tt/2yAItEp

Let me know if there is something else i can clarify.

Simultaneous calculation of means from a vector based on a grouping condition in R

I was wondering if there is a way to simultaneously obtain the means of k groups from y in the following R code:

k = gl(3, 5, 15)
y = as.vector(unlist(mapply(FUN = rnorm, n = rep(5, 3), mean = c(4, 5, 6))))

Here is what I have tried with no success:

mean(y[k == c(1, 2, 3)])

If-statements in Bash Syntax issues produce right answers, while right code shows wrong answers

I am fairly new to bash scripting and am struggling with some if-statement syntax.

I have currently written up the following loop:

for (( i = 2; i < $# - 1; i++)); do
    if [ $i -ne 0]; then
        if [ $i -ne 1]; then
            echo "$i was not 1 or 0. Please correct this then try again."
            exit 1;
        fi
    fi
done

This code is supposed to test whether any arguments after the first are either a 1 or a 0.

While the following errors are printed:

./blink.sh: line 36: [: missing `]'
./blink.sh: line 36: [: missing `]'

...the code actually runs fine afterwards (so the errors don't kill the program).

My understanding, however, is that in bash, you put spaces before and after the expression inside the if statement. So this:

if [ $i -ne 0]; then

Becomes:

if [ $i -ne 0 ]; then

However, running this code produces the following:

2 was not 1 or 0. Please correct this then try again.

This does not change regardless of what the actual arguments are. Changing the if statement to double brackets does not change the answer here. So I'm unsure either where my code is wrong or what is happening when I have the broken code that is still causing it to get to the right answers.

Thanks!

How to get process priority in python

Right now, I m using psutil.nice() function in for process in psutil.process_iter() loop. If I try to campare priority like this:

if process.nice() != psutil.HIGH_PRIORITY_CLASS:
     do something..

It does not work. So my question is: How to compare process priority in python using psutil? Thanks for all answers and have a noce evening :)

Batch file, If Statement not working

The following if statement is not running. It just ends the bat file It stops the process. Why is this happening? How do I stop it?

    if "%Choice%"=="si" (GOTO Case2) else (
        if "%Choice%"=="s" (GOTO Case1) else (
            if "%Choice%"=="ti" (GOTO Case4) else (
                if "%Choice%"=="t" (GOTO Case3) else (
                    if "%Choice%"=="i" (GOTO Case5) else (
                        if "%Choice%"=="cp" (GOTO Case6) else (
                            if "%Choice%"=="kp" (GOTO Case7) else (
                                if "%Choice%"=="?" (GOTO CaseHelp) else (
                                    if "%Choice%"=="c" (GOTO Case8) else (
                                        if "%Choice%"=="sl" (GOTO Case9) else (
                                            if "%Choice%"=="sf" (GOTO Case10) else (
                                                if "%Choice%"=="fz" (GOTO Case11) else (
                                                    if "%Choice%"=="dc" (GOTO Case12) else (
                                                        if "%Choice%"=="cm" (GOTO Case12) else (
                                                            if "%Choice%"=="wh" (GOTO Case13) else (
                                                                if "%Choice%"=="vs" (GOTO Case14) else (
                                                                    if "%Choice%"=="it" (GOTO Case15) else (
                                                                        if "%Choice%"=="tm" (GOTO Case16) else (
                                                                            if "%Choice%"=="d" (GOTO Case17) else (
                                                                                if "%Choice%"=="ed" (GOTO Case18) else  (
                                                                                    if "%Choice%"=="be" (GOTO Case19) else (
                                                                                        if "%Choice%"=="me" (GOTO Case20) else (
                                                                                            if "%Choice%"=="ap" (GOTO Case21) else (
                                                                                                if "%Choice%"=="pc" (GOTO Case22) else (
                                                                                                    if "%Choice%"=="sc" (GOTO Case23) else (
                                                                                                        if "%Choice%"=="c" (GOTO Case24) else (
                                                                                                            if "%Choice%"=="ll" (GOTO Case25) else (
                                                                                                                if "%Choice%"=="ij" (GOTO Case26) else (
                                                                                                                    GOTO CaseError)
                                                                                                )
                                                                                            )
                                                                                        )
                                                                                    )
                                                                                )
                                                                            )
                                                                        )
                                                                    )
                                                                )
                                                            )
                                                        )
                                                    )
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                )
            )
        )

Also, is there an alternative of using an if statement as this method is uite time consuming.

JS & Jquery: if statement run even tho the terms of the statement are not true

Im trying to make a simon game and i ran through a problem that just randomly occurred (it worked fine before), every time after the showColorStart() function executes and you click on the given color, the if statement on line 33 runs even tho colorsClicked[index] is equal to colorsPicked[index], and the statement needs to run when they are not equal. i cant find the problem, im looking through the code over and over again and cant find the problem. here's the code:

// Setting Variables
var gameStatus = false;
var strict = false;
var playerTurn = true;
var colors = ['green', 'red', 'yellow', 'blue'];
var colorsPicked = [];
var colorsClicked = [];
var level = 1;
var index = -1;
var lindex = 0;
var showOn = false;
// Game Status Function
$('#start').click(function(){
    if(gameStatus == false){
        gameStatus = true;
        gameStart();
    }
});
// Game Start Function
function gameStart(){

}
// Chaning color buttons
$('.cubes').click(function(e){
    if(playerTurn = true){
        index++;
        $(e.target).addClass(e.target.id);
        colorsClicked.push(e.target.id);
        setTimeout(function(){
            $(e.target).removeClass(e.target.id);
        }, 500);
        // Player's turn & check if got the right colors
        if(colorsClicked[index] !== colorsPicked[index]){
            index=0;
            lindex=0;
            alert('Failed! Try again.');
            showColorStart();
        } else {
            if(colorsPicked.length == colorsClicked.length){
                level++;
                randomColor();
                showColorStart();
            }
        }
    } else {
        return;
    }
});
// Random Color Picking Function
function randomColor(){
    var random = Math.floor(Math.random() * 4);
    colorsPicked.push(colors[random]);
}
// Colors Showing at Start of a level
function showColorStart(){
 if(!showOn){
    showOn == true;
    playerTurn = false;
    lindex = 0;
    var colorLoop = setInterval(function(){
        if(colorsPicked[lindex] == 'green'){
        $('#green').addClass('green');
    } else if(colorsPicked[lindex] == 'red'){
        $('#red').addClass('red');
    } else if(colorsPicked[lindex] == 'yellow'){
        $('#yellow').addClass('yellow');
    } else if(colorsPicked[lindex] == 'blue'){
        $('#blue').addClass('blue');
    }
    setTimeout(function(){
        $('#green').removeClass('green');
        $('#red').removeClass('red');
        $('#yellow').removeClass('yellow');
        $('#blue').removeClass('blue');
    }, 500);
    lindex++;
    if(lindex == colorsPicked.length){
        clearInterval(colorLoop);
        showOn = false;
        lindex = 0;
        index = 0;
        colorsClicked = [];
        $('#disp').html('Your Turn!');
        setTimeout(function(){
            $('#disp').html('');
        }, 1000);
        playerTurn = true;
    }
    }, 1500);
 } else {
     return;
 }
}
randomColor();
randomColor();
showColorStart();
<DOCTYPE html>
<html>
    <head>
        <title>Simon Game</title>
        <link href="style.css" type="text/css" rel="stylesheet"/>
        <link href='bootstrap.min.css' type="text/css"/>
    </head>
    <body>
       <div class="container">
  <div class="menu">
    <input type='button' value='Start' id='start' class='btn'>
    <input type='button' value='Restart' id='restart' class='btn'>
    <input type='button' value='Strict' id='strict' class='btn'>
  </div>
  <div class='board'>
    <div class='display'><p id='disp'></p></div>
    <br>
    <table>
      <tbody>
        <tr>
          <td class='cubes' id='green'></td>
          <td class='cubes' id='red'></td>
        </tr>
        <tr>
          <td class='cubes' id='yellow'></td>
          <td class='cubes' id='blue'></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
        <script src="http://ift.tt/2n9t8Vj"></script>
        <script src="app.js"></script>
    </body>
</html>

'else if' logical statements in gnuplot

The new gnuplot (5.x) has new syntax for logic, but I cannot get the 'else if' statement to work. For example:

if(flag==1){
plot sin(x)
}
else{
plot cos(x)
}

does work, but:

if(flag==1){
plot sin(x)
}
else if(flag==2){
plot cos(x)
}
else if(flag==3){
plot tan(x)
}

does not. I have tried many combinations of {} and placement of 'if' and 'else' to no avail. Does anyone know how to correctly implement 'else if' in gnuplot 5.x?

The gnuplot guide (http://ift.tt/2k9nAxu) has no examples of the new logic syntax using 'else if' but does have examples using the old syntax, but I would rather avoid the old.

loop back to beginning of program Java

I am new to Java, would anybody be able to give me any guidance on how I can get this program to continuously run after user input? Should i use a while loop? Many thanks!

System.out.println("Would you like to deposit or withdraw?");
Scanner user_input = new Scanner (System.in);
String transaction_type;
transaction_type = user_input.next();
String transaction;

 if (transaction_type.equals("withdraw")){
 numberOfWithdrawals++;
 System.out.println(numberOfWithdrawals);
} else if (transaction_type.equals("deposit")){
    numberOfDeposits++;
    System.out.println(numberOfDeposits);
} else if (transaction_type != "withdraw" && transaction_type != "deposit")
{
    System.out.println("Invalid input, please re-enter desired transaction");
    next = sc.nextLine();
}
}

JS if / else if / not working correctly

I am having some difficulties in getting this work, and can't figure out what is causing the issue. Basically I am checking if local storage has item 3-step, if not create it and give it the value of 1. By having the value of 1 then add class "selected" to first LI, if the value is 2 then add class "selected" to second LI, and so on - this is happening on click of buttons and it is saving the values to the local storage correctly.

However when the page is refreshed and it does the check to see which li to add the class of "selected", it does not work. Only works if the value is 1, then it will add the class to the first LI, the other LIs will not work for some reason.

 var ls;
 if( localStorage.getItem('3-step') == null ) {
    var ls = 1;
    localStorage.setItem('3-step', ls);
 } else {
    var ls = parseInt( localStorage.getItem('3-step') );
    if( ls == 1 ) {
       $('#li-one').addClass('selected');
    } else if ( ls == 2 ) {
       $('#li-two').addClass('selected');
    } else if ( ls == 3 ) {
       $('#li-three').addClass('selected');
    }
 }
.selected {
   background: red;
}
<script src="http://ift.tt/notapP"></script>
<ul id="ul">
   <li id="li-one" class="section">
      Stuff One
   </li>

   <li id="li-two" class="section">
      Stuff Two
   </li>

   <li id="li-three" class="section">
      Stuff Three
   </li>
</ul>

But in the js script during the check to see what value is in the local storage, if I make the div id all to #li-one it works. Meaning if it's –– if(ls == 3){ $('#li-one').addClass('selected') –– this works, but if it's –– if(ls == 3){ $('#li-two').addClass('selected') OR if(ls == 3){ $('#li-three').addClass('selected') –– this does not work.

ALSO, I cannot get the example here to work at all – i guess localstorage is not allowed.

Thank you so much,

Sergio

can i use case inside if statement in pascal

i want to using case on if statement, can i use it? because i always got error when i compile it ;w;

error i got : Tahun.pas(26,21) Fatal: Syntax error, ";" expected but "ELSE" found Tahun.pas(0) Fatal: Compilation aborted

here my code :

uses Crt;
var
sisa, bulan, tahun : integer;

begin
ClrScr;
writeln('masukkan tahun'); read(tahun);
sisa := tahun mod 4;
if sisa =0 then
writeln('masukkan bulan 1-12'), read(bulan);
 case bulan of
  1: write('31');
  2: write('29');
  3: write('31');
  4: write('30');
  5: write('31');
  6: write('30');
  7: write('31');
  8: write('30');
  9: write('31');
  10: write('30');
  11: write('31');
  12: write('30');
  else write('bulan tidak lebih dari 12');
end;
else
writeln('masukkan bulan 1-12'), read(bulan);
 case bulan of
  1: write('31');
  2: write('28');
  3: write('31');
  4: write('30');
  5: write('31');
  6: write('30');
  7: write('31');
  8: write('30');
  9: write('31');
  10: write('30');
  11: write('31');
  12: write('30');
else write('bulan tidak lebih dari 12')
end;
 readln;
 readln;

end.

or maybe you know how to improve the code? ;w;

Thank you for answering ;w;

C++ palindrome not working

I wanted to create function that returns true/false according if the input is a palindrome or not, when given abcddcba or aba it does not give true, but it should . plz help

bool checkPalindrome(char input[],int p=0) {
    if(input[1]=='\0'){
        return true;
    }
    if(sizeof(input)%2==0) { 
        int a = sizeof(input); 
        for(int i=0;i<(a/2);i++) {  
            if(input[0+i]==input[a-i-2]){
                p++;
            }
        }
        if(p==a/2){
            return true;
        } else{
            return false;
        }
    }
    else{
        int a = sizeof(input); 
        for(int i=0;i<((a-1)/2);i++)
        {
            if(input[0+i]==input[a-i-2]){
                p++;
            }
        }
        if(p==(a-1)/2){
            return true;
        } else{
            return false;
        }
    }
}

Does testing .includes() on flattened array before testing on various subarrays improve performance in js?

I am writing a program that checks whether particular keywords come back in a string, using .includes(). I have categorised the keywords in a json object, mostly because I want separate counts per category.

My first approach was to loop through each word in the text, and run an if-statement for each array in the keywords object. This resulted in 6 different if-statements for each word in the text, which I figured might not be very efficient, especially because many words in the text do not match any of the words in any of the keywords arrays.

I then decided to check whether it would be better to flatten my keywords object to a single array, and to check whether a word matched any of the words in the flattened array before moving on to the more specific arrays of keywords.

I have included a simplified example below:

The list of keywords:

{
  "category1": {
    "subcategory1": [
      "keyword",
      "keyword"
    ],
    "subcategory2": [
      "keyword"
    ]
  },
  "category2" : {
    "subcategory1" : [
      "keyword",
      "keyword",
      "keyword"
    ],
    "subcategory2" : [
      "keyword",
      "keyword"
    ]
  },
  "category3": [
    "keyword",
    "keyword",
    "keyword"    
  ]
}

Now, for the second approach, I flattened the json object (keywordList) to a number of arrays, then reducing it to a single array (keywordListArray) using reduce(). I then included an if-statement that would filter out any of the words that were in neither of the arrays, before executing more specific tests.

 for (let property in text) {

    if (keywordListArray.includes(property)) {
    // Will this improve performance?

        if (keywordList.category.subcategory.includes(property)) {
          result.category.subcategory ++;
        }
        if (keywordList.category.otherSubcategory.includes(property)) {
          result.category.subcategory ++;
        }

    }
  }

I then checked the execution time of each approach. I have provided a simplified example, but in my case, my keywords object consisted of 6 different array with about 10 keywords each. The input text is about 200 characters long, and will probably return some 15 matches with the keywords.

text of 200 words:

Execution time without flattened array and prior filter (approach 1): 10-12 ms Execution time with flattened array and prior filter (approach 2): 9-11 ms

I have also tested with 400 words, but there is barely any difference in execution time.

I was wondering which approach you guys would recommend, both in terms of writing 'good code' and in terms of performance?

Two assumptions to get started:

  • The more words of the text that match a keyword, the more redundant the prior filter using the flattened array.
  • The more categories (arrays) in the json object, the more if statements, and the slower the approach without prior filter.

Is this true, and do you guys expect there to be a large performance difference when employing this in a larger scale project?

Thanks in advance! Daan

To not call a function again that's already called in the 'if line' in python

enter image description here

is there any way to not call a function that's already called in the 'if line' before in Python? I think it's not that good, to call same function that's already resulted just before, I thought there must be a way to use and assign it in if line..

vendredi 29 septembre 2017

How to set variable in while loop and call it after

I am trying to modify email notification code so that when a condition is met, a variable will change.

Basically, if the last $key_row->keyVal in the loop has any upper or lower letters in the 13 character string, then it will make the server addresss variable equal to server2.domain.com. Else server address variable equals server1.domain.com . Server address variable does not exist yet and won't be used outside this area.

Thank you for any help.

    if (isset($_POST['emailcustomer']) && $_POST['emailcustomer'] == "1")
    {
        // Send email
        $to = email_sanitize($row->ordEmail);
        $subject = 'Keys';

        $message = '
        <b>Keys Order</b><br />
        Thanks for your recent order. Here are the keys that you ordered: '.$row->ordID.':<br /><br />
        ';

        while ($key_row = $key_query->fetch_object())
        {
            $message .= 'Username: ' . $key_row->keyVal . ' / Password: ' . $key_row->keyVal . ' / Expiration: ' . strtoupper(date('d-M-Y', strtotime($key_row->keyEnd))) . '<br />';
        }
$message .= '<br />     
<br />
Server Address:  server.domain.com (<---Variable Here)<br />
';

        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= 'From: ' . $from_name . ' <' . $from_email . '>' . "\r\n";

        mail($to, $subject, $message, $headers);

        print 'Email sent.';
    }

C++ Comparing consecutive integers of a string

I am writing a program to determine if a given set of integers is increasing, decreasing, or neither.

For example a string of "123456" would be increasing, and "54321" is decreasing.

My solution:

string my_str = "12345";

f = my_str.at(0);
s = my_str.at(1);
t = my_str.at(2);
l = my_str.at(3);
p = my_str.at(4);

if(f<=s<=t<=l<=p){

cout << "The string is increasing" << endl;

}

 if(f>=s>=t>=l>=p){

cout << "The string is decreasing" << endl;

}

Now I am not sure if this were even to work, but I understand the concept I am just having trouble putting this into code on C++. So is this the best way to go about it?

Edit: I understand this code is in-complete its just supposed to be a generalization to help me get a better understanding. The small code I posted prints out increasing regardless of the inputs, and it's not reading the my_str input, I had thought it would just output increasing or decreasing after running the program.

below is my code, i can't figure out why break statement is working for all cases? and not returning for new loop [duplicate]

This question already has an answer here:

import json
from difflib import get_close_matches
data= json.load(open("data.json"))
def dictionary(word):
    word=word.lower()
    if word in data:
        return data[word]
    elif len(get_close_matches(word,data.keys()))>0:
        response=input("Did you mean %s instead? If yes enter Y: "% get_close_matches(word,data.keys())[0])
        if response=='Y'or'y':
            return data[get_close_matches(word,data.keys())[0]]
    else:
        print("Word does not exist. Please double check it! ")
        return ""

while True:
    word=input("Search your word: ")
    result=(dictionary(word))
    for ans in result:
        print(ans)
    demand=input("To close type 'Y' else 'N': ")
    if demand == 'Y' or 'y':
        break

Need to add a zero in front of the minute when minute < 10 minutes Python

    if EndTimeMinute < 10:
        EndTimeMinute = EndTimeMinute 

Need to add zero here

Currently the result is just coming out as a single digit. So the time is going out to 1:1. I need to make it so that my code bring out the time as 1:01.

Unable to convert 12-hour format to 24-hour format [duplicate]

This question already has an answer here:

I am solving a question which asks to convert 12-hour time format to 24-hour format. I am using C language to implement the program.

I don't know why, but the output of my program for any input in PM is something starting from 10. For example, for input 07:03:23PM the output should be 19:03:23, but my output comes out to be 10:03:23. For input 03:03:23PM, the output should be 15:03:23, but again my output comes to be 10:03:23.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

char* timeConversion(char* s)
{
    int t,k,i=1,l;
    char* r = malloc(50 * sizeof(char));
    if(s[8]=='P')
    {
        if(s[0]!='1'&&s[1]!='2')
        {
         t = ((s[1]-'0')*1+(s[0]-'0')*10) + 12;
         sprintf(r,"%d",t);
        }
        else
            r[0]='0';r[1]='0';
        for(i=2;i<8;i++)
        {
            r[i]=s[i];
        }

    }
    else
        for(i=0;i<8;i++)
            r[i]=s[i];
    r[i]='\0';
    return r;
}

int main() {
    char* s = (char *)malloc(512000 * sizeof(char));
    scanf("%s", s);
    int result_size;
    char* result = timeConversion(s);
    printf("%s\n", result);
    return 0;
}

In timeConversion function I have allocated a memory whose base address is pointed by char pointer r. In r I store the result after the conversion. I have used sprintf() to store the value of "integer" t (which contains the value of first two digits of time after conversion to 24-hour format) into "string" r.

I have checked the program using a debugger, and after the execution of sprintf() statement, r contains value 10 even though value stored in t is 19 for the first input case.

I don't know what is causing this problem.

Re-writing from switch to if else

Need help changing this C program from switch to if or if else statements for a homework assignment. I'm new to coding so just a push in the right direction is all I need. The program is designed to read letters i.e "a/A" and then output the total number of times that letter was inputted. I just need a way to convert it from switch cases to if and if else statements.

/* Counting letter grades */

#include <stdio.h>

/* function main begins program execution */
int main( void ) 
{ 
int grade; /* one grade */
int aCount = 0; /* number of As */
int bCount = 0; /* number of Bs */ 
int cCount = 0; /* number of Cs */ 
int dCount = 0; /* number of Ds */
int fCount = 0; /* number of Fs */

printf(  "Enter the letter grades.\n"  ); 
printf(  "Enter the EOF character ('m')to end input.\n"  );

/* loop until user types 'm' */ 
while ((grade=getchar()) !='m') { 

/* determine which grade was input */
switch (grade) {  /* switch nested in while */

  case 'A':      /* grade was uppercase A */
  case 'a':      /* or lowercase a */
      ++aCount;  /* increment aCount */
      break;     /* necessary to exit switch */

  case 'B':     /* grade was uppercase B */
  case 'b':     /* or lowercase b */
      ++bCount;  /* increment bCount */
      break;     /* exit switch */

  case 'C':     /* grade was uppercase C */
  case 'c':     /* or lowercase c */
      ++cCount; /* increment cCount */
      break;    /* exit switch */

  case 'D':     /* grade was uppercase D */
  case 'd':     /* or lowercase d */
      ++dCount; /* increment dCount */
      break;    /* exit switch */

  case 'F':     /* grade was uppercase F */ 
  case 'f':     /* or lowercase f */ 
     ++fCount; /* increment fCount */
     break;    /* exit switch */

  case '\n':   /* ignore newlines, */ 
  case '\t':   /* tabs, */
  case ' ' :   /* and spaces in input */
      break;   /* exit switch */

  default:    /* catch all other characters */
     printf( "Incorrect letter grade entered." );
     printf( " Enter a new grade.\n" );
      break;  /* optional; will exit switch anyway */
  }         /* end switch */ 
}           /* end while */

/* output summary of results */
 printf( "\nTotals for each letter grade are:\n" );
 printf( "A: %d\n", aCount ); /* display number of A grades */
 printf( "B: %d\n", bCount ); /* display number of B grades */
 printf( "C: %d\n", cCount ); /* display number of C grades */
 printf( "D: %d\n", dCount ); /* display number of D grades */
 printf( "F: %d\n", fCount ); /* display number of F grades */ 
 return 0; /* indicate program ended successfully */ 
} /* end function main */

Assigning variables a new value under a different method Java

I'm pretty new to programming and I was assigned a code where I have to deal 6 random numbers from 1 to 52 to three different players(objects). These numbers need to be transformed to their card values from 1 to 13 afterwards.

After generating the first hand (1 to 52 random values) I used another similar method to assign the new values (1-13) but whenever I go ahead and try to perform another action with them I get the same value from the first set assigned (1-52)

Here's my code so far

public void seleccionarCartas(){ //Selects an initial value for the cards
        c1 = mazo[random.nextInt(mazo.length)];
        c2 = mazo[random.nextInt(mazo.length)];
        c3 = mazo[random.nextInt(mazo.length)];
        c4 = mazo[random.nextInt(mazo.length)];
        c5 = mazo[random.nextInt(mazo.length)];
        c6 = mazo[random.nextInt(mazo.length)];
        }


        public void crearMano(){ //verifies that the card values are not repeated

        if (c1==c2) {
            c1 = mazo[random.nextInt(mazo.length)]; 
            System.out.println(c1);
        } else if (c1==c3){
            c1 = mazo[random.nextInt(mazo.length)];
            System.out.println(c1);
        } else if (c1 == c4){
            c1 = mazo[random.nextInt(mazo.length)];
            System.out.println(c1);
        } else if (c1==c5) {
            c1 = mazo[random.nextInt(mazo.length)];
            System.out.println(c1);
        } else if (c1==c6){
            c1 = mazo[random.nextInt(mazo.length)];
            System.out.println(c1);
        } else {
            System.out.println(c1);
        }

        if (c2==c1) {
            c2 = mazo[random.nextInt(mazo.length)];
            System.out.println(c2);
        } else if (c2==c3){
            c2 = mazo[random.nextInt(mazo.length)];
            System.out.println(c2);
        } else if (c2 == c4){
            c2 = mazo[random.nextInt(mazo.length)];
            System.out.println(c2);
        } else if (c2==c5) {
            c2 = mazo[random.nextInt(mazo.length)];
            System.out.println(c2);
        } else if (c2==c6){
            c2 = mazo[random.nextInt(mazo.length)];
            System.out.println(c2);
        } else{
            System.out.println(c2);
        }

        if (c3==c2) {
            c3 = mazo[random.nextInt(mazo.length)];
            System.out.println(c3);
        } else if (c3==c1){
            c3 = mazo[random.nextInt(mazo.length)];
            System.out.println(c3);
        } else if (c3 == c4){
            c3 = mazo[random.nextInt(mazo.length)];
            System.out.println(c3);
        } else if (c3==c5) {
            c3 = mazo[random.nextInt(mazo.length)];
            System.out.println(c3);
        } else if (c3==c6){
            c3 = mazo[random.nextInt(mazo.length)];
            System.out.println(c3);
        } else {
            System.out.println(c3);
        }

        if (c4==c2) {
            c4 = mazo[random.nextInt(mazo.length)];
            System.out.println(c4);
        } else if (c4==c3){
            c4 = mazo[random.nextInt(mazo.length)];
            System.out.println(c4);
        } else if (c4 == c1){
            c4 = mazo[random.nextInt(mazo.length)];
            System.out.println(c4);
        } else if (c4==c5) {
            c4 = mazo[random.nextInt(mazo.length)];
            System.out.println(c4);
        } else if (c4==c6){
            c4 = mazo[random.nextInt(mazo.length)];
            System.out.println(c4);
        } else {
            System.out.println(c4);
        }


        if (c5==c2) {
            c5 = mazo[random.nextInt(mazo.length)];
            System.out.println(c5);
        } else if (c5==c3){
            c5 = mazo[random.nextInt(mazo.length)];
            System.out.println(c5);
        } else if (c5 == c4){
            c5 = mazo[random.nextInt(mazo.length)];
            System.out.println(c5);
        } else if (c5==c1) {
            c5 = mazo[random.nextInt(mazo.length)];
            System.out.println(c5);
        } else if (c5==c6){
            c5 = mazo[random.nextInt(mazo.length)];
            System.out.println(c5);
        } else {
            System.out.println(c5);
        }


        if (c6==c2) {
            c6 = mazo[random.nextInt(mazo.length)];
            System.out.println(c6);
        } else if (c6==c3){
            c6 = mazo[random.nextInt(mazo.length)];
            System.out.println(c6);
        } else if (c6 == c4){
            c6 = mazo[random.nextInt(mazo.length)];
            System.out.println(c6);
        } else if (c6==c5) {
            c6 = mazo[random.nextInt(mazo.length)];
            System.out.println(c6);
        } else if (c6==c1){
            c6 = mazo[random.nextInt(mazo.length)];
            System.out.println(c6);     
        } else {
            System.out.println(c6);
        }

        }



        public void asignarValores(){ //supposed to assign the new value to the variable, but it prints/uses the previous one
            if (c1==1 && c1==14 && c1==27 && c1==40){
                c1 = 1;
            } else if (c1==2 && c1==15 && c1==28 && c1==41){
                c1 = 2;
            } else if (c1==3 && c1==16 && c1== 29 && c1 ==42){
                c1 = 3;
            } else if (c1==4 && c1==17 && c1== 30 && c1 ==43){
                c1 = 4;
            } else if (c1==5 && c1==18 && c1== 31 && c1 ==44){
                c1 = 5;
            } else if (c1==6 && c1==19 && c1== 32 && c1 ==45){
                c1 = 6;
            } else if (c1==7 && c1==20 && c1== 33 && c1 ==46){
                c1 = 7;
            } else if (c1==8 && c1==21 && c1== 34 && c1 ==47){
                c1 = 8;
            } else if (c1==9 && c1==22 && c1== 35 && c1 ==48){
                c1 = 9;
            } else if (c1==10 && c1==23 && c1== 36 && c1 ==49){
                c1 = 10;
            } else if (c1==11 && c1==24 && c1== 37 && c1 ==50){
                c1 = 11;
            } else if (c1==12 && c1==25 && c1== 38 && c1 ==51){
                c1 = 12;
            } else if (c1==13 && c1==26 && c1== 39 && c1 ==52){
                c1 = 13;
            }



            if (c2==1 && c2==14 && c2==27 && c2==40){
                c2 = 1;
            } else if (c2==2 && c2==15 && c2==28 && c2==41){
                c2 = 2;
            } else if (c2==3 && c2==16 && c2== 29 && c2 ==42){
                c2 = 3;
            } else if (c2==4 && c2==17 && c2== 30 && c2 ==43){
                c2 = 4;
            } else if (c2==5 && c2==18 && c2== 31 && c2 ==44){
                c2 = 5;
            } else if (c2==6 && c2==19 && c2== 32 && c2 ==45){
                c2 = 6;
            } else if (c2==7 && c2==20 && c2== 33 && c2 ==46){
                c2 = 7;
            } else if (c2==8 && c2==21 && c2== 34 && c2 ==47){
                c2 = 8;
            } else if (c2==9 && c2==22 && c2== 35 && c2 ==48){
                c2 = 9;
            } else if (c2==10 && c2==23 && c2== 36 && c2 ==49){
                c2 = 10;
            } else if (c2==11 && c2==24 && c2== 37 && c2 ==50){
                c2 = 11;
            } else if (c2==12 && c2==25 && c2== 38 && c2 ==51){
                c2 = 12;
            } else if (c2==13 && c2==26 && c2== 39 && c2 ==52){
                c2 = 13;    
            }   

            if (c3==1 && c3==14 && c3==27 && c3==40){
                c3 = 1;
            } else if (c3==2 && c3==15 && c3==28 && c3==41){
                c3 = 2;
            } else if (c3==3 && c3==16 && c3== 29 && c3 ==42){
                c3 = 3;
            } else if (c3==4 && c3==17 && c3== 30 && c3 ==43){
                c3 = 4;
            } else if (c3==5 && c3==18 && c3== 31 && c3 ==44){
                c3 = 5;
            } else if (c3==6 && c3==19 && c3== 32 && c3 ==45){
                c3 = 6;
            } else if (c3==7 && c3==20 && c3== 33 && c3 ==46){
                c3 = 7;
            } else if (c3==8 && c3==21 && c3== 34 && c3 ==47){
                c3 = 8;
            } else if (c3==9 && c3==22 && c3== 35 && c3 ==48){
                c3 = 9;
            } else if (c3==10 && c3==23 && c3== 36 && c3 ==49){
                c3 = 10;
            } else if (c3==11 && c3==24 && c3== 37 && c3 ==50){
                c3 = 11;
            } else if (c3==12 && c3==25 && c3== 38 && c3 ==51){
                c3 = 12;
            } else if (c3==13 && c3==26 && c3== 39 && c3 ==52){
                c3 = 13;    
            }       

            if (c4==1 && c4==14 && c4==27 && c4==40){
                c4 = 1;
            } else if (c4==2 && c4==15 && c4==28 && c4==41){
                c4 = 2;
            } else if (c4==3 && c4==16 && c4== 29 && c4 ==42){
                c4 = 3;
            } else if (c4==4 && c4==17 && c4== 30 && c4 ==43){
                c4 = 4;
            } else if (c4==5 && c4==18 && c4== 31 && c4 ==44){
                c4 = 5;
            } else if (c4==6 && c4==19 && c4== 32 && c4 ==45){
                c4 = 6;
            } else if (c4==7 && c4==20 && c4== 33 && c4 ==46){
                c4 = 7;
            } else if (c4==8 && c4==21 && c4== 34 && c4 ==47){
                c4 = 8;
            } else if (c4==9 && c4==22 && c4== 35 && c4 ==48){
                c4 = 9;
            } else if (c4==10 && c4==23 && c4== 36 && c4 ==49){
                c4 = 10;
            } else if (c4==11 && c4==24 && c4== 37 && c4 ==50){
                c4 = 11;
            } else if (c4==12 && c4==25 && c4== 38 && c4 ==51){
                c4 = 12;
            } else if (c4==13 && c4==26 && c4== 39 && c4 ==52){
                c4 = 13;    
            }   

            if (c5==1 && c5==14 && c5==27 && c5==40){
                c5 = 1;
            } else if (c5==2 && c5==15 && c5==28 && c5==41){
                c5 = 2;
            } else if (c5==3 && c5==16 && c5== 29 && c5 ==42){
                c5 = 3;
            } else if (c5==4 && c5==17 && c5== 30 && c5 ==43){
                c5 = 4;
            } else if (c5==5 && c5==18 && c5== 31 && c5 ==44){
                c5 = 5;
            } else if (c5==6 && c5==19 && c5== 32 && c5 ==45){
                c5 = 6;
            } else if (c5==7 && c5==20 && c5== 33 && c5 ==46){
                c5 = 7;
            } else if (c5==8 && c5==21 && c5== 34 && c5 ==47){
                c5 = 8;
            } else if (c5==9 && c5==22 && c5== 35 && c5 ==48){
                c5 = 9;
            } else if (c5==10 && c5==23 && c5== 36 && c5 ==49){
                c5 = 10;
            } else if (c5==11 && c5==24 && c5== 37 && c5 ==50){
                c5 = 11;
            } else if (c5==12 && c5==25 && c5== 38 && c5 ==51){
                c5 = 12;
            } else if (c5==13 && c5==26 && c5== 39 && c5 ==52){
                c5 = 13;    
            }   

            if (c6==1 && c6==14 && c6==27 && c6==40){
                c6 = 1;
            } else if (c6==2 && c6==15 && c6==28 && c6==41){
                c6 = 2;
            } else if (c6==3 && c6==16 && c6== 29 && c6 ==42){
                c6 = 3;
            } else if (c6==4 && c6==17 && c6== 30 && c6 ==43){
                c6 = 4;
            } else if (c6==5 && c6==18 && c6== 31 && c6 ==44){
                c6 = 5;
            } else if (c6==6 && c6==19 && c6== 32 && c6 ==45){
                c6 = 6;
            } else if (c6==7 && c6==20 && c6== 33 && c6 ==46){
                c6 = 7;
            } else if (c6==8 && c6==21 && c6== 34 && c6 ==47){
                c6 = 8;
            } else if (c6==9 && c6==22 && c6== 35 && c6 ==48){
                c6 = 9;
            } else if (c6==10 && c6==23 && c6== 36 && c6 ==49){
                c6 = 10;
            } else if (c6==11 && c6==24 && c6== 37 && c6 ==50){
                c6 = 11;
            } else if (c6==12 && c6==25 && c6== 38 && c6 ==51){
                c6 = 12;
            } else if (c6==13 && c6==26 && c6== 39 && c6 ==52){
                c6 = 13;    
            }

        }   

Pandas Conditional Drop

I'm trying to conditionally drop rows out of a pandas dataframe, using syntax as such:

if ((df['Column_1'] == 'value_1') & (df['Column_2'] == 'value_2')):
    df['Columns_3'] == df['Column_4']
else:
    df.drop()

Thanks in advance for the help.

Is there any way to take information from strings and take them into another string?

I'm wondering if it is possible to take information from strings and get it into another string as described below:

So i have 2 modes for my application. Good against and Bad against.

These are few of string i have.

        String[] abaddon = {"abaddon", "abba","lord of avernus"};
        String[] ancientapparation = { "ancient apparition", "aa", "kaldr"};

And then I have mode 1 which i have writen out what it should write so for example

if user writes "abaddon" it will get thrown as a string and then looked for in the mode one which will find it

       else if (abaddon.Contains(vyberlow))
        {
            counter = (lina[0] +"\n" + lion[0] +"\n" + undying[0] +"\n" +outworlddestroyer[0] +"\n" + slark[0] +"\n" + axe[0] +"\n" + doombringer[0]+"\n" + ancientapparation[0]+"\n" +shadowdemon[0]+"\n");
            Console.WriteLine("\nAbaddon je slaby proti: \n\n" + counter);
        }

And there are another strings for the heroes and I need to do that mode 2 takes information from here so when user selects mode 2 and writes "lion" it will write out abaddon + others it took from all these "else ifs". Since I have about 114 different strings and I wanna use the information I already wrote for the mode 1.

I hope it makes any sense and I'm grateful for any reply.

If statement issue with Char * when trying to get OpenCL gpu device types

Ive been trying to verify which OpenCL platform amd gpu`s are located in, and at the same time count if there are more than one amd gpu on the system. I can get all visible outputs but im having a hard time using if statements to check if the displayed card actually are a advanced micro devices unit, i hope anyone can help me out a little here. Here is the current code:

if (listdevices)
{
    int i, j;
    char* value;
    char* ellesmere = "Ellesmere";
    char* valuemodel;
    char* amdman1 = "Advanced Micro Devices, Inc.";
    char* amdman2 = "Advanced Micro Devices, Inc";
    char* amdman3 = "AMD";
    char* amdman4 = "Advanced Micro Devices, Inc. ";
    char* value2;
    size_t valueSize;
    cl_uint platformCount;
    cl_platform_id* platforms;
    cl_device_type device_type;
    cl_uint deviceCount;
    cl_device_id* devices;
    cl_uint maxComputeUnits;
    cl_uint globalMemsize;
    uint64_t gpus = 0;
    bool amdplatformlocated = false;
    uint64_t amdplatform;
    uint64_t currentplatform;
    uint64_t countamd;

    // get all platforms
    clGetPlatformIDs(0, NULL, &platformCount);
    platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id) * platformCount);
    clGetPlatformIDs(platformCount, platforms, NULL);

    for (i = 0; i < platformCount; i++) {
        printf("\n\nPlatform-index: %d: \n\n", i);
        currentplatform = i;

        // get all devices
        clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, 0, NULL, &deviceCount);
        devices = (cl_device_id*)malloc(sizeof(cl_device_id) * deviceCount);
        clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, deviceCount, devices, NULL);

        // for each device print critical attributes
        for (j = 0; j < deviceCount; j++) {

            gpus++;

            // print device info & check if AMD model
            clGetDeviceInfo(devices[j], CL_DEVICE_NAME, 0, NULL, &valueSize);
            value = (char*)malloc(valueSize);
            clGetDeviceInfo(devices[j], CL_DEVICE_NAME, valueSize, value, NULL);
            printf(" %d. Device: %s.\n", j + 1, value);
            if (value == ellesmere) {
                amdplatformlocated = true;
                amdplatform = currentplatform;
                printf(" %d.%d Located AMD Device: %s\n", j + 1, 2, amdplatformlocated);
            }
            free(value);

            // print manufacturer info & check if AMD
            clGetDeviceInfo(devices[j], CL_DEVICE_VENDOR, 0, NULL, &valueSize);
            value = (char*)malloc(valueSize);
            clGetDeviceInfo(devices[j], CL_DEVICE_VENDOR, valueSize, value, NULL);
            clGetDeviceInfo(devices[j], CL_DEVICE_VENDOR, valueSize, value2, NULL);
            printf(" %d.%d Vendor: %s\n", j + 1, 1, value);
            if (value2 == amdman1 || value2 == amdman2 || value2 == amdman3 || value2 == amdman4) {
                amdplatformlocated = 1;
                amdplatform = currentplatform;
                printf(" %d.%d Located AMD Device: %s\n", j + 1, 2, amdplatformlocated);
                countamd++;
            }
            free(value);

            // print hardware device version
            clGetDeviceInfo(devices[j], CL_DEVICE_VERSION, 0, NULL, &valueSize);
            value = (char*)malloc(valueSize);
            clGetDeviceInfo(devices[j], CL_DEVICE_VERSION, valueSize, value, NULL);
            printf(" %d.%d Hardware version: %s\n", j + 1, 2, value);
            free(value);

            // print software driver version
            clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, 0, NULL, &valueSize);
            value = (char*)malloc(valueSize);
            clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, valueSize, value, NULL);
            printf(" %d.%d Software version: %s\n", j + 1, 3, value);
            free(value);

            // print c version supported by compiler for device
            clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, 0, NULL, &valueSize);
            value = (char*)malloc(valueSize);
            clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, valueSize, value, NULL);
            printf(" %d.%d OpenCL C version: %s\n", j + 1, 4, value);
            free(value);

            // print parallel compute units
            clGetDeviceInfo(devices[j], CL_DEVICE_MAX_COMPUTE_UNITS,
                sizeof(maxComputeUnits), &maxComputeUnits, NULL);
            printf(" %d.%d Parallel compute units: %d\n", j + 1, 5, maxComputeUnits);
        }

        free(devices);

    }

    printf("\nWe have registered %d GPU`s on your System\n", gpus);
    if (amdplatformlocated == 1) {
        printf("It seems that platform %d contains AMD GPU`s., amdplatform);
    }
    else {
        printf("\nDid you find your AMD Card on this list?\n");
    }

    free(platforms);
    win_exit();
    return 0;
}

Which currently on a AMD RX570 Card gives this output:

> Platform-index: 0:
> 
> 
> 
> Platform-index: 1:
> 
>  1. Device: Ellesmere.
>  1.1 Vendor: Advanced Micro Devices, Inc.
>  1.2 Hardware version: OpenCL 2.0 AMD-APP (2442.12)
>  1.3 Software version: 2442.12
>  1.4 OpenCL C version: OpenCL C 2.0
>  1.5 Parallel compute units: 32
>  1.6 Maximum Memory Size:

We have registered 1 GPU`s on your System

Did you find your AMD Card on this list?

if (value == ellesmere) does not work neither do those in vendor section. Why is this? Both are current char * and if i make a simple code to compare those two it works, what am i not seeing?

Thanks

New to python having trouble with if and numbers

The assignment that i need to do is make a code in python that accepts three numbers from a user and displays a message if the sum of any two numbers equals the third.

this is my pseudcode is

start

input num1, num2, num3

if (num1 + num2 = num3) or (num1 + num3 = num3) or (num2 + num3 = num1) then

output "some of any two numbers is equal to the third"

end if

stop

this is my code so far not sure how to do the if part

num1 = input("Enter number 1: ")
num2 = input("Enter number 2: ")
num3 = input("Enter number 3: ")
num1 = int(num1)
num2 = int(num2)
num3 = int(num3)
if num1 + num2 == num3

Python - how to get this condition to work in one line:

Here is the condition:

if not (hasattr(link, "class") and 'gen' in link.parent.get('class')):

The thing is sometimes link has no class attribute so I get:

TypeError: argument of type 'NoneType' is not iterable

Is there anyway I manage this condition to work without adding extra ifs?

Edited: Thanks to John Gordon now I know that I can use get('class', []) and my problem is fixed. But I'm still curious if it was any other way. I mean, what if this solution was not possible, is it possible to get this to work by somehow changing the order of statements or somehow teach if to not go for further if hasattr(link, "class") is false?

Pseudocode elseifs syntax

In pseudocode, is it more better to be indenting 'else if' statements almost as though the 'if' part is nested within the 'else' part?

As you see here, I feel like the 3rd/5th/7th line of code should not be indented, but instead at the same level as the 'if' statement. Is it true that these 'if' part should be nested within the preceding "else" part? If so, why aren't there more 'End if' statements, surely there wouldn't be one 'End if' which closes 3 'if' statements.

Here is an example from php code (random language, this following concept applies to any other language anyways):

example php code

As you see here, the elseif statements are not 'nested' - as if the 'elseif' statement are two separate statements but the 'elseif' is instead, one coherent statement. This 'elseif' does indeed have the same meaning as an 'if' nested within an 'else' yes, however, surely that does not mean the 'else if' statements should be nested within the previous 'else if' (refer back to 1st screenshot).

In pseudo-code, which style of indentation is correct in syntax and is more readable to other programmers?

else statement with no if condition isn't default [duplicate]

This question already has an answer here:

public int compareTo(Tool b)
{
    if(cost > b.cost)
        return 1;
    else if(cost == b.cost)
    {
        if(name.compareTo(b.name) < 0)
            return 1;
        else if(name.compareTo(b.name) == 0)
            return 0;
        else if(name.compareTo(b.name) > 0)
            return -1;
    }
    else
        return -1;
}

NetBeans gives an error at the last brace because "missing return statement". This is solved if I remove the "else", but shouldn't return -1 be the default codepath?

How to figure out future date in java

I have a assignment to do that calls for a user picking a date from 0-6 (zero being Sunday, 1 is Monday, and 6 is Saturday. etc) and then they pick a number of days that elapsed from that day. For example if the user put in today was 3 (which is Wednesday) and 2 days elapsed which makes it Friday I do not understand how to code that or figure out an equation to apply the elapsed days to the 0-6 week. If someone was to enter in 15 instead of a small number I would know what day that would be in my head from simple addition but I cant transfer that to my code.

Note: I am importing Scanner class for the user input.

jquery click conditional statement based on selector top position

I am attempting to create my very first jQuery post slider.

The slider has previous and next buttons which offset the top position of the div containing all the post items. ie. increments or decrements the top position value by the '.post-item' height.

I am facing difficulty with a conditional statement to disable the previous and next buttons based on the value of the CSS top property of the div. For example, disable previous button if top position > 0

I am new to programming and I was hoping to learn by others examples pertaining to my situation, to better grasp the concepts. Any help and guidance on how to best achieve this would be a huge help for me. At the bottom of the post I have included my rather embarrassing progress on one of my attempts.

JavaScript Source

(function ($) {
    $(document).ready(function () {

        $('.prev-btn').click(function () {
                $(".posts-body").animate({
                    top: "+=142"
                }, {"duration": 400, "easing": "easeOutBack"});

        });

        $('.next-btn').click(function () {
            $(".posts-body").animate({
                top: "-=142"
            }, {"duration": 400, "easing": "easeOutBack"});
        });
    });
})(jQuery);

HTML Markup

<div class="buttons">
    <span class="prev-btn ">Up</span>
    <span class="next-btn ">Down</span>
</div>
<div class="post-slider">
    <div class="posts-body">
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
    </div>
</div>

Failed Attempt

(function ($) {
        $(document).ready(function () {
            $('.prev-btn').click(function () {
                var selector = document.querySelector(".posts-body");
                var offset = selector.offsetTop;

                if (selector.css("top") > 0) {
                    $(".posts-body").animate({
                        top: "+=142"
                    }, {"duration": 400, "easing": "easeOutBack"});
                }
                console.log(offset);

            });

            $('.next-btn').click(function () {

                var selector = document.querySelector(".posts-body");
                var offset = selector.offsetTop;

                $(".posts-body").animate({
                    top: "-=142"
                }, {"duration": 400, "easing": "easeOutBack"});

                console.log(offset);
            });
        });
    })(jQuery);

Thanking you very much for your time and help.

What is the correct approach to use if in this situation?

I didn't find an answer that satisfies me about this newbie javascript (using jQuery) question...

I have these 2 codes inside a document ready...

CODE 1

$('myElement').click(function(){
     if(isMobile()){
         //do something...
     }
});

CODE 2

if(isMobile()){
    $('myElement').click(function(){
       // do somthing...
    });
}

What is the correct approach and why?

Thanks guys

Is using 'like' a possibility in TestComplete?

How do I write an if statement that searches for a similarity, rather than a direct result?

For example, I want to search for labels that begin with ABC:

if(label == 'ABC') //but I have two other labels: 'ABC1' and 'ABC2'

Is there a way to do something like: (if label like 'ABC'), instead of three separate if statements? I know I could else if() if I need to, but I want to avoid hard coding labels since they can be added, deleted, updated, etc.

Thank you.

Countifs and ranges

I'm trying to write some code that requires a cell value to be within a range of dates. This is what I have written so far (albeit a few name changes for simplicity):

=IF(COUNTIFS('[SheetA.xlsx]TabA'!A2:AA2, "submit", '[SheetA.xlsx]TabA'!B2:AB2, '[SheetA.xlsx]TabB'!A9:A13) >= 1, '[SheetA.xlsx]TabA'!C2, "")

Basically, if a cell in a row contains the word "submit" AND the cell to the right of it has a date (within a specific range of five days), I'd like the function to return the third cell of that row.

The range in bold is a range of dates.

This formula doesn't work when I use a range, but returns expected values when I enter a single date. What should I change?

Excel If formula with OR, avoiding #N/A

Currently facing a problem, long story short: I'm trying to combine 2 formulas into one, by making use of the OR-function, but if one of the 2 conditions does not exist, it gives me an #N/A back. There's 3 conditions that can happen: "MTI", "MTI Z" and "MTO". What I would like is that the formula searches for any combination in column L with either "MTI" or "MTI Z" (might also be both) and if that combination exists, give back a 1. If not (so only MTO exists) then return a 0 (in this case it will be an #N/A, but I can fix that with either ISNA or IFERROR).

Formula 1 is:

=IF(CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0),1,0)

Formula 2 is

=IF(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0),1,0)

Both formulas work, giving back a "1" when there is respectively a "MTI" or "MTI Z"

However, when I try to combine them, if 1 of the 2 does not exist in the list, it gives me an #N/A, even though I'm using OR (which would state if at least 1 of the 2 exists, go ahead).

=IF(OR(CONCATENATE(A2,B2,"MTI Z")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI Z"),L:L,0),0)
,CONCATENATE(A2,B2,"MTI")=INDEX(L:L,MATCH(CONCATENATE(A2,B2,"MTI"),L:L,0),0)),1,0)

How can I adjust my formula so that it does work?

Google Script Custom Function simple IF statement not working

I am new to Google Scripts. I have created a custom function script in my Google Sheets spreadsheet. I know the process works because I have see the data being passed to the function and data being returned.

The problem that I have is with the IF statement. It is not finding "yes" even though there are multiple "yes" 's in the column. They all fail to the else. I even tried it with just the IF and no else but not seeing any "hello"'s.

So can you help me understand why this IF would not work? Why return input is returning the sent text but when inside the function it can't seem to qualify it?

Thank you for any help you can provide.

function DOUBLE(input) {

if (input == "yes") {
return "hello";

} else {

   return input;

}

}

Ruby: Use Date.Parse to determine if date is erroneous

I have test file that has a list of tests to run on my other file which demand an assert for an erroneous date

require "minitest/autorun"
require "./simple_date"

describe SimpleDate do
  it "works as expected" do
    assert_raises { SimpleDate.new(1969, 12, 31) }
    assert_raises { SimpleDate.new(2016, 1, 32) }
    assert_raises { SimpleDate.new(2016, 2, 30) }
    assert_raises { SimpleDate.new(2016, 3, 32) }
    assert_raises { SimpleDate.new(2016, 4, 31) }
    # ... there are more this is just a sample
  end

This part of my other file works:

require 'date'

class SimpleDate
  attr_reader :year, :month, :day
  def initialize(year, month, day) 
    if !year.between?(1970, 2020)
      raise 'Error: Year not betwen 1970 and 2020'
    elsif !month.between(1, 12)
      raise 'Error: Month not between 1 and 12'
    elsif !day.between?(1, 31)
      raise 'Error: Day not between 1 and 31'
    end    

This part of my other file does not work.

begin
  Date.parse(year, month, day)
rescue
  raise 'Date Format Error'
end

Can you please help me better format my second part so that it will pass the tests?

Python - Requests - If-Else statement prints out strangely?

So I have been playing around abit with request and it went good until I started to play around with "errors" which I mean if there is no name then it should print out no name..

However I come to this problem that whenever there is no name I get a traceback and also a really strange out prints which I can't find the logic of it.

As you can see below I have given exempels on what the program does with different code...

Input:

r = s.get(Url)
names = soup(r.text, 'html.parser')
findName = names.find('div', {'class':'nameslist'})

 if (r.status_code == 200):
    for name in names.find_all('option'):

        global nameID
        if myName == foundName:
            nameID = name.get('value')
            print('Profile-1 Found name')
        else:
            print("Did not find name")

    if (findName != None):
            notepresent = True
            print('There is a value')
        else:
            global addtonotes
            notepresent = False
            addtonotes = {'id': nameID}
            add2notes(addtonotes)   

Output:

Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Process Process-2:
Traceback (most recent call last):
  File "C:\Python\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Python\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Test.py", line 153
     addtonotes = {'id': nameID}
NameError: name 'nameID' is not defined
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name
Profile-1 Found name
Did not find name
Did not find name
Did not find name
Did not find name
Did not find name

but then if i add sys.exit on

else:
            print("Did not find name")
            sys.exit()

then it will just say

Did not find name
Did not find name

even though the first one do find a name so it will just exit and say both are not finding...

BUT if I remove the else statement

then it will just give me the trackback meanwhile the Profile-1 prints out the same say.

As you can see what I want is if there is no name then it should just print out Did not find name once and then just sys.exit from there (Using multi-processing so the whole program wont end).

So I quite cant understand what is going on.. Maybe someone does find the issue?

My wish print is:

(If it finds name)

profile-1 find name <---- Profile 1 etc
Did not find name  <--- Profile 2 etc

and then continue the code.

What could possible go wrong? (Feel free to comment if anything missing or missunderstood)

Mini boss fight game

I wrote this code which subtracts a random number from (1, 20) from a variable newhealth. But it only does this once, how can I use the new health and run it though the program again till newhealth is equal to 0?

import random

i = random.randrange(1,20)

a = input("do you want to damage the boss (y/n): ")

bosshealth = 100
newhealth = bosshealth - i


if (a == "y"):
    print("You deal {} damage, the new health is {}".format(i, newhealth))
elif (a == "n"):
    print("You do nothing..")
else:
    print("cant you ready?")

Performing a task based in specific time interval in python

I am trying to switch on and off the LED based on a set set_car_id returning some value within a time interval. If the set returns some value, i want the LED to be brighter for 8 seconds. In the code shown below, once the set returns a value, the LED is switched on for 8 seconds. But, if the set returns a value at 5 second (within the 8 sec), then the LED won't be switched on till next 13 sec, it will be on for 3 more seconds and then suddenly switches off. I am showing only smaller part of the code. Any suggestions to solve?

last_bright_time = None            
last_dim_time = None
new_action = -1
def LED_control(set_car_id):
    global last_bright_time
    global last_dim_time
    curr_time = time.time()
    should_remain_bright = False
    should_remain_dim = False
    if (new_action == 0):      #new_action ==0 corresponds to set_car_id returning some value
        if last_bright_time == None:
            last_bright_time = time.time()
        if  (curr_time - last_bright_time) < 8:
        should_remain_bright = True
    if  ((len(set_car_id) > 0) or should_remain_bright = True):
        car_light(1)                # function to bright the LED
        last_dim_time = None
    else:
         car_light(0)               # function to dim the LED
         last_bright_time = None

Use If inside a Select - Where

I was wondering: Is it possible to use an IF statement inside a WHERE clause for a SELECT? Here's a sample:

SELECT var1, var2, .. AS name
FROM table1 C, table2 F, table3 D,.. 
WHERE C.id = f.id, AND ..
AND (IF expression THEN F.num <0; -- <-- is this possible?
     ELSE F.num >0);

Thanks in advance

Can multiple if statements be used in a for loop?

Is there a way to make a for loop iterate a list of strings by using some multiple conditions?. I am trying to build a for loop which should iterate each element of a list made of strings, but it looks like my for loop doesn't operate each condition to each iterable of my list.

For instance,

I have many strings which differs due to their own contents, E.g(DNA has 'T' instead of 'U', RNA has 'U' instead of 'T' and an unknow (UNK) which has neither 'T' nor 'U' or any other characters.

The input is ['tacaactgatcatt', 'aagggcagccugggau','gaaaaggcaggcg','guaccaguuu'.'acggggaccgac'] The output should be the type of DNA sequence:

Result: DNA, RNA, UNK, RNA, UNK

I think my mistake is due to a misuse of break sentences in a for loop, but I can't figure out how to fix it.

This is what I get so far:

seq = list(input('Enter your sequence:').upper())

for obj in seq:
    if 'U' not in obj and 'T' in obj:
        print('Result: DNA')
        break


    if 'U' in obj and 'T' not in obj:
       print('Result: RNA')
       break


else:
    print('Result: UNK')

Short Hand JavaScript IF Else

I have this shorthand version of a JavaScript if else function and I am wondering how would it look if it was normal if else:

var criteriaField = criteria.hasOwnProperty('searchTerm') ? 'name': 'price';

What is the best/idioms way in python to handle series of function check

I would like to ask what's the best/idioms way in python to handle this type of code logic.

list_a = []

def func_a():
  if some check not pass
     return False

  # check pass
  add some stuff to list_a and return True

def func_b():
  if some check not pass
     return False

  # check pass
  add some stuff to list_a and return True

def func_c():
  if some check not pass
     return False

  # check pass
  add some stuff to list_a and return True

def apply_function():
  if fun_a():
     return list_a
  if fun_b():
     return list_a
  if fun_c():
     return list_a
  ...

  return list_a   #empty list

If there are more than 10 functions need to check in apply_function(), is there any better way to handle?

This maybe work for me

If funcA() or funcB() or funcC():
  return list_a

return list_a

Does any() can be use in this situation?

Thanks.

If/Else Statements in C are not working

Working on a basic computer science project for class and am stuck on this issue. I am experienced in Java but am just beginning in C language. It seems to simply skip over my if/else statement as if it were not there, could someone help me understand this?

#include <stdio.h>
int main()
{
        //Systems Programming: Project3 - Justus Milhon
        //Requests User Input
        printf("Enter temparature in Farenheit (int up to 3 digits): ");

        //Names and scans in Farenheit value
        float fare;
        scanf("%f", &fare);

        //Declares and calculates Celcius value
        float celc;
        celc = 5.0 / 9.0 * ( fare - 32 );

        //Determines approptiate description (if/else system)
        char desc[50] =  "if statement is not running :( "; 
        if(fare == -40){
            char desc[50] = "Ouch! Cold either way!!";
        }
        else if(fare == 32){
            char desc[50] = "Freezing point of water";
        }
        else if(fare == 70){
            char desc[50] = "Room temperature";
        }
        else if(fare == 99){
            char desc[50] = "Average body temperature";
        }
        else if(fare == 212){
            char desc[50] = "Boiling point of water";
        }
        else{
            char desc[50] = "final else stetement is being used :(";
        }

        //Prints output
        printf("Farenheit          Celsius          Description\n----------        
        ----------         ----------\n%.0f                 %.3f        
        %s\n", fare, celc, desc);
        return 0;
}

Removing file using name contains in Ruby

I have written the below code to keep a file that matches the passed in name and removes the rest of the files in the folder.

def removeFiles2(path, namePart)
aft_logger=AFTLogger.new

Dir[path+'/*'].each do |fname|
    break if !(fname.include? namePart)
    else File.delete(fname)
 end
end

end end

But I am getting the below error.

Operation not permitted - Operation not permitted - //CSLK-CISP-81-01/jboss/server/TeamCI_CEPHEUS_OR_R81_Spider_110/home/RoSModule/XML/In/Error: 
Operation not permitted - Operation not permitted - //CSLK-CISP-81-
01/jboss/server/TeamCI_CEPHEUS_OR_R81_Spider_110/home/RoSModule/XML/In/Error tempDevMode.rb line 37 in function test

What am I doing wrong here? Any help would be much appreciated.

jeudi 28 septembre 2017

How can I make it so if the first player inputs a wrong command then it will a specific prompt?

I am trying to make a game of rock-paper-scissors-spock-lizard. I have been learning about if/else statements. I am trying to make it so that if player1 inputs an invalid command then it will print out "Sorry, this is not a valid command" like with the else statement. It works if both players input a command and one is wrong, but not if just player1 did. Could you help me figure out what I am supposed to do? Here is my code:

    package csc212hw03;
    import java.util.Scanner;

    public class Main {

public static void main(String[] args) {
    String player1;
    String player2;
    String player1Choice;
    String player2Choice;
    String line;

           // “1” for Paper
    //“2” for Rock
    //“3” for Spock
    //“4” for Lizard
    //“5”for Scissors
   Scanner kb = new Scanner(System.in);
   System.out.println("Player 1, please enter your name:");
   player1 = kb.nextLine();

   System.out.println("Player 2, please enter your name:");
   player2 = kb.nextLine();

   System.out.println(player1 + ", please enter your command:");
   player1Choice = kb.nextLine();

   System.out.println(player2 + ", please enter your command:");
   player2Choice = kb.nextLine();

   if (player1Choice.equals("1") && player2Choice.equals("2")) {
       System.out.println(player1 + " wins! Paper covers Rock.");
       System.out.println("Thank you for playing.");
   } else if (player2Choice.equals("2") && player1Choice.equals("1")){
       System.out.println(player2 + " wins! Paper covers Rock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("1")&& player2Choice.equals("1")) {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("2")&& player2Choice.equals("2")) {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("1")&& player2Choice.equals("3")) {
       System.out.println(player1 + " wins! Paper disproves Spock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("3") && player2Choice.equals("1")) {
       System.out.println(player2 + " wins! Paper disproves Spock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("3")&& player2Choice.equals("3"))  {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("2") && player2Choice.equals("3")) {
       System.out.println(player2 + " wins! Spock vaporizes Rock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("3") && player2Choice.equals("2")) {
       System.out.println(player1 + " wins! Spock vaporizes Rock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("3") && player2Choice.equals("5")) {
       System.out.println(player1 + " wins! Spock smashes Scissors.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("3")) {
       System.out.println(player2 + " wins! Spock smashes Scissors.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("5")) {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("2") && player2Choice.equals("5")) {
       System.out.println(player1 + " wins! Rock crushes Scissors.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("2")) {
       System.out.println(player2 + " wins! Rock crushes Scissors.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("2") && player2Choice.equals("4")) {
       System.out.println(player1 + " wins! Rock crushes Lizard.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("4") && player2Choice.equals("2")) {
       System.out.println(player2 + " wins! Rock crushes Lizard.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("3") && player2Choice.equals("4")) {
       System.out.println(player2 + " wins! Lizard poisons Spock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("4") && player2Choice.equals("3")) {
       System.out.println(player1 + " wins! Lizard poisons Spock.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("1")) {
       System.out.println(player1 + " wins! Scissors cuts Paper.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("1") && player2Choice.equals("5")) {
       System.out.println(player2 + " wins! Scissors cuts Paper.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("4")) {
       System.out.println(player1 + " wins! Scissors decpitates Lizard.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("4") && player2Choice.equals("5")) {
       System.out.println(player2 + " wins! Scissors decapitates Lizard.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("5") && player2Choice.equals("5")) {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("4") && player2Choice.equals("4")) {
       System.out.println("Draw!");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("4") && player2Choice.equals("1")) {
       System.out.println(player1 + " wins! Lizard eats Paper.");
       System.out.println("Thank you for playing.");
   } else if (player1Choice.equals("1") && player2Choice.equals("4")) {
       System.out.println(player2 + " wins! Lizard eats Paper.");
       System.out.println("Thank you for playing.");
   } else {
       System.out.println("I'm sorry, this is not a valid command.");
       System.out.println("Thank you for playing.");

   }
      }
    }

MYSQLi PHP Query if X else X

I am trying to run a query the gather various data depending on one of the table fields.

So basically if cotype is 1 I only want to check 1 possible match for name however if it is greater than 1 I have to check for multiplay name matches

SELECT * FROM mydirectory WHERE (cotype = '1' AND name='1' AND status='1' AND c_deleted='0') OR (cotype > 1 AND (name='1' OR name='2' OR name='2') AND status='1' AND c_deleted='0') ORDER BY cotype DESC, coname ASC

This will trigger resukts but it seems to run both queries not one or the other.

TIA

how can i make a game with checkKey and if/else if statements

function checkKey(e) {
var event = window.event ? window.event : e;
console.log(event.keyCode);

    if(event = 38){
        robotArm.grab();
    } else if(event = 40){
        robotArm.drop();
    } else if(event = 37){
        robotArm.moveLeft();
    } else if(event = 39){
        robotArm.moveRight();
    }
}

Hi, My problem is that it only grabs and it doesn't care which key I press how can i make it so that only the arrow keys are used and that the arm moves from left to right and drop the block when it grabbed one?

Functions not being executed

I am super new at coding, taking my first programming class this semester. We have just learned about functions with an assignment to use functions to make a program that calculates the area and perimeter of a rectangle.

When I run the program, nothing happens. I can't figure out why the first function getInt isn't being initialized.

As shown in the code below, the user is not being asked to enter either the width or height. Any and all help is appreciated.

def getInt(wid, hght):
 if wid <1:
    print("Integer value must be between 1 and 60, please re-enter: ")
 if wid >60:
    print("Integer value must be between 1 and 60, please re-enter: ")
 wid=float(input("Enter the width (1 - 60): "))
 if hght<1:
    print("Integer value must be between 1 and 20, please re-enter: ")
 if hght>20:
    print("Integer value must be between 1 and 20, please re-enter: ")
 hght=float(input("Enter the height (1 - 20: "))
 return wid
 return hght

def calcPerimeter(width, height):
 width=getInt.wid
 height=getInt.hght
 perimeter=2*(width+height) 
 return perimeter

def calcArea(width, height):
 width=getInt.wid
 height=getInt.hght
 area=width*height
 return area

def Main():
 getInt
 calcPerimeter
 calcArea
Main()

multiple if statements in batch not executing but everything else works

OK I'm trying to make a batch program to execute multiple java programs in a set place based on the user input. the directory part works the only thing that seems to cause me trouble is the if statements running the java programs.here is my code:

@echo off
:START
echo Last Name First Initial:
set /p Name=""
cls.
echo %Name%
setlocal enabledelayedexpansion
echo BLP or BPP or LMP:
set /p Type=""
cls.
echo %Name%
echo %Type%

echo Chapter Number:
set /p ChapterNumber=""
set ch=ch
set Chapter=%ch%%ChapterNumber% 
cls.

echo %Name%
echo %Type%
echo %Chapter%
pause

r:
cd R:\4\%Name%\%Type%\%Chapter%\
dir

IF "%Type%"=="lmp"(

IF "%Chapter%"=="ch1"(
echo.
echo CSYes
echo.
java CSYes
echo.
echo Poem
echo.
java Poem
echo.
echo Count
echo.
java Count
echo.
echo Simple
echo.
java Simple
echo.
echo Hello
echo.
java Hello
echo.
echo Problems
echo.
java Problems
echo.
pause
cls
goto :START
)

IF "%Chapter%"=="ch2"(  

    )
)


IF "%Type%"=="bpp"(

IF "%Chapter%"=="ch1"(
echo.
echo Novel
echo.
java Novel
echo.
echo Song
echo.
java Song
echo.
echo Tree
echo.
java Tree
echo.
echo Websites
echo.
java Websites
pause
cls
goto :START
)

IF "%Chapter%"=="ch2"(


)
)


pause
cls.
goto :START

pleeeease help I'm lost and i feel like i have tried everything thanks :)

How To Return a Result in Excel based on a specific text value that is found 2 or more times in a range of cells

I am using a spreadsheet to capture test results. There are multiple different cells where the users capture the result of the test for the specific sample they are testing (pass/fail/etc).

I want to have one cell show the overall conclusion of the test. The criteria I need for the calculation is as follows: If there are >=2 different cells that have the value "Conclusion - Fail", then the overall result would be a fail. If there is only 1 "Conclusion - Fail", then it would be pass.

I figured this would be an easy if then statement, but I am having trouble getting this to work.

Please any help would be greatly appreciated, thanks!

How to use let bindings conditionally in Clojure

I'm new to Clojure and trying to concisely write a recursive function to merge two sorted sequences into a new sorted sequence.

This is my attempt, which doesn't compile:

(defn seq-merge [a-seq b-seq]
  (cond
    (empty? a-seq) b-seq
    (empty? b-seq) a-seq
    :else (let (if (< (first a-seq) (first b-seq))
                 [f (first a-seq) r (rest a-seq) h b-seq]
                 [f (first b-seq) r (rest b-seq) h a-seq])
            (cons f (seq-merge r h)))))

Initially, I wanted something like:

(if condition
  (let [...] 
  (let [...]
    (code-that-uses-conditional-bindings))

But it seemed that each 'let' needed to be directly followed by the code so this didn't work.

The aim is to not have to repeat the (cons f (seq-merge r h)) line twice if it can be avoided.

My current solution is this:

(defn seq-merge [a-seq b-seq]
  (cond
    (empty? a-seq) b-seq
    (empty? b-seq) a-seq
    :else (let [a-low? (< (first a-seq) (first b-seq))
                f (if a-low? (first a-seq) (first b-seq))
                r (if a-low? (rest a-seq) (rest b-seq))
                h (if a-low? b-seq a-seq)]
            (cons f (seq-merge r h)))))

But this seems much clunkier by having an 'if' for every binding value.

Crystal Reports formula to create new field data based on specific condition?

I am relatively new to Crystal Reports (I have version 2013) so I understand how some things work, but I cannot figure this issue out.

My database source for the report is secure and cannot be changed, so I have to make the change in crystal reports. Basically I have a field called Jurisdiction that has a set number of possible entries. I need to create a new entry in the Jurisdiction field if a certain city is within the CITY field. Here is what I am thinking for code, but I cannot get it right:

if {database.CITY}='SPRINGFIELD' then {database.JURISDICTION}='SPRINGFIELD' 

else {database.JURISDICTION}=defaultattribute

I know that the defaultattribute does not work here, but I do not know what to use. I have also tried the code without the else statement which does not give me any errors, but on the report it displays "False". Also can I create just a regular formula to drag onto the report or should it be created within the Section expert in the details section?

mssql which is the syntax 'if'

I have this code in mssql:

SELECT
    t1.Id,
    t2.Id,
    t1.QuantityIn,
    t1.PriceIn,
    t2.QuantityOut,

    (If (t2.QuantityOut - t1.QuantityIn)=0

        THEN t2.QuantityOut

    Else t2.QuantityOut - t1.QuantityIn ) AS Quant,

    t2.PriceOut

FROM t1

LEFT JOIN t2 ON t2.Id = t1.Id

In software MsSql Server Management Studio error is

Incorrect syntax near the keyword 'If'.

What is the correct syntax for 'if' in my case?

Thank you!

PHP,MYSQL If table's value is equal to text

$delivery = "SELECT `Delivery` FROM `order` WHERE 1";
if($delivery == "Atsiimtas"){ echo "do stuff";}

This code doesn't work, i checked mysql it all good.Help ,thanks

c++ program does not run completely (if-else statements)

I'm trying to run a C++ program. The first part of it is to calculate someone's age. There are different cout's for different age ranges. But for some reason the program stops after calculating the age in years and doesn't continue with the rest. I want it to calculate the age in months too. When I try to run it in the terminal, it does 2017-birthday. But after that nothing else appears. I think there's a problem with the way I put all the if-else statements for the part of age in years, but I'm not sure. The date is set as 25 September 2017, hence I put 9 minus birthmonth.

#include <iostream>
using namespace std;

int main()
{
int birthday,birthmonth;
int ageinyears;

// birthyear     
cout << "What is your birthyear? ";
cin >> birthyear;
if (birthyear <= 2017) 
{
  cout << "Your age in years is "
       << 2017-birthyear << endl;
  cin >> ageinyears;
  if (ageinyears < 10)
  {
  cout << "You are too young for university." << endl;
  return 0;
  }

  else if (ageinyears > 100)
  {
  cout << "You are too old for university." << endl;
  return 0;
  }

  else 
  cout << "Continue with the next question.";

}
else
  cout << "The year you filled in is invalid. Try again." << endl;
  return 0;

// birthmonth   
cout << "Fill in your birthmonth as numbers.";
cin >> birthmonth;
if (0 < birthmonth && birthmonth < 13)
  cout << "Your age in months is "
       << ((ageinyears * 12) + (9 - birthmonth)) << endl;
else 
  cout << "The month you filled in is invalid. Try again.";
  return 37;

}//main

Does the following Python code execute both if and else?

if print("welcome"):
    print("heelloo!")
else:
    print("bbye!")

This piece of code prints both welcome and bbye. So, is the if condition never executed, or is it something else? Kindly explain as I am fairly new to Python.

if statement and for loop to append new data to original data frame

I have some model outputs that I want to integrate back into the original data file. I was able to do this using nested ifelse(), however I want a way to generalize the process so that I can run it as a batch process across multiple data sets. This is what I originally tried.

The model outputs correspond to time chunks, while each original data point is associated with a discrete time.

I decided to manually run one day at a time (here is an example of one parameter on one day), and with this very large and ugly ifelse was able to correctly aggregate the data.

track[,"phase"]= ifelse((phaseTable1$start[1]<=track$Time)& (track$Time< phaseTable1$end[1]), phaseTable1$phase[1],
                  ifelse((phaseTable1$start[2]<=track$Time)& (track$Time< phaseTable1$end[2]), phaseTable1$phase[2],
                         ifelse((phaseTable1$start[3]<=track$Time)& (track$Time< phaseTable1$end[3]), phaseTable1$phase[3],
                                ifelse((phaseTable1$start[4]<=track$Time)& (track$Time< phaseTable1$end[4]), phaseTable1$phase[4],
                                       ifelse((phaseTable1$start[5]<=track$Time)& (track$Time< phaseTable1$end[5]), phaseTable1$phase[5],
                                              ifelse((phaseTable1$start[6]<=track$Time)& (track$Time< phaseTable1$end[6]), phaseTable1$phase[6],
                                                     ifelse((phaseTable1$start[7]<=track$Time)& (track$Time< phaseTable1$end[7]), phaseTable1$phase[7],
                                                            ifelse((phaseTable1$start[8]<=track$Time)& (track$Time< phaseTable1$end[8]), phaseTable1$phase[8],
                                                                   ifelse((phaseTable1$start[9]<=track$Time)& (track$Time< phaseTable1$end[9]), phaseTable1$phase[9],
                                                                          ifelse((phaseTable1$start[10]<=track$Time)& (track$Time< phaseTable1$end[10]), phaseTable1$phase[10],
                                                                                 ifelse((phaseTable1$start[11]<=track$Time)& (track$Time< phaseTable1$end[11]), phaseTable1$phase[11],
                                                                                        ifelse((phaseTable1$start[12]<=track$Time)& (track$Time< phaseTable1$end[12]), phaseTable1$phase[12],
                                                                                               ifelse((phaseTable1$start[13]<=track$Time)& (track$Time< phaseTable1$end[13]), phaseTable1$phase[13],
                                                                                                      ifelse((phaseTable1$start[14]<=track$Time)& (track$Time<phaseTable1$end[14]), phaseTable1$phase[14],
                                                                                                             ifelse((phaseTable1$start[15]<=track$Time)& (track$Time< phaseTable1$end[15]), phaseTable1$phase[15],
                                                                                                                    ifelse((phaseTable1$start[16]<=track$Time)& (track$Time< phaseTable1$end[16]), phaseTable1$phase[16],
                                                                                                                           ifelse((phaseTable1$start[17]<=track$Time)& (track$Time< phaseTable1$end[17]), phaseTable1$phase[17],
                                                                                                                                  ifelse((phaseTable1$start[18]<=track$Time)& (track$Time< phaseTable1$end[18]), phaseTable1$phase[18],
                                                                                                                                         ifelse((phaseTable1$start[19]<=track$Time)& (track$Time< phaseTable1$end[19]), phaseTable1$phase[19],
                                                                                                                                                ifelse((phaseTable1$start[20]<=track$Time)& (track$Time< phaseTable1$end[20]), phaseTable1$phase[20],
                                                                                                                                                       ifelse((phaseTable1$start[21]<=track$Time)& (track$Time< phaseTable1$end[21]), phaseTable1$phase[21],
                                                                                                                                                              ifelse((phaseTable1$start[22]<=track$Time)& (track$Time< phaseTable1$end[22]), phaseTable1$phase[22],
                                                                                                                                                                     ifelse((phaseTable1$start[23]<=track$Time)& (track$Time< phaseTable1$end[23]), phaseTable1$phase[23],
                                                                                                                                                                            ifelse((phaseTable1$start[24]<=track$Time)& (track$Time< phaseTable1$end[24]), phaseTable1$phase[24], 
                                                                                                                                                                                   ifelse((phaseTable1$start[25]<=track$Time)& (track$Time< phaseTable1$end[25]), phaseTable1$phase[25],
                                                                                                                                                                                          ifelse((phaseTable1$start[26]<=track$Time)& (track$Time< phaseTable1$end[26]), phaseTable1$phase[26], 
                                                                                                                                                                                                 ifelse((phaseTable1$start[27]<=track$Time)& (track$Time< phaseTable1$end[27]), phaseTable1$phase[27],
                                                                                                                                                                                                        ifelse((phaseTable1$start[28]<=track$Time)& (track$Time< phaseTable1$end[28]), phaseTable1$phase[28],
                                                                                                                                                                                                              ifelse((phaseTable1$start[29]<=track$Time)& (track$Time< phaseTable1$end[29]), phaseTable1$phase[29],
                                                                                                                                                                                                                      ifelse((phaseTable1$start[30]<=track$Time)& (track$Time< phaseTable1$end[30]), phaseTable1$phase[30],
                                                                                                                                                                                                                             ifelse((phaseTable1$start[31]<=track$Time)& (track$Time< phaseTable1$end[31]), phaseTable1$phase[31], 
                                                                                                                                                                                                                                    ifelse((phaseTable1$start[32]<=track$Time)& (track$Time< phaseTable1$end[32]), phaseTable1$phase[32],
                                                                                                                                                                                                                                          ifelse((phaseTable1$start[33]<=track$Time)& (track$Time< phaseTable1$end[33]), phaseTable1$phase[33],
                                                                                                                                                                                                                                                  ifelse((phaseTable1$start[34]<=track$Time)& (track$Time< phaseTable1$end[34]), phaseTable1$phase[34],
                                                                                                                                                                                                                                                         ifelse((phaseTable1$start[35]<=track$Time)& (track$Time< phaseTable1$end[35]), phaseTable1$phase[35],phaseTable1$phase[35]

                                                                                                                                                                                                                      )))))))))))))))))))))))))))))))))))

This worked, however it is quite unwieldy and the number of nested conditions varies from day to day within the data.

I tried to rework this into a more practical loop

for ( j in 1:nrow(phaseTable1)){
if((phaseTable1$start[j]<=track$Time)&(track$Time< phaseTable1$end[j])){track$tau== phaseTable1$tau[j]}

 }

and constantly get this warning which results in no data being aggregated

In if ((phaseTable1$start[j] <= track$Time) & (track$Time <  ... the condition has length > 1 and only the first element will be used

I tried it again like this

    for ( j in 1:nrow(phaseTable1)){
        track$phase<-ifelse(((phaseTable1$star [j]<=track$Time)&(track$Time< phaseTable1$end[j])),  phaseTable1$phase[j],"")))
}

And the new columns appear in the data frame but they are empty.

I tried again using a wrapper from the thatssorandom package recommended in a blog post, which also resulted in an error.

for ( j in 1:nrow(phaseTable1)){
ie(
  i(((phaseTable1$start[j]<=track$Time)&(track$Time< phaseTable1$end[j])),track$phase<- phaseTable1$phase[j]),
e("na"))

  }

Is there an obvious mistake I'm making or is there another solution to achieve what I am trying to do? I admit I'm a relatively amateur r user, and I have explored other ifelse forum questions but haven't been able to figure out what I'm doing wrong. I have a working loop that allows me to run my models day by day within the dataframe. If I am able to get this next loop to run then I will be able to nest it into the first loop, and will be able to aggregate the data in batches. Any insight as to what the solution might be will be much appreciated!