dimanche 31 mars 2019

i want to show the avalible times as bold and unavaliable times(strike) in label with corresponding to api data

for api data for day(different timings for all days & sunday closed) and date, get the entering time and leaving time, from that change the label as bold in avialiable time and strike on unaavaliable times.

before entering time all times are unavaliable and after leaving all times are unavaliable and also lunch time unavaliable

how to write the condition from api data to the label change(to bold/ strike)

API Data:

 Optional(<__NSSingleObjectArrayI 0x600003873050>(
 {
  day = Saturday;
  dArray = "<null>";
  enteringTime = "09.00 am";
  entryTime = "<null>";
  exitTime = "<null>";
  id = 13;
  leavingTime = "05.00 pm";
  lunchtimeFrom = "13:00";
  lunchtimeTo = "14:00";
 }

R: changing some column values, but not all, based on other column's values: problems with ifelse() and if(){}

I want to change certain values in one column (B) if a certain value appears in another column (A) but otherwise for the column values to remain unchanged. For example, in the following simplified version of my data I want to change the value in column B to be "0" if the value in column A is "none" otherwise I want the values in column B to remain unchanged

df <- data.frame(ID=c(1:4),A=c("1/wk","none","1/mo","1/wk"),B=c("3",NA,NA,"depends"))
    > df
      ID    A       B
    1  1 1/wk       3
    2  2 none    <NA>
    3  3 1/mo    <NA>
    4  4 1/wk depends

I tried this

df$B <- ifelse(df$A == "none","0",df$B)
    > df
      ID    A    B
    1  1 1/wk    1
    2  2 none    0
    3  3 1/mo <NA>
    4  4 1/wk    2

While this does change ID 2 to "0" in column B (which I want), it also changes the other values in column B. I want my output to look like this:

> df
  ID    A       B
1  1 1/wk       3
2  2 none       0
3  3 1/mo    <NA>
4  4 1/wk depends

I also tried to use if(){} but can't figure out how to use it when there are multiple columns involved

I am not particular about what function to use (though I prefer answers that use base R). PS - while I have found similar questions on stackoverflow none of the answers have worked for me.

Why doesn't this if else statement work it keeps entering error?

I am trying to find the highest value for this set of variables but it keeps providing errors. I was wondering if the logic of the statements is wrong and how it can be fixed? h1=3 h3=4 h5=8

  if h1>=h3>=h5
    puts "example"
    elsif h1>=h5>=h3
     puts "w"
    elsif h3>=h1>=h5
     puts "e"
    elsif h3>=h5 >=h1
     puts "yeah"
    elsif h5>=h1>=h3
     puts "cool"
    elsif h5>=h3>=h1
     puts "bish"
  end

Looping through XML file to replace certain elements (Python)?

I am trying to loop through a certain XML file in python in order to replace certain lines. I am very new to XML file formats and I dont know how libraries such as elementTree or minidom works. The XML file in question is as followed:

<?xml version="1.0" encoding="utf-8"?>
<StructureDefinition xmlns="http://hl7.org/fhir">
  <url value="http://example.org/fhir/StructureDefinition/MyPatient" />
  <name value="MyPatient" />
  <status value="draft" />
  <fhirVersion value="3.0.1" />
  <kind value="resource" />
  <abstract value="false" />
  <type value="Patient" />
  <baseDefinition value="http://hl7.org/fhir/StructureDefinition/Patient" />
  <derivation value="constraint" />
  <differential>
    <element id="Patient.identifier.type">
      <path value="Patient.identifier.type" />
      <short value="Description of identifier&#xD;&#xA;YY" />
      <definition value="A coded type for the identifier that can be used to determine which identifier to use for a specific purpose.&#xD;&#xA;YY1" />
    </element>
    <element id="Patient.identifier.type.coding">
      <path value="Patient.identifier.type.coding" />
      <short value="Code defined by a terminology system&#xD;&#xA;XX" />
      <definition value="A reference to a code defined by a terminology system.&#xD;&#xA;XX2" />
    </element>
    <element id="Patient.maritalStatus.coding">
      <path value="Patient.maritalStatus.coding" />
      <short value="Code defined by a terminology system&#xD;&#xA;XX" />
      <definition value="A reference to a code defined by a terminology system.&#xD;&#xA;XX1" />
    </element>
    <element id="Patient.contact.relationship.coding">
      <path value="Patient.contact.relationship.coding" />
      <short value="Code defined by a terminology system&#xD;&#xA;XX" />
      <definition value="A reference to a code defined by a terminology system.&#xD;&#xA;XX1" />
    </element>
    <element id="Patient.contact.organization.identifier.type.coding">
      <path value="Patient.contact.organization.identifier.type.coding" />
      <short value="Code defined by a terminology system&#xD;&#xA;XX" />
      <definition value="A reference to a code defined by a terminology system.&#xD;&#xA;XX1" />
    </element>
  </differential>
</StructureDefinition>

as you can see above, there are places marked with XX (short value), or XX1 (definition value) that I want to replace with some text. Furthermore, the places marked with XX are all under 'short value' of some element with name ending in '.coding', and XX1 are all under 'definition value' (which is all sub-elements of the 'differential' element). I can't quite figure out how to organize this, what I have so far is as below:

from xml.dom.minidom import parse # use minidom for this task

dom = parse('C:/Users/Joon/Documents/FHIR/MyPatient.StructureDefinition.xml') #read in your file

replace1 = "replacement text" #set replace value
replace2 = "replacement text2" #set replace value2
res = dom.getElementsByTagName('*.coding') #iterate over tags
for element in res:
    print('true')
    element.setAttribute('short value', replace1)
    element.setAttribute('definition value', replace2)

with open('MyPatientUpdated.StructureDefinition.xml', 'w', encoding='UTF8') as f:
    f.write(dom.toxml()) #update the dom, save as new xml file

I can't get the loop to print 'true' because 'res' is an empty list. Any help is greatly appreciated, thank you in advance!

How do you get this if/else statement to print out the method call in this java project? [duplicate]

This question already has an answer here:

I'm making a simple calculator program that allows the user to input the function they (adding, subtracting, multiplying, or division) and put in the first and second number of their equation. I've got all of the methods for adding, subtracting and whatnot but I have one problem on my hands and that's creating an if-else statement in the main method that prints out the result of the chosen function.

Here's the code:

import static java.lang.System.*;
import java.util.*;

public class calculator1
{
    public static void main(String[] args)
    {
        Calculator ti_83 = new Calculator();
        Scanner scan = new Scanner(in);

        out.print("Do you want to add, subtract, multiply or divide?: ");
        String function = scan.nextLine();

        out.print("Type in the first number you want to " + function + ": ");
        double num1 = scan.nextDouble();

        out.print("Type in the second number you want to " + function + ": ");
        double num2 = scan.nextDouble();

        if(ti_83.whatFunction(function) == "add")
            out.print("\nFinal sum:\n");
            out.println(ti_83.addition(num1, num2));

        else if(ti_83.whatFunction(function) == "subtract")  // <------- this is where I get the error
            out.print("\nFinal difference:\n");
            out.println(ti_83.subtraction(num1, num2) + "\n");


    }
}

class Calculator
{
    String math = null;
    double add, sub, multiply, divide;

    String whatFunction(String func)
    {
        if(func.equalsIgnoreCase("add") || func.equalsIgnoreCase("a"))
            math = "add";
        else if(func.equalsIgnoreCase("subtract") || func.equalsIgnoreCase("s"))
            math = "subtract";
        else if(func.equalsIgnoreCase("multiply") || func.equalsIgnoreCase("m"))
            math = "multiply";
        else if(func.equalsIgnoreCase("divide") || func.equalsIgnoreCase("d"))
            math = "divide";
        return math;
    }

    double addition(double n1, double n2)
    {
        add = n1 + n2;
        return add;
    }

    double subtraction(double n1, double n2)
    {
        if(n1 > n2)
            sub = n1 - n2;
        else
            sub = n2 - n1;
        return sub;
    }

    double multiplication(double n1, double n2)
    {
        multiply = n1 * n2;
        return multiply;
    }

    double division(double n1, double n2)
    {
        if(n1 > n2)
            divide = n1 / n2;
        else
            divide = n2 / n1;
        return divide;
    }

}

An explanation as to why this if-else statement isn't running would be appreciated.

if statement fails when used with semi-colon separator

I don't understand why I'm having an error with Python when I use a single-line if statement after a semicolon (used as separator).

This is ok:

if True: print("it works")
#### it works

But this gives a syntax error:

a=1; if True: print("it should work?")
#### SyntaxError: invalid syntax

I use Python3, with Spyder.

Thanks for any explanation!

How to get an outcome for r plot for a code that implements a beta-delta model

My code for getting a proper plot in R does not seem to work (I am new to R and I am having difficulties with coding).

Basically, using the concept of temporal discounting in the form of beta-delta model, we are supposed to calculate the subjective value for $10 at every delay from 0 to 365.

The context of the homework is that we have to account for the important exception that if a reward is IMMEDIATE, there’s no discount, but if it occurs at any delay there’s both an exponential discount and a delay penalty.

I created a variable called BetaDeltaValuesOf10, which is 366 elements long and represents the subjective value for $10 at each delay from 0 to 365.

The code needs to the following properties using for-loops and an if-else statement:

1) IF the delay is 0, the subjective value is the objective magnitude (and should be saved to the appropriate element of BetaDeltaValuesOf10.

2) OTHERWISE, calculate the subjective value at the exponentially discounted rate, assuming 𝛿 = .98 and apply a delay penalty of .8, then save it to the appropriate element of BetaDeltaValuesOf10.

The standard code given to us to help us in creating the code is as follows:

BetaDeltaValuesOf10 = 0

Delays = 0:365

Code to get subjective value/preference using exponential discounting model:

ExponentialDecayValuesOf10 = .98^Delays*10

0.98 is the discount rate which ranges between 0 and 1.

Delays is the number of time periods in the future when the later reward will be delivered

10 is the subjective value of $10

Code to get subjective value using beta-delta model:

0.8*0.98^Delays*10

0.8 is the delay penalty

The code I came up with in trying to satisfy the above mentioned properties is as follows:

for(t in 1:length(Delays)){BetaDeltaValuesOf10 = 0.98^0*10

if(BetaDeltaValuesOf10 == 0){0.98^t*10}

else {0.8*0.98^t*10} }

So, I tried the code and did not get any error. But, when I try to plot the outcome of the code, my plot comes up blank.

To plot I used the code:

plot(BetaDeltaValuesOf10,type = 'l', ylab = 'DiscountedValue')

I believe that my code is actually faulty and that is why I am not getting a proper outcome for my plot. Please let me know of the amendments to the code and if the community needs any clarification, I will try to clarify as soon as I can.

Python - How to write varying number of 'if (condition) or if(condition)'?

I was trying to make a parser in Python which goes through multiple files, searches for given words, and returns all the lines that contain that string.

The method I am using is making the same line from the document containing a searched word print multiple times, if that line contains multiple words that user is trying to search.

The search method I am using currently is :

for line in range(0,length_of_documents):
    for word in range(0,words):
        if words[word] in document[line]:
            print(document[line])

To overcome this, I need to write something like :

for line in range(0,length_of_documents):
    for word in range(0,words):
        if words[0] in document[line] or if words[1] in document[line] or if words[2] in document[line]:
            print(document[line])

But I don't know how many words the user can enter for the search string. What is a possible solution for this?

I have used eval() function which gets passed in the string dynamically generated 'if words[0] in document[line] or if words[1] in document[line] or........' during runtime, but that does not work. I get syntax error at 'if'.

How to index variables in loops in stata?

I am trying to replace entries of a variable 'personid' if the values of the other variables match each other. I usually code in python and r, so i tried to do this by indexing the variables and looping it. But it doesn't seem to work in Stata. Does anyone have advice? My code is below:

forvalues i=1/1545 {
if contestantname == contestantname[_n-1] & villageid == villageid[_n-1] & SeatCategory == SeatCategory[_n-1] {
    if  personid[_n-1] == . {
        replace personid[_n-1] == personid 
        }

    else if {replace personid == personid[_n-1]
        }
}

thanks!

Unused arguments while using ifelse in R shiny

in app.R in server function

server <- function(input, output) {

I have this reactive function which checks the radiobutton input and populates the input choice in select input.

var <- reactive({
    switch(input$selectBy,
           "cname" =  customers[,1],
           "cloan_num" =  customers[,2]
          )
  })

Now I wanted to change the label in the selectInput function based on radio button but I am not able to do so.

  ifelse(input$selectBy == "cname", lbText = "Select Customer Name", lbText = "Select Loan AC Number" )

in the above line I am getting

Error in ifelse(input$selectBy == "cname", lbText = "Select Customer Name", : unused arguments (lbText = "Select Customer Name", lbText = "Select Loan AC Number")

  output$selInp <- renderUI({
      selectInput("noc",lbText, var(), selected = NULL, multiple = FALSE,
                selectize = TRUE, width = NULL, size = NULL)
  })

Full Code:

ui=fluidPage(

  titlePanel("Title"),
  sidebarLayout(position = "left",

  sidebarPanel(
      fluidRow(

        uiOutput("selInp"),

        radioButtons("selectBy", "Search By:",
                     c("Customer Name" = "cname",
                       "Customer Loan No" = "cloan_num")),

        pickerInput("branch","Branch", choices=unique(customers[,4]), options = list(`actions-box` = TRUE),multiple = T),

        dateInput("endDate", "End Date:", value = "2018-12-30")
      )
    ),

  mainPanel()

  )

)

########################## server function ################################

server <- function(input, output) {

  var <- reactive({
    switch(input$selectBy,
           "cname" =  customers[,1],
           "cloan_num" =  customers[,2]
          )
  })

  ifelse(input$selectBy == "cname", lbText = "Select Customer Name", lbText = "Select Loan AC Number" )

  output$selInp <- renderUI({
      selectInput("noc",lbText, var(), selected = NULL, multiple = FALSE,
                selectize = TRUE, width = NULL, size = NULL)
  })



}

shinyApp(ui, server)

How to extract and use TRUE answers of one function in another

I need to create a function(y) where y is the specified number of multiples of three. For example, if 3 is inputted as y, then 3, 6 and 9 should be printed. My thought process was having a function(x) with an if statement to identify whether a number is a multiple of three or not and then using a which statement on the TRUE answers in function(x) in function(y)

This is my function(x):

f <- function(x) { if (any(x %% 3== 0)) { TRUE } else { FALSE } }

function(y) will be along the lines of a which statement where 3 is the first number displayed and then up to the number of specified multiples of three by using the TRUE answer in function(x) and will print each answer and stop once it is up to the specified number. I am just not too sure how to execute my thought process or if there is a better way to do this?

samedi 30 mars 2019

Batch file not opening correct menu option when errorcode is returned

I have written a batch file that gets input from the user to open a file, then displays a menu. Input is then prompted from the user using a .exe C file I wrote and returns the number the user entered, or "-1" if input was not a number. No matter which option I use, the program always open notepad regardless of the menu option. Any help would be great. Ive included code for the batch file and my c input file.

I have checked my C program and it seems to be returning what it is supposed to so it might just be an issue with formatting on the batch side. I included just for reference.

BATCH FILE:

REM 1. Clear the screen
REM ------------------------------------------------------
cls


REM 2. Getting user input
REM ------------------------------------------------------

SET /p "FileToProcess=Please enter file(s) to process:" 

REM 3. Checking for file
REM ------------------------------------------------------
IF EXIST "%FileToProcess%" (
    cls
    :MENU
    ECHO 1. Open in Notepad
    ECHO 2. Open in Word
    ECHO 3. Open in Notepad ++
    ECHO 4. Print

    myChoice.exe
    )

    IF ERRORLEVEL 1 (
    cd C:\Windows
    notepad.exe %FileToProcess%
    GOTO END
    )

    IF ERRORLEVEL 2 (
    cd C:\Program Files (x86)\Microsoft Office\root\Office16
    WINWORD.EXE %FileToProcess%
    GOTO END
    )

    IF ERRORLEVEL 3 (
    cd C:\Program Files\Notepad++
    notepad++.exe %FileToProcess%
    GOTO END
    )

    IF ERRORLEVEL 4 (
    cd C:\Windows
    notepad.exe /P %FileToProcess%
    GOTO END
    )

    IF ERRORLEVEL -1 (

    ECHO Sorry your input was not accepted!
    pause
    GOTO MENU
    )
REM 4. Display error if no file found
REM -----------------------------------------------------
) ELSE (

    ECHO File does not exist!
    GOTO END

)


:END

C INPUT PROGRAM CODE:

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

#pragma warning(disable:4996)
// main
int main(void)
{
    // variables
    int num;
    char userInput[10] = "";

    // requesting input
    printf("Please enter a menu option: ");
    fgets(userInput, 81, stdin);

    // checks input
    if (sscanf(userInput, "%d", &num) == 1)
    {
        return num;
    }
    else
    {
        return -1;
    }

    return 0;

}

Part of println not showing expected result

I was given this assignment to do and I have gotten all my variables values and calculated some stuff. However I couldn't show the System.out.println("Recommended Graphics Quality: " + performance); it would not show the string performance at all.

File file = new File("Computers.txt");//Grabs file and scans it
  try{
     Scanner inputFile = new Scanner(file);//opens the file
     gpuSpeed = inputFile.nextInt();
     cpuSpeed = inputFile.nextInt();
     numCore = inputFile.nextInt();
     choiceMonitor = inputFile.nextInt();
  } catch (FileNotFoundException e){
     System.out.println("File not found");
  }

switch(choiceMonitor)
{
  case 1:
     performanceScore = ((5 * gpuSpeed) + (numCore * cpuSpeed)) * 1;
     monitor = "1280 x 720";
     break;

  case 2: 
     performanceScore = ((5 * gpuSpeed) + (numCore * cpuSpeed)) * .75;
     monitor = "1920 x 1080";
     break;

  case 3: 
     performanceScore = ((5 * gpuSpeed) + (numCore * cpuSpeed)) * .55;
     monitor = "2560 x 1440";
     break;

  case 4: 
     performanceScore = ((5 * gpuSpeed) + (numCore * cpuSpeed)) * .35;
     monitor = "3840 x 2160";
     break;
}

if(performanceScore > 17000.0)
{
  performance = "Ultra";
}
else if(performanceScore > 15000.0 && performanceScore < 17000.0)
{
  performance = "High";
}
else if(performanceScore > 13000.0 && performanceScore < 15000.0)
{
  performance = "Medium";
}
else if(performanceScore > 11000.0 && performanceScore < 13000.0)
{
  performance = "Low";
}
else if(performanceScore == 11000.0 || performanceScore < 11000.0)
{
  performance = "Unable to Play";
}
System.out.println("Recommended Graphics Quality: " + performance);

Print files and directories using if-then-else and state whether or not it's a file or directory

Create an if-then-else statement to test if a file, represented by the variable $filename, is in fact a file. The statement should also output a notification message which indicates the result of the test.

My goal is to incorporate the above, but by listing the contents of the current directory only and next to each line it states if it's a file or directory [maybe in color].

So far I have gotten this to work.

filename="wp-config.php"

if [ -f "${filename}" ] ; then echo "${filename} is a file" elif [ -d "${filename}" ] ; then echo "${filename} is a directory" fi

How to fix 'Error in if (p_change[j] == dat[i, 1]) { : missing value where TRUE/FALSE needed' in a loop?

I am new to R. I am running a loop which basically compares the values contained in a vector (p_change) with the values in a column of a data frame (dat). In case the number coincides, I want a value of the same row but a different column to be subtracted by one. This is a sample of the vector (p_change):

p_change <- c(30101,92901,92031,90630,90282,10401)

The data frame (dat) to which it is compared is as follows: enter image description here

The for loop that I am running is this one:

for (i in 1:nrow(dat)) {
  for (j in 1:length(p_change)) {
    if (p_change[j]==dat[i,1]) {
      dat[i,4] <- 1-dat[i,4] # Subtraction of a unit (polarity change)
    } else {
      i = i+1
    }
  }
}

However, after running it, it throws me the following error 'Error in if (p_change[j] == dat[i, 1]) { : missing value where TRUE/FALSE needed'. I was wondering if you spot the glitch that causes the error. Thanks!

How would I fix this if statement in C to get it working as intended?

In this piece of code for a "contact management system" I am having difficulty in getting the intended output for a line. Basically, during this one part when you are adding a new contact, it asks you to "please enter an apartment #" as shown below:

if (yes() == 1)
{
printf("Please enter the contact's apartment number: ");
address->apartmentNumber = getInt();
if (address->apartmentNumber > 0) {
}
else {
printf("*** INVALID INTEGER *** <Please enter an integer>: ");
address->apartmentNumber = getInt();
}

}
else
{
address->apartmentNumber = 0;
}

Now, according to my assignment, you're supposed to enter the word (instead of a number, get it?) "bison" which brings up the output:

* INVALID INTEGER * Please enter an integer:

For context, this part works absolutely fine. However, you're then directed to put in the integer "-1200" which should then bring up the prompt

* INVALID APARTMENT NUMBER * Please enter a positive number:

It is this part that I'm having issue in because simply put, I don't know where to put it, whether in the if statement or outside of it. Im not sure, and would kindly like some help with this.

I have attempted to correct the problem my self, but it just gives me double of the Invalid integer output instead of this correct Invalid apartment number statement. Here is my (failed) attempt:

 if (yes() == 1)
    {
        printf("Please enter the contact's apartment number: ");
        address->apartmentNumber = getInt();
        if (address->apartmentNumber > 0) {
        }
        else {
        printf("*** INVALID INTEGER *** <Please enter an integer>: ");
        address->apartmentNumber = getInt();
        }
        if (address->apartmentNumber < 0) {
        }
        else {
        printf("*** INVALID APARTMENT NUMBER *** <Please enter a 
        positive number>: ");
        address->apartmentNumber = getInt();       
    }
        else
        {
        address->apartmentNumber = 0;
        }

Invert if statement with pipes

I want to add a command to my .bash_profile that runs a script if it's not already running. Below is my attempt.

if ps ax | grep reminder.py | grep -v grep;
  echo 'i want to get rid of this line'
then
  python /Users/Jesse/Dropbox/reminder/reminder.py &
fi

I can't figure out the syntax for inverting the if statement.

I tried a bunch of stuff similar to this:

if ! ps ax | grep reminder.py | grep -v grep
then
  python /Users/Jesse/Dropbox/reminder/reminder.py &
fi

None of my attempts were successful.

I'm running on macOS if that's relevant.

If Cell Is Blank, Fill With Other Cell’s Text Data

This is probably simple for you experts out there. I've tried so many ways, and in so many locations w/in the code, but none are working for me. Please help!

All I’m trying to do is get data from CELL RANGE B4:B4000 to copy automatically to CELL RANGE J4:J4000 should CELL RANGE J4:J4000 be empty.

FYI: Data being inputted via a user-form.

Option Explicit

Private Sub CmdButton_CONTINUE1_Click() 

Dim TargetRow As Integer
Dim FullName As String   'Variable for FULL NAME = CELL RANGE J4:J4000
Dim QBFileName As String   'Variable Quick Books File Name = CELL RANGE B4:B4000
Dim UserMessage As String

FullName = Txt_Client_First_Name & " " & Txt_Client_LAST_Name
QBFileName = Txt_QB_File_Name

'begin check if EDIT or ADD New Entry Mode
If Sheets("Engine").Range("B4").Value = "NEW" Then  'ADD New Entry Mode


'BEGINS VALIDATION CHECK: IF in "ADD New Entry Mode" mode to prevent duplicate FULL NAME J Column entries

If Application.WorksheetFunction.CountIf(Sheets("Database").Range("J3:J4000"), FullName) > 0 Then

MsgBox "Client's Full Name already exists", 0, "Check" 
Exit Sub 

End If  'ends validation check OF Duplicate FULLNAME (J Column)


'BEGINS VALIDATION CHECK: IF in "ADD New Entry Mode" to prevent duplicate QBFileName B Column entries

If Application.WorksheetFunction.CountIf(Sheets("Database").Range("B3:B4000"), QBFileName) > 0 Then

MsgBox "QuickBooks File Name already exists", 0, "Check" 
Exit Sub 

End If
~~~~

R - If statement function to set value of new column

I have 2 columns pos and neg, each with a integer value.

I would like to create a new column score, with each element of this column given a value of:

  • 1 if pos > neg
  • 0 if pos = neg
  • -1 if pos < neg

What would be the best way to do this? I am new to creating functions in R, so any help or direction is appreciated.

Problem with try and if statement in a while loop

I thought I clearly understand the exception handling, while loop and conditional statements. But I came across this simple problem that my code execution never reaches the except statement.

I made the code as simple as possible to point out the problem. So the code requires to press '1'. Only then it can escape the while loop. Anything else should go to exception. Characters, such as 'a' and 'b' does - because they cannot be converted to an integer. But any other number does not trigger the exception. It just goes back to the input step. Why is it like that? Clearly any other number except 1 is not equal to 1.

while True:
    click = input('Press 1')
    try:
        if int(click) == 1:
            print('correct')
            break
    except:
        print('wrong')

modelling and if/else pattern inside an rxjs observable pipeline

I have an epic where I am listening to an action stream, when an action of 'AUTH_STATUS_CHECKED' occurs switch over to a new observable authState(app.auth()). This new observable tells me if I am authenticated or not.

If the auth observable returns a user then dispatch 'SIGNED_IN' action with the user as the payload.

If a user does not exist then fore off a promise app.auth().signInWithPopup(googleAuthProvider) and when you get the response dispatch 'SIGNED_IN'.

If there are any errors, catch them and let me know in the console.

based on the logic above I have implemented the pipeline below

export const fetchAuthStatus = action$ =>
      action$.pipe(
        ofType('AUTH_STATUS_CHECKED'),
        switchMap(() =>
          authState(app.auth()).pipe(
            map(user =>
              user
                ? { type: 'SIGNED_IN', payload: user }
                : app
                    .auth()
                    .signInWithPopup(googleAuthProvider)
                    .then(user => ({ type: 'SIGNED_IN', payload: user }))
            ),
            catchError(error => console.log('problems signing in'))
          )
        )
      );

It's not working as expected. If there is no user the promise gets fired but it does not wait for the response and the dispatch never gets fired.

I'm clearly new to rxjs and I'm having trouble figuring this out. I've gone through the docs and tried using a tap() and mergeMap() but am getting the same error.

Any guidance would be appreciated.

Create condition for dateRange with another associated fields in laravel

I am trying to create a sales filtering page where the user can set the dateRange and if they want they can also set the currency and the customer's name as part of the filter. here's the screenshot.

enter image description here

And here's my code;

public function filterSale(Request $request)
{

    $customer = \DB::table('companies')->where('category', '=', 'customer')->pluck('comp_name','id')->all();
    $currencies = \DB::table('currencies')->orderBy('default', 'desc')->pluck('acronym','id')->all();

    $currency = $request['currency_id'];
    $company = $request['company_id'];

    if($request->from_date != '' && $request->to_date != ''||$request['currency_id']!=''||$request['company_id']!='')
    {
        $sales = Sales::where('publish','=',1)
                ->whereBetween('created_at', array($request->from_date, $request->to_date))
                ->where('currency_id','=', $currency)
                ->where('company_id','=', $company)
                ->get();

        return view ('reports.salesReport', compact ('sales', $sales))
                                            ->with ('currency', $currency)
                                            ->with ('company', $company)
                                            ->with('customer', $customer)
                                            ->with('currencies', $currencies);
    }

What I am trying to achieve is that if the user set the dateRage and leave the currency and customer empty, the the data should display all regardless of their currency and which customer it belong to.

OR Customer + datetrage OR currency + dateRange OR currency + customer + daterage.

how can I achieve that?

Thank you so much in advance!

If conditions are never satisfied (even though they are)

I wrote an if statement followed by an else statement. Now even if the conditions are satisfied, it will just go to the else statement.

I've tried using Objects.equal() but that's not really what I want since I'm using >= signs instead of == signs, it also gives me errors and basically the whole program doesn't work. I also tried putting all conditions to the default values so I can be sure that they are satisfied but still nothing.

This is the function that contains the if statement.

function evolve() {
            if (coins >= 1000000000 && timesbuyj1 >= 10 && timesbuyj2 >= 10 && timesbuyj3 >= 10) {
                evolutions = evolutions += 1
                var coins = 0
                var timesbuyj1 = 0
                var price01cs = 15
                var timesbuyj2 = 0
                var price1cs = 100
                var timesbuyj3 = 0
                var price8cs = 1100
                var timesbuyj4 = 0
                // a bunch of lines of code that doesn't concern this here //
                }
            } else {
                alert("You don't meet the requirements.")
            }
        } 

When I change the values to satisfy the conditions, I expect everything to reset, change, etc.. But it just gives tells me You don't meet the requirements. and doesn't run the code it's supposed to run.

vendredi 29 mars 2019

Looping comparing two values in R

While looping over a partially filled correlation matrix (it has been filtered beforehand), I want to compare the variances for the two variables within the loop and keep the variable with the highest variance in a vector.

This is a capture of the correlation matrix:

enter image description here

Variances have been calculated in a separate dataframe (var) and the order of the variances coincides with the order of the variables in the correlation matrix.

enter image description here

The snippet of code that does not work is as follows:

vec <- c()

for (i in ncol(mcor)) {
  for (j in nrow(mcor)) {
    if (is.na(mcor[i,j])) {
      j = j+1      
    } else {
      if (var[j,2] > var[i,2]) {
        vec <- c(vec, var[j,2])
      } else {
        vec <- c(vec, var[i,2])
      }
    }
  }
}

Conditionals in Ruby

I have a simple method which will generate an addition problem, get the users answer from the command line, then output if they are right or wrong, however it always defaults to the "incorrect" condition and I can't get it to work

def questionPromt
    firstNumber = rand(20)
    secondNumber = rand(20)
    equation = firstNumber + secondNumber
    puts "What is #{firstNumber} + #{secondNumber} ?"
    useranswer = gets.chomp
    if equation == useranswer
        puts "good job " 
    else
        puts "wrong answer"

    end
       end

Help appreciated.

Simplify the complex if statements in java

Is there a way to simplyfy the below code, I can combine condition1 and condition2 but I want the else statements print different messages for each step.

if(condition1){
    if(condition2){
        if(condition3){
            //do something
        }
    }
    else{
       //sout condition2 failed
    }
}
else{
    //sout condition1 failed
}

Dropdown menu changes its preselect when an if statement is used

I have a dropdown menu with a preselected option and when I use an if statement later in the code saying that if one dropdown menu option is selected then it will show my text but it then changes the preselected to my if statements selection. That may be very confusing.

            <p>
                Filter Products By:
                <select id="sbProductsFilter" onchange="displayProducts();">
                    <option id ="All" >All</option>
                    <option id = "Expired" selected>Expired</option>
                    <option id = "NotExpired" >NotExpired</option>
                </select>
            </p>

            <!-- Products Output -->
            <span><strong>Department | Product | Price ($) | Shelf Life</strong></span>
            <div id="productOutput">[Print Products here...]</div>
        </form>
    </fieldset>
    <br>


    <script>

            var food1 = new Product( "Avacados",             "Produce" ,     8.99,       ("June 27, 2019") );
        var food2 = new Product( "<br/>Baguette",             "Bakery" ,      5.99,       ("July 30, 2019") );
        var food3 = new Product( "<br/>Beef",                 "Deli" ,        14.99,      ("April 1, 2019") );
        var food4 = new Product( "<br/>Pears",                "Produce" ,     5.50,       ("April 2, 2019") );
        var food5 = new Product( "<br/>2L Chocolate Milk",    "Dairy" ,       4.99,       ("March 21, 2019") );
        var food6 = new Product( "<br/>Pumpkin Pie",          "Bakery" ,      10.50,      ("March 13, 2019") );
        var food7 = new Product( "<br/>Grapes",               "Produce" ,     6.99,       ("February 1, 2018") );
        var food8 = new Product( "<br/>Loaf of Bread",        "Bakery" ,      5.99,       ("March 30, 2019") );
        var food9 = new Product( "<br/>Cheddar Cheese",       "Dairy" ,       10.99,      ("March 14, 2019") );
        var food10 = new Product( "<br/>Margarine",            "Dairy" ,       8.99,       ("June 14, 2017") ) ;
        var food11 = new Product( "<br/>Salami",               "Deli" ,        5.99,       ("March 13, 2019") );
        var food12 = new Product( "<br/>Oranges",              "Produce" ,     7.50,       ("May 2, 2019") );
        var food13 = new Product( "<br/>Chicken",              "Deli" ,        21.99,      ("March 22, 2019") );
        var food14 = new Product( "<br/>Turkey",               "Deli" ,        14.99,      ("April 3, 2019") );
        var food15 = new Product( "<br/>Peppers",              "Produce" ,     3.99,       ("March 27, 2019") );
        var food16 = new Product( "<br/>Ham",                  "Deli" ,        9.99,       ("May 5, 2019") );
        var food17 = new Product( "<br/>Chocolate Cake",       "Bakery" ,      19.99,      ("October 10, 2007") );
        var food18 = new Product( "<br/>10kg White Flour",     "Bakery" ,      12.99,      ("September 30, 2020") );


        products.push(food1.fullproduct());
        products.push(food2.fullproduct());
        products.push(food3.fullproduct());
        products.push(food4.fullproduct());
        products.push(food5.fullproduct());
        products.push(food6.fullproduct());
        products.push(food7.fullproduct());
        products.push(food8.fullproduct());
        products.push(food9.fullproduct());
        products.push(food10.fullproduct());
        products.push(food11.fullproduct());
        products.push(food12.fullproduct());
        products.push(food13.fullproduct());
        products.push(food14.fullproduct());
        products.push(food15.fullproduct());
        products.push(food16.fullproduct());
        products.push(food17.fullproduct());
        products.push(food18.fullproduct());

        if (document.getElementById("All").selected = "true"){
            document.getElementById('productOutput').innerHTML = products 
             }

    </script>
</body>

My page should load with the Expired dropdown preselected and when I select the All dropdown option it should display all of the array.

How to fix error code "missing value where TRUE/FALSE needed"

I am looking to take a data set (df_freeGammas) and summarize certain components of the set. The data set is split into subjects and different test numbers (subject 1, test 1). Some subjects have more than 1 test for them. Each test has a subset of 16 rows of data corresponding to the test and subject. I want to be able to use a loop or nested loop to place the subject number in a results matrix. I have figured out a way to do this, but I keep getting the error: "Error in if (df_freeGammas[n, 2] != df_freeGammas[n + 1, 2]) { : missing value where TRUE/FALSE needed" Please help.

I have tried adding more if loops as well as a while loop.

for (n in 1:nrow(df_freeGammas)){
+    if (df_freeGammas[n,2] != df_freeGammas[n+1,2]){
+         Results[n/16,1] = df_freeGammas[n,1]}
+       else if (df_freeGammas[n,1] != df_freeGammas[n+1,1]){
+           Results[n/16,1] = df_freeGammas[n,1]}
+         else 
+           invisible()

I expect the result but without the error message.

Issues with multiple elseif statements

Trying to create a lengthy series of if else statements. Basically, four different scenarios to bring up different button based on queries.

If the event is free, have a button saying so.

However, if the event is free, but you have to RSVP (like our meetups), show this button

Or if there are tickets but the event isn’t free but has a discount, show this button,

Else if there are tickets but they aren’t free, show this button.

And this is what I currently have.

if ( isset($additional_fields[ 'Price' ]) == 'Free' ) {
    echo '<button class="btn-free">This Event is Free!</button></a>';
} elseif( isset($additional_fields[ 'Tickets' ]) && (isset($additional_fields[ 'Price' ])) == 'Free' ) {
    echo '<a href="' . $additional_fields[ 'Tickets' ] . '" target="_blank"><button class="btn-rsvp">Free with RSVP</button></a>';
} elseif( isset($additional_fields[ 'Tickets' ]) && (isset($additional_fields[ 'Price' ])) != 'Free' && (isset($additional_fields[ 'Discounts' ]))) {
    echo '<a href="' . $additional_fields[ 'Tickets' ] . '" target="_blank"><button class="btn-discount">Tickets ' . $additional_fields[ 'Discount Text' ] . '</button></a>';
} elseif( isset($additional_fields[ 'Tickets' ]) ){
    echo '<a href="' . $additional_fields[ 'Tickets' ] . '" target="_blank"><button class="btn-tkts">Get Tickets</button></a>';
}

Code works.... to a point. If I have an event that is free, I get the This Event is Free button, but if I have an event that is free but also offers tickets / rsvp, I still get the first free button with no link. The second step should be occurring here. Not the first. Same deal if add a price or anything beyond the word 'Free'.

Is my order correct? Or something else in the code?

In an if/else if statement, the variable is being locked into the first option. How can I fix this?

This is my general code (in JavaScript):

let x = Math.floor(Math.random()×6)+1);

if (x=1){do this} else if (x=2){do that} else if.... and so on. 

Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?

Best way to combine a permutation of conditional statements

So, I have a series of actions to perform, based on 4 conditional variables - lets say x,y,z & t. Each of these variables have a possible True or False value. So, that is a total of 16 possible permutations. And I need to perform a different action for each permutation.

What is the best way to do this rather than making a huge if-else construct.

Lets see a simplified example. This is how my code would look if I try to contain all the different permutations into a large if-else construct.

if (x == True):
    if (y == True):
        if (z == True):
            if (t == True):
                print ("Case 1")
            else:
                print ("Case 2")
        else:
            if (t == True):
                print ("Case 3")
            else:
                print ("Case 4")
    else:
        if (z == True):
            if (t == True):
                print ("Case 5")
            else:
                print ("Case 6")
        else:
            if (t == True):
                print ("Case 7")
            else:
                print ("Case 8")
else:
    if (y == True):
        if (z == True):
            if (t == True):
                print ("Case 9")
            else:
                print ("Case 10")
        else:
            if (t == True):
                print ("Case 11")
            else:
                print ("Case 12")
    else:
        if (z == True):
            if (t == True):
                print ("Case 13")
            else:
                print ("Case 14")
        else:
            if (t == True):
                print ("Case 15")
            else:
                print ("Case 16")

Is there any way to simplify this? Obviously, my objective for each case is more complicated than just printing "Case 1".

How could I get this if statement to work right?

For my program, I would like something that asks for the number of students, asks for their scores and then display an output of how many of those scores were A's,B's,C's,etc. So if i input 5 students, I should be able to enter those 5 scores and THEN it'll display the corresponding grades. Instead, it displays the corresponding grades after inputting one score and then asks for another score.

//Declarations
    int A=0,B=0,C=0,D=0,F=0, score,I, students;
    I=1;

    System.out.println("How many students are in your class: ");
    students = input.nextInt();
    while (I<=students) {
    System.out.println("enter a score:");
    score=input.nextInt();


    if(score >= 90 && score <= 100)
        A++;
    else if(score>=80 && score<=89)
        B++;
    else if(score>=70 && score<=79)
        C++;
    else if(score>=60 && score<=69)
        D++;
    else if(score>=0 && score<=59)
        F++;


       System.out.println("Total number of A's:"+ A);
       System.out.println("Total number of B's:"+ B);
       System.out.println("Total number of C's:"+ C);
       System.out.println("Total number of D's:"+ D);
       System.out.println("Total number of F's:"+ F);


}

}}

How to increment a variable within a loop to move an object a certain amount of points the rotate to a new direction

rotate in a clockwise square: first go North 3 times, then East 3 times, then South 3 times, then West 3 times then repeats.

Currently my code rotates the bird north to east to west, then north to east to south, and moves up 2 North, but doesn't increment any other direction

creating for loops with an array and a temp variable storing a string direction simply to check which direction is needed

public Direction getMove(){
        if(count > 12){
            count = 0;
        }else if(count <= 12){
            if(count >= 0 && count <= 3){
                count++;
                return Direction.NORTH;
            }else if(count > 3 && count <= 6){
                count++;
                return Direction.EAST;
            }else if(count > 6 && count <= 9){
                count++;
                return Direction.SOUTH;
            }else if(count > 9 && count <= 12){
                count++;
                return Direction.WEST;
            }
        }

Laravel - Redirection if connected

I am a young French developer and I am at a dead end about redirections under Laravel.

I have user tables, namely Client(users) and Employes (admin) and I can log on without problem with a login form that sends me to 2 different pages:

 Connected as a client-> mon-compte,
 Logged in as an employe-> gestion-admin.

However, if I am logged in as a client and I change the url mon-compte by gestion-admin, I have access to this page and vice versa ...

So I set guards and middlewares under Laravel that seem to work but that alternately I will say. In my web.php, I have 2 groups:

Route::group([
'middleware' => 'App\Http\Middleware\Employe',
], function () {
    Route::get('/mon-compte', 'ControllerConnexion@accueilClient');
    Route::view('mon-compte', 'pages/mon-compte');
    Route::get('/gestion-admin', 'ControllerConnexion@redirectClient');
});

Route::group([
'middleware' => 'App\Http\Middleware\Client',
], function () {
    Route::get('/gestion-admin', 'ControllerConnexion@accueilEmploye');
    Route::view('gestion-admin', 'pages/gestion-admin');
    Route::get('/mon-compte', 'ControllerConnexion@redirectEmploye');

});

In this order of position of the groups, the access used is blocked if I change the url /gestion-admin by /mon-compte if I connect as a client, I arrive directly on the gestion-page page . If I change the url and want to go to mon-compte, it sends me back to gestion-admin.

By cons, if I reverse the 2 groups of position:

Route::group([
'middleware' => 'App\Http\Middleware\Client',
], function () {
    Route::get('/gestion-admin', 'ControllerConnexion@accueilEmploye');
    Route::view('gestion-admin', 'pages/gestion-admin');
    Route::get('/mon-compte', 'ControllerConnexion@redirectEmploye');

});

Route::group([
'middleware' => 'App\Http\Middleware\Employe',
], function () {
    Route::get('/mon-compte', 'ControllerConnexion@accueilClient');
    Route::view('mon-compte', 'pages/mon-compte');
    Route::get('/gestion-admin', 'ControllerConnexion@redirectClient');
});

I have the opposite effect ....

I admit that I have no solution.

If statement test fails when comparing numbers read from file

I have a file with the following input (Sample not full file) JANE,SMITH,12,1000298,2 CLARA,OSWALD,10,10890298,4 We have FirstName, Lastname, Grade, ID, and School. I have a loop that reads each into their own variable. The last number (2,4) indicates what school they belong to and I have the code that changes the 2 to HS, and 4 to ML. I need to have the test pass. Where if it finds 2 do this find a 3 do this and so on.

#!bin/bash
OLDIFS=$IFS
IFS=","

while read  First_Name Last_Name Grade Student_Id school
do 


 if [[ $school == 2 ]]
    then
        School=$(echo $school | sed -e 's/2/HS/g')
    elif [[ $school == 3 ]]
     then
        School=$(echo $school | sed -e 's/3/MI/g')
      else
       School=$(echo $school | sed -e 's/4/ML/g')
   fi
   echo $First_Name $Last_Name $Grade $Student_Id $School
done < $1
IFS=$OLDIFS

Ok. So school has 2,4 as per the input from the file. When it finds a 2 it should change that 2 to HS. But the test fails. Even if I use -eq it fails. I add "" just to see if it did anything, but nothing. When I echo $school it gives me the right numbers 2,4 but It fails to compare it. Correct output JANE,SMITH 12 1000298 HS CLARA OSWALD 10 10890298 ML

What I get is CLARA OSWALD 10 10890298 ML As it skips straight to the else part. It does not check the first one. And if I try to check for $school == 4 or (-eq) it will just fail that too.

Why won't this if statement comparing WPF ImageSources be executed?

I'm checking that an image matches the image source that I want, which will then instantiate a class "Queen". To do this, I am iterating through a list of objects, "nodes", which has a method, getType(), which returns an image. I am checking each of the images in this colony.getNodes() list.

I am 100% sure that at least one of the images matches "H:\Year 13\Computing\Ant Simulation\QueenRoom.png" as I have checked using breakpoints. So why won't it ever enter my if statement.

I have also tried instead of comparing colony.getNodes()[i].getType().Source to a new instance of BitmapImage, creating a BitmapImage variable before the for loop, however this didn't help.

        for (int i = 0; i < colony.getNodes().Count; i++)
        {
            if (colony.getNodes()[i].getType().Source == new BitmapImage(new Uri(@"H:\Year 13\Computing\Ant Simulation\LarvaRoom.png")))
            {
                nurseryFood.Add(colony.getNodes()[i].getLocation(), 0);
            }
            if (colony.getNodes()[i].getType().Source == new BitmapImage(new Uri(@"H:\Year 13\Computing\Ant Simulation\QueenRoom.png")))
            {
                queen = new Queen(colony.getNodes()[i].getLocation(), colony.getNodes()[i].getType().Margin);
            }
        }

I also have another if statement which has exactly the same problem. Testing using breakpoints, the if statements are never entered. How can I make this work?

i have home work about script C and create IF Else Statement

I have a problem like this

A Taxi company has regulations regarding the rates charged to passengers as follows: For the first Kilometer = $ 5 For the second and next Kilometer = $ 3 Input: Distance traveled Output: Amount of payment

how to create a C script for an IF-ELSE Statement

please help me

I need the answer from a form to immediately redirect to another form

I have a one question radio button form. I want the answer to immediately redirect to page A if answer is A or redirect to page B if answer is B. I know that the answer probably relies on javascript, but I am fairly new to coding and javascript is my achilles' heel.

I have the form selecting and a basic if else statement - just not sure how to tie the two together. Some other questions here were helpful, just not enough to fully help me put something together. Here is my current code:

<?php
include '../header.php';
echo '<h2>Conference Registration Form</h2>';

echo '<p>Please fill out the form below.  If you have any questions or problems, please contact us at 123.456.7890.</p>';
echo '<p style="font-weight: bold;">Note: additional options will appear as you fill out the form.</p>';
echo '<p>All prices are in US dollars.</p>';
echo '<form id="gate" action="index.php" method="post">';
echo '<p>I work at Teflon as a faculty member, staff member, or graduate student.<br>';
echo '<input type="radio" name="gateway" value="Yes"> Yes<br>';
echo '<input type="radio" name="gateway" value="No"> No<br>';
echo '</p>';

// branching for different forms
if($gateway=="Yes") {
            header ('answer Yes url');

} else if($gateway=="No") {
            header ('answer No url');

         }    
    echo '</form>';
    echo '<div class="clear"></div>';
    echo '</div>';
    echo '</div>';          

include '../footer.php';
?>
</body>
</html>
`````````````

I would love some help connecting A and B to my statement. I would love to be able to do it without the user having to click Submit - have it redirect when they make the choice.

If Statement In Bash With Variable

I am trying to check if a remote version is greater than a local version with variables and if statements.

But, so far the variables echo the correct version but even if the remote version is greater than a local version nothing happens with the if statement, what am i doing wrong.

Thanks

lversion_notepadqq() {
    notepadqq -v
}

rmersion_notepadqq() {
    curl -s https://api.github.com/repos/notepadqq/notepadqq/releases | grep tag_name | cut -d \" -f 4 | grep v| tr -d 'v,' | head -1
}

Remote=$(curl -s https://api.github.com/repos/notepadqq/notepadqq/releases | grep tag_name | cut -d \" -f 4 | grep v| tr -d 'v,' | head -1)
Local=$(notepadqq -v)
echo Local Version: $Local
echo Remote Version: $Remote

if (( rmersion_notepadqq > lversion_notepadqq )); then 
    echo Updating && Update_Notepadqq
else
    echo No Update Needed
fi

#Neither if statement seems to work

if (( $Remote > $Local )); then 
    echo Updating && Update_Notepadqq
else
    echo No Update Needed
fi

How to return a value when the fields don't match in SAP Infoset

I have Main table EKPO joined to tables MLGN and MLGT as outter joins. I have created an extra field in the infoset and want it to return a value from table MLGT under certain conditions. 1. if Fields MLGN-LTKZE and MLGT-LGTYP match then return the associated MLGT-LGPLA field. 2. IF MLGN-LTKZE = R1, then only return relevant MLGT-LGPLA where MLGT-LGTYP = 006. 3. if MLGN-LTKZE <> MLGT-LGTYP return blank.

Currently I can do the 1st 2 conditions but unable to fit in the 3rd as it conflicts with the number 2.

I have tried a variety of IF statements and various orders for the IF conditions. I've tried different joint types and ways.

IF MLGN-LTKZE = 'R1'. select LGPLA as LGPLA from *MLGT into BINALOC where *MLGT~LGTYP eq '006'. ENDSELECT.
else. select LGPLA as LGPLA from *MLGT into BINALOC where *MLGT~LGTYP eq MLGN-LTKZE. endselect. endif.

This the current code I have in the extra field coding section.

I want the the field to return blank when the fields I mentioned before do not match. Currently it returns a copy of the field above it.

How to make a function containing all true values of another function

I have a function(x) that includes an if statement in r where the output of the inserted value is either TRUE or FALSE. I now want to make another function(y) which will display (y) number of true values. For example if I was testing in the first function whether a number is divisible by three, which would be true. Then in the next function, if I input 3, I want to program the function so it displays the first three true numbers, so in this case 3, 6, 9.

Download File using python script behind corporate proxy

I am putting together a script that will download a file from the web .... However some ppl sit being a corporate firewall so this means that if you are @ home the below code works but if you are in the office it hangs unless you set proxy variable manually and then run ....

What I am thinking is create an if statement ... The if statement will check the users IP address and if they user has an IP address in the 8.x or 9.x or 7.x then use this proxy ... Otherwise ignore and proceed with download

The code I am using for this download is below ... I am pretty new to this so i am not sure how to do an if statement for the IP and then use proxy piece so any help would be great

import urllib.request
import shutil
import subprocess
import os
from os import system

url = "https://downloads.com/App.exe"
output_file = "C:\\User\\Downloads\\App.exe"
with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)


If session is set do this, if not run a while loop, not working?

Im attempting to fill a selection box with a session value if it is set. If not i need it to fill the selection box with a list of cups from my database. The session seems to be being set, however, the selection box isnt being filled, its still loading the list of cups.

<select name="cupname" required>
<option value='Holder' disabled selected>Please Select</option> 
    <?php
    if (isset($_SESSION['c_cname'])) {
        echo $_SESSION['c_cname'];
        exit();
    } else {
        while($rows = $resultSet->fetch_assoc()){
            $cupname = $rows['cup_name'];
            echo "  <option value='$cupname'>$cupname</option>";
        }
    }
?>
</select>

Convention for leaving body of an if/else blank

Disclaimer

I'm not entirely sure if this is the right SE for this, but I'll start here anyway.

Background

I was reading this question earlier and was looking at this code snippet in one of the answers

auto z = [&](){ static auto cache_x = x; 
    static auto cache_y = y; 
    static auto cache_result = x + y;
    if (x == cache_x && y == cache_y)
       return cache_result;
    else
    {
        cache_x = x; 
        cache_y = y; 
        cache_result = x + y;
        return cache_result;
    }
};

Personally, I would be inclined to rewrite it as follows, with a single return statement

auto z = [&](){ static auto cache_x = x; 
    static auto cache_y = y; 
    static auto cache_result = x + y;
    if (x == cache_x && y == cache_y)
    {
    }
    else
    {
        cache_x = x; 
        cache_y = y; 
        cache_result = x + y;
    }
    return cache_result;
};

but this leaves a blank body for the if part.

We could rewrite the if/else to just be if(!(x == cache_x && y == cache_y)) but this runs the risk of being misunderstood (and can get messy).

My Question

What is the more accepted way of writing something like this, should we

  • have multiple return statements
  • leave the body of the if blank
  • rewrite the if condition to be the negated version
  • something else

Please note, I usually code in Java whereas the sample code is in C++. I am interested in the generally accepted way of doing things, as opposed to specific C++ constructs/methods.

Write a program for calculating the income tax to be paid by an individual earning less than 1 crore. Use conditional statements only

Write a program for calculating the income tax to be paid by an individual earning less than 1 crore. Use conditional statements only.

Use the following rules:

There are 3 types of rules are following while paying tax. The types are mentioned based on Age.

1.For General(non-Seniors): •If income is up to 2,50,000/- then tax NIL (0). •If income Rs. 2,50,001/- to Rs. 3,00,000/- - then tax 10%. •If income Rs. 3,00,001/- to Rs. 5,00,000/- - then tax 10%. •If income Rs. 5,00,001/- to Rs. 10,00,000/- - then tax 20%. •If income Above Rs. 10,00,000/- - then tax 30%. 2.For Senior citizens (>= 60 & < 80): •If income is up to 2,50,000/- then tax NIL (0). •If income Rs. 2,50,001/- to Rs. 3,00,000/- - then tax NIL (0). •If income Rs. 3,00,001/- to Rs. 5,00,000/- - then tax 10%. •If income Rs. 5,00,001/- to Rs. 10,00,000/- - then tax 20%. •If income Above Rs. 10,00,000/- - then tax 30%. 3.For Very senior citizens (>= 80): •If income is up to 2,50,000/- then tax NIL (0). •If income Rs. 2,50,001/- to Rs. 3,00,000/- - then tax NIL (0). •If income Rs. 3,00,001/- to Rs. 5,00,000/- - then tax NIL (0). •If income Rs. 5,00,001/- to Rs. 10,00,000/- - then tax 20%. •If income Above Rs. 10,00,000/- - then tax 30%.

Additional information:

• The basic exemption limit for individuals (i.e. below 60 years of age) is Rs. 2.50 lakhs. •The basic exemption limit for senior citizens (60 years to 80 years) is Rs. 3.00 lakhs. •The basic exemption limit for very senior citizens (80 years and above) is Rs. 5.00 lakhs. •No extracess is to be levied.

Take the income and age as inputs and return the income tax.

using return in If Statement Vb.net

so i want to use a return in a If Statement thats return in a part of the code :( i want to check if the condition is valid in every DataGridView cells, so it will verify the first value if the condition not valid then it will check the second value without do any action. i hope thats clear

For i As Integer = 0 To DataGridView1.RowCount - 1
                    ' ruturn here !
                    If DataGridView1.Rows(i).Cells(6).Value = dt.Rows(0)(5) Then

                        DataGridView1.Rows(i).Cells(4).Value += 1
                    Else
                        If i = DataGridView1.RowCount - 1 Then
                            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), qnt, dt.Rows(i)(4), dt.Rows(i)(5))
                        Else
                            Return 'return to scan the second row ( i = 1,2,3... etc)
                        End If
                    End If
                Next

sap hana calculated column check for multiple IDs

i want to create a calculated column, which will show two values: Y or N

2 columns are here important, "VAT-ID" and "CUSTOMER-ID". the calculated column will check if a customer-ID has multiple VAT-IDs. If yes the value "Y" should be displayed, else "N".

for example, the first 5 rows of the customer-id column are: 123456

654321

666666

123456

654321

the first 5 rows of the VAT-id column are: EE999999999

AA999999999

GG999999999

KK999999999

AA999999999

the first 5 rows of the calculated column should be then: Y

N

N

Y

N

any Help would be appreciated

Bash: Safe to remove all occurrences of -n inside brackets?

I recently found this "bug" in my bash script;

if [ "$var" ]; then
    echo "Condition is true"
fi

where what I meant was to check if $var is non-empty, i.e. [ -n "$var" ]. As it happens, the code seems to work perfectly fine without the -n. Similarly, I find that I can replace [ -z "$var" ] with [ ! "$var" ].

I tend to like this implicit falseyness (truthiness) based on the (non-)emptyness of a variable in other languages, and so I might adopt this pattern in bash as well. Are there any danger to doing so, i.e. edge cases where the two set of syntaxes are inequivalent?

jeudi 28 mars 2019

how do I use else and if statements

both of my options are coming up when I run the code

I have tried two if statements else if and else

cout << "would you like to hit or stand?" << endl; //asking if you would ike to hit or stand

bool hit; //the hjitting opption
bool stand; // the stand / hit option

cin >> hit, stand; // the avaiabillity for hitting or standing (player input)
if ( hit = true) // if you hit
{
    for (n = 1; n <= 1; n++) //loop for how many cards are you have
    {
        num = rand() % 13; //get random number
        cout << num << "\t"; //outputting the number
    }
}

{
    cout << "you stand \n"; // saying you stand

I expect the code to output the number when u say hit and say you stand when you say stand but it is out putting either just the hit just the stand or bothenter code here

C: Why do I only need getchar() to remove characters sometimes?

I need some help with explaining the use of getchar() to remove characters from the input buffer. In the following code, the user is asked to input a choice to select, and then depending on the choice, another input is required, either type int or type char (string). In the int case, getcar() is not needed and scanf takes in input correctly. But in the char case, scanf fails to get input without using getchar() beforehand. Is there a reason why that is?

printf("Available Ciphers:\n1) Caesar Cipher\n2) Vigenere Cipher\nSelected Cipher: ");
if(scanf("%d", &choice) != 1){
    printf("Error: Bad selection!\n");
    exit(EXIT_SUCCESS);
} else if (choice != 1 && choice != 2){
    printf("Error: Bad Selection!\n");
    exit(EXIT_SUCCESS);
//If the choice entered is correct, then run the following.
} else {
    if(choice == 1){
        printf("Input key as nuumber: ");
        if(scanf("%d", &caesarkey) != 1){ //Why is getchar() not needed here?
            printf("Error: Bad Key!\n");
            exit(EXIT_SUCCESS);
        }
        //morecode here
    } else if (choice == 2){
        printf("Input key as string: ");
        while(getchar() != '\n');  //Why is this needed here?
        /*Uses scanf and not fgets, since we do not want the
        key to contain the newline character '\n'. This is
        due to the fact that the newline character is not
        considered in the function that encrypts and decrypts
        plaintext and ciphertext.*/
        if(scanf("%[^\n]s", vigencipherkey) != 1){
            printf("Error, Cannot read inputted key!\n");
            exit(EXIT_SUCCESS);
        }
        //More code here..
    }
}

Compare number to string/ or change datatype

I have a file with numbers such as 2,3,4,5 never greater than 5 or lower than 2. I read them in using a loop. My if statement do not work and i narrow it down to what i think is differents datatype.

I can't use -eq because it causes an invalid arithmetic operator error.

#!bin/bash

while read -r number
do
if [[ $number == 2 ]]
then
    echo "found two"
 elif [[ $number == 3 ]]
    echo "found three"
 elif [[ $number == 4 ]]
    echo "found four"
else [[ $number == 5 ]]
    echo "found five"
fi
done < $1

Whenever it matches 2,3,4 or 5 it should be found a match. I know it sounds dumb but I just want to be able to get it to compare.

If, else if, else statement causing syntax error in EJS - Unexpeted Identifier [duplicate]

This question already has an answer here:

I'm currently working on a simple web app for hosting games, just to mess around. I have some javascript/json files for handling HTTP requests and setting up variables within the rendered HTML pages. However, I'm running into a weird problem when trying to use if, else if, else statements in my EJS files. Specifically, I'm running into a syntax error stating there is an unexpected identifier while compiling ejs. Here is snippet of my code from the EJS file below:

<%
var friendsList = '';
if (current_user.username == 'Guest') {
    friendsList += '<li>Login to see your friends online</li>';
}
else if(current_user.friends.length == 0) {
    friendsList += '<li>You haven't made any friends yet</li>';
}
else {
    for (i=0; i<current_user.friends.length; i++) {
        friendsList += '<li>' + current_user.friends[i] + '</li>';
    }
} %>
<%- friendsList %>

The idea is to buildup a javascript string that matches HTML formatting and then insert that string directly into the existing HTML in the EJS file. This code results in the error I described. However, if I remove the else-if part of the statement as shown below:

<%
var friendsList = '';
if (current_user.username == 'Guest') {
    friendsList += '<li>Login to see your friends online</li>';
}
else {
    for (i=0; i<current_user.friends.length; i++) {
        friendsList += '<li>' + current_user.friends[i] + '</li>';
    }
} %>
<%- friendsList %>

there is no error and the HTML renders the way I want it to, albeit with some missing functionality. I have wracked my brain and looked into why the code is behaving like this all day but cannot find a solution. Does anyone know why the EJS isn't compiling with the else-if statement included?

Can't get Slider to print different Text between intervals

I want to print a different Texts in multiple intervals of a Slider

If (value > 0 && value < 3){text1}

If (value > 3 && value < 5){text2}

If (value > 5 && value < 8){text3}

If (value > 8 && value < 10){text4}

I know how i try is completely wrong. I would appreciate if someone explained how should i set up such an event.

String vaker = '';
  double _value = (0.0);

  void _setValue(double value)
   => setState(() => _value = value){
    if (_value> 0.0 && _value < 0.3)
      setState((){
        vaker = 'Egy nappal előre kapja a HáVéGét';
      });
};


new Slider(
    value: (_value),
    onChanged: _setValue,
    activeColor: Colors.orange,
    inactiveColor: Colors.white,
          ),
  new Text('${(vaker)}'),

Hope you understand what I'm trying to do. Thanx in advance for every advice!

I don't understand why I get this error, error: 'else' without 'if' [on hold]

I'm working an assignment from my Computer Science class and basically, you've gotta make a program that allows the user to input some random words and the algorithm you've made should return the longest word of the three provided by the user.

Here's what I've gotten so far:

import static java.lang.System.*;
import java.util.*;

// public class
public class Java2507
{
    public static void main(String[] args)
    {
        Problem07 answer = new Problem07();
        Scanner scan = new Scanner(in);

        out.print("Enter word1 --> ");
        String word1 = scan.nextLine();

        out.print("Enter word2 --> ");
        String word2 = scan.nextLine();

        out.print("Enter word3 --> ");
        String word3 = scan.nextLine();

        out.println();
        out.println("The longest word is " + answer.findLongest(word1, word2, word3));
    }
}


class Problem07
{
    String answer;
    String findLongest(String w1, String w2, String w3)
    {
        if(w1.length() > w2.length())
        {
            if(w1.length() > w3.length())
            {
                answer = w1;
            }
            return answer;
        }


        else if(w2.length() > w1.length())
        {
            if(w2.length() > w3.length())
            {
                answer = w2;
            }
        }
        return answer;

        else   //  <------ this is where I get the error
        {
            if(w3.length() > w2.length())
            {
                answer = w3;
            }
            return w3;
        }
    }
}

If any of you are more advanced in java programming, your help will be appreciated.

How to identify if 'span' child tag exist in 'p' tag returned by beautifulsoup?

I am making a web scrapper that scrapes an online novel from the index webpage and the code creates and epub file for each book of the novel. I the translator of the novel has set up the webpages for the novel in 2 different formats. The first format is a 'p' tag with spam tag inside. the 'spam' tag has a bunch of css in it for each section of the paragraphs depending if its normal text or initialize. The other format is the text in the 'p' tag with no span tag and css code. I have been able to use Beautiful soup to get the portion of the code that only has the novel from the webpage. I am stuck trying to make an if statement that says if 'span' exists inside the chapter content run this code else this code.

I have tried using if chapter.find('span') != []: and if chapter.find_all('span') != []: from beautiful soup, but these beautiful soup codes return actual values not a Boolean values. I tested this by printing yes or no if chapter had the tag but solution would only say yes or only say not when I checked both 2 different chapters that I can conform didn't have different formats.

How I'm getting code from individual chapters of novel websites using this

    #get link for chapter 1 from index
    r = requests.get(data[1]['link'])
    soup = BeautifulSoup(r.content, 'html.parser')

    # if webpage announcement change 0 to 1
    chapter = soup.find_all('div', {"class" : "fr-view"})[0].find_all('p')

after this point depending on the chapter it will return code similar to:

    #chapter equals this
    [<p dir="ltr"><span style="color: rgb(0, 0, 0); background-color: transparent; font-weight: 400; font-style: normal; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">Chapter 1 - title</span></p>,
    <p dir="ltr"><span style="color: rgb(0, 0, 0); background-color: transparent; font-weight: 400; font-style: normal; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">stuff</span></p>,
    <p dir="ltr"><span style="color: rgb(0, 0, 0); background-color: transparent; font-weight: 400; font-style: italic; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">italizes</span><span style="color: rgb(0, 0, 0); background-color: transparent; font-weight: 400; font-style: normal; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap"> stuff</span></p>]


or it will return

    #chapter equals this
    [<p>Chapter 6 - title</p>,
    <p>stuff</p>]

I'm trying to make and if statement that can read chapter and tell me if spam tag or not so I can execute the correct code.

how to get IF statement to work for looking up string in dataframe column [duplicate]

This question already has an answer here:

I only get "no" values written to my "eliminate" column when i know i should get some "yes"? df['Account Number'] is a dataframe column. I am looking for a string stored in variable "a".

Please help

import pandas as pd
a = user_input_links[1]
a = a.strip()

for i in df['Account Number']:
    if df['Account Number'].str.contains(a) is True:
        df['eliminate'] = "yes"
    else:
        df['eliminate'] = "no"


df.head()

How to use an if/else statement to plot different colored lines within a plotting for-loop (in R)

I created a for loop to plot 38 lines (which are the rows of my matrix, results.summary.evap, and correspond to 38 total samples). I'd like to make these lines different colors, based on a characteristic pertaining to each sample: age. I can access the age in my input matrix: surp.data$Age_ka.

However, the matrix I am looping over (results.summary.evap) does not have sample age or sample name, though each sample should be located in the same rows for both surp.data and results.summary.evap.

Here is the for loop I created to plot 38 lines, one corresponding to each sample. In this case, results.summary.evap is what I am plotting from, and this matrix is derived from information in the surp.data input file.

par(mfrow=c(3,1)) 
par(mar=c(3, 4, 2, 0.5))
plot(NA,NA,xlim=c(0,10),ylim=c(0,2500), ylab = "Evaporation (mm/yr)", xlab = "Relative Humidity")
for(i in 1:range){
  lines(rh.sens,results.summary.evap[i,])
}
```


I'd like to plot lines in different colors based on the age associated with each sample. I tried to incorporate an if/else statement into the loop, that would plot in a different color if the corresponding sample age was greater that 20 in the input file. 


```
for(i in 1:range){
  if surp.data$Age_ka[i]>20 {
lines(rh.sens,results.summary.evap[i,], col = 'red')
} else {
  lines(rh.sens,results.summary.evap[i,], col = 'black')
  }
}

This for loop won't run (due to issues with parentheses). I'm not sure if what I am doing if fundamentally wrong, or if i've just missed a parenthesis somewhere. I'm also not sure how to make this a bit more robust; for example, by plotting in 6-8 different colors based on age ranges, rather than just two.

Thank you!

how to select every 1st 2nd 3rd .... nth

simply i wanted to do this for a loop;

<div class="A">query_result_1</div>
<div class="B">
    <span>query_result_2</span>
    <span>query_result_3</span>
</div>
<div class="c">query_result_4</div>
<div class="A">query_result_5</div>
<div class="B">
    <span>query_result_6</span>
    <span>query_result_7</span>
</div>
<div class="C">query_result_8</div>

  1. How to select 1st, 5th, 9th ...etc results to attend A class?
  2. How to select 2nd, 6th ... etc results to attend B class before it ?
  3. How to select 4th, 8th ... etc results to attend C class?

I hope i am clear...

input the number and find the largest and lowest number using jquery

<script type="text/javascript">
  function largest() {
    var num1, num2;
    num1 = Number(document.getElementById("N").value);
    num2 = Number(document.getElementById("M").value);
    if (num1 > num2) {
      window.alert(num1 + "-is largest");
    } else if (num2 > num1) {
      window.alert(num2 + "-is largest");
    }
</script>

How to get Functions output and re-use within IF/else Statement

I have function at the bottom of my script which counts for how many tools were used.

Then based on how many tools were used I want to perform different actions.

I can easily check the output of the Function but I struggle to put it into If statement.

var HowManyTools = HowManyTools1();

if (HowManyTools <= 2) {
  Category13();
} else if (HowManyTools >= 6) {
  Category12();
} else(HowManyTools > 2) {
  Category12();
}

function HowManyTools1() {}

How to get Functions output and re-use it within IF Statement?

Tried a few examples from here but to no avail

How to implement a correct If Then Else Statement in an Antlr Grammar?

I'm working on a statement's extention on a .g4 grammar (named Simple.g4) in ANTLR, I'm trying to implement an "if then else Statement" including a new instruction called ifStatement in section statement but I'm having issue with the code I generated.

Is this the correct form to implement the if statement?

Here is the code I'm working with using Eclipse IDE + ANTLR Plugin:

grammar Simple;


//PARSER RULES


block       : '{' statement* '}';




statement   : assignment    ';' 
            | deletion      ';' 
            | print         ';'
            | varDec        ';' 
            | ifStatement   ';' 
            | funDec        ';' 
            | block;




assignment  : ID '=' exp;


deletion    : 'delete' ID;                                  

print       : 'print' exp;

exp   : '(' exp ')'                             #baseExp
        | '-' exp                               #negExp     
        | left=exp op=('*' | '/') right=exp     #binExp
        | left=exp op=('+' | '-') right=exp     #binExp
        | ID                                    #varExp     
        | INT                                   #valExp     
        | BOOL                                  #valExp     
        | expression cmp='>' expression         #boolExp    
        | expression cmp='<' expression         #boolExp    /
        | expression cmp='==' expression        #boolExp
        | expression cmp='!=' expression        #boolExp
        | expression cmp='>=' expression        #boolExp
        | expression cmp='<=' expression        #boolExp                                            



// If-Then-Else

 ifStatement : 'if' '(' exp ')' 'then' exp 'else' exp               



// LEXER RULES


TRUE   : 'true' ;
FALSE  : 'false';
IF     : 'if'   ;
THEN   : 'then' ;
ELSE   : 'else' ;
VAR    : 'var'  ;  
INT    : 'int'  ;
BOOL   : 'bool' ;

//IDs

fragment CHAR   : 'a'..'z' |'A'..'Z' ;
ID              : CHAR (CHAR | DIGIT)* ;

fragment DIGIT  : '0'..'9'; 
INT             : DIGIT+;

//Boolean   
BOOL            : 'true' | 'false';

//Escape Sequence
WS              : (' '|'\t'|'\n'|'\r')-> skip;
LINECOMMENTS    : '//' (~('\n'|'\r'))* -> skip;
BLOCKCOMMENTS    : '/*'( ~('/'|'*')|'/'~'*'|'*'~'/'|BLOCKCOMMENTS)* '*/' -> skip;

If statement condition fails and skips straight to the else part

I'm reading in a file and school comes in forms of number 2,3,4,5 and each corresponds to a specific school like HS, Middle school etc. But my condition always fails and causes it to go to the else statements.

#!bin/bash
OLDIFS=$IFS
IFS=","

while read  First_Name Last_Name Grade Student_Id school
do  

if [ $school == 2 ]
    then
    School=$(echo $school | sed -e 's/2/HS/g')
    echo "$NAME"."$last_Name" "$NAME" "$last_Name" "$Grade"thGrade 
    "$Student_Id" "$School"

  elif [ $school == 3 ]
    then
    School=$(echo $school | sed -e 's/3/MI/g')
    echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..." 
    "$Student_Id" "$School"

  elif [ $school == 4 ]
     then
    School=$(echo $school | sed -e 's/4/MO/g')
    echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..." 
    "$Student_Id" "$School"

  else
    School=$(echo $school | sed -e 's/5/K/g')
    echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..." 
    "$Student_Id" "$School"

fi


done < $1   
IFS=$OLDIFS

The condition fails and it skips to the else statement.

My for loop stopped processing because of my if statement

I wanted to get all of my positions using for loop

for i := 0; i < len(word)-1; i++ {

    j := i + 1

    fmt.Println(i, j)
}

if I just process the above function, the outputs are what I wanted until, I started inserting this if statement

if word[i]-word[j] == 0 || word[i]-word[j] == 1 || word[i]-word[j] == 2 || word[i]-word[j] == 3 || word[i]-word[j] == 255 || word[i]-word[j] == 254 || word[i]-word[j] == 253 {
    return word
} else {
    return " "
}

My for loop stops after only processing one letter in the word, which is 0 from i and 1 from j

How can I check if String contains the domain name listed in ArrayList having multiple domains in Java?

I'm trying to allow request from specific domains only which are listed in ArrayList, so I need to put a conditional check if URL contains the domains listed in ArrayList then allow otherwise throw an Exception.

Suppose my ArrayList = [abc.com, def.com, xyz.com] I want to check if my URL contains any of these domains from ArrayList then return true else return false.

I tried below code, but it checks the domain name one by one. However, it returns false if domain name is valid -

ArrayList = [abc.com, def.com, xyz.com]

public static boolean isListContainValidDomain(List<String> arraylist) {
String reqURL = "dev.def.com";
boolean isValid = true;

    for (String str : arraylist) {

        if(!reqURL.contains(str.toLowerCase())){
            isValid = false;
        }
    }
    return isValid;
}

Can anyone please help on this.

How to refactor if statement using De Morgans law java

So I have a very unreadable if statement and someone suggested me to look at De Morgans law and refactor it so it would be more clean and readable. I got the idea how to do it with simple and short statements but I really do not know how to refactor my code. Note that first two are objects! Thanks for your help!


    if (!userTemplate.getFromAccount().equals(document.getDetails())
                        && !userTemplate.getBenAccount().equals(document.getFromAccount())
                        && !userTemplate.getDetails().equals(document.getBenAccount())
                        && !userTemplate.getBenType().equals(document.getBenType())
                        && !userTemplate.getAmount().equals(document.getCreditAmount()))


IF contains more than one string do "this" else "this"

trying to make a script that request more info (group Id) if there are SCOM-groups with identical names:

function myFunction {

[cmdletbinding()]

    param(

        [parameter(Mandatory=$true)]

        [string[]]$ObjectName

        )

 

foreach($o in $ObjectName)

 

    {

        $p = Get-SCOMGroup -DisplayName "$o" | select DisplayName

       

        <#

        if($p contains more than one string){"Request group Id"}

        else{"do this"}

        #>            

    }

}

Need help with the functionality in the commentblock

multiple targets in multiple ifs, depending on one another VBA

I have a data table, in which, set of rows need to be hidden based on criteria set in different set of cells. I wrote something which basically is "cave man coding" and of course it does not work :)

I have created if's and tried to put ifs within ifs, but literally nothing is happening with this code.

I only wrote it 2 sets of rows, but it is around 30 different sets (not yet written)

Sub Worksheet_Change(ByVal Target As Range)
Set Target = Range(Cells(7, 8), Cells(7, 8))
Set Target1 = Range(Cells(3, 2), Cells(3, 2))
    If Target.Value = "No"
        Rows("8:29").EntireRow.Hidden = True
        If Target.Value = "Yes" And Target1.Value = "Half" Then
            Rows("22:29").EntireRow.Hidden = True
        ElseIf Target.Value = "Yes" And Target1.Value = "Full" Then
            Rows("8:29").EntireRow.Hidden = False
        End If
    End If

Set Target = Range(Cells(30, 8), Cells(30, 8))
Set Target1 = Range(Cells(3, 2), Cells(3, 2))
    If Target.Value = "No"
        Rows("31:56").EntireRow.Hidden = True
        If Target.Value = "Yes" And Target1.Value = "Half" Then
            Rows("47:56").EntireRow.Hidden = True
        ElseIf Target.Value = "Yes" And Target1.Value = "Full" Then
            Rows("31:56").EntireRow.Hidden = False
        End If
    End If
End Sub

So, in a short summary i have two variables in cell B3 (Half and Full)

and in Row H in specified cells (e.g. H7, H30 and so on) Yes/No options. rows 7, 30 (any row, having Yes/no option) are headers of topics from 8 to 29 details of this topic are included.

if H7 (H30 ...) is No - entire details should be hidden (rows 8-29; 31-56 and so on) - Valua in B3 does not matter. If H7 (H30...) is Yes, then value in B3 matters: If H7 (H30...) is Yes and B3 is half - rows 22-29 hidden (47-56 and so on) rows 8-21 are unhidden in this case If H7 (H30...) is Yes and B3 is full - rows 8-29 are unhidden.

Hope i explained it well.

Please help me to improve my code, to be able to do set goal.

IF + AND + Date range formula

I have a problem to create a formula so I want to ask you for your help. Excel sheet has 150 000 rows and with this formula I want to safe a time. I have a Date, Name and Status and I need to see in other cell which Name was 4x or more time in consecutive GOOD or OK

https://imgur.com/a/v45qlTT

I think IF + AND + DATE Range it’s enough, but I don’t know how to put it together.

Thanks a lot for your suggestions !

Why my if statement doesn't apply on all cases?

I would like to iterate through a file of rows which contains a column called consequents. Consequents contain a list of itemsets. I want to check if every item n in each consequent belongs to y. If it belongs, then create a dictionary of consequents. If not, exclude the row .

 y = ['CHOL = 220', 'CHOL = 300',  'CHOL = 200', 'CHOL = 240', 'CHOL = 350',
         'CHOL = 230', 'CHOL = 235', 'LM = 20', 'LM = 25', 'LM = 30', 'LM = 15', 'LM = 35' ]

This is the code I used

for i, row in ass_rules.iterrows():
    flag3 = False
    single_antecedent = False

    for l, n in enumerate(consequents):
        flag3 = False
    if len(consequents) >= 1 and n in y:  
        flag3 = True

    if flag3:
         consequents_list.append(consequents)
         rules['consequents'] = consequents_list

The problem is, after using the condition, it includes some consequents that has items n which doesn't belong to y, such as: frozenset({'DIAB = n', 'LM = 20'}) frozenset({'CHOL = 220', 'SEX = F'}). What is wrong with my code?

  frozenset({'CHOL = 230'}),
  frozenset({'LM = 20'}),
  frozenset({'LM = 20'}),
  frozenset({'LM = 20'}),
  frozenset({'LM = 20', 'SEX = F'}),
  frozenset({'LM = 20'}),
  frozenset({'CHOL = 230'}),
  frozenset({'CHOL = 230'}),
  frozenset({'AL = 0.0', 'CHOL = 230'}),
  frozenset({'CHOL = 220'}),
  frozenset({'CHOL = 220', 'DIAB = n'}),
  frozenset({'CHOL = 220', 'SEX = F'}),
  frozenset({'LM = 20'}),
  frozenset({'DIAB = n', 'LM = 20'})
  frozenset({'CHOL = 220', 'SEX = F'})```

How to correctly use values from textboxes in html

I wanted to use values from textboxes but failed so i tried with constant values and now I am getting a NAN error. I am showing my result in a label btw.


function myFunction() {
var translength = 2400
var transSpacing = 150
var transEndOverhang = 75
var transStartOverhang = 75

var longLength = 6000
var LongSpacing = 150
var LongStartOverhang = 75
var LongEndOverhang = 75




if ( transSpacing !=0)
 document.getElementById('longAmount').value = ((transLength - transStartOverhang - transEndOverhang) / transSpacing) +1;
   document.getElementById('longAmount').innerHTML =  document.getElementById('longAmount').value
 if ( document.getElementById('longAmount').value > 0 && transStartOverhang + ((document.getElementById('longAmount').value -1) * transSpacing) + transEndOverhang < transLength)
 document.getElementById('longAmount').value = longAmount +1;
  document.getElementById('longAmount').innerHTML = document.getElementById('longAmount').value
}

How can solve this if clause problem in my project?

There is a project that I am doing, that search bus ticket beside two city and show it to user. It don't have problem when user searching ticket only go. There is also searching for going and return bus ticket. When it searching for going and return it happen problem. It don't show error message if going or return time is empty one of them.

I added code to check size of array that I get from web server. But after it that show if there is ticket in going time and don't show error for returning time(that doesn't have ticket). Also if going time don't have ticket and returning time has ticket. In that time It show returning time ticket in both screen. It should show error message in going time.

 else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {

                            JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
                            if (result.length()>0) {
                                JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
                                sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);}
            /* if user choose going and return this part work*/                    if (has_return) {
                                    if (result.length() > 1) {
                                        JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
                                        sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
                                    }

                                }

                        } else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAİLURE)) {

                            sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
                        }

