jeudi 28 février 2019

Vba to replace nested if

=IF(D3>0,"FFR",IF(E3>0,"COO", IF(F3>0,"DPT")))

What should I put in vba to replace this formula? Was given hint to use loop for 5000 rows of data (the above is a shorter version.)

look at all instances of an array in a if statement?

I have about 20 different sheets and I wrote some google script to combine all of the data into a master sheet. Now I'd like like to be able to exclude certain sheets. My idea to do this was to storage the names of those sheet in a variable. This is what I have so far, but I am getting an error? Any ideas?

label is the name of the Column that I am scanning each sheet for and masterSheetName is the sheet where I am storing the data.

 if (sheetName !== masterSheetName && sheetName !== skippedsheets) 

lines are the ones I am having trouble with. It is not going though all of the instances of skipped sheets.

Is there a way to do this with a for each loop?

function getColVals(label, masterSheetName) {

  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var colValues = []
  for ([i,sheet] in sheets) {
    var sheetName = sheet.getSheetName();
    var skippedsheets = ["HHS 1","HHS 2"];
    Logger.log(skippedsheets);
    Logger.log(skippedsheets[0]);
    if (sheetName !== masterSheetName && sheetName !== skippedsheets) {
    var colValues2 = getColValues(label,sheetName);
    colValues = colValues.concat(colValues2);
    } 

  }
  return colValues; 

}

thank you, Jerome

UWP - Automatic if statement with sequence condition

I have a condition where if file = 2016, then folder_id = 1, if file = 2015 then folder_id = 2, like so on. How do I apply the if statement automatically (instead of entering one by one) with C# language?

Recurring line disappearance, issue with while loop

*I'm new to python, so be gentle...

Overall issue: I have had an issue in multiple codes I've written lately where lines get skipped and it is obviously an error on my part. I know I must be messing up ordering of something, but I'm just not seeing it. My most recent issue can be found here: Is there any reason Python would skip a line?

Now, I want to write an application to pre-sell a limited number of tickets. Here are the conditions:

"Each buyer can buy as many as 4 tickets. There are a total of 15 tickets that are available to pre-sell. The program should prompt the user for the amount of tickets they want to purchase and then display the number of remaining tickets. Repeat until all tickets have been sold, and then display the total number of buyers."

A similar problem is occurring.

buy = int()
ticket_num = 15
buyers = 0

while ticket_num > 0:
    buy = int(input("How many tickets would you like to purchase? "))
    if buy > 4:
        print("You cannot buy that many (4 max).")
        buy = input("How many tickets would you like to purchase? ")
    else:
        ticket_num = ticket_num - buy
        print("There are currently", ticket_num, "remaining.")
        buyers = buyers + 1

print() 

print("The total number of buyers was:", buyers)

It appears that the print line in the 'else' structure is not being read and I don't quite understand why...

Can anyone lend me any insight into what my overall misunderstanding is..?

what's the difference betwwen "if -if -else" and "if-elif-else"

enter link description here

when I typed this code:

def gradingStudents(grades):
    ls = []
    for grade in grades:
        if grade <38:
            new_grade = grade
        else:
            n = grade //10
            t = grade % 10 
            if t <5 and (5-t)<3:
                new_grade = n * 10 + 5

            if t > 5 and (t - 5) >2:
                new_grade = (n+1) * 10
            else:
                new_grade =grade
        ls.append(new_grade)   
    return ls

It's get the wrong answer.But when I changed the second if statement to elif,it's correct.I'm not very clear about what happened:

 def gradingStudents(grades):
    ls = []
    for grade in grades:
        if grade <38:
            new_grade = grade
        else:
            n = grade //10
            t = grade % 10 
            if t <5 and (5-t)<3:
                new_grade = n * 10 + 5

            # I use "elif" replace "if"
            elif t > 5 and (t - 5) >2:
                new_grade = (n+1) * 10
            else:
                new_grade =grade
        ls.append(new_grade)   
    return ls

Python 3: check that command runs without exception in "if .. else" block without using "try .. except"

Is there any native language construction in Python 3 to check if some line of code can be run without exception without using "try .. except" block?

E. g.: I parse a list of files and need to select only those files that start with UNIX-date and "_" symbol to and pass them to another module. I don't need neither the result of conversion at the moment, nor the type of exception nor the text of exception, only the fact that this file suites the requirements:

FileList = ["1550889019_FileName1.tar", "New_document.doc", "1550000000_FileName2.7z", "Song.mp3"] 
ValidFiles = []
for FileName in FileList:
    # Cut everything after first '_' symbol, convert to integer and try to parse as a date
    if no_exception(datetime.date.fromtimestamp(int(re.sub(r'_.*$', '', FileName)))):
        ValidFiles.append(FileName)

DoSmth(ValidFiles)

P. S.: I know that I can declare "no_exception()" function, run the code inside a "try .. except" block there and return false on exception, but I search for native "more elegant" solution right now.

In jquery, if the if statement don't return anything, then do nothing

I have a calendar on my web page, and this script will add a class if the day on the task matches the current day. This work if i do have any tasks on that current day. But if i dont, it will give me an error on this current script and all the others script on my web page making the web page useless. So the question is, how to i make jquery just ignore and do nothing if the if statement doesn't return anything?

var d = new Date(2019, 1, 24);
var month = d.getMonth() + 1; //.getMonth() is 0-11
var day = d.getDate();

if (day < 10) {
  day = '0' + dd;
}

if (month < 10) {
  month = '0' + month;
}

 var mydivs = document.getElementsByClassName("mydiv");
 for(var i = 0; i < mydivs.length; i++) {
     if (mydivs[i].children[0].innerHTML == `${day}.${month}`) {
        mydivs[i].className += " today";
     }
 }
.today {
  border: 2px solid red;
  color: red;
}
<div class="mydiv">
    <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-24T11:30:00+01:00">24.02</span>
</div>

<div class="mydiv">
    <span class="date-display-single day" property="dc:date" datatype="xsd:dateTime" content="2019-02-25T11:30:00+01:00">25.02</span>
</div>

C++ if statement not printing desired output

Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine Any help is appreciated

#include <iostream>
using namespace std;
/*
  Write a C++ program that asks the user for an integer. 
  The program finds and displays the first power of 3 
  larger than the input number using while 

*/
int main() {
  int input = 0;
  int base = 3;
  int exponent = 0;
  int sum = 1;

  cout << "Enter a number: ";
  cin >> input;

  while (sum < input) {
    // This is the if statement giving me problems
    if (input == 1) {
      exponent += 1;
      sum = 3;
    }
    // This else if statement seems to work fine
    else if (input == 3) {
      exponent += 2;
      sum = 9;
    }
    else {
      exponent++;
      sum *= base;
    }
  }
  // Print output 
  cout << "3 to the power of " << exponent << " is equal to " << sum;
  cout << endl << "It is the first power of 3 larger than " << input;
  return 0;
}

In Java If/Else loop only else is working [duplicate]

This question already has an answer here:

I'm a student and i have an assignment. Our assignment is about converting but in if/Else loops i have a problem. [these are my codes][1]

Always working else statement.

function is ignoring if/else as if it doesnt exist

I have been trying for awhile and i couldn't get it to work so i decided to come here to ask.

#include <stdio.h>
char CMD[255];
int main ()
{
    fgets (CMD, 255, stdin);
    exi("hello", printf ("hello\n"));
}
int exi (char INPUT[255], char PROG[255])
{
    if (strcpy(INPUT,PROG)==0){
        PROG;
    }
    else{
        system(CMD);
    }
}

Code within "ext()" If and else is ignored completely and i have no idea why. any help will be appreciated.

Creating a function with a condition in Python

I need to create a function named 'Bernoulli' that should take 2 input variables 'rr' and 'p' and should return a value of 1 if rr is less than or equal to p and a value of 0 if rr is greater than p.

The code I have produced so far is this:

rr=float(input())
p=float(input())
def bernoulli(rr,p):
  if rr<=p:
    return 'X=1'
  else:
    return 'X=0'

I am not sure how correct this is.

Upon running tests I get this feedback: Your program took too long to execute. Make sure that it isn't waiting for input and that there is no infinite loop.

Selenium if locate on screen unable to locate element

I'll keep this question simple: I have an if statement:

if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):

And i get this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id, "mission_countdown")]"}

Why do I get this? I mean its an if statement, IF its on screen

Thanks for helping

Google Sheets MID formula outputs weird value not compatible with IF function

In Google Sheets, the MID formula seems to output a weird value type that doesn't work well with comparison functions, namely IF.

Below, The Row 1 shows the function in each cell, Row 2 show the column names, and Row 3 shows the values.

Each cell with a number is of type Custom Number Format: 123

 SOURCE      "=IF($A2>123,$A2-1,$A2)"   "=MID($A2,1,3)" "=IF($C2>123,$C2-1,$C2)"

 Col A        Col B                      Col C            Col D
 ---------------------------------------------------------------
 123          123                        123              122

The expected output from the IF check in Col D on the MID output is 123, yet it's outputting 122 (even though 123 is NOT greater than 123).

Even if I change the formats of each cell to Number 1,000.12, the IF check on MID's output is wrong.

Why is this?

Unreachable code detected in IF/ELSE statement

I need some assistance please... I am having problems with the ELSE statement, the code executes whatever that is in the IF bracket but never reach the ELSE bracket. It works without issues with Chrome but fail every time with IE. This is my code:

IWait<IWebDriver> wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(3.00));
        IList<IWebElement> boxList = _driver.FindElements(By.CssSelector("ListBox option"));

        bool textExists = false;

        foreach (var option in boxList)
        {
            if (option.Text.Equals("TEST"))
            {
                textExists = true;
                break;
            }
        }

        if (!textExists)
        {
            _driver.FindElement(By.Id("AddButton")).Click();

            var newRecordInfo = table.CreateSet<FeatureInfo>();

            foreach (var recordData in newRecordInfo)
            {
                _driver.FindElement(By.Id("DescTextBox")).SendKeys(recordData._discription);
                _driver.FindElement(By.Id("PaTextBox")).SendKeys(recordData._score);

                new SelectElement(_driver.FindElement(By.Id("DropDown"))).SelectByValue("1");
                _driver.FindElement(By.Id("SaveButton")).Click();
            }
        }
        else 
        {
            SelectElement Select = new SelectElement(_driver.FindElement(By.Id("ListBox")));
            Select.SelectByText("TEST");

            _driver.FindElement(By.Id("DeleteButton")).Click();

            IAlert alert = _driver.SwitchTo().Alert();
            alert.Accept();

            //IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
            //js.ExecuteScript("window.confirm = function(msg) { return true; }");

            Thread.Sleep(1000);


        }

SUM of multiple columns text in Excel

Is the first time writing a command in excel so I have no particular idea what I'm doing.

As you can see from the image I'm trying to get in the "All Stores" column all the Stores that have the "X" in them.

At the moment the command that I'm using is displaying the output of the first cell where it finds an "X".

In this particular example the expected result would be "Store1, Store3".

Thank you for your support!

Product Store Example

Check if records exist with Python

I'm going from SQL to python and I'm still kind of confused. It's the following here in my code I want to know if the select values ​​of the result variable exist in the select of the sell variable, and if they exist do nothing, and if they do not load the data. In sql I used If exists, I do not know what the equivalent in python is. Thank you very much in advance.

Example I am bringing a record from a sql table and loading into another mysql table, then in case you already have those records in the mysql table I want you to print on the screen: you do not have new records, and in case you have a record you have not yet are in the table of Mysql I want to load those logs.

Note: I set the data in the dataframe and then load it in mysql

import pymysql.cursors
import pyodbc
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import Integer, VARCHAR, DECIMAL, DATETIME 
from datetime import date


connection = pyodbc.connect("DSN=SQLServer")  #autocommit=True

try:
    with connection.cursor() as cursor:
        result = "SELECT * FROM dw.dbo.vW_sale"
        df = pd.read_sql_query(result,connection,index_col=None,coerce_float=True, parse_dates= 'DataBaseContrato')
        cursor.execute(result)
        table = cursor.fetchall()
        print(table)             

finally:
    connection.close()

#Conexão Mysql
cnx = create_engine('mysql+pymysql://test:test@test/dw')
cnxmysql = pymysql.connect(host='test',
                             user='test',
                             password='test',
                             db='dw')
try:
    with cnxmysql.cursor() as cursor2:
        sale = "SELECT * FROM ft_sale_test"
        cursor2.execute(venda)
        sale = cursor2.fetchall()
        print(sale)
finally:
    cnxmysql.close()

df.to_sql(con=cnx, name= 'ft_sale_test',if_exists= 'replace', index= False)
print('Loading data')

My if statement line goes through even if it's True and should execute its return line

I'm running a while function. Inside this while func User input an int value that append to a list. I want to get the index of the last similar input from the list. But it keeps printing 'never entered' even the User input was already entered once on twice (see below)

list = [] #that list append from User in the while loop

def user(num):
    if num in list:
        return(drawlist.index(num))
    else:
        print(never entered)

Inside that while function :

...

print(user(num))

why is outer variable not available in if conditional

    function NumStuff(num) {
    this.num = num;
    this.multipleOfFour = function () {

        //if multiple of 4
        if (this.num % 4 === 0) {
            console.log(this.num + " is a multiple of Four");
            console.log("the structure of the given integer " + 
                        this.num + " is ");

            for (let i = 0; i < this.num; i++) {
                if (4 * i === this.num) { //why is this.num outside of 
                                          //lexical scope
                    console.log(this.num + " = " + i + " x 4");
                    break;
                }
            }
            //if not a multiple of 4
        } else {
            console.log(this.num + " isn't a multiple of 4 but here is the integer's structure:");
            let remainder = this.num % 4;
            let tempNum = this.num - remainder;
            for (let i = 0; i < tempNum; i++) {
                if (4 * i === tempNum) {
                    console.log(this.num + " = " + i + " x 4 + " + remainder);
                    break;
                }
            }
        }
    };
}

let num = prompt("Enter an integer:");
let n = new NumStuff(num);
n.multipleOfFour();

Say we enter 20 as our num. It passes through the multipleOfFour() and hits the first if conditional. This.num(20) % 4 is equal to 0 so it passes.Then we loop through i to find what number times 4 is equal to 20. This.num is in the scope of the for statement but not in the scope of the inner if conditional of the for statement. Why is that so?

if (expression) VS "Traditional If" in AHK

The following simple script displays Yes, then No.

I don't get it.

From what I read in the AHK documentation, I suspect this has something to do with the if (expression) VS "Traditional If". But I find the documentation not very clear on this subject.

Could someone explain this?

#SingleInstance force
#NoEnv

Toto := "c"

If (Toto In a,b)
    MsgBox Yes
Else
    MsgBox No

If Toto In a,b
    MsgBox Yes
Else
    MsgBox No

Excel - How to add words to an Excel IF statement

I am creating a spreadsheet for a Dungeons and Dragons game that I run to help measure initiative and turn orders.

The formula I'm trying to do is to convert the rounds passed into real time. 1 Round being 6 seconds, 10 rounds being 1 minute.

I think the math is fine, the problem is adding the words "Seconds" when the value of Rounds passed is equal to 2-9, and greater than 10.

This is the formula I have now: =IF(I3=10,"1 Minute",IF(I3=1,"6 Seconds",IF(I3>1,I3*6+" Seconds")))

(I3 being the Rounds Passed cell)

Actions Scrip 3.0 Else If Conditions (TEXT)

i need to make a Else If Conditions. I make a form with Adobe Flash, at the first page, i need to make a login form. I want to make Input Text, but the input text must be filled. If the input text is empty, i want to make alert if the form must be filled. In my idea. its have a one input text called "nama.text" and in the bottom of the input text, i put a button called "next.text". And then, i put dynamic text "alert.text" in the bottom of the button.

I want, if the button pressed by user with a filled input text, user will be direct to go to next frame. But, if the input text is empty, i want to make alert "Nama Must Be filled" and make user stay in this page and cannot go to next frame until the Nama.text is filled. Iam so sorry for my english, but i hope, everyone here understand with my questions. Big Thanks :)

Jenkins Pipeline - if statement always returns false

I currently have a problem. I am working with openshift and am trying to use an if statement depending on wether an Integration Test in a seperate container succeeded. This this is a snippet of my code