Unable to check multiple if else condition in JQuery

I am trying to check some multiple conditions in JQuery but it doesn't return the desired result. whatever I input it always went to else condition.

$(function() {
  $('#installment').on("keydown keyup", check);
  function check() {
    var inst = Number($("#installment").val());
    if (inst === 2 || inst === 4 || inst === 6 || inst === 12) {
      return true;
    } else {
      $("#installment").val('');
      alert("you can not set wrong value");
      return false;
    }
  }
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<tr>
  <td>Number of Installment</td>
  <td><input type="text" name="installment" id="installment"></td>
</tr>

mercredi 27 mars 2019

Issue with the 'If Exisit' and 'else' function in Batch Script

So I want to run the operation (denoated by S1) in sub directories only under the condition that the sub directories contain a .mkv file with and a .ttf OR .otf file. This what I have done do far...

For /F Delims^=^ EOL^= %%A In ('Dir/B/AD 2^>Nul^|FindStr/IVXC:"Revised"'
) Do If Exist "%%A\*.mkv" ( 
If Exist "%%A\*.ttf" (
        If Not Exist "Revised\" MD "Revised" 2>Nul||Exit /B
        Call :S1 "%%A")
) else ( 
If Exist "%%A\*.otf" (
        If Not Exist "Revised\" MD "Revised" 2>Nul||Exit /B
        Call :S1 "%%A"))
GoTo :EOF

The issue is the S1 operation only takes place when there is a .otf file and not the .ttf file. However if I do this...

For /F Delims^=^ EOL^= %%A In ('Dir/B/AD 2^>Nul^|FindStr/IVXC:"Revised"'
) Do If Exist "%%A\*.mkv" ( 
Do If Exist "%%A\*.ttf" (
        If Not Exist "Revised\" MD "Revised" 2>Nul||Exit /B
        Call :S1 "%%A")
) else ( 
If Exist "%%A\*.otf" (
        If Not Exist "Revised\" MD "Revised" 2>Nul||Exit /B
        Call :S1 "%%A"))
GoTo :EOF

By adding a Do right before the If Exist in the 3rd line, the script functions as intended but the I would keep getting prompted

'Do' is not recognized as a internal or external command

Could I please get some help with the issue of getting the script to function as intended without the prompts?

I would like put a optional "wrong number. Try again" when is

I have just started learn java codes, that is why might I have a simple question that is not simple for me.

I would like put a optional "wrong number. Try again" when is entered different number than secretNum. May you guys help me out on this code?

// I need learn how put "try again" when the number is != than guess number.

    /* I have tried
     * 1)Change the signal "==" or "!=".
     * 2) do {
        System.out.println("Guess what is the number 0 to 10: ");
        if (sc.hasNextInt()) {
            guess = sc.nextInt();
        }
    } while(secretNum != guess);{
    System.out.println("Well done");
    System.out.println();
    System.out.println("Are you ready for the next step?");
    System.out.println();
    }
     */

import java.util.Scanner;

public class GuessNumber {




    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter name:");
        if(sc.hasNextLine()) {
            String userName = sc.nextLine();
            System.out.println("Hello " + userName + ",");
            System.out.println();
        }

        int secretNum = 5;
        int secretNum2 = 15;
        int guess = 0;
        do {
            System.out.println("Guess what is the number 0 to 10: ");
            if (sc.hasNextInt()) {
                guess = sc.nextInt();
            }
        } while(secretNum != guess);{
        System.out.println("Well done\n");
        System.out.println("Are you ready for the next step?\n");
        } 


        // I need learn how put "try again" when the number is != than guess number. 

        /* I have tried
         * 1)Change the signal "==" or "!=".
         * 2) do {
            System.out.println("Guess what is the number 0 to 10: ");
            if (sc.hasNextInt()) {
                guess = sc.nextInt();
            }
        } while(secretNum != guess);{
        System.out.println("Well done");
        System.out.println();
        System.out.println("Are you ready for the next step?");
        System.out.println();
        }
         */


        System.out.println("Enter Yes or No");
 while(!sc.next().equals("yes")&& !sc.next().equals("no"));{
    System.out.print("Yes");    
        }

        do {
        System.out.println("Guess what is the number 11 to 20: ");
        if (sc.hasNextInt()) {
            guess = sc.nextInt ();
        }
        }while(secretNum2 != guess);{
        System.out.println("Congratulations");
        System.out.println();
        System.out.println("The End");
        }
        }
        }
````````