podTemplate(....

){
  node(myLabel){
    container('jnlp'){
      ...
      stage(Integration Tests){
        ...
         script{
          def status = sh(script: 'oc describe pod myapps-integration-tests | grep -i status: | awk {\'print $2\'}', returnStdout: true)
          echo "Status of Interation Test Job ${status}"
          echo status
          if("${status}" == "Succeeded"){             
            echo "Integration tests successfull"  
          } else {              
            echo "Integration Tests failed"
            error("The integration tests failed.")              
          }
        }
        ...
}

Now the problem is, that this if statement always always returns false. status echoes as Succeeded but still the statement returns false. I've tried with and without the script block. I tried

if(status == "Succeeded")

but still. It always tells me my integraion test failed. If i replace the statement with "Succeeded" == "Succeeded" just for testing it passes as expected. Does anyone have an idea what I am doing wrong?

JavaScript "if X" then condition content replace

im trying to edit an shop content without editing HTML (code is closed for editions, i can add only some JS or CSS. There is a div:

<div class="product_section" id="projector_shipping_info" style=""><label>
Ready to send</label><div><span class="projector_delivery_days" 
id="projector_delivery_days" style="display: inline;">in 21 days   </span> 
</div><a class="shipping_info" href="#shipping_info" title="Check time and price"> Check time and price</a></div>

Im trying to make an "if" statement to replace hard "in 21 days" shipping time, into "in 3 to 10 days". I need to use IF, cause the shipping time is one of three possible status: 21 days, 9 days and 3 days. Would love to change it for "3 to 10 days", "2-4 days" and "1-2 days".

I've tested already (and it worked out)

document.getElementById('projector_delivery_days').innerHTML = '';
var p = document.createElement('p');
p.innerHTML = "Shipping in 3-5 days";
document.getElementById('projector_shipping_info').appendChild(p);

But its static one. Wish to make an IF from this. I've tried

document.body.onload=function(){ var
div1=document.getElementsById('projector_delivery_days')[0];  
if(div1.innerHTML=="in 21 days   "){
document.getElementsById('projector_delivery_days')[0].innerHTML="in 3 to 10 days   ";   }    }

But it appears to do nothing, same goes with

function shipping(){
var d1 = document.getElementById('projector_delivery_days');
  if(d1.innerHTML==='in 21 days   '){
  d1.innerHTML='in 3 to 10 days   ';
  document.getElementById('projector_shipping_info').appendChild(d1);
  }
};

I've been struggling with this for like 2-3 days. Can someone send some help?

Excel IF function help required

I have difficulties with IF in Excel. What I need is to auto populate a cell (d2) with "0,5" if the value of different cell (c2) is equal or less than "85". Thank you!

Change the value of a variable in function of another one (Python)

I'm trying to create a variable by mixing two in function of the values of one of them (both are inside of the table df):

 A = [0, 1, 2, x, 4, 5, x, 7, 8, x, 10]
B=[2,3,4]

for i,j in A,B:
    if i = 'x':
        return i=j
    else i=i

mercredi 27 février 2019

Loop across rows and colums with nested data

I have the following data structure: Meetings in Persons in Groups. The groups met differently often and the number of group members varied for every meeting.

 $ GroupID                    : chr  "1" "1" "1" "1" ...
 $ groupnames                 : chr  "A&M" "A&M" "A&M" "A&M" ...
 $ MeetiID                    : chr  "1" "1" "2" "2" ...
 $ Date_Meetings              : chr  "43293" "43293" "43298" "43298" ...
 $ PersonID                   : num  171 185 171 185 185 113 135 113 135 113 ...
 $ v_165                      : chr  "3" "3" "4" "3" ...
 $ v_166                      : chr  "2" "2" "3" "3" ...
 $ v_167                      : chr  "2" "4" "4" "3" ...
 $ v_168                      : chr  "6" "7" "4" "5" ...
 $ problemtypes_categories: chr  "Knowledgeproblem" "Knowledgeproblem" "Motivationalproblem" "Coordinationproblem" ...
 $ v_165_dicho                : num  0 0 0 0 1 1 1 0 0 1 ...
 $ v_166_dicho                : num  0 0 0 0 0 0 0 0 0 0 ...
 $ v_167_dicho                : num  0 0 0 0 1 1 0 0 0 0 ...

Now I have to create a new variable that should be binary (0/1) with the name agreement_levels. So, every time, a person in one group has - regarding the same learning meeting - a same problem type category than the other learner(s) of the same group at the same meeting, both learners (or three or four, depending on the group size for a respective meeting) should get the value 1 at the agreement variable, else they should all get 0. Whenever a person (e.g., among four learners) already has a different category of problem than the others, there is a 0 on the agreement variable for all. If only 1 person is in the data set for one and the same meeting, there must be a NA at agree. When one person has NA at the problemtype variable, however, and there are 2 people in the data set for the same meeting, both get 0 at agree; but if there are 4 people for the same meeting in the data set and one of them has NA at problemtype, then only this person but not the others get NA at agree.

I did already write a command, but it is not working yet and still does not consider the NAs:

 GroupID1 <- df$GroupID[1:nrow,]
                         TreffID1 <- df$TreffID[1:nrow,]
                         for(i in 1:(GroupID1 -1){
                           for(j in 1:(TreffID1 -1){
                             if(df[i, 3] == df[i+1, 3]-1){
                                  if(df[i, 15] == df[i+1, 15]-1){
                                      df[c(i, i+1), 28] <- 1,
                                      df[c(i, i+1), 28] <- 0

Many thanks in advance.

dput(head(df))
structure(list(GroupID = c("1", "1", "1", "1", "1", "2"), v_187_corr = c("A&M", 
"A&M", "A&M", "A&M", "A&M", "Adornos"), TreffID = c("1", "1", 
"2", "2", "3", "1"), Datum.Treffen = c("43293", "43293", "43298", 
"43298", "43303", "43269"), PersonID = c(171, 185, 171, 185, 
185, 113), `Number participants per group` = c(2, 2, 2, 2, 2, 
2), lfdn = c(784, 858, 867, 866, 1008, 395), v_162 = c("L", "L", 
"K", "K", "M", "K"), v_163 = c("Schuldrecht und Anspruchsgrundlagen sehr umfangreich", 
"Schuldrecht ist sehr umfangreich", "Wir haben am gleichen Tag Klausur geschrieben und danach war die Motivation und Konzentration nicht mehr voll da.", 
"Direkt nach der Prüfung wieder zu lernen ist schwierig", "Der Lernstoff war  sehr langweilig uns somit sehr zäh zu erlernen", 
"Wir brauchten lange, bis wir richtig angefangen haben, da unsere Motivation heute nicht wirklich groß war. Wir sind deshalb auch nicht wirklich schnell vorangekommen."
), v_165 = c("3", "3", "4", "3", "5", "5"), v_166 = c("2", "2", 
"3", "3", "1", "4"), v_167 = c("2", "4", "4", "3", "5", "5"), 
v_164 = c("Fälle üben", "Prüfungsvorbereitung", "Vorbereitung auf die nächste Klausur.", 
"Wiederholung des Stoffea", "Klausurvorbereitung", "Wir wollten das erste Kapitel durchnehmen. Wir haben es auch geschafft."
), v_168 = c("6", "7", "4", "5", "6", "5"), problemtypen_oberkategorien = c("Verständnisprobleme", 
"Verständnisprobleme", "Motivationsprobleme", "Motivationsprobleme", 
"Motivationsprobleme", "Motivationsprobleme"), passung.exkl = c("0", 
"0", "0", "0", "1", "1"), passung.inkl = c("1", "0", "0", 
"0", "0", "1"), zPassng = c("0.5", "-0.5", "-0.5", "-0.5", 
"-0.5", "0.5"), zPassng.std = c("0.60342314080027204", "-1.6551034719093201", 
"-1.6551034719093201", "-1.6551034719093201", "-1.6551034719093201", 
"0.60342314080027204"), zZufri = c("0.82498531022632304", 
"1.5538558270282199", "-0.63275572337746999", "9.6114793424426206E-2", 
"0.82498531022632304", "9.6114793424426206E-2"), zprobtyp = c("-0.78941313079864905", 
"-0.78941313079864905", "1.2651521698892201", "1.2651521698892201", 
"1.2651521698892201", "1.2651521698892201"), prb_pass = c("-0.47635015077549703", 
"1.3065604135556499", "-2.0939577488772598", "-2.0939577488772598", 
"-2.0939577488772598", "0.76342209594483601"), v_165_dicho = c(0, 
0, 0, 0, 1, 1), v_166_dicho = c(0, 0, 0, 0, 0, 0), v_167_dicho = c(0, 
0, 0, 0, 1, 1), agree_group_withinmeet_levelrat = c("1", 
"1", "1", "1", "NA", "0"), agree_probtyp_ja_nein = c("1", 
"1", "1", "1", "NA", "1"), agree_group_withinmeet_overall = c("1", 
"1", "1", "1", "NA", "0")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

BASH - loop (for) with IF thru each line from file

I Have file (halted.txt) with data like below

IMPORT_FRP_DRAWDOWN_MQ,1
eFXO_IMPORT_RFQ_MQ,1
IMPORT_FROM_MCDM,1
deal_export,1

and now the question is how to loop against this file and perform some action (add +1 to number of the ned) only ones for each lines and stop when number is 5 or >5

IFS=$'\n' # make newlines the only separator
set -f    # disable globbing

for p in $(cat < "halted.txt"); do
   if [[ $p == *"5"* ]]; then
       echo "There is 5 on the end", $p
   elif [[ $p > *"5"* ]]; then
       echo "add +1 till 5"
       awk -F, '{$2=$2+1}1' OFS=, halted.txt > temp && mv temp halted.txt
   fi
done

Currently every run's number 1 is increased not only ones but 4 times, because I have 4line inside file. then first run will give me

IMPORT_FRP_DRAWDOWN_MQ,4
eFXO_IMPORT_RFQ_MQ,4
IMPORT_FROM_MCDM,4
deal_export,4

next one 8 etc. How to make sure that as results only +1 will be added?

Is there any reason Python would skip a line?

I'm just a few months into learning python and I'm trying to write a program which will help to test characteristics of a password. I'm so close to getting what I need but one line seems like it keeps getting skipped and I can't figure out why... Here's the code:

def main():

    print("Create a password. Password must follow these rules:")
    print("  - password must be at least 8 characters long")
    print("  - password must have one uppercase AND lowercase letter")
    print("  - password must have at least one digit")

    isValidPassword()

def isValidPassword():
    password = []
    password2 = []

    print()

    print("Enter password:", end="")
    pass1 = input("")    
    print("Re-enter password:", end="")
    pass2 = input("")

    password.append(pass1)
    password2.append(pass2)

    if password == password2 and len(password) >= 8 and password.isupper() == False and password.islower() == False and password.isalpha() == False and password.isdigit() == False:
        print("Password will work.")
    else:
        print("Password will not work. Try again.")
        isValidPassword()

main()

When I run the code, the print statement ("Password will work.") underneath my if statement will not print, even though I enter a password which meets all of the requirements. I have run the if statement in another file, outside of the def isValidPassword() function and it seems to work just fine.

Can anybody lend me any insight as to why this won't work..?

Creating a Guessing Game 4 digits

I wanted to make a guessing game. This game should guess a 4 digit number and then tells what number did i guess right and tells the place of the digit whether it is the first second third or fourth digit. Lastly, after guessing the game and checking the correct placements of the number it should also display score. Can someone kindly help me im new in using python and ive done some research but i couldnt find exact answer.

Ifelse Statement to Replace Value in Corresponding Row

I have a dataframe like below:

 Col1     Col2     COl4    Col5
   A         B       NA      NA
   M         L       NA      lo
   A         N       NA      KE

How do I make the logic where, if Col1 = A, replace NA in COl4 with "Pass"?

When I try using ifelse, I do not get the expected output.

Expected output should be:

 Col1     Col2     COl4    Col5
   A         B     Pass      NA
   M         L       NA      lo
   A         N     Pass      KE

Why does my addDays method work for some parameters but not others?

I am working on an APCS assignment to make a date class, and in it we needed an addDays method that add days to a date. So for example in the client code it would say date1.addDays(60000)

My code works for some addDays (ex. 1000) but doesn't work for others (ex. 60000)

public void addDays(int days){
    while(days>0){            
            day++;
            days--;
            if(day>daysInMonth(month)){
                month++;
                day = 1;
            }
            if(month>12){
                year++;
                month = 1;
                day = 1;
            }
    }
}

automatically split data in list and order list elements and send to function

I have recently created a GUI, which contents tables. User can insert values in cells. As shown figur below.

enter image description here

I want to use values to make some calculation based on values given by user. Rows can be added and removed based on choice of user. with other word, the data I get from user could come from just one row or several rows.

I manage to obtain all values from tables automatically and assign them to python list. Each row gives 5 elements in the list.

I have achieved that. Data in python list have to be processed and organised. This is exactly I want to have help. Because few dags I have been thinking, and I can not figure out, how to continue...

Python data as list from table. as an example.

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '', 11, 12, 13, 14] 

What I want to achieve!

I want to split list into 3 times len(data).

I have also achieved this.

def split_seq(seq, num_pieces):
    start = 0
    for i in range(num_pieces):
        stop = start + len(seq[i::num_pieces])
        yield seq[start:stop]
        start = stop

for data in split_seq(data, int(len(data)/5)):
    print(data)

Output would be:

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
['', 11, 12, 13, 14]

The difficulty for me starts here.

I want to take each splitted list and throw them into a if condition and store values as variables and message those values to a external function.

Something like this below:

for i in range(len(splitted_list1)):
    if splitted_list1[0] == '':
       do nothing
    else:
       x_+str(i)= splitted_list1[i]
       externalfunc(x_1,x_2,x_3,x_4,x_5)

for i in range(len(splitted_list2)):
    if splitted_list2[0] == '':
       do nothing
    else:
       x_+str(i)= splitted_list2[i]
       externalfunc(x_1,x_2,x_3,x_4,x_5)

continues depending on number of splitted_lists

..............

I appreciate any help and you are welcome to come with another idea to come around this.

Optimize a chain of IFs that use the .Find function

I've the forum a couple of times to check for answers, but this is the first time I ask a question.

I wrote a code that needs to find a couple of strings, and the actions are based on which strings it has found first. The problem is: right now I have a bunch of "ifs" and I think my code could be smaller. I think I'm writing the same thing twice, but I can't see how to write only once Also, I created some functions to make the code smaller.

I thought about using a Loop until I find one of the words, but I can't find a good way to exit the loop and tell which the word I found. Or use Select Case.

Thank you for your help and I apologize if I haven't followed some rule here.

Below is the function that I use in the code:

Function FindCell(FoundCell As Range, Text As String, RowUnid1 As Integer, RowUnid2 As Integer)

Set wb = ActiveWorkbook

With wb.Sheets("Preparation")

    Set FoundCell = .Range(("A" & RowUnid1), ("A" & RowUnid2)).Find(What:=Text, LookIn:=xlValues, SearchOrder:=xlByColumns)

End With
End Function

This is part of the code, with comments explaining

Call FindCell(FoundCell, "Próxima Intervenção:", RowUnid1, RowUnid2)    

If FoundCell Is Nothing Then                                                    'If it doesn't find "Próxima Intervenção:"
    Call FindCell(FoundCell, "Próximas Interven", RowUnid1, RowUnid2)           'Tries to find "Próximas Interven"

    If FoundCell Is Nothing Then                                                'If it does not find "Próximas Interven"
        Call FindCell(FoundCell, "Previsão de uti", RowUnid1, RowUnid2)         'Tries to find "Previsão de uti"

        If FoundCell Is Nothing Then                                            'If it does not find "Previsão de uti"
            Call FindCell(FoundCell, "Previsão para", RowUnid1, RowUnid2)       'Tries to find "Previsão para"

            If FoundCell Is Nothing Then                                        'If it does not find "Previsão para"
                Call FindRow(RowContato, "Contato", RowUnid1, RowUnid2)         'Finds "Contato", which is a string it will always find
                Call BreakLineTest(RowObjetivo, RowContato, "F", i)             'This is a function that determines wether it's going to copy 1, 2 or 3 lines, starting at the row where it found the word "objetivo" (RowObjetivo) (This part is not in here in the pasted code), using the row "contato" as a parameter

            Else                                                                'If it finds "Previsão para"
                RowPrevisao = FoundCell.Row         'assigns the number of the row where it found "Previsão para"
                Call BreakLineTest(RowObjetivo, RowPrevisao, "F", i)            'Now it uses RowPrevisao as a parameter
            End If

        Else                                                                    'If it finds "Previsão de"
            RowPrevisao = FoundCell.Row
            Call BreakLineTest(RowObjetivo, RowPrevisao, "F", i)                'Now it uses RowPrevisao as a parameter
        End If

    Else                                                                        'If it finds "Próximas Interven"
        RowProxInt = FoundCell.Row
        Call BreakLineTest(RowObjetivo, RowProxInt, "F", i)                     'Uses RowProxInt as a parameter
        Call FindCell(FoundCell, "Previsão de uti", RowUnid1, RowUnid2)         'Finds "Previsao de uti"

        If FoundCell Is Nothing Then                                            'If it does not find Previsão de"
            Call FindCell(FoundCell, "Previsão para", RowUnid1, RowUnid2)       'finds "Previsão para"

            If FoundCell Is Nothing Then                                        'If it doesn't find "Previsão para"
                Call FindRow(RowContato, "Contato", RowUnid1, RowUnid2)         'Finds "contato"
                Call BreakLineTest(RowProxInt, RowContato, "G", i)              'Uses RowContato as a parameter

            Else                                                                'If it finds "Previsão para"
                RowPrevisao = FoundCell.Row
                Call BreakLineTest(RowProxInt, RowPrevisao, "G", i)              'Uses RowProxInt as a parameter

            End If
        Else                                                                    'If it finds "Previsão de"
            RowPrevisao = FoundCell.Row
            Call BreakLineTest(RowProxInt, RowPrevisao, "G", i)                  'Uses ProxInt as parameter

        End If
    End If

Else                                                                            'If it finds "Próxima Intervenção"
    RowProxInt = FoundCell.Row
    Call BreakLineTest(RowObjetivo, RowProxInt, "F", i)                         'Uses ProxInt as parameter
    Call FindCell(FoundCell, "Previsão de uti", RowUnid1, RowUnid2)             'Tries to find "Previsão de"

    If FoundCell Is Nothing Then                                                'If it doesn't find "Previsão de"
        Call FindCell(FoundCell, "Previsão para uti", RowUnid1, RowUnid2)         'Tries to find "Previsão para"

        If FoundCell Is Nothing Then                                            'If it doesn't find "Previsão para"
            Call FindRow(RowContato, "Contato", RowUnid1, RowUnid2)             'Finds "contato"
            Call BreakLineTest(RowProxInt, RowContato, "G", i)
        Else                                                                    'If it finds "Previsão para"
            RowPrevisao = FoundCell.Row
            Call BreakLineTest(RowProxInt, RowPrevisao, "G", i)
        End If

    Else                                                                        'If it finds "Previsão de"
        RowPrevisao = FoundCell.Row
        Call BreakLineTest(RowProxInt, RowPrevisao, "G", i)
    End If
End If

After getting an input from a user I receive an error when apply if statement condition

store_data = pd.read_csv('/Users/user/PycharmProjects/Apriori /heart_disease.csv')

name = raw_input("Disease prediction? (Yes, No)")
type(name)

if name == 'Yes':
    df1 = store_data[['DIAB','AL ','SEX']]  #itemset filteration

elif name == 'No':
    df1 = store_data[['DIAB','SMOK','CHOL']]

I keep getting

File "", line 1 elif name == 'No': ^ SyntaxError: invalid syntax

The same happens when I try to use else with no condition

else: 
df1 = store_data[['DIAB','SMOK','CHOL']]

r: using `for` and `if` to run run function on numeric vars only

I have a four column dataframe with date, var1_share, var2_share, and total. I want to multiply each of the share metrics against the total only to create new variables containing the raw values for both var1 & var2. See below code (a bit verbose) to construct the dataframe that contains the share variables:

df<- data.frame(dt= seq.Date(from = as.Date('2019-01-01'), 
    to= as.Date('2019-01-10'), by= 'day'),
    var1= round(runif(10, 3, 12), digits = 1), 
    var2= round(runif(10, 3, 12), digits = 1))
df$total<- apply(df[2:3], 1, sum)
ratio<- lapply(df[-1], function(x) x/df$total)
ratio<- data.frame(ratio)
df<- cbind.data.frame(df[1],ratio)
colnames(df)<- c('date', 'var1_share', 'var2_share', 'total')
df

The final dataframe should look like this:

> df
date var1_share var2_share total
1  2019-01-01  0.5862069  0.4137931     1
2  2019-01-02  0.6461538  0.3538462     1
3  2019-01-03  0.3591549  0.6408451     1
4  2019-01-04  0.7581699  0.2418301     1
5  2019-01-05  0.3989071  0.6010929     1
6  2019-01-06  0.5132743  0.4867257     1
7  2019-01-07  0.5230769  0.4769231     1
8  2019-01-08  0.4969325  0.5030675     1
9  2019-01-09  0.5034965  0.4965035     1
10 2019-01-10  0.3254438  0.6745562     1

I have nested an if statement within a for loop, hoping to return a new dataframe called share. I want it to skip date when using the share variables for I've incorporated is.numeric so that it ignores date, however, when I run it, it only returns the date and not the desired result of date, the share of each variable (as separate columns), and the total column. See below code:

for (i in df){
  share<- if(is.numeric(i)){
     i * df$total
    } else i
  share<- data.frame(share)
  return(share)
}
share

> share
share
1  2019-01-01
2  2019-01-02
3  2019-01-03
...

How do I adjust this function so that share returns a dataframe containing date, variable 1 and 2 raw variables, and total?

PHP - If statement comparing string with contents of txt file

I did some research and couldn't find a clear answer to my problem. This is what I have:

<?php
    session_start();
    $gen_num = file_get_contents($_SESSION['filename']);
    $inp_num = $_POST['form-input'];
    if($gen_num === $inp_num){
        echo "Yes! The numbers match!";
    } else {
        echo "No, the numbers do not match&hellip;";
    }
?>

Where the 'filename' has a string of numbers and 'form-input' is carried from a previously submitted HTML form.

Why does the IF test fail when the strings are identical?

Logical operation "else without if" [on hold]

I am having problem with the if else statements. The moment I'm using "If", the error says "cannot resolve method 'if(boolean)'. And other error that says "else without if"

Please help.

 package com.learn.test;

    import javax.swing.*;

    public class test
    {
        public static void main(String[] args)
        {
            int number;
            String input;

            input = JOptionPane.showInputDialog("Enter your marks:");
            number = Integer.parseInt(input);

            If (number == 10)
            {
                JOptionPane.showMessageDialog(null, "The number is 10");
            }

            else if (number > 10)
            {
                JOptionPane.showMessageDialog(null, "The number is greater than 10");


            }


            }

}

How to include IF statement for ignoring NA cases in ggplot2

Hi everyone and thanks for reading my question,

I have tried to find a solution via similar topics, but haven't found anything suitable. This may be due to the search terms I have used. If I have missed something, please accept my apologies.

Here is my data (a bit shortened, but reproduce-able):

country year        sector      UN              ETS
BG      2000        Energy      24076856.07     NA
BG      2001        Energy      27943916.88     NA
BG      2002        Energy      25263464.92     NA
BG      2003        Energy      27154117.22     NA
BG      2004        Energy      26936616.77     NA
BG      2005        Energy      27148080.12     NA
BG      2006        Energy      27444820.45     NA
BG      2007        Energy      30789683.97     31120644
BG      2008        Energy      32319694.49     30453798
BG      2009        Energy      29694118.01     27669012
BG      2010        Energy      31638282.52     29543392
BG      2011        Energy      36421966.96     34669936
BG      2012        Energy      31628708.27     30777290
BG      2013        Energy      27332059.98     27070570
BG      2014        Energy      29036437.07     28583008
BG      2015        Energy      30316871.19     29935784
BG      2016        Energy      27127914.93     26531704
BG      2017        Energy      NA              27966156
CH      2000        Energy      3171899.5       NA
CH      2001        Energy      3313509.6       NA
CH      2002        Energy      3390115.69      NA
CH      2003        Energy      3387122.65      NA
CH      2004        Energy      3682404.04      NA
CH      2005        Energy      3815915.41      NA
CH      2006        Energy      4031766.36      NA
CH      2007        Energy      3718892.16      NA
CH      2008        Energy      3837098.91      NA
CH      2009        Energy      3673731.74      NA
CH      2010        Energy      3846523.62      NA
CH      2011        Energy      3598219.48      NA
CH      2012        Energy      3640743.25      NA
CH      2013        Energy      3735935.29      NA
CH      2014        Energy      3607411.44      NA
CH      2015        Energy      3292576.93      NA
CH      2016        Energy      3380402.57      NA
CY      2000        Energy      2964656.86      NA
CY      2001        Energy      2847105.45      NA
CY      2002        Energy      3008827.44      NA
CY      2003        Energy      3235739.95      NA
CY      2004        Energy      3294769.3       NA
CY      2005        Energy      3483623.91      3471844
CY      2006        Energy      3665461.17      3653380
CY      2007        Energy      3814469.11      3801667
CY      2008        Energy      3980439.76      3967293
CY      2009        Energy      4005649.27      3992467
CY      2010        Energy      3880758.22      3868001
CY      2011        Energy      3722369.39      3728038
CY      2012        Energy      3557560.24      3545929
CY      2013        Energy      2839148.88      2829732
CY      2014        Energy      2950111.64      2940320
CY      2015        Energy      3032961.55      3023003
CY      2016        Energy      3310941.55      3300001
CY      2017        Energy      NA              3287834

The code below is running smoothly and delivers what it should enter image description hereHowever, once the loop reaches a country (here CH) which ONLY has NA values in energy$ETS, the loop will just stop. What I need is to add an IF statement which allows to EITHER ignore the case described and just jumps to the next country (instead of aborting the operation) OR which plots only energy$UN (i.e. it only plots the variable ('UN') which has available data, as energy$ETS ONLY offers NA values).

IMPORTANT: I do not want to exclude all NA values, but I need the loop keep operating if it encounters a country which has no values for energy$ETS

ctry <- unique(energy$country)

# Color settings: colorblind-friendly palette
cols <- c("#999999", "#E69F00", "#56B4E9", "#009E73",           
"#F0E442", "#0072B2", "#D55E00", "#CC79A7")

for(i in (1:length(ctry))){

plot.df <- energy[energy$country==ctry[i],]
ets.initial <- min(plot.df$year)
x <- plot.df$UN[plot.df$year>=ets.initial & plot.df$year<2017]
y <- plot.df$ETS[plot.df$year>=ets.initial & 
plot.df$year<2017]
m1 <- round(summary(lm(y~x))$r.squared,3)
m2 <- round(lm(y~x-1)$coef,3)

p <- ggplot() +
geom_line(data=plot.df,aes(x=plot.df$year, y=plot.df$UN, 
color='UN 1.A.1'), na.rm=TRUE) +
geom_line(data=plot.df,aes(x=plot.df$year, y=plot.df$ETS, 
color='ETS 20')) + annotate(geom='text',label=paste0("R^2==",m1),x=2014,y=Inf,vjust=2,hjust=0,parse=TRUE,cex=3) +
annotate(geom='text',label=paste0("beta==",m2),x=2014,y=Inf,vjust=4,hjust=-0.15,parse=TRUE,cex=3)+
labs(x="Year",y="CO2 Emissions (metric tons)",z="",title=paste("Energy sector emissions for",ctry[i])) + 
theme(plot.margin=unit(c(.5,.5,.5,.5),"cm")) +
scale_color_manual(values = cols) +
scale_y_continuous(labels = scales::comma) +
scale_x_continuous(breaks = seq(2000, 2017, by = 5)) +
labs(color="Datasets")
p ggsave(p,filename=paste("H:/figures_energy/",ctry[i],".png",sep=""),width=6.5, height=6)
}

Thank you very much for any type of help!!

Best,

Constantin

Creating an if statement using var1 is None | var1 < var 2

I am trying to make what I thought would be a simple if statement. It goes as follows:

if (Main.longest_word is None) | (len(Main.longest_word) < len(word)):
            Main.longest_word = word

My issue is that I keep getting TypeError: object of type 'NoneType' has no len()

This makes sense to me, and I have solved the issue by simply turning my original if statement into two separate if statements.

My question is: Is there a way to make this if statement works as one, or am I forced to make two separate if statements in this situation.

Thanks for any advice.

Variable comparison and pattern replacement

I am trying to create a bash script that uses the sed command to replace a pattern by a variable that contains a string or put a space if there is nothing in the variable. I cannot find the good way to write it and make it work. Here is the part where I have issues:

a_flag=$(echo $a | wc -w)

if  [[ $a_flag = 0 ]]; then
    sed -i -e 's/#b/\\hspace{2cm}/g' source.tex
else
    sed -i -e "s/#b/$a/g" source.tex
fi

When running this, the condition is always false. I tried [] or (()) for the if statement but I just can't find a way to fix it.

Defining a function with condition

I have a silly problem. My df looks like this:

       FID_2     STA_SID           s2            s1  Qh_STA  Qh_FID2  \
14 222143.00 26040713.00           0.00        0.00    8.00    17.00   
15 222143.00 26040713.00           0.00        8.00    6.00    17.00   
13 222143.00 26040713.00           0.00        6.00    3.00    17.00   
17       NaN 26033594.00 29445425.00        1707.00    5.00      nan   

I defined the following function and command:

A = 0.8

def seekDO(row):
       if (row['Qh_STA'])/row['Qh_FID2'] < A :
          return 1
       if ((row['Qh_STA'] + row['s1'])/row['Qh_FID2'] < A) :
          return 1
       if ((row['Qh_STA'] + row['s1'] + row['s2']) / row['Qh_FID2'] < A) :
          return 1
       return 0

df['DO'] = df.apply (lambda row: seekDO(row),axis=1)

The problem is that for DO I get

    DO   
14  1  
15  1  
13  1  
17  0 

Instead of

    DO   
14  1  
15  0  
13  0  
17  0 

Can you perhaps see where I got mistaken?

If statement using a runnable handler

I am creating an android application and I am adding a shake feature using the library seismic https://github.com/square/seismic

With this shake feature I am trying to make it so that depending on the count of each shake it will open a respective page i.e. shake once for page 1, shake twice for page 2 and so on.

I am using a handler to wait 1700ms before initiating the if statement so it knows the correct count rather than straight away going to the first if statement (when count is 1) but it still goes from page 1 to page 2 to page 3 rather than waiting and going to the correct page the first time.

Home Class

mShakeDetector.setOnShakeListener(new com.example.name.project.ShakeDetector.OnShakeListener() {

            @Override
            public void onShake(final int count) {
                System.out.println(count);

                final Intent tts = new Intent(context, ttsScreen.class);
                final Intent stt = new Intent(context, sttScreen.class);
                final Intent cbb = new Intent(context, cbbScreen.class);
                final Intent ocr = new Intent(context, ocrScreen.class);

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        if( count == 1 ) {
                            startActivity(tts);
                        }
                        else if (count == 2) {
                            startActivity(stt);
                        }
                        else if (count == 3) {
                            startActivity(cbb);
                        }
                        else if (count == 4) {
                            startActivity(ocr);
                        }
                    }
                }, 1800);



            }
        });

ShakeDetector Class

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;

public class ShakeDetector implements SensorEventListener {

    /*
     * The gForce that is necessary to register as shake.
     * Must be greater than 1G (one earth gravity unit).
     * You can install "G-Force", by Blake La Pierre
     * from the Google Play Store and run it to see how
     *  many G's it takes to register a shake
     */
    private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
    private static final int SHAKE_SLOP_TIME_MS = 500;
    private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

    private OnShakeListener mListener;
    private long mShakeTimestamp;
    private int mShakeCount;

    public void setOnShakeListener(OnShakeListener listener) {
        this.mListener = listener;
    }

    public interface OnShakeListener {
        public void onShake(int count);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // ignore
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (mListener != null) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            float gX = x / SensorManager.GRAVITY_EARTH;
            float gY = y / SensorManager.GRAVITY_EARTH;
            float gZ = z / SensorManager.GRAVITY_EARTH;

            // gForce will be close to 1 when there is no movement.
            float gForce = (float)Math.sqrt( gX * gX + gY * gY + gZ * gZ );


            if (gForce > SHAKE_THRESHOLD_GRAVITY) {
                final long now = System.currentTimeMillis();
                // ignore shake events too close to each other (500ms)
                if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                    return;
                }

                // reset the shake count after 3 seconds of no shakes
                if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                    mShakeCount = 0;
                }

                mShakeTimestamp = now;
                mShakeCount++;

                mListener.onShake(mShakeCount);
            }
        }
    }
}

So essentially the shake detector class registers shake counts for 3 seconds before resetting which is fine but now in my Home class, I want it to register my shakes wait X seconds and then open the class properly but I'm not sure what is wrong with my approach?

I added a system out of the count, and its detecting shakes fine

I/System.out: 1 I/System.out: 2 I/System.out: 3

But it goes from page 1 to page 2 to page 3 (you can see the transitions); what is the reason for this?

I want to check a IF formula by using the IFS function

I have the following IF function, which tells us the source of some data in Excel.

=IF(D168=T168, " ", IF(AND(S168=0, R168<>0), "Invalid number", IF(AND(R168=0, Q168<>0),"Invalid Text", IF(AND(D168=0, T168<>0), "Source X", IF(AND(T168<>0, T168<>F168, OR (T168=G168, T168=O168, T168=P168)), "Source Y", " ")))))

Now I want to check that this formula is pulling the right source with an IFS function. I have tried IFS(D168=T168, " ", S168=0 R168<>0, "Invalid Number") but this formula returns an error.

I want to basically translate the IF formula above into an IFS formula.

if statement in a array

I have a data which im posting using cURL. Now i was wondering if i can pass 2 variables for 1 array.

This is the code that im using to send data

$data = [
    'completion_date'       =>  '31/03/2019',
    'customer_id'           =>  80,
    'full_name'             =>  '',
    'email_address'         =>  'email@email.com',
    'telephone'             =>  '012122212',
    'mobile'                =>  '0787878',
    'address'               =>  'Line 1 address'.chr(10).'Line 2 address',
    'city'                  =>  'City',
    'county'                =>  'County',
    'postcode'              =>  'Postcode',
    'site_company_name'     =>  'Site Company Name',
    'site_full_name'        =>  'Site Contact Name',
    'site_telephone'        =>  '012121212',
    'site_mobile'           =>  '07878787',
    'site_fax'              =>  'Depreciated, not in use',
    'site_email_address'    =>  'email@email.com',
    'site_address'          =>  'Site Line 1 address'.chr(10).'Line 2 address',
    'site_city'             =>  'Site City',
    'site_county'           =>  'Site County',
    'site_postcode'         =>  'Site Postcode',
    'site_notes'            =>  'Site Notes',
    'customer_ref'          =>  $RecordID,
    'wo_ref'                =>  'Customer Job Ref',
    'po_ref'                =>  $OrderID,
    'short_description'     =>  'short description of job',
    'description'           =>  'long description of job',
    'customer_notes'        =>  'Customer notes',
    'job_products'          =>  json_encode($job_products)
];

now i was wondering if i can do something like this

'customer_notes'        =>  $variable1 or $variable2,

what im trying to accomplish is if the $variable1 is empty use data from $variable2 and the other way around. is there a way of doing it or not really ?

'full_name'=> if $var1 empty use $var2

combining ks.test, var.test, t.test and wilcox.test into a decision-tree like function or if else function in r

I have my data like:

df1 <- read.table(text = "A1 A2 A3 A4 B1 B2 B3 B4
1 2 4 12 33 17 77 69
34 20 59 21 90 20 43 44
11 16 23 24 19 12 55 98
29 111 335 34 61 88 110 320
51 58 45 39 55 87 55 89", stringsAsFactors = FALSE, header = TRUE, row.names=c("N1","N2","N3","N4","N5"))

I want to compare the values between A and B, by row. First I want to test whether the distribution of A and B is normal distributed by ks.test. Second I will test whether the variation between A and B is different by var.test. For non-normal distributed results (p ks.test <0.05), I will conduct the wilcox test by wilcox.test. For normal distributed results, I will conduct the ttest by separating them into equal and unequal variance ttest by t.test. Finally I combine all the results.

What I have done is, first, I set up five functions of ks.test, var.test, wilcox.test and two t.test:

kstest<-function(df, grp1, grp2) {
  x = df[grp1]
  y = df[grp2]
  x = as.numeric(x)
  y = as.numeric(y)  
  results = ks.test(x,y,alternative = c("two.sided"))
  results$p.value
}
vartest<-function(df, grp1, grp2) {
  x = df[grp1]
  y = df[grp2]
  x = as.numeric(x)
  y = as.numeric(y)  
  results = var.test(x,y,alternative = c("two.sided"))
  results$p.value
}
wilcox<-function(df, grp1, grp2) {
  x = df[grp1]
  y = df[grp2]
  x = as.numeric(x)
  y = as.numeric(y)  
  results = wilcox.test(x,y,alternative = c("two.sided"))
  results$p.value
}
ttest_equal<-function(df, grp1, grp2) {
  x = df[grp1]
  y = df[grp2]
  x = as.numeric(x)
  y = as.numeric(y)  
  results = t.test(x,y,alternative = c("two.sided"),var.equal = TRUE)
  results$p.value
}

ttest_unequal<-function(df, grp1, grp2) {
  x = df[grp1]
  y = df[grp2]
  x = as.numeric(x)
  y = as.numeric(y)  
  results = t.test(x,y,alternative = c("two.sided"),var.equal = FALSE)
  results$p.value
}

Then I calculated the p value of ks.test and var.test for subsetting the data:

ks_AB<-apply(df1,1,kstest,grp1=grepl("^A",colnames(df1)),grp2=grepl("^B",colnames(df1)))

ks_AB
[1] 0.02857143 0.69937420 0.77142857 0.77142857 0.21055163

var_AB<-apply(df1,1,vartest,grp1=grepl("^A",colnames(df1)),grp2=grepl("^B",colnames(df1)))

var_AB
[1] 0.01700168 0.45132827 0.01224175 0.76109048 0.19561742

df1$ks_AB<-ks_AB
df1$var_AB<-var_AB

Then I subset the data by what I have described above:

df_wilcox<-df1[df1$ks_AB<0.05,]
df_ttest_equal<-df1[df1$ks_AB>=0.05 & df1$var_AB>=0.05,]
df_ttest_unequal<-df1[df1$ks_AB>=0.05 & df1$var_AB<0.05,]

Finally I calculate the corresponding test to the new dataframes, and merge the results

wilcox_AB<-as.matrix(apply(df_wilcox,1,wilcox,grp1=grepl("^A",colnames(df_wilcox)),grp2=grepl("^B",colnames(df_wilcox))))

ttest_equal_AB<-as.matrix(apply(df_ttest_equal,1,ttest_equal,grp1=grepl("^A",colnames(df_ttest_equal)),grp2=grepl("^B",colnames(df_ttest_equal))))

ttest_unequal_AB<-as.matrix(apply(df_ttest_unequal,1,ttest_unequal,grp1=grepl("^A",colnames(df_ttest_unequal)),grp2=grepl("^B",colnames(df_ttest_unequal))))

p_value<-rbind(wilcox_AB,ttest_equal_AB,ttest_unequal_AB)
colnames(p_value)<-c("pvalue")

df<-merge(df1,p_value,by="row.names")

df
  Row.names A1  A2  A3 A4 B1 B2  B3  B4      ks_AB     var_AB     pvalue
1        N1  1   2   4 12 33 17  77  69 0.02857143 0.01700168 0.02857143
2        N2 34  20  59 21 90 20  43  44 0.69937420 0.45132827 0.39648631
3        N3 11  16  23 24 19 12  55  98 0.77142857 0.01224175 0.25822839
4        N4 29 111 335 34 61 88 110 320 0.77142857 0.76109048 0.85703939
5        N5 51  58  45 39 55 87  55  89 0.21055163 0.19561742 0.06610608

I know my code is tedious and stupid, but it works for my data very well. I am now want to know I do I combine my above code to a new decision-tree-like function of if else function, which will like: enter image description here

mardi 26 février 2019

How do I use and if statement based around the results of data in html while using python?

I am attempting to label items in a csv file based on contents in an html which is being scraped using BeautifulSoup. For some items, more information is required to fulfill what is needed to be presented in said csv file.

I am trying to use and if statement to determine what to label something as in the csv file.

Here is the code:

                if prodictid is 'Bonus':
                        productname = ((container["data-product"]) + " Bonus Edition")
                else:
                        productname = (container["data-product"])

and here is the html. You can see where it says bonus, that is what I have as productid:

<span class="highlight">Bonus</span>

The code later on prints everything to the csv file without adding " Bonus Edition" even when productid is "Bonus".

Is there something I am missing? My current theory is that I am not having it check the string properly, but I do not know where to go from there or if that is even the case.

How to make array2d = array2d and make n = n + 1 in c

I want array2d = array2d and make n = n + 1 A[1][1]=A[1][2]&&A[1][1]=A[1][3] make n=n+1 What type of code must be used?

Matching a String with Array of String in Java Script

    str1 = booking_kode.substring(0, 3);
    B = ["800", "807", "826", "847", "866"];
    C = ["827", "846"];
    E = ["867", "879"];
    F = ["880", "899"];

    if (str1 = array B){
        print ('Prefix , first 3 digit = ' + str1 + '\n')
        comm_code = 'B000'
        print ('Comm_Code = ' + comm_code + '\n')
    }
    else if (str1 = array C) {
        print ('Prefix , first 3 digit = ' + str1 + '\n')
        comm_code = 'C000'
        print ('Comm_Code = ' + comm_code + '\n')
}
    else if (str1 = array E) {
        print ('Prefix , first 3 digit = ' + str1 + '\n')
        comm_code = 'E000'
        print ('Comm_Code = ' + comm_code + '\n')
}
    else if (str1 = array F) {
        print ('Prefix , first 3 digit = ' + str1 + '\n')
        comm_code = 'F000'
        print ('Comm_Code = ' + comm_code + '\n')
}
    else {
        print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n')
        comm_code = 'D000'
        print ('Comm_Code = ' + comm_code + '\n')
}

Hello,

I want to know how to match the string Str1 with the value of the Array B,C,E,F.

I mean :

If Str1 = 800|| 807 || 826 || 847 || 866, Then Comm_code = B000
If Str1 = 827 || 846 then Comm_code = C000
If Str1 = 867 || 879 then Comm_code = E000
If Str1 = 880 || 899 then Comm_code = F000
Else Default --> Comm_code = D000

Please kindly advice.

p.s. : Fyi, I'm using EcmaScript 2015 / ES5.

python: if-else statement only performing else: [duplicate]

This question already has an answer here:

input("Welcome to the cloud watching club! We need a bit of information about you before you join (press enter to continue)")

memberAge = input("How old are you?")

ageLimit = 100

if( ageLimit > memberAge ):
    answerOne = raw_input("Are you patient? [yes, no]")
else:
    print("I'm sorry, you do not qualify for this club :[")

Solver if cell = "Yes" then use that option

I am facing a problem when i want to add a constraint in solver. My issue is that i have an input sheet where i have the following:

Two-man shifts = Yes/no

Possible in real life = Yes/no

The value from those fields should be implemented in the solver so that if it says two-man shifts = no. Then solver shouldn't include those opportunities which has two-man shifts, i have tried many options and my final try was like this, but it didnt work: Sheet for solver

But it keeps using the two man shifts despite the value is = no i have used the following formula for the cells in D20-G20 (this will always be 1 since it is one-man shifts and should always be included)

=IF('Performance oversigt'!$C$19="yes";1;1)

In H20-K20 (the opportunities which is two-man shifts).

=IF('Performance'!$C$19="no";-1;1)

I changed the value to -1 because 0 didnt work but i wouldn't help.

I hope that some of you guys might be able to help me out on this one, i think the issue is caused by the signs, but i can't figure it out.

How can I check if a string has +, -, or . (decimal) in the first character?

I am writing a program that will determine if a double literal is 4 characters, and print it out on the screen. I believe I did the part right where I will check to see if there are exactly 4 characters. I am stuck on how to check if a +, - or . is the first character. With my str.charAt(0) == "+" || "-" || "." I am receiving an Incompatible operand error.

public class Program4 {

    public static void main(String[] args) {



    Scanner stdIn = new Scanner(System.in);

    String str;

    System.out.println("Please enter a valid (4 character) double literal consisting of these numbers and symbols: '+', '-', '.', (decimal point), and '0' through '9'");

    str = stdIn.nextLine();
    int length = str.length();

    // the next if statement will determine if there are exactly 4 characters \\
    if ( length == 4 ) { 

        // the next if statement checks for a +, -, or . (decimal) in the first character \\
        if ( str.charAt(0) == "+" || "-" || ".") {

        }
    }


    else {  

        System.out.println ("Please restart the program and enter in a valid 4 character double literal.");

    }

    }
}

IF statement running but not doing what's inside

I have a form that if you check one box, it send a boolean 'true' to the database, and then Im receiving the response and this is what I wanna work with.

THE FORM

$('#promotion-container footer').before(`
   <span class="buttonRedemp">
      <button class="redddButt load-button2" data="Reedem Card">Reedem Card</button>
   </span>

    `)

MY LOGIC WHEN RECEIVING THE INFORMATION

    if (buttonRedemption == true){
        console.log('Im true', eventName, buttonRedemption, typeof buttonRedemption)
        $('.redddButt').css('display', 'inline')
    }

    if(buttonRedemption == false || buttonRedemption == 'null' || buttonRedemption == null){
      console.log('IM SUPER FALSE', eventName, buttonRedemption, typeof buttonRedemption)
      $('.redddButt').css('display', 'none')
    }

the result is every card even if they are null or false or true are getting the button, but the weird thing is in the console I can see the correct information

enter image description here

Is this a normal behavior, how can I only make the button appear on the 3 cards that are true?

why this constructor doesn't give me the right answer

i did a break from programming for a while and i want to realize why this class doesn't give me the right answer i expect to get:

public class Date
{
    private int _day;
    private int _month;
    private int _year;
    public Date(int day, int month, int year)
    {
        _day=day;
        _month=month;
        _year=year;
        if((day<1||day>31)&&(month<1||month>12)&&(year<1000||year>9999))
            {
                _day=26;
                _month=2;
                _year=2019;
            }
        }
    public String toString()
    {
        return _day+"/"+_month+"/"+_year;
    }
    public static void main(String[]args)
    {
        Date test= new Date(5,13,1999);
        System.out.println(test.toString());
    }
}

When I insert the values to "test" object as (32,5,1999) it prints out 26.2.2019 hen I insert the values as (5,14,1999) it prints out 5.14.1999 and when I insert the values as (5,6,900) it prints out as 5.8.900 why don't I get the default values that I set at the constructor when the user inputs an illegal value (26.2.2019) thank you for your answers :)

Java gomoku algorithm with If's and loops: Constant null error

I am trying to create a java gomoku player that scans the board (8*8 2D array) and return a move that is somewhat competent (not using any complex data structures yet).

There is a GUI that lets me test a program, but every time I run this I get a 'null' and my player looses.

I've tried to put comments to explain - I dont know which part is causing the nulls so I've had to put my whole class here.

class Player160489815 extends GomokuPlayer{

public Move chooseMove(Color[][] board, Color myColour) {
    //first argument is current state of the board (each cell contains Color.black, Color.white or null)
    //second argument identifies which colour I am playing (Color.black or Color.white)

    //Initialise two variables to hold best values for row and column
    int x = 0; //int for row
    int y = 0; //int for col

    //2 loops to scan the entire board and evalute each empty square
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            //check is square is empty - if not, then ignore
            if (board[i][j] == null) {
                //give x,y values of empty square (possible valid move)
                x=i;
                y=j;
                //Check if the next two cells happen to be the same colour
                if (board[i + 1][j] == myColour && isNextSpaceSameHorizontal(board, myColour, i + 1, j) == true) {
                    //if true, moving to i,j would make a 3 in a row
                    x=i;
                    y=j;
                    //now check if text 3 cells = same colour
                    if (board[i + 2][j] == myColour && isNextSpaceSameHorizontal(board, myColour, i + 2, j) == true) {
                        //if true, moving to i,j would make a 4 in a row
                        x=i;
                        y=j;
                        //do same for next 4 cells
                        if (board[i + 3][j] == myColour && isNextSpaceSameHorizontal(board, myColour, i + 3, j) == true) {
                            //if true, moving to i,j would make a 5 in a row; since this is a winning move: return
                            return new Move(i, j);
                        }
                    }
                }
                //repeat above but horizontally
                if (board[i][j + 1] == myColour && isNextSpaceSameVertical(board, myColour, i, j + 1) == true) {
                    //if true, moving to i,j would make 3 in a row
                    x=i;
                    y=j;
                    if (board[i][j + 2] == myColour && isNextSpaceSameHorizontal(board, myColour, i, j + 2) == true) {
                        //if true, moving to i,j would make a 4 in a row
                        x=i;
                        y=j;
                        if (board[i][j + 3] == myColour && isNextSpaceSameHorizontal(board, myColour, i, j + 3) == true) {
                            //if true, moving to i,j would make a 5 in a row; since this is a winning move: return
                            return new Move(i, j);
                        }
                    }
                }
            }
        }//first for-loop
    }//second for-loop
    return new Move(x, y);
}//end chooseMove methods

//this method will check is the next horizontal cell is the same colour
public boolean isNextSpaceSameHorizontal(Color[][] board, Color me, int a, int b){
    boolean isTrue = false;
    if (board[a][b].equals(me)) {
        isTrue = true;
    }
    return isTrue;
}

//this method will check is the next vertical cell is the same colour
public boolean isNextSpaceSameVertical(Color[][] board, Color me, int a, int b){
    boolean isTrue = false;
    if (board[a][b].equals(me)) {
        isTrue = true;
    }
    return isTrue;
}

}//end class

The Move object has two fields, row and col, corresponding to a move at board[row][col], so both fields should be between 0 and 7

Help much appreciated.

Is php-mysql: update column with different values depending on condition involving PHP variable

I have a webform with the string variables $participant1, participant2, and $winner in php.When a form is posted it updates the columns participant and winner for two rows in my_table. The column type for winner is BOOLEAN.

Here is what my table currently looks like:

ID |Game |Participant | Winner
-------------------------------
1     1     John          NULL
2     1     Frank         NULL

The submitted variable $winner will be the name of either participant ('John' or 'Frank'). When it is submitted, I'd like for 1 to be set for which ever participant the string $winner matches. And 0 for the other participant.

i.e. if $participant1 =='John' and $winner=='John' Then the table should look like:

ID |Game |Participant | Winner
-------------------------------
1     1     John          1
2     1     Frank         0

I can't seem to figure this part out.

I tried:

$participant1= mysqli_escape_string( $con, $params['participant1']);
$participant2= mysqli_escape_string( $con, $params['participant2']);
$Winner= mysqli_escape_string( $con, $params['Winner']);    

mysqli_query($con, "UPDATE my_table SET Winner = IF('$Winner'=='$participant1',1,0) WHERE Participant ='$participant1');

mysqli_query($con, "UPDATE my_table SET Winner = IF('$Winner'=='$participant2',1,0) WHERE Participant ='$participant2'");

Winner still shows NULL afterwards. Is there a primarily MySQL way to do this?

Creating a New Variable Based On a Matched Array ID Value

I am extracting XML file data using DOMdocument and foreach loops. The XML file data contains tag names, ids, node values and attributes all which are used to extract the data I need.

I am struggling with using an if statement to define a variable that I want to echo. The premise of the if statement is if a certain id equals a certain id number then a new variable will be equal to the node value of that id number. I've put ** ** around the two or three lines of code that are the point of issue. They are at the bottom of the PHP code.

The if statement has three possible id values (only one will match) and the node value data of the matched id should be set equal to the new variable. If the <category id="1104"/> then the node value from <category id="1104">6-Speed A/T</category> will equal the new variable $transmissionfinal. Thus, $transmissionfinal should equal 6-Speed A/T. Whereas currently, it equals A/T.

Any help is appreciated!

Here is the XML data followed by my code:

XML 1

<factoryOption standard="false" optionKindId="7" utf="C" fleetOnly="false">
   <header id="1379">TRANSMISSION</header>
   <description>TRANSMISSION, 6-SPEED AUTOMATIC FOR RWD</description>
   <oem-description sequence="1">6-speed automatic transmission</oem-description>
   <oem-description sequence="2"><![CDATA[With the 6.2L engine on your CTS<em>-V<sup>&nbsp; </sup></em>Wagon, the 6-speed automatic transmission&nbsp;provides smooth, seamless transitions throughout its gear range, perfectly complementing the luxurious feel and responsive steering of a RWD vehicle. Thanks to Performance Algorithm Shifting, you can change the shift points simply by sliding the lever, enjoying a more aggressive progression for an exhilarating experience during sustained performance driving. And, with finger-actuated paddle shift controls on the steering wheel, this automatic immediately converts into a manual.]]></oem-description>
   <category id="1043"/>
   <category id="1104"/>
   <category id="1130"/>
   <category id="1131" removed="true"/>
   <price unknown="false" invoiceMin="0.0" invoiceMax="0.0" msrpMin="0.0" msrpMax="0.0"/>
   <styleId>331824</styleId>
   <installed cause="OptionCodeBuild"/>
</factoryOption>

XML 2

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
 <S:Body>
  <CategoryDefinitions xmlns="urn:description7b.services.chrome.com">
     <responseStatus responseCode="Successful" description="Successful"/>
      <category>
         <group id="6">Powertrain</group>
         <header id="15">Transmission</header>
         <category id="1104">6-Speed A/T</category>
         <type id="15">Transmission</type>
      </category>
      <category>
         <group id="6">Powertrain</group>
         <header id="37">Drivetrain</header>
         <category id="1043">Rear Wheel Drive</category>
         <type id="3">Drivetrain</type>
      </category>
      <category>
         <group id="6">Powertrain</group>
         <header id="15">Transmission</header>
         <category id="1130">A/T</category>
         <type id="16">Transmission - Type</type>
      </category>
  </CategoryDefinitions>
 </S:Body>
</S:Envelope>

PHP CODE

<?php


$xml = file_get_contents('XML/XML 1');
$dom = new DOMDocument();
$dom->loadXML($xml);

//Category XML
$txml = file_get_contents('XML/XML 2');
$tom = new DOMDocument();
$tom->loadXML($txml);

foreach ($tom->getElementsByTagName('category') as $catty){
  foreach($catty->getElementsByTagName('category') as $cattydef){
    $cattyid = $cattydef->getAttribute("id");
    $cattyvalue = $cattydef->nodeValue;
    $cattyarray[$cattyid] = $cattyvalue;
   }
  }

foreach ($dom->getElementsByTagName('factoryOption') as $factoryopt){
 foreach($factoryopt->getElementsByTagName('category') as $factcategory){
   if ($factoryopt->getElementsByTagName('header')->item(0)->getAttribute('id') == '1379'){
     $todescription = $factoryopt->getElementsByTagName('description')->item(0)->nodeValue;
   if($factcategory->getAttribute('removed')=='true'){
       $tocategory = "";
     }
     else{
       $tocategory = $factcategory->getAttribute('id');
     }
     $toarray[$tocategory] = $todescription;
  }
 }
}

foreach ($toarray as $tocatid => $tomeat){
  foreach($cattyarray as $tcid => $tcmeat){
    if($tocatid == $tcid){
      $toarray[$tocatid] = $tcmeat;
    **if ($tocatid == ('1104' || '1105' || '1106')){
      $transmissionfinal = $toarray[$tocatid];**
    }
   }
  }
 }
echo $transmissionfinal;


echo "<br><br>";


?>

R: using FOR-loop and IF-ELSE constructs to omit odd numbers in column

For a project, I was asked to create a FOR-loop with IF-ELSE construct where I omit the odd numbers in a column of the dataframe. However, when I was trying to construct it I couldn't get the right answer. This is how my code looks like:

for(i in 1:nrow(my_columns)) {
if (my_columns$id[[i]] %% 2 != 0) {
my_columns$id <- my_columns$id[[-i]]
  }
}

Then R returns this error message:

 Error in my_columns$id[[-i]] : 
 attempt to select more than one element in integerOneIndex

I think I am making a mistake in the part where the if statement has to return a value. Could you please tell me what my mistake is? Moreover, can you help me create the for-loop?

Thank you!

If function: Multiple required conditions - either continue or stop Node continuing with the function

I am looking to do an initial check on two conditions before I continue executing my code below. If no match is returned for both I want Node.js to stop any further processing. Not sure whether I should wrap my main code within the if function or just leave this as a check at the header of the code.

myValue = 500;
nameLow = "lato";
customerValue = 450;

// Initial check
if (nameLow == 'georgia' && myValue >= customervalue) {
    // Continue executing the code within or other code outside of if function
} else {
    // make Node.js stop executing and close
}

// Main code below (only executed when both conditions match

I am unsure whether to use return, continue, break and exitprocess() in these instances

Also, how could this be done better with a ternary statement?

Apply 'if' condition to compare two pandas column and form a third column with the value of the second column

I have two columns in pandas dataframe and want to compare their values against each other and return a third column processing a simple formula.

  if post_df['pos'] == 1:

    if post_df['lastPrice'] < post_df['exp']:
        post_df['profP'] = post_df['lastPrice'] - post_df['ltP']
        post_df['pos'] = 0
    else:
        post_df['profP'] = post_df['lastPrice'] - post_df['ltP']

However, when I run the above code I get the following error: if post_df['pos'] == 1: File "/Users/srikanthiyer/Environments/emacs/lib/python3.7/site-packages/pandas/core/generic.py", line 1479, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have tried using np.where which works but since I intend to build a complex conditional structure want to keep it simple using if statements.

how can i minimize my javascipt function?

I'm making a javascript function that gets certain stuff out an URL and calculates a value. This function works well but i would like to have some feedback on how i can minimilize this function with less code. It looks messy like this right now.

I would really appreciate some help.

Code:

getURL()
        {
            const myURL = this.blok.image;


                if (myURL != null)
                {
                    const split = myURL.split('/');

                    const array = split[5];

                    const split2 = array.split('x');

                    const height = split2[0];

                    const width  = split2[1];

                    const calc = width / height * 100;

                    alert(calc);
                }
                else {

                    return
                }
        }

Loop, if statements and column affecting another - VBA

Good Afternoon,

I am trying to automatize a report I have to build on a weekly basis, and I am struggling on one of the actions. Basically, I would like to check the content of column AN. Following the content, it should write in column BD a specific information. I would like the range to be from AN2 to last row. (there is no blank).

'To initiate the loop:
Sub New_Customer_Performance()


Dim LastRow As Long, x As Long LastRow = Cells(Rows.Count, "AN").End(xlUp).Row For x = 1 To LastRow
  Range("BC2").Select




'Then the IF statements: If Cells(x, "AN").Value Like "Time" Then Cells(x, "BD").Value = "A_On Time" ElseIf Cells(x, "AN").Value Like "*Credit*" Then Cells(i, "BD").Value = "B_Credit hold" ElseIf Cells(x, "AN").Value Like "*Customer*" Then Cells(i, "BD").Value = "C_Customer setup" End If Next x End Sub

basically, there is 8 or 9 Else If statements, but they are all written the same way. I might add a "Else" at the end in case there is other scenario. Thank you in advance for your help !

IF...ELSE in R Assistance

I am trying to write an If...Else statement in R and I am running into some difficulties. I have a data set that has 20 years of data and the values of VariableA need to be adjusted based on the specific year they are in (VariableB). I tried using an If...Else statement but I keep getting:

VariableA VariableB Multiplier VariableC 100 1998 1.4 140 100 1998 1.4 140 100 1999 1.7 170 100 1999 1.7 170 100 2000 2.0 200 100 2000 2.0 200

Error: unexpected '}' in " }"

The code that I have been trying to get to work is below:

Data <- function(DMG, YEAR){
if(YEAR = "1998"){
Data$TotDmg2017 <- Data$DMG * 1.433988335
}
}

I am not sure if this is the correct code to be using or if this is the most efficient way of doing this. I am unfamiliar with loops and If...Else statements so any assistance would be most appreciated.

multiple condition in if statement error in python [duplicate]

This question already has an answer here:

I didn't understand the if statement in python

x = "qqq @aaa test word anyword #bbb"
y = x.split()
for word in y:
    if '@' in word:
        print(word)

The output is "@aaa" but i want to add other condition,

x = "qqq @aaa test word anyword #bbb"
y = x.split()
for word in y:
    if '@' or '#' in word:
        print(word)

The output is all of list.

when I add parenthesis;

x = "qqq @aaa test word anyword #bbb"
y = x.split()
for word in y:
    if ('@' or '#') in word:
        print(word)

The output is "@aaa" ,again

Why? what is the logic of if statement? How can write more than one statement in if block?

How to translate my Excel If statement into the SQL Query

I am having a small issue translating my excel if statement into a CASE clause. Bellow I have posted my current SQL statement and the IF statement i am trying to fit in. Ideally i would like it to sit in the Where clause but if i need another column i will take that. Highlighted in bold is a different header.

Because of the way my where clause is set up it mean i only get half results

IF Statement is =IF(PD="AC","S",IF(PD="CS","S",IF(PD="CA","S",IF(**PT="SS","S"," ")**)))

Current SQL

SELECT 

`O C`
,`S O N`
,`O D`
,`O M`
,`P M`
**,`PT`**
,`P S T`
**,`PD`**
,`Q O`
,`P I V`
,`O C`
,`O I N`
,`P G`
,`P C`

FROM AEORCQ

WHERE (`PT` IN ('Misc','SS'))
AND (`PD` IN ('AC','C','C','S'))

Display a message if loop is empty

I would like to display a message like "no content" using a "if" in my template.

I tried :

views.py

 

It does not work, thanks.

How to create an if statement based on multiple conditions?

I'm trying to implement an if condition in Matlab that when two objects get at a distance of 30 meters of each other should accelerate until 100 m and after that it should behave normal. The condition should not work when the distance gets lower than 100 m but only when it reaches 29 m or below, until 100 m.

As I've read, Matlab will only take the first statement from the left so I was thinking to write the condition in 2 steps, but got stuck.

This is what I've done so far:

%%%%functia ----osc----simplu
function yprim=osccar1(t,y)
global dist1
if dist1<30
    antr=1;
elseif dist1>30
    antr=1;
end
if dist1<100
    bntr=1;
else
    bntr=2;
end
%    if dist1<30 && (dist1<100)
%         indth=1;
%    elseif dist1<100
%        indth=1;
%    else
%         indth=0;
%     end

magn=(y(1)^2+y(2)^2+y(3)^2)^(3/2);
yprim=zeros(6,1);
% if indth==1
if antr==bntr
    yprim(1,1)=y(4);
    yprim(2,1)=y(5)-0.001;
    yprim(3,1)=y(6);
    yprim(4,1)=double(y(1)/magn);
    yprim(5,1)=double(y(2)/magn);
    yprim(6,1)=double(y(3)/magn);
else
    yprim(1,1)=y(4);
    yprim(2,1)=y(5);
    yprim(3,1)=y(6);
    yprim(4,1)=double(y(1)/magn);
    yprim(5,1)=double(y(2)/magn);
    yprim(6,1)=double(y(3)/magn);
end

lundi 25 février 2019

(ANDROID Is it possible to insert to sqlite database after nested if statements returns true?

I am supposed to check the aller(arraylist) if it contains the allergies and check listview onitemclick if the (texts)item name matches the current food in the database. If it returns true then the user would not be able to insert that food. However, there are other foods in the database that doesn't have any relations to the allergies. How do I insert the food to the database after all the nested if statements finish? *SOME IF's ARE STILL EMPTY BECAUSE THERE IS STILL NO FOOD FOR THE SPECIFIC ALLERGY

 if (bmi1 < 18.5){
                if(caltotal<limit){
                    if(aller.contains("Milk")){
                        if(texts.equals("Milk")){
                            all();
                        }
                    }if(aller.contains("Cheese")){
                        if(texts.equals("Cheese")){
                            all();
                        }
                    }if(aller.contains("Butter")){

                    }if(aller.contains("Nuts")){

                    }if(aller.contains("Shrimp")){
                        if(texts.equals("Boiled Shrimp")){
                            all();
                        }
                    }if(aller.contains("Squid")){

                    }if(aller.contains("Crab")){

                    }if(aller.contains("Lobster")){

                    }if(aller.contains("Chocolate")){

                    }if(aller.contains("Coconut")){

                    }if(aller.contains("Chicken")){
                        if(texts.equals("Chicken Adobo")||(texts.equals("Chicken Burger")||(texts.equals("Chicken Wing")))){
                            all();
                        }
                    }if(aller.contains("Soy")){

                    }if(aller.contains("Eggs")){
                        if(texts.equals("Fried Egg")||(texts.equals("Egg (Over easy)")||(texts.equals("Egg Scrambled")||(texts.equals("Omelette"))))){
                            all();
                        }
                    }if(aller.contains("Pork")){
                        if(texts.equals("Bacon")||(texts.equals("Sausage")||(texts.equals("Pork Adobo")||(texts.equals("Pork Chop")
                                ||(texts.equals("Pork Longganisa")))))){
                            all();
                        }
                    }if(aller.contains("Beef")){
                        if(texts.equals("Beef Tapa")||(texts.equals("Bulalo")||(texts.equals("Meatloaf")||(texts.equals("Corned Beef")||
                                (texts.equals("Beef Tapa")||(texts.equals("Burger")||(texts.equals("Beef Caldereta"))||(texts.equals("Chili"))
                                        ||(texts.equals("Chili Dog"))||(texts.equals("Hotdog"))||(texts.equals("Steak"))||(texts.equals("Luncheon Meat"))
                                        ||(texts.equals("Longganisa")))))))){
                            all();
                        }
                    }else{
                        insertFood(type1, name1, grams, fat1, cal1, carbs1, protein1, mtype, date);
                        Toast.makeText(getActivity(), "Food has been Added!", Toast.LENGTH_SHORT).show();
                    }
public void all(){
    AlertDialog.Builder exit = new AlertDialog.Builder(getActivity());
    exit.setMessage("You are allergic to this!");
    exit.setCancelable(false);
    exit.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    AlertDialog alertDialog = exit.create();
    alertDialog.show();
}

Java If statement not correctly detecting and working if the state isn't a valid transition/state

So i am to create a mock state machine that works to take in an order file and a state machine file. This order file has information on the orders and the state in which its currently in and then transitioning to. So far as my program works now it can detect and process these transitions properly but then i am also to flag invalid lines or invalid transitions. So i would think that i would use an If statement in order to detect that if this given state or given transition compared to the current one is not detected then it should mark this line as invalid. The issue i'm having is exactly that though, my if statement which should do that for some reason prints out either nothing at all and acts like there aren't any invalid transitions which based on the given text file to test with there are. Or it will print out the same thing three times. It should be detecting that cancelled and fulfilled are terminal states or states that don't have any transitions and are final states and that any new lines with that same order number after should be flagged but these following lines don't even appear to be acknowledged. So i'm wondering why this else if statement isnt working as intended. The trouble area is listed with the comments in all caps.

Code - ParseState.java

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

import javax.sound.sampled.Line;

import com.fasterxml.jackson.databind.ObjectMapper;

import csi311.MachineSpec.StateTransitions; 

public class ParseState {

    public ParseState() {
    }


    public void run(String filename, String filename2) throws Exception {
        System.out.println("Parse State");
        HashMap<String, String> hmap = new HashMap<>();
        HashMap<String, String> h2map = new HashMap<>();
        ArrayList<String> flaggedids = new ArrayList<String>();
        ArrayList<String> flaggedidz = new ArrayList<String>();
        HashMap<String, String> h3map = new HashMap<>();
        ArrayList<String> pendingids = new ArrayList<String>();
        ArrayList<String> fulfilledids = new ArrayList<String>();
        ArrayList<String> cancelledids = new ArrayList<String>();
        ArrayList<String> submittedids = new ArrayList<String>();
        ArrayList<String> backordered = new ArrayList<String>();

        if (filename != null && filename2 != null) {
            String json = processFile(filename); 
            MachineSpec machineSpec = parseJson(json);
            dumpMachine(machineSpec); 
                String line = null;
                String orderid = "\\d\\d\\d-[A-Za-z][A-Za-z][A-Za-z]-\\d\\d\\d\\d";
                String timestamp = "\\S[0-9]{12}";
                String customerid = "\\S[0-9]{8}";
                String price = "\\S[0-9]{0,4}.[0-9]{2}";
                String quantity ="\\d{1,4}";
                String description = "\\w+";

                BufferedReader brrr = new BufferedReader(new FileReader(filename2));
                while((line = brrr.readLine()) != null) {
                    if(line.trim().isEmpty()) {
                        continue;
                    }
                String [] lineSplit = line.split(",");
                //System.out.println(lineSplit.length);
                String pkgtimestmp = lineSplit[0].trim();
                String pkgOrderId = lineSplit[1].trim();
                String pkgCustId = lineSplit[2].trim();
                String pkgState = lineSplit[3].trim();
                String pkgOrderDesc = lineSplit[4].trim();
                String pkgQuantity = lineSplit[5].trim();
                String pkgPrice = lineSplit[6].trim();
               // System.out.println(pkgtimestmp);
               // System.out.println(pkgOrderId);
               // System.out.println(pkgCustId);
               // System.out.println(pkgState);
              //  System.out.println(pkgOrderDesc);
               // System.out.println(pkgQuantity);
               // System.out.println(pkgPrice);
                if(lineSplit.length >= 2) {
                    //System.out.println(pkgOrderId);
                    if(pkgOrderId.matches(orderid)) {
                        //System.out.println(pkgOrderId);
                        // make it so that if same id placing order other order will be tracked too!
                        if(hmap.containsKey(pkgOrderId)) {

                            //System.out.println(pkgOrderId);
                            if(lineSplit.length == 7) {
                                //System.out.println(pkgOrderDesc);
                                if(pkgtimestmp.matches(timestamp)&& pkgCustId.matches(customerid)&& pkgQuantity.matches(quantity)
                                        && pkgPrice.matches(price)) {
                                    //System.out.println(pkgOrderId);
                                    //System.out.println(pkgOrderId + ":" + pkgState);
                                    String state1 = h3map.get(pkgOrderId);
                                    //System.out.println(state1);
                                    for(StateTransitions lt : machineSpec.getMachineSpec()) {
                                        //System.out.println(state1);
                                        //System.out.println(pkgState);
                                        if(lt.getState().contains(state1.toLowerCase())) {
                                            //System.out.println(state1);
                                            //System.out.println(pkgState);


                                            if(lt.getTransitions().contains(pkgState.toLowerCase())) {
                                                //System.out.println(state1);
                                                //System.out.println(pkgState);

                                                h3map.put(pkgOrderId, pkgState);

                                            }
                                            // WONT PRINT ANYTHING FOR SOME REASON
                                            else if(!lt.getTransitions().contains(pkgState.toLowerCase())) {
                                                System.out.println(state1);
                                                System.out.println(pkgState);
                                            }
                                        }
                                        // PRINTS WAY TOO MUCH INFORMATION WAY TOO MANY TIMES
                                        else if(!lt.getState().contains(state1.toLowerCase())) {
                                            System.out.println(state1);
                                            System.out.println(pkgState);
                                        }
                                    }


                                }
                                else if(!(pkgtimestmp.matches(timestamp)&& pkgCustId.matches(customerid)&& pkgQuantity.matches(quantity)
                                        && pkgPrice.matches(price))){
                                    flaggedids.add(pkgOrderId);
                                    if(!flaggedidz.contains(pkgOrderId)) {
                                        flaggedidz.add(pkgOrderId);
                                    }
                                }
                            }
                            else if(!(lineSplit.length == 7)) {
                                flaggedids.add(pkgOrderId);
                                if(!flaggedidz.contains(pkgOrderId)) {
                                    flaggedidz.add(pkgOrderId);
                                }
                            }

                        }
                        else if(!hmap.containsKey(pkgOrderId)) {
                            //System.out.println(pkgOrderId);
                            hmap.put(pkgOrderId, pkgCustId);

                            if(lineSplit.length == 7) {
                                //System.out.println(pkgOrderId);
                                if(pkgtimestmp.matches(timestamp)&& pkgCustId.matches(customerid)&& pkgQuantity.matches(quantity)
                                        && pkgPrice.matches(price)) {
                                    //System.out.println(pkgOrderId);
                                    //System.out.println(pkgState);
                                    for(StateTransitions gt : machineSpec.getMachineSpec()) {
                                        //System.out.println(pkgState);
                                        if(gt.getState().contains("start")) {
                                            //System.out.println(pkgState);
                                            if(gt.getTransitions().contains(pkgState.toLowerCase())) {
                                                h3map.put(pkgOrderId, pkgState);
                                                //System.out.println(h3map);
                                            }
                                        }
                                    }

                                }
                                else if(!(pkgtimestmp.matches(timestamp)&& pkgCustId.matches(customerid)&& pkgQuantity.matches(quantity)
                                        && pkgPrice.matches(price))){
                                    flaggedids.add(pkgOrderId);
                                    if(!flaggedidz.contains(pkgOrderId)) {
                                        flaggedidz.add(pkgOrderId);
                                    }
                                }
                            }
                            else if(!(lineSplit.length == 7)) {
                                //System.out.println(pkgOrderId);
                                flaggedids.add(pkgOrderId);
                                if(!flaggedidz.contains(pkgOrderId)) {
                                    flaggedidz.add(pkgOrderId);
                                }
                            }
                        }
                    }
                    else if(!pkgOrderId.matches(orderid)){
                        if(!flaggedids.contains(pkgOrderId)) {
                        flaggedids.add(pkgOrderId);
                                }
                        if(!flaggedidz.contains(pkgOrderId)) {
                            flaggedidz.add(pkgOrderId);
                                }
                            }

                        }
                    }

                for(int i = 0; i < flaggedids.size(); i++) {
                System.out.println("Flagging order: " + flaggedids.get(i));
                }
                //System.out.println("this is" + hmap);
                System.out.println("flagged " + flaggedidz.size());
                System.out.println("final mapping" + h3map);
                brrr.close();
        }
    }




    private void dumpMachine(MachineSpec machineSpec) {
        if (machineSpec == null) {
            return;
        }
        for (StateTransitions st : machineSpec.getMachineSpec()) {
            System.out.println(st.getState() + " : " + st.getTransitions());
        }
    }

    private String processFile(String filename) throws Exception {
        System.out.println("Processing file: " + filename); 
        BufferedReader br = new BufferedReader(new FileReader(filename));  
        String json = "";
        String line; 
        while ((line = br.readLine()) != null) {
            json += " " + line; 
        } 
        br.close();
        // Get rid of special characters - newlines, tabs.  
        return json.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll("\r", " "); 
    }


    private MachineSpec parseJson(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try { 
            MachineSpec machineSpec = mapper.readValue(json, MachineSpec.class);
            return machineSpec; 
        }
        catch (Exception e) {
            e.printStackTrace(); 
        }
        return null;    
    }


    public static void main(String[] args) {
        ParseState theApp = new ParseState();
        String filename = null; 
        String filename2 = null;
        if (args.length > 0) {
            filename = args[0]; 
            filename2 = args[1];
        }
        try { 
            theApp.run(filename, filename2);
        }
        catch (Exception e) {
            System.out.println("Something bad happened!");
            e.printStackTrace();
        }
    }   



}

CODE - MachineSpec.java

package csi311;

import java.io.Serializable;
import java.util.List;

@SuppressWarnings("serial")
public class MachineSpec implements Serializable {

    // Since defined as an inner class, must be declared static or Jackson can't deal.
    public static class StateTransitions implements Serializable {
        private String state; 
        private List<String> transitions;
        public StateTransitions() { }
        public String getState() { return state; }
        public void setState(String state) { this.state = state.toLowerCase(); } 
        public List<String> getTransitions() { return transitions; } 
        public void setTransitions(List<String> transitions) { 
            this.transitions = transitions;
            if (this.transitions != null) {
                for (int i = 0; i < transitions.size(); i++) {
                    transitions.set(i, transitions.get(i).toLowerCase()); 
                }
            }
        } 
    }

    private List<StateTransitions> machineSpec;
    public MachineSpec() { }
    public List<StateTransitions> getMachineSpec() { return machineSpec; } 
    public void setMachineSpec(List<StateTransitions> machineSpec) { this.machineSpec = machineSpec; } 


}

ORDER FILE TO TEST

1543113695001, 001-ABC-4567, 123456789, PENDING  ,   bagel toaster             ,   1,    19.95
1543113695002, 001-ABC-4567, 123456789, submitted,   bagel toaster             ,   2,    39.90
1543113695003, 001-ABC-4567, 123456789, fulfilled,   bagel toaster             ,   2,    39.90
1543113695004, 002-123-4567, 123456789, fulfilled,   bagel                     ,   1,     1.50
1543113695005, 003-AAA-4599, 123456799, PENDING  ,   bagel toaster             ,   1,    19.95
1543113695006, 003-AAA-4599, 123456799, cancelled,   bagel toaster             ,   1,    19.95
1543113695007, 003-AAA-4599, 123456799, fulfilled,   bagel toaster             ,   1,    19.95
1543113695008, 004-AAA-4598, 123456799, pending,     bagel toaster             ,   1,    19.95
1543113695009, 005-AAA-4597, 123456799, pending,     bagel toaster             ,   1,    19.95
1543113695010, 005-AAA-4597, 123456799, cancelled,   bagel toaster             ,   1,    19.95
1543113695011, 006-AAA-4597, abcdefghi, pending,     bagel toaster             ,   1,    19.95
1543113695011, 006-AAA-4597, abcdefghi, pending,     bagel toaster             ,   1,    19.95
1543113695012, 007-AAA-4597, 112233445, pending,     bagel toaster             ,   1,    19.95
1543113695013, 007-AAA-4597, 112233445, submitted,   bagel toaster             ,   1,    19.95
1543113695014, 007-AAA-4597, 112233445, backordered, bagel toaster             ,   1,    19.95
1543113695015, 007-AAA-4597, 112233445, fulfilled,   bagel toaster             ,   1,    19.95

State Machine File

{ "machineSpec" : [ 
    { "state" : "START", "transitions" : ["pending", "submitted"] }, 
    { "state" : "pending", "transitions" : ["PENDING", "cancelled", "submitted"] }, 
    { "state" : "submitted", "transitions" : ["cancelled", "submitted", "backordered", "fulfilled"] },
    { "state" : "backordered", "transitions" : ["backordered" ,"cancelled", "fulfilled"] }
] }  

Current Output

Parse State
Processing file: test.in
start : [pending, submitted]
pending : [pending, cancelled, submitted]
submitted : [cancelled, submitted, backordered, fulfilled]
backordered : [backordered, cancelled, fulfilled]
PENDING
submitted
PENDING
submitted
PENDING
submitted
submitted
fulfilled
submitted
fulfilled
submitted
fulfilled
PENDING
cancelled
PENDING
cancelled
PENDING
cancelled
cancelled
fulfilled
cancelled
fulfilled
cancelled
fulfilled
cancelled
fulfilled
pending
cancelled
pending
cancelled
pending
cancelled
pending
submitted
pending
submitted
pending
submitted
submitted
backordered
submitted
backordered
submitted
backordered
backordered
fulfilled
backordered
fulfilled
backordered
fulfilled
Flagging order: 002-123-4567
Flagging order: 006-AAA-4597
Flagging order: 006-AAA-4597
flagged 2
final mapping{004-AAA-4598=pending, 005-AAA-4597=cancelled, 001-ABC-4567=fulfilled, 003-AAA-4599=cancelled, 007-AAA-4597=fulfilled}