mardi 31 mars 2020

The left-hand side of an assignment must be a variable? [closed]

I'm trying to do a uni activity which involved writing the following program. I keep getting an error on line 27 where I've got else (employeetype == 2) {, the error is as follows The left-hand side of an assignment must be a variable Syntax error, insert "AssignmentOperator Expression" to complete Assignment Syntax error, insert ";" to complete Statement.

I'm new to java and don't really understand what I've done wrong here as the same assignment works in the if statement properly but not the else.

Could someone help me please?

import java.util.*;
public class TaskFive {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        System.out.println("Please type 1 if you are hourly rated or 2 if you are a salesperson.");
        double employeetype = console.nextDouble();
        double pay;

        if (employeetype == 1) {
            System.out.println("Please enter your hourly rate:");
            double hourly = console.nextDouble();

            System.out.println("Please enter the total hours you worked:");
            double hoursworked = console.nextDouble();

            if (hoursworked > 40) {
            double  overtimepay = hoursworked - 40;
             pay = (overtimepay * (hourly * 1.5)) + (40 * hourly);
            }
            else {
             pay = (hoursworked * hourly);
            }}

            else  (employeetype == 2) {
            System.out.println("Please enter your commission rate as a decimal:");
            double comrate = console.nextInt();
            System.out.println("Please enter your sales value:");
            double sales = console.nextInt();

            pay = 500 + (sales * comrate);

            }

        double tax = (pay*.3);
        double netsalary = pay - tax;

        System.out.println("Tax: " + tax);
        System.out.println("Net Salary: " + netsalary);

        }

    }

Do you know a way to change the loop for something more productive?

i'm looking to do that loop with the condition in a way that is simpler and more productive. Can anybody can think of a way to do it? Thank you in advance for your help!! :)

OptVariableControle =np.array([])    
    j = 1
    for i in range (0,27):
        if  i == 2 :
            j = j+1
        if  i == 5:
            j = j+1
        if  i == 8:
            j = j+1
        if  i == 11:
            j = j+1
        if  i == 14:
            j = j+1
        if  i == 17:
            j = j+1
        if  i == 20:
            j = j+1
        if  i == 23:
            j = j+1
        OptVariableControle =np.append(OptVariableControle, 
                        (optionsActualise[i] + betas["beta" + str(j)]* (optionsActualise[i]-esperences[i])))

Efficient way to use If statement for checking the value is not being used in Javascript or JQuery

I have four textboxes say textbox1, textbox2, textbox3, textbox4 in my HTML doc on a button click for btn1 I want to make sure that all the values entered in all four textboxes are distinct & unique. For which I am using the if condition.

$("#btn1").on("click", function(){

    if($("#textbox1").val() === $("#textbox2").val() || 
       $("#textbox1").val() === $("#textbox3").val() ||
       $("#textbox1").val() === $("#textbox4").val() ||
       $("#textbox2").val() === $("#textbox3").val() || 
       $("#textbox2").val() === $("#textbox4").val() ||
       $("#textbox3").val() === $("#textbox4").val() ) 
    {  alert("Values are not unique please check them."); }

});

Is there any way shorter than this?

Python - Interate and compare over list and dict in dict in parallel

I want to iterate over a list and a dict in a dict in parallel and find the same strings. If it found the same strings I want to add a value and key pair to the dicts I was iterating over.

I sadly can't get it to work. I simplified the problem to make the code easier to exchange here.

x = ['a', 'c', 'f', 'h']
y = {'root_name': [
        {'value01': 'key01', 'value02': 'a'},
        {'value01': 'key02', 'value02': 'b'},
        {'value01': 'key03', 'value02': 'c'},
        {'value01': 'key04', 'value02': 'd'},
        {'value01': 'key05', 'value02': 'e'},
        {'value01': 'key06', 'value02': 'f'},
        {'value01': 'key07', 'value02': 'g'},
        {'value01': 'key08', 'value02': 'h'},
        {'value01': 'key09', 'value02': 'i'},
        {'value01': 'key10', 'value02': 'j'}
                   ]}

for i, j in zip(x, y['root_name']):
    if i == j['value02']:
        y['root_name']['key_exists'] = True

how do i make this if loop work in javascript?

I was trying to make a very basic and simple physics engine using a class called gameobject representing objects to which gravity would apply.

if ( ! this.y + ':' + this.x in this.ground ) {
        this.y -= 1
        document.getElementById(this.ref).style.bottom = this.y + "%"
        console.log(this.y)
    }

here this should lower the GameObject (this) by 1%, this.coords being a list containing coordinates of solid objects but when i run this nothing happens and I don't get any errors.

here is the code:

class GameObject {
constructor(ref, x, y, ground) {
    this.ref = ref
    this.x = x
    this.y = y
    this.ground = ground

    document.getElementById(this.ref).style.position = 'absolute';
    document.getElementById(this.ref).style.left = this.x + '%'
    document.getElementById(this.ref).style.bottom = this.y + '%'
}

update() {
    if ( ! this.y + ':' + this.x in this.ground ) {
        this.y -= 1
        document.getElementById(this.ref).style.bottom = this.y + "%"
        console.log(this.y)
    }
}

}

Two var as true in an IF statement

I am trying to figure out how I can use two var:

var s = document.getElementById('styledselect1');

var d = document.getElementById('styledselect2');

and check with an "if" statement if both of them are equal to a certain number, like below:

if (s.value == 0 and d.value == 5)

How can I declare this "and" between these two values?

styledselect1 and styledselect2 are select options..

My Nested IF Function is failing, but why?

I have done a lot of research on this but i am struggling to find the answer due to each question being specific to their data.

I have a nested IF function, where i would like it to change the cell value to either "Completed" or "Not Completed" depending on a few criteria.

Firstly, the function looks through the Data and then sees if the cell value matches a value in the data, then if true, looks at the next value and if there is a match, it then goes through the corresponding matches and sees if all values are set to delivered. If they are all delivered, the cell should change to "Completed", and if not "Not Completed".

Below is the function i have, that currently fails on the first IF.

{=IF('Sub Tasks'!J:J=A2,IF('Sub Tasks'!K:K=B2,IF('Sub Tasks'!AA:AA="Delivered","Completed","Not Completed"),"NOT TRUE1"),"NOT TRUE2")}

There are also screenshots of the test i am running.

OutputSheet OriginalData

Explicit or implicit else after conditionals succeed?

I often have methods in my APIs that have conditionals prior to performing the work intended. These checks (normally) raise an exception specific to the API (not user generated such as providing a string to a method using a float). They take the following form:

if condition_1:
    raise APIException('Msg 1')
elif condition_2:
    raise APIException('Msg 2')
...
elif condition_n:
    raise APIException('Msg n')
else:
    # do work

The conditionals are all able to be completed prior to any work and never depend on it being done prior. If any exception is generated during the else portion, its because of improper method use.

After looking at these methods and seeing this structure throutout my APIs, I've begun to wonder if this is a stylistic approach problem or not? That is, should I keep it this way where its explicit that the else portion means "all checks have passed now begin" or remove it thus making it implicit:

if condition_1:
    raise APIException('Msg 1')
elif condition_2:
    raise APIException('Msg 2')
...
elif condition_n:
    raise APIException('Msg n')
# do work

Further, given that each conditional suspends function execution prior to the work, is the if-elif stack another stylistic approach problem? That is, should I just use if or keep elif:

if condition_1:
    raise APIException('Msg 1')
if condition_2:
    raise APIException('Msg 2')
...
if condition_n:
    raise APIException('Msg n')
# do work

From the Zen of Python, I would say keeping if-elif-else is "Explicit is better than implicit" so this may answer itself, but from a idiomatic standpoint, does successive if vs if-elif really alter the readability/maintainability of the code? It does imply multiple conditions may happen simultaneously, which is why I prefer the if-elif because only one causes the function to suspend. I don't believe any of these forms alter performance.

Speed up IF/ELIF search over index in multiple lists?

Is there a faster way to run the following code: (checks if a value in the df.index is in multiple lists, and if so it appends a string to one list and the index to another list)

truth = []
t_ind = []
for ind in df.index.values:
    if ind in t4:
        truth.append('a')
        t_ind.append(ind)
    elif ind in t8:
        truth.append('b')
        t_ind.append(ind)
    elif ind in nk:
        truth.append('c')
        t_ind.append(ind)
    elif ind in mono:
        truth.append('d')
        t_ind.append(ind)
    elif ind in b:
        truth.append('e')
        t_ind.append(ind)
    else:
        truth.append('Other')
        t_ind.append(ind)

where t4, t8, mono, nk and b are seperate lists with index values (int)

I am getting an invalid syntax error when using elif statement (Not an indentation error)

Should be an easy issue to solve. If you see my code below, the line that reads 'elif target_2.got_away == True:' is returning an invalid syntax error. I have read other posts on this an all tips regard either not using an 'IF' statement before the elif or wrong indentation, which I believe this to be neither.

def refresh_window():
  if len(target_sprites) > 0:
   window.blit(bgr, (0,0))
  if len(target_sprites) == 0:
    window.blit(winner, (0,0))
  if target_1.got_away == True:
    window.blit(loser, (0,0)
  elif target_2.got_away == True:
    window.blit(loser, (0,0))
  elif target_3.got_away == True:
    window.blit(loser, (0,0))
  elif target_4.got_away == True:
    window.blit(loser, (0,0))
  elif target_5.got_away == True:
    window.blit(loser, (0,0))
  elif target_6.got_away == True:
    window.blit(loser, (0,0))
  player_sprites.draw(window)
  target_sprites.draw(window)
  for item in all_bullets:
    pygame.draw.rect(window, BLUE, (item['x']-5, item['y']-5, 10, 10))
    b_hitbox = (item['x']-10, item['y']-10, 20, 20)
    pygame.draw.rect(window, BLUE, b_hitbox, 2)
  pygame.display.update()

Lua, Else not allowed condition? - Why?

Why is the “else” statement not allowed to have a then? or conditions? (is it because it is the final condition within the else-if conditions it represents?)

I am struggling to understand this concept please give a simple explanation for a beginner programmer who just learned about variables.

The question I pose above, was discovered when I received a error with my “else” statement in the code I typed below:

`message = 0 condition = 30

if condition <=10 message = “try harder”

elseif condition <=20 then message = "Almost learning"

else condition = <=30 —This is the line where I get the error message message = "Now you’re getting it"

end print(message)`

Would appreciate someone breaking down in laymen terms why else is not allowed to have < or > or then or other conditions. Thank you.

Compact code for different lay out of disabled Angular Material buttons

I've been wondering if there's any easy way to change the lay out of a disabled button from Angular Material.

Right now, I do it using a ng-container and a ng-template. This works fine, but as you can see the code is not very compact because the only difference between the two buttons (in essence) is class="disabled" and this class should only be used if the button is disabled. I know there's more difference than just that but that's because I just removed (click) etc. for the disabled button since it isn't used anyway. Same goes for the disabled property on the non-disabled button, there's no point in having it.

                <ng-container *ngIf="disabledNext; else next">
                    <button mat-button class="disabled" type="button" [disabled]="disabledNext">
                        Next
                    </button>
                </ng-container>
                <ng-template #next>
                    <button mat-raised-button (click)="nextDate()" type="button">
                        Next
                    </button>
                </ng-template>

I'm looking for an answer along the lines of this but I'm not sure if that's possible

<button mat-button-raised class="disabledNext ? disabled : ''">Next</button>

OR some kind of CSS selector that works if the disabled property of the button is true

button.disabled { ... }

Is there a way to avoid the for-loops to boost my code in python?

I need some help to boost my performance. I got a given volume, which is a 3d-matrix out of 0s and 1s, representing the voxels. A also got a List of points. For every voxel in the volume I would like to know the Distance to the closest point contained in the list. The following code can be very time consuming.

for index, voxel in np.ndenumerate(Volume):

    if voxel == 1:    

            for index2 in ListofPoints:
                distance = np.sqrt((index[0]-index2[0])**2+(index[1]-index2[1])**2+(index[2]-index2[2])**2)
                distances.append(distance)

            Result_Distances[index] = np.amin(distances)

This takes about 1 Minute to compute, because my Volume can be very big (>1000 voxels). My ListofPoints is smaller (about 100 points).

Is there a smart way I can avoid the time consuming for loops? I also tried the map() function, but couldn't implement it in a way, so there is improvement.

Thank you for your help!

Use IF and VLOOKUP to change a cell value in VBA

I am trying to use Vlookup in VBA to change a value elsewhere in the sheet, based on the selection from a drop-down list.

I also want to combine this with an IF statement, so I want to select a calculated output number, if the valued looked up above is changed to 50%.

code is:

Dim nmcr_apalutamide_progress_num As Integer

Dim nmcr_apalutamide_ptc As Double

Range("nmcr_apalutamide_ptc").Value = 0.5

Dim result As Integer
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("model")


If Range("nmcr_apalutamide_ptc").Value = 0.5 Then
Range("result = Application.WorksheetFunction.VLookup(sheet.Range("nmcr_comparator_treatment"), sheet.Range("E52:H61"), 4, False)").Value = 0.5
'also change comparator percentage to 50%'


result = Application.WorksheetFunction.VLookup(sheet.Range("nmcr_comparator_treatment"), sheet.Range("D139:H146"), 5, False)
'find outcome comparator number'

End If

This shouldn't be that hard to do, I am not sure what I am missing.

Python3 : ifelse statement error in Python 3 code [closed]

Hello There,

I am a beginner python developer. I made a simple python3 code which have three case.

  1. if age = less than 18 then print you cannot drive
  2. when age = 18 print we will think about you
  3. when age = more than 18 you can drive

    • and if the input or age = more than 100 then it should print invalid age


    and this program works very well but if i use nested if else statement it doesn't work here is the code :

age calculator for driving

print()
print("\t Age requirement for Driving")
age = int(input(" Enter Your Age : "))
if age < 18:
    print(" Sorry, You're under age. You cannot drive")
elif age == 18:
    print(" Sorry, we cannot Decide. we will think about you :) ")
elif age > 100:
    print(" Invalid Age !!! Your are not immortal ;)")
else:
    print(" Congratulation !!! You can Drive")

Code with Nested if else statement

print()
print("\t Age requirement for Driving")
age = int(input(" Enter Your Age : "))
if age < 18:
    print(" Sorry, You're under age. You cannot drive")
    if age > 100:
        print(" Invalid Age")
elif age == 18:
    print(" Sorry, we cannot Decide. we will think about you :) ")
else:
    print(" Congratulation !!! You can Drive")

this code doesn't work please help !!!

Create new column based on multiple conditions in multiple columns

I'm working with a messy big data patient file (> 40 million rows). Each patient (id) has several rows. Each row (roughly) represents one consultation with a symptom/disease code (icpc). I add a new column with categories for patients with specific conditions (based on columns icpc and icpc2).

My raw data.frame (df) looks something like this (this is fabricated data, id is much longer in my dataset and I left out irrelevant columns which I like to drop):

id icpc icpc2 reg.date 
123 D95 F15   19JUN2015 
123 F85       15AUG2016 
332 A01       16MAR2010 
332 A04       20JAN2018
332 K20       20FEB2017
100 B10       01JUN2017 
100 A04       11JAN2008
113 T08       18MAR2018
113 P28       19JAN2017 
113 D95 A01   16JAN2013
113 A04       01MAY2009
551 B12 A01   03APR2011
551 D95       09MAY2015

Say I want to categorize patients with D95 and/or A01 as YES in the new column named 'condit' (based on two columns. I've been trying the following:

df.cat <- df %>%
  group_by(id) %>%
  mutate(condit = 
           if_else(icpc == c("D95", "A01") | icpc2 == c("D95", "A01") ~ 'yes', 'no'))

But this gives an error:

Error: `condition` must be a logical vector, not a `formula` object
Run `rlang::last_error()` to see where the error occurred.

I have also tried using case_when instead of if_else because I also need make a seperate file with multiple options for condit.

This is the data.frame I want:

id icpc icpc2 reg.date  condit
123 D95 F15   19JUN2015 yes
123 F85       15AUG2016 yes
332 A01       16MAR2010 yes
332 A04       20JAN2018 yes
332 K20       20FEB2017 yes
100 B10       01JUN2017 no
100 A04       11JAN2008 no
113 T08       18MAR2018 yes
113 P28       19JAN2017 yes
113 D95 A01   16JAN2013 yes
113 A04       01MAY2009 yes
551 B12 A01   03APR2011 yes
551 D90       09MAY2015 yes

Any help will be greatly appreciated. Thank you!

Output only items from Column B to Column C when All 3 conditions are met in Column A

I have two columns, one with account types (-A -B -C -D -E, etc) I only want Column B to be output into Column C if the account holder from Column B has all three account types (-A -B and -C)

Objective: Output Row from Column B into Column C IF Column A ends with -A, -B and -C

Here is what I have tried:

=IF(RegExMatch(A2:A,"-A") AND (RegExMatch(A2:A,"-B") AND (RegExMatch(A2:A,"-C"),"$ColumnB","No Output")

Clearly does not work and I am terrible with Google Sheets.

utp

Define IF-THEN statements within labels

Following this question, consider that you want to do multiple things if a condition is met. pseudocode:

if condition then
    do things
else if other conditions then
    do other things
else
    other things
end if

From this page one could define the if statement within a dummy procedure:

DROP PROCEDURE IF EXISTS <procedure_name>();
DELIMITER $$

CREATE PROCEDURE <procedure_name>()
BEGIN
    IF (<conditions>) THEN
        -- do things
    ELSEIF (<conditions>) THEN
        -- do other things
    ELSE 
        -- other things
    END IF;
END$$

DELIMITER ;

<procedure_name>();

which is honestly the ugliest way of implementing an if statement I have ever seen in any programing language, ever!

This page suggests some one-liner if statement syntax in the form of

SELECT IF(<condition>, 'true message', 'false message');

to print out messages or nested

SELECT <fields>
IF (<condition>)
AS <custom_label>
FROM <table>

to only select rows from a table that meet a specific condition of a specific field/column.

Now I was wondering if it is possible to implement if statements in a more canonical way. For example, using labels to contain IF-THEN statements:

<label>: IF (<conditions>) THEN
    -- do things
ELSEIF (<conditions>) THEN
    -- do other things
ELSE 
    -- other things
END IF <label>;

or

<label>: BEGIN
IF (<conditions>) THEN
    -- do things
ELSEIF (<conditions>) THEN
    -- do other things
ELSE 
    -- other things
END IF;
END <label>;

which are slightly less ugly. The goal is to find a more sensible and concise way of defining if statements, so other solutions are also appreciated. Thanks for your support in advance.

I want to check if 4 Conditions are meet something should happen

i am still new to c# i am trying to write a code that would check my if condition if 4 conditions are met then something happens. Here is my codes:enter code here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
public class NameTrans : MonoBehaviour {
    public string thename;
    public GameObject inputField;
    public GameObject textDisplay;
    public GameObject textDisplay2;

    // Use this for initialization
    public void Showname () {
        thename = inputField.GetComponent<Text>().text;
     if (thename.ToUpper().Contains("Man".ToUpper()) || thename.ToUpper().Contains("Dog".ToUpper()))
        {

            textDisplay2.SetActive(false);
            textDisplay.SetActive(true);
            textDisplay.GetComponent<Text>().text = "WOrks" ;
        }
       else
        {
            textDisplay.SetActive(false);
            textDisplay2.SetActive(true);
            textDisplay2.GetComponent<Text>().text = "Not WORK" ;
        }

            }


}


Logic to read a file for different intervals

I need to develop a logic, where - I get 4 fixed file in 2, 5, 9, 11 months Except above I get monthly files for 1, 3, 4, 6, 7, 8, 10, 12.

Note: All files come with same name.

Now, I need to read these files accordingly every month and push data into a table. If I have files monthly, I will read it and push data to table directly. If I do not have a file for any of the period among 1, 3, 4, 6, 7, 8, 10, 12 then I need to consider 2nd month file (from table) for 3, 4 & 5th month file (from table) for 6, 7, 8 & 9th month file (from table) for 10 & 11th month file (from table) for 12, 1 reading.

I tried many ways, but unable to arrive at the correct results.

Your kind help needed.

What would be a optimized statement for ternary operation

I found two of the following operations working same

  1. var x = someValue ? someValue : 1

  2. var x = someValue || 1

what would be the best practice and why ?

code shows error in numpy if(A[0,i]<=0.5)

if(A[0,i]<=0.5) shows error in numpy whats wrong here is my syntax not correct i am using jupiter ipython notebooks what is wrong with my code it shows syntax error

lundi 30 mars 2020

How to convert list append with for, if, elif to list comprehension

I' like to convert list append code with mulitple for and if, elif to list comprehension. I tried but only temp_list worked. temp_list2 did not work properly

Original code

temp_list = []
temp_array = accd['ACCD_SEQ'].values
temp_list = [i for i in temp_array if len(accd[accd['ACCD_DTL'].str.contains(i)]) != 0]

temp_list2 = []

for i in temp_list:
    if len(accd[accd['ACCD_DTL'].str.contains(i)]) == 1:
        temp_list2.append(i)
    elif len(accd[accd['ACCD_DTL'].str.contains(i)]) > 1:
        for j in range(len(accd[accd['ACCD_DTL'].str.contains(i)])):
            temp_list2.append(i)
    else:
        pass

My trial

temp_list2 = [i if len(accd[accd['ACCD_DTL'].str.contains(i)]) == 1 else i for j in range (len(accd[accd['ACCD_DTL'].str.contains(i)])) if len(accd[accd['ACCD_DTL'].str.contains(i)]) > 1 for i in temp_list

This code said "UnboundLocalError : local variable 'i' referenced before assignment"

Anyone can help to fix it?

How to create an if else statement for length units with javascript

My goal is to create a true mathematical statement with length units. The only part I am having trouble with, is the if else part of the Javascript. What should I change, so that my if else statement for length units works? This is what I have done so far:

var operators = ['+', '-'];
var e = ['km', 'm'];

function F1() {
  num1 = document.getElementById("num1");
  num2 = document.getElementById("num2");
  rnum1 = Math.floor((Math.random() * 10) + 1);
  rnum2 = Math.floor((Math.random() * 10) + 1);
  num1.innerHTML = rnum1;
  num2.innerHTML = rnum2;
  oper = document.getElementById("operator");
  op = operators[Math.floor(Math.random() * 2)];
  oper.innerHTML = op;
  eht = document.getElementById("e1");
  eht2 = document.getElementById("e2");
  eh = e[Math.floor(Math.random() * e.length)];
  eh2 = e[Math.floor(Math.random() * e.length)];
  eht.innerHTML = eh;
  eht2.innerHTML = eh2;
  answer = document.getElementById("answer");

  if (eh = 'km') {
    if (eh2 = 'm') {
      answer.innerHTML = eval(rnum1 * 1000 + op + rnum2);
    } else {
      if (eh = 'm') {
        if (eh2 = 'km') {
          answer.innerHTML = eval(rnum1 + op + rnum2 * 1000);
        } else {
          if (eh = 'km') {
            if (eh2 = 'km') {
              answer.innerHTML = eval(rnum1 * 1000 + op + rnum2 * 1000);
            } else {
              answer.innerHTML = eval(rnum1 + op + rnum2)
            };
          }
        }
      }
    }
  }
<p> <label id="num1"> </label> <label id="e1"> </label>
  <label id="operator"> </label>
  <label id="num2"> </label> <label id="e2"> </label> =
  <label id="answer">m </label> </p>
<button onclick="F1()"> New </button>

How can I structure for and if loops to construct Latin squares?

My objective is to construct every unique Latin Square given a size n. The R command rlatin(n) uses a Markov chain to construct a random Latin Square of size n x n. However, this command won't just construct all Latin Squares of its size.

Below is my code:

L <- function(n){
  size <- factorial(n) * factorial(n-1)
  l <- list()
  l[[1]] <- rlatin(n)
  for(k in 2:size){
    new <- rlatin(n)
    for(j in 1:(k-1)){
      if(new == l[[j]]){
        new <- rlatin(n)
      }
    }
    l[[k]] <- new
  }
  l
} 

This is not working properly, and I cannot see why. Can someone please shed some light on my errors? Additionally, once all Latin Squares are constructed, is there a way that I can organize them so there is some clear in the Latin Squares?

How to remove class from body if condition is not met?

I'm working with an if statement to show an alert message depending on certain conditions.

Under the second condition New Article I want a specific css class to be added (show-banner-alert). I am able to get the css added but its now affecting the conditions following it.

I've tried adding a $("body").removeClass and adding a new class with different properties but I am unable to get rid of the first-class successfully.

Here is my code:

$(window).on("load", function(e) {
  $('.preloader').fadeOut('slow');

  if (document.cookie.includes("isDismissed=true")) {
    document.body.classList.add("alert.container");
  } else if ("@pageTitle" === ("New Article") !== "-1") {
    document.body.classList.add("show-banner-alert");
  } else if ("@pageTitle".indexOf("Test") !== "-1") {
    $("body").removeClass("show-banner-alert").addClass("show-alert");
  } else if ("@pageTitle".indexOf("New Home") !== "-1") {
    document.body.classList.add("show-alert");
  } 
});

Adding a third condition in else if statement

I have an alert message showing under certain conditions. I currently have two conditions and the alert message is working the way I want. I am attempting to add a third condition but when doing so it does not appear at all even for the two conditions before it.

My logic breakdown that I am trying to create with an if else statement.

If isDismissed is true do not show alert. If cookie isDimissed does not exist, display alert for title "Test" or "New Article"

$(window).on("load", function(e) {
  $('.preloader').fadeOut('slow');

  if (document.cookie.includes("isDismissed=true")) {
    document.body.classList.add("alert.container");
  } else if ("@pageTitle".indexOf("Test") !== -1) {
    document.body.classList.add("show-alert");
  } else { ("@pageTitle".indexOf("New Article") !== -1) {
    document.body.classList.add("show-alert");
});

Python exam grader marking a question wrong when its right

So I have this code that's supposed to grade student files, and everything works fine on student 1 However, when student 2 gets graded it's not displaying that he gets a 100% it says the answer they put (which is A) is wrong then it puts the correct answer (which is A) and it's marking his test as a 95% what am I doing wrong?

    total= 0
    for i in range(1, (minLen)+1):
        if student_lines[i] == answer_lines[i]:
            total += 1

            percentage= int((total/minLen)*100)
    print(" ")
    print("You scored", str(percentage) + "% on the exam.")
    print(" ")
    if percentage >= 93:
        print("You earned the letter grade A")
    elif percentage >= 90 and percentage < 93:
        print("You earned the letter grade A-")
    elif percentage >= 87 and percentage < 90:
        print("You earned the letter grade B+")
    elif percentage >= 83 and percentage < 87:
        print("You earned the letter grade B")
    elif percentage >= 80 and percentage < 83:
        print("You earned the letter grade B-")
    elif percentage >= 77 and percentage < 80:
        print("You earned the letter grade C+")
    elif percentage >= 73 and percentage < 77:
        print("You earned the letter grade C")
    elif percentage >= 70 and percentage < 73:
        print("You earned the letter grade C-")
    elif percentage >= 67 and percentage < 70:
        print("You earned the letter grade D+")
    elif percentage >= 60 and percentage < 67:
        print("You earned the letter grade D")
    elif percentage < 60:
        print("You earned the letter grade F")

    print(" ")
    if total < 100:
        print("You missed the following questions:")
        print(" ")
        print("Qn#\tYour Answer\tCorrect Answer")
        for i in range(1, (minLen)+1):
            if student_lines[i] != answer_lines[i]:
                incorrect_list= list(student_lines[i].split(','))
                correct_list= list(answer_lines[i].split(','))
                print(incorrect_list[0] + ".", "\t    ", incorrect_list[1].replace("\n", ""), "\t\t   ", correct_list[1].replace("\n",""))
    if total == 100:
        print("Congratulations you got all the questions correct")```


Add an IF to an arrayformula in Google Sheets

I have a simple one that is driving me nuts. I have a long list of NPS scores and I need to create a new column and add the following formula. It works great if I drag to the bottom but I can't always do that and need to to be added using an arrayformula but I'm pulling out what hair I have left trying to make it work :(

=if(A3<=6,"Detractor",if(A3>=9,"Promoter","Neutral"))

How do I paste data from the first day of the month for the whole month>

I have a data frame containing weights for stocks in a portfolio, it is around 1000 stocks and 4000 days of data. I want to apply the weights of the first day of each month to all days of that month. However, I still want to retain the structure of daily data.

My data is similar to this:

data<-as.data.frame(matrix(1:4000,nrow=200,ncol=20))

rownames(data)<-seq(as.Date("2018/01/01"),as.Date("2018/07/19"),1)

So I want to have the values of the first of January copied to all days of January, values of the first day of February copied to all days in Februari etc. I have no clue how to handle this.

Any tips?

Create new column when have repeat values and when have break points

Im trying to create a new column with some conditions that I dont know yet how to do, I have this data frame for example

area
AR
AR
AR
AM
AM
AR
AR
AR
AM
AM
AM
AM
...
AM

So, when have AR x times and after this have one or until 20 AM and came back have AR, I want a new column with AR. By the moment when have AM x times and only AM, without come back to AR, I want new column with AM. Like this:

area    area2
AR      AR
AR      AR
AR      AR
AM      AR
AM      AR
AR      AR
AR      AR
AR      AR
AM      AM
AM      AM
AM      AM
AM      AM
...     ...
AM      AM

I tried to do with sequence, but I don't know if is the best way

df$seq <- sequence(rle(as.character(df$area))$lengths)

Someone know how to do? Thanks!

How to create a binary value to capture null values in R?

Here is a simplified version of my current dataset:

v1    v2     v3
null  b      c
a     b      c
a     null   c 

I want to create a new column called 'v4' that would be a 1, ONLY if v1 is null, and 0, if v1 was not null.

The desired output would look like this

v1    v2     v3 v4
null  b      c  1
a     b      c  0
a     null   c  0

Any help with this would be greatly appreciated.

How to have two separate functions not interfere with another?

I have an alert message that appears on the page for the first time creating a cookie on Dismiss. I created a function on page load to check if the cookie exists, do not display alert and if it does not exist display alert message. I also have another function in place to check if the pageTitle is "Test" display the alert message.

At the moment my alert message is showing even after clicking dismiss and a cookie is generated because of the second function check on pageTitle. If I remove the check on pageTitle I do get the desired result I want but the message appears on all pages when I only want it to appear with the pageTitle = Test

I am attempting to have both checks work properly with one another for example, if cookie exists do not show an alert, if it doesn't exist and the pageTitle = test show alert message

First function

  $(window).on("load", function (e) {
    $('.preloader').fadeOut('slow');

    if (document.cookie.includes("isDismissed=true")) {

        document.body.classList.add("alert.container");
    } else {
        document.body.classList.add("show-alert");
    }
});

Second function

 if("@pageTitle".indexOf("Test")  !== -1) {
       document.body.classList.add("show-alert");
    }

Changing dates in a dataframe based on the time of day?

I am working on a project that defines the time of day as 7am to 7 am rather than the traditional Midnight to Midnight. I need some help changing the dates in this dataframe to match our definition of day. For example, if this dataframe says 3:54am on December 21st, I need the date to change to December 20th. However, if it says 8:59PM then the date would remain identical to what is already in the dataset.

In simpler terms, I need to change the date for all times that fall between Midnight and 7AM. Is an Ifelse statement the best way to get at this?

Sorry for the confusing language but I couldn't think of a better way of phrasing what I'm getting at with this idea.

enter image description here

How to ignore characters in a statement in R?

so currently I have variable a, b, and c. I have a column 'v4' that is a binary variable based off of the 'v1' column. 1 (a,b, or c) 0 (not).

Example:

v1 v2 v3 v4
a  b  c  1
b  b  c  1
d  b  c  0

An issues I have with my data is that sometime they have years or other characters before the value. For example, I have instances of '2020 c'. This would be correct and I would want to capture this in column 'v4'. However, if these years come after it would be incorrect. Example, 'c 2020' would appear as a 0 in column 'v4'.

Example of how I want it to look:

v1     v2 v3 v4
a      b  c  1
b      b  c  1
d      b  c  0
c 2020 b  c  0
2020 c b  c  1
1990 c b  a  1

How could I made this work? Currently I am using

df1$v4 <- as.integer(grepl("(a|b|c)$", df1$v1))

this is good at capturing all instances, but I am not able to exclude the instances where the data is coming after the the variable I am trying to capture. Hopefully this makes sense.

How can I use a Boolean operator in if Clause in Python

a, b are a data frames consisting Boolean values and c is used for counting the number of true cases satisfying both the conditions ie only counts true values. I have tried many like using a.bool(true) but no luck as I am new to python.

x1 = True
if a = x1 
and if b = x1
      c = c + 1
      print(c)

Invalid syntax of Else: 3.8

I'm a newbie in python scripting and would like to know how to fix the code below. I would like to know how to solve the Invalid Syntax of Else statement, thank you!

import os
import zipfile

f = open("filelist.txt","w+")
path=("pathtofile")
directory=os.fsencode(path)
filenames = []
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".zip"):
        with zipfile.ZipFile(filename, 'r') as zipObj:
            contents = zipObj.namelist()

    listfile = (str(contents))
    remchar = "'[]"
    for char in remchar:
            a = listfile.replace(char,"")
    f.write (a)
    continue
    else:
        pass

    f.close()

False positive in Bash condition

I am writing a bash script to check on multiple servers if Tomcat 5 is installed. When running the script, even if the find command stored in the variable command returns nothing, the tomcat variable is still set to '1' in the if statement.

I know there must be something wrong with my if statement but I'm not sure what. Below is the function that runs the command on the remote server

function search() {

        local login=$1
        local server_fqdn=$2

        local command="sudo find / -name \"tomcat-5*\""
        ssh -oBatchMode=yes -o ConnectTimeout=6 $login@$server_fqdn "$command"
        if [ "$?" = 0 ];
        then
                echo "Tomcat found"
                tomcat=1
        else
                echo "No tomcat here!"
        fi
}

How can I get the function to enter the 'else' condition if command returns nothing?

Matlab program to calculate GPA and CGPA of a student

I wish to know a program on MATLAB to calculate GPA and CGPA of a student. As I am new to MATLAB, I am eager to compute this program and this will be very helpful for me as a newcomer.

GPA should be out of 5 and it should use an interactive script.

Comparing a list with a dictionary and producing new list. Length of new list is 1?

I am trying to produce a List B by comparing elements from List A with X elements in Dictionary A. The List B should produce all Y elements from the dictionary where X and List A match.

This is my code:

for i in range(0,Len): # Len is length of List A
    tu = tuple1[3*i:3*i+3]

    if tu in diction:
        for x,y in diction.items():
            if tu == x:
                protlist = [y]
                print(*protlist,end =" ") # This prints each y value in a linear fashion
                break
print(len(protlist))  

This code will superficially produce the correct list. However when I call for the length of the list, it is outputted as 1. I tried replacing protlist = [y] with protlist.append(y). This gave the correct length of the list and the wrong output.

I also tried using the join function instead with ''.join(y) but this also gave the incorrect length of the list.

How can I edit the code so that both the correct output and length of list is achieved? Thank you.

if statement dataframe python New attemp

I asked the question in the following post and it got closed:

Previous Post

and it got closed by @Brad Solomon and marked as duplicate. But the suggested links did not helped in my solution. So again my questions:

I am trying to calculate a value and making a if statement based on Product, but I could not find a good and easy why how it should work. I am just receiving an error but no proper solution. Maybe someone knows how to fix it?

The code looks like the following:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Date' : ['11/8/2011', '11/8/2011', '11/8/2011'],
                   'ID' : ['ID 1', 'ID 2', 'ID 3'],
                   'A' : [100, 200, 50],
                   'B' : [0.2, 0.5, 0.9],
                   'C' : [0.02, 0.05, 0.09],
                   'Product' : ['P1', 'P2', 'P1'],
                   'Type' : ['Food', 'Non-Food', 'Food']
                  })
def calc_1(df):
    calc = np.log(df['A'] / df['B']) + (df['C'])
    return calc

def calc_2(df):
    calc2 = 0.0
    d1_calc = 0.0

    d1_calc = calc_1(df)

    if df['Product'] == 'P1':
        if df['Type'] == 'Food':
            calc2 = d1_calc*np.log(df['A']/(df['B']*df['C']))

    elif df['Product'] == 'P2':
        if df['Type'] == 'Non-Food':
            calc2 = d1_calc*np.exp(df['A']/(df['B']*df['C'])) 
    else:
        raise Exception('No Calc')
    return calc2

calculation = calc_2(df)
print(calculation)

I am getting the following error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-d5a5d719b0f8> in <module>
----> 1 calculation = calc_2(df)
      2 print(calculation)

<ipython-input-12-4304ba3859f1> in calc_2(df)
      5     d1_calc = calc_1(df)
      6 
----> 7     if df['Product'] == 'P1':
      8         if df['Type'] == 'Food':
      9             calc2 = d1_calc*np.log(df['A'])

~/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Check Element not in array in java script? [duplicate]

Hi I am New to JS i trying below code

a=[0,1,3]
if (2 in a){ console.log(a)}

in above code i am checking element is available are not. but in above case 2 is not in array but condition show true why?

i know we can check condition like this a.includes(2) why in above case showing true?

Thanks Advance.

Confused with complexity

    for key in string_list:
       if key in new:
          same.append(key)

I'm really bad with complexity and I am trying my to best learn. Is the complexity of this code O(n^2)? Because it is comparing 2 lists or is it O(n) as I just used one for loop. string_list and new are just two lists

dimanche 29 mars 2020

how to write if condition for an element has next element in pure javascript

I would like to write some code if an element has next element as a sibling in Pure Javascript. Thanks in advance. Following is an example.

A B

if( a has next element siblings ) { my code goes here }

Scanner is not appearing (FizzBuzz Excercise)

I started learning Java recently and I ran into this problem. I'm trying to do the FizzBuzz exercise but my I think my scanner is not working. I have this code

         Scanner scanner1 = new Scanner (System.in);
        System.out.print("Number: ");
        int scanner2 = scanner1.nextInt();
        if ((scanner2 % 5 == 0) && (scanner2 % 3 == 0))
            System.out.println("FizzBuzz");
        else if ((scanner2 % 5) == 0){
            System.out.println("Fizz");
        }
        else if ((scanner2 % 3) == 0){
            System.out.println("Buzz");
        }
        else {
            System.out.println(scanner2);
        }

and whenever I execute it, Netbeans show's up

BUILD SUCCESSFUL (total time: 0 seconds) 

without me even entering any value, the scanner basically is not working I have java.util.* imported and no errors are showing up at all. Thank you very much in advance.

Error: incompatible types:byte cannot be converted to Boolean (illegal start of expression)

Good morning everyone this is my first time using StackOverflow and pretty much my first programming experience. I'm trying to learn Java and I'm using NetBeans IDE. while learning about if, conditions and expressions I faced this error that I can't know the cause of. the guy in my tutorial has it and it's fine and he doesn't have any errors (he's using IntelliJ). here is my code

 byte Temp = 20;
        /*The error shows up here*/ if (Temp => 30){
            System.out.println("It's a Hot day!");
            System.out.println("Drink Alot of Water!");
        }
        else if (Temp > 20)
            System.out.println("It's a Nice day!");
        else 
            System.out.println("It's a Cold day!");

I tried with == and it worked fine I'm not sure what the problem is, any help is much appreciated Thank you very much

Can I have a python tkinter button with an if/else statement in its function that performs different actions depending on file found?

I want a tkinter button to do one thing or another depending on what file the function finds in a specific directory.

Is it possible to do it with something like this sample code, or how could it be accomplished? (This code seems to ignore the "else" part of the function.)

def test():

    x = glob('C:/*file1.txt')[0]
    y = glob('C:/*file2.txt')[0]

    if x:
        #Do stuff

    else:
        #Do this stuff

tk.Button(root,
          text = "Test",
          command = test,
          fg="gray17",
          width = 15).pack()

EXCEL: ignore row if all 4 cells are 0; get name if any of the 4 cells is greater than 0

i have a list of names(Column A), the numbers in columns B to F are result of a formula. Im trying to create a FOR LOOP code that will check columns B to F, if all cells in B to F are zero then the code should ignore the current row and skip to the next row; if any of the cells in columns B to F is greater than 0, then the code should get the corresponding name in Column A.

Example: If any of the cells in B2, C2, D2, and E2 is greater than 1, then i should get the name/value of A2. if all cells in B2, C2. D2, and E2 are all zeros, then proceed to check next row and do the same thing.

here's the code i used to try to get the names that has any of the 4 column cell values greater than 1

     For i = 2 To LastCalcAnalystRowIndex '//wsCalculations.Cells(Rows.Count, "CP").End(xlUp).Row

    '//Get Component from cell in column "BP"
        Analyst = wsCalculations.Cells(i, "CP").Value
        Component = wsCalculations.Cells(i, "CN").Value
        weeknumber = wsCalculations.Range("BR2").Value + 3

            If wsCalculations.Cells(i, "B").Value = 0 And wsCalculations.Cells(, "C").Value = 0 _
            And wsCalculations.Cells(i, "D").Value = 0 And wsCalculations.Cells(i, "E").Value = 0 _
            And wsCalculations.Cells(i, "F").Value = 0 Then
            Exit For
            Else
            wsCalculations.Cells(i, "A").Value = wsCalculations.Cells(i, "CP").Value
            End If
            Next

using the code above, i tried to get the names which all 4 column values are not equal to zero, but the result i get is just a copy of the original list. i highlighted the rows i want my code to skip. i also included the result i get and the result i want to get. Below is a sample data. My original data has 54 rows. data. can anyone please tell me what im getting wrong?

if statement dataframe python [duplicate]

I am trying to calculate a value and making a if statement based on Product, but I could not find a good and easy why how it should work. I am just receiving an error but no proper solution. Maybe someone knows how to fix it?

The code looks like the following:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Date' : ['11/8/2011', '11/8/2011', '11/8/2011'],
                   'ID' : ['ID 1', 'ID 2', 'ID 3'],
                   'A' : [100, 200, 50],
                   'B' : [0.2, 0.5, 0.9],
                   'C' : [0.02, 0.05, 0.09],
                   'Product' : ['P1', 'P2', 'P1'],
                   'Type' : ['Food', 'Non-Food', 'Food']
                  })
def calc_1(df):
    calc = np.log(df['A'] / df['B']) + (df['C'])
    return calc

def calc_2(df):
    calc2 = 0.0
    d1_calc = 0.0

    d1_calc = calc_1(df)

    if df['Product'] == 'P1':
        if df['Type'] == 'Food':
            calc2 = d1_calc*np.log(df['A']/(df['B']*df['C']))

    elif df['Product'] == 'P2':
        if df['Type'] == 'Non-Food':
            calc2 = d1_calc*np.exp(df['A']/(df['B']*df['C'])) 
    else:
        raise Exception('No Calc')
    return calc2

calculation = calc_2(df)
print(calculation)

I am getting the following error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-d5a5d719b0f8> in <module>
----> 1 calculation = calc_2(df)
      2 print(calculation)

<ipython-input-12-4304ba3859f1> in calc_2(df)
      5     d1_calc = calc_1(df)
      6 
----> 7     if df['Product'] == 'P1':
      8         if df['Type'] == 'Food':
      9             calc2 = d1_calc*np.log(df['A'])

~/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How would I create an if statement for strings based on multiple conditions in R?

So I want to create a new column in my dataset that would be "1" if True and "0" if false.

My data is setup similar to this:

v1 v2 v3
a  b  c
b  b  c
d  b  c

Let's say that I want my if statement to be setup to where if v1 equals a, b, or c, then the new column would be 1. Under this new condition, I would want my new dataset to look like this.

v1 v2 v3 v4
a  b  c  1
b  b  c  1
d  b  c  0

How would I go about setting this up? Hopefully I made sense explaining this, I tried to simplify as much as possible.

Python: My if statement is not working but I don't get any error?

I am creating a tic-tac-toe game and the move_base function in my script is not working. I have seen this type of if statement used before and I don't know why the function is not working. There are no errors but the function doesn't update num_word or moves. I do not have a lot of python experience so I do not know what I am doing wrong. I will add more features to the game but I can't because the basic part of it is not working. I have not seen any other place that tells me how to fix this.

#tic tac toe game
#global variables
game_over = False

#game script
def game():
    #game variables

    #positions on the board
    one = '1'
    two = '2'
    three = '3'
    four = '4'
    five = '5'
    six = '6'
    seven = '7'
    eight = '8'
    nine = '9'
    positions = [one, two, three, four, five, six, seven, eight, nine]

    num_chosen = ''
    #moves in the game
    moves = 0

    #prints board
    def board():
        print(f'{one}|{two}|{three}')
        print(f'{four}|{five}|{six}')
        print(f'{seven}|{eight}|{nine}')

    #how to check who won
    def check_win_base(xo, num1, num2, num3):
        if num1 == xo and num2 == xo and num3 == xo:
            if(xo == 'x'):
                print('x player wins')
                game_over = True
            elif(xo == 'o'):
                print('o player wins')
                game_over = True
    #check_win_base applied to all numbers
    def check_win(xo):
        check_win_base(xo, one, two, three)
        check_win_base(xo, four, five, six)
        check_win_base(xo, seven, eight, nine)
        check_win_base(xo, one, four, seven)
        check_win_base(xo, two, five, eight)
        check_win_base(xo, three, six, nine)
        check_win_base(xo, one, five, nine)
        check_win_base(xo, three, five, seven)

    #checks if game is a draw
    def check_draw():
        if moves == 9:
            print('The game is a draw')
            game_over = True

    #how to pick a square
    def move_base(xo, num_word, num):    
        if num_chosen == num:
            num_word = xo
            moves += 1
    #move_base applied to all numbers
    def move(xo):
        move_base(xo, one, 1)
        move_base(xo, two, 2)
        move_base(xo, three, 3)
        move_base(xo, four, 4)
        move_base(xo, five, 5)
        move_base(xo, six, 6)
        move_base(xo, seven, 7)
        move_base(xo, eight, 8)
        move_base(xo, nine, 9)

    #all the required functions put together
    def turn(xo):
        board()
        print(f'{xo} move')
        num_chosen = int(input())
        move(xo)
        check_win(xo)
        check_draw()

    turn('x')
    turn('o')
    turn('x')
    turn('o')
    turn('x')
    turn('o')
    turn('x')
    turn('o')
    turn('x')

#checks if game is over or not
if game_over == False:
    game()
else:
    print('Game Over')

php) code inside if(empty($param1)){} still runs even $param1 is not empty [solved]

I have been working on this problem for several hours but I couldn't figure out why empty() in if statement doesn't work as I expected.

fetch.php

    header('Content-Type: application/json');

function fetchApi($param1){
    $apiKey="SOME TEXT WHICH I WILL NOT POST HERE";
    $curl = curl_init();
    if(empty($param1)){       
        $body = json_decode(file_get_contents('php://input'), true);
        $bodyObject = (object) $body;
        if($bodyObject->target=="main"){
            $bodyObject->link = $bodyObject->link . "random?number=4".$apiKey;
            curl_setopt($curl, CURLOPT_URL, $bodyObject->link);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl); 
            echo $output;
        }
    }else{
        echo $param1;
    }
    curl_close($curl);
}
fetchApi('');

this is my fetch.php code, I need to run fetchApi in two different situations. The first situation is when index.html is loaded. Javascript will automatically fetch to fetch.php and runs function fetchApi with empty string as parameter. Have tested hundreds time and it works fine.

But the problem is, I need to run this function in search.php too, when user searches something.

form in index.html

 <form action="search.php" method="GET">
     <label for="check">ingradients</label><input id="check"type="checkbox"/>
     <input type="text" name="search" placeholder="SEARCH"/>
 </form>

search.php

<!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
 </head>
 <body>
  <?php 
    $searchId = $_GET["search"];
    include ('fetch.php');
    fetchApi($searchId);
   ?>
</body>
</html>

as you can see, in search.php I include fetch.php and calls function fetchApi with argument $_GET["search"] , but I get this error when I search something.

Notice: Undefined property: stdClass::$target in C:\xampp\htdocs\spoonacular\fetch.php on line 16

I can't understand why php shows such error. I passed an argument, it's not empty, why php still runs algorithms inside if(empty($param1)){}? I tried if($param1==''){} also but it doesn't work too.

How to do if I want totally ignore everything inside if(empty($param1)) if function parameter is not empty string or NULL?

Nested If Else Question Not Working in Dataframe

I'm working with a coloumn in a dataframe of numeric data called "L_D" which has a range of values from 0.6-1.9. I'm trying to create a new column that categorizes the range in 3 ranges: "high" for L_D>1.4, "low" for L_D<0.9, or "medium".

#add L/D grouping to CompStrngth, <0.9=Low aspect ratio; >1.4=High Aspect Ratio, else = other raio
ifelse(CompStrngthData$L_D > 1.4, CompStrngthData$L_D_group <- "high",
   ifelse(CompStrngthData$L_D > 0.9, CompStrngthData$L_D_group <- "medium",
        CompStrngthData$L_D_group <- "low" )
)

When I run this code, it produces the desired result in the console. But when I open up the dataframe, it produces a column filled with "low".

Because of that I found the cut function and it works great with the desired results

CompStrngthData$L_D_group <- cut(CompStrngthData$L_D, breaks = c(-Inf,0.9,1.4,Inf), labels = c("low", "medium", "high"))

I'm sure it's a simple mistake I'm overlooking with the dataframe or ifelse function, just looking to understand my error.

Condition-statements aren't working,What's wrong with this php code?

With the help of this php function, users can create a blank page on my website.But it has some problems that I failed to solve. In brief they are,

  1. In this code,it shows three undifined index on page load & submit, they appear in php logs (on submit in page if showing error is on) :
if (isset($_POST['oke'])) {
    $plink = permalink();
    $plink2 = permalink('ya');
    $nama = preg_replace("/(\W)/",'-',strtolower(trim($_POST['nama'])));
    $link = $nama;
    $posisi = strip_tags($_POST['posisi']);
    $div=strip_tags($_POST['div']);
    $hak=strip_tags($_POST['hak']); 
    if (empty($link) or preg_match("/([0-9]+)|index|header|footer/",$link)) $error = 'Invalid name only a-z';
    if (array_key_exists($link,$plink2)) $error = 'Name already exists';

The error is


'php' log:
[29-Mar-2020 05:00:10 America/Detroit] PHP Notice:  Undefined index: nama in /storage/emulated/0/data_files/www/manage/phone/editpanel/page.php on line 11
[29-Mar-2020 05:00:10 America/Detroit] PHP Notice:  Undefined index: posisi in /storage/emulated/0/data_files/www/manage/phone/editpanel/page.php on line 13
[29-Mar-2020 05:00:10 America/Detroit] PHP Notice:  Undefined index: div in /storage/emulated/0/data_files/www/manage/phone/editpanel/page.php on line 14
[29-Mar-2020 05:00:10 America/Detroit] PHP Notice:  Undefined index: hak in /storage/emulated/0/data_files/www/manage/phone/editpanel/page.php on line 15

2.if a page with given name already exists then it should show warning that the page already exists, but any name you enter no matter they exist or not warning is showing!! What should I do?? I need your help to correct this code, And thanks in advance. Page.php

<?php
defined('NBER') or die ('Acess Error');
echo '<div id="right">';
menu_atas("Add Page");
if (isset($_POST['oke'])) {
    $plink = permalink();
    $plink2 = permalink('ya');
    $nama = preg_replace("/(\W)/",'-',strtolower(trim($_POST['nama'])));
    $link = $nama;
    $posisi = strip_tags($_POST['posisi']);
    $div=strip_tags($_POST['div']);
    $hak=strip_tags($_POST['hak']); 
    if (empty($link) or preg_match("/([0-9]+)|index|header|footer/",$link)) $error = 'Invalid name only a-z';
    if (array_key_exists($link,$plink2)) $error = 'Name already exists';
    if (!$error) {
    //get newfile//
    $data="data/$user_nama/page";
    $opendir=opendir($data);
    while(false !== ($file=readdir($opendir))) {
    if ($file == "." or $file == ".." or preg_match("/([a-z]+)/",str_replace('.php','',$file))) continue;
    $pfile []= str_replace('.php','',$file);
    }
    $lastfile= max($pfile);
    $nextfile=$lastfile + 1;
    $newfile=$nextfile.".php";
    //create a new page file//
    $open=fopen("$data/$newfile","w");
    fwrite($open,"");
    //write content to the page//
    $d = "data/$user_nama/alat/permalink.dat";
        $o1 = fopen($d,'r');
        $last_konten = fread($o1,filesize($d));
        $nl = $nextfile.'='.$link;
        $konten = trim($last_konten.','.$nl,',');
        $o2 = fopen($d,'w');
        $sukses = fwrite($o2,$konten);
    if ($sukses) header('location: ?act=pagelist');
    }
} 
$error = (@$error) ? '<div class="error">'.@$error.'</div>' : '';
echo '
'.@$error.'
<form action="" method="post">
Page name:<br/>
<input type ="text" name="example-page"/><br/>
<input type ="submit" name="oke" value="Add New Page"/><br/>
</form>
';
menu_bawah();
echo '</div>';
?>

NOTE: if I change input name="example-page" to link or nama any changes are not taking place!

Python3: If and else are running fine but when I add elif there is no output

I'm trying to run a simple if, elif and else statements. My code is:

def main():
    x, y = 100, 100


    if (x < y):
        st = "x is less than y"
    elif (x == y):
        st = "x is the same as y"
    else:
        st = "x is greater than y"

    print(st)

I started with just if and else, and I got "x is greater than y". Obviously, it's not correct so I added an elif statement to get "x is the same as y". However, when I run the above code, there is no output. It doesn't come up with error, just blank.

Can someone explain to me why is it so or what I am doing wrong?

the value is never used although it's used

I'm getting an error in my code that (the first in the main if and the main if else) value of tn in the if statement is never used, although the other assigned value with above it is okay, and other tn values are okay, and I used tn at the end as in a textview. so the application skips it and uses the next tn value..

String Classification = null;
            String tn = null;
            if (pi<0){
                pi=0;
            }
            if (p200<=50){
                if (p4<50) {
                    if (p200<5) {
                        if (cu>4 && cc<=3 && cc>=1){
                            Classification="GW";
                            tn = "Well graded gravels, Gravel-Sand mixtures, little or no fines";
                            //  ^^^ THIS ONE ^^^

                        }
                        else
                            Classification="GP";
                            tn = "Poorly graded gravels, Gravel-Sand mixtures, little or no fines";
                    }
                    if
                    (p200>12){
                        if ( (pi<y )|| pi<4){
                            Classification="GM";
                            tn ="Silty gravels, Poorly graded gravel-sand-silt mixtures";
                        }
                        if (pi>7 && pi>=y){
                            Classification="GC";
                            tn ="Clayey gravels, Poorly graded gravel-sand-clay mixtures";

                        }
                    }
                    if (p200>=5 && p200<=12) {
                        if (cu>4 && cc<=3 && cc>=1 && (pi<4 || pi<y )) {
                            Classification = "GW-GM";
                            tn="Well graded silty gravel";
                        }
                        else if (cu>4 && cc<=3 && cc>=1 && pi>7 &&pi>=y) {
                            Classification = "GW-GC";
                            tn="Well graded clayey gravel";
                        }
                        else if (pi<4 || pi<y){
                            Classification = "GP-GM";
                            tn="Poorly graded silty gravel";
                        }
                        else if (pi>7 && pi>=y){
                            Classification = "GP-GC";
                            tn="Poorly graded clayey gravel";
                        }
                    }
                }
                else if (p4>50){
                    if (p200<5){
                        if (cu>6 && cc>=1 && cc<=3){
                            Classification="SW";
                            tn="Well graded sands, gravelly sands, little or no fines";
                            //^^^ AND THIS ONE ^^^
                        }
                        else
                            Classification="SP";
                            tn ="Poorly graded sands, gravelly sands, little or no fines";
                    }
                    else if (p200>5){
                        if ((pi<y ) || pi<4){
                            Classification="SM";
                            tn="Silty sands, Poorly graded sand-silt mixtures";
                        }
                        else if (pi>7 && pi>y){
                            Classification="SC";
                            tn="Clayey Sands, Poorly graded sand-clay mixtures";
                        }
                    }
                    if (p200>=5 && p200<=12) {
                        if (cu>6 && cc<=3 && cc>=1 && (pi<4 || pi<y)) {
                            Classification = "SW-SM";
                        }
                        else if (cu>6 && cc<=3 && cc>=1 && pi>=7) {
                            Classification = "SW-SC";
                        }
                        else if (pi<4 ||pi<y ){
                            Classification = "SP-SM";
                        }
                        else if (pi>7 && pi>y){
                            Classification = "SP-SC";
                        }
                    }

                }

            }
            else if (p200>50){
                if (ll<50){
                    if (pi>7  && pi>y){
                        Classification="CL";
                        tn ="Inorganic clays of low to medium plasticity, gravelly clays, sandy clays, silty clays, lean clays";
                    }
                    else if(pi<4){
                        Classification="ML";
                        tn="Inorganic silts and very fine sands, rock flour, silty or clayey fine sands with slight plasticity";
                    }

                }
                else if (ll>50){
                    if (pi>y){
                        Classification="CH";
                        tn="Inorganic clays of high plasticity, fat clays";
                    }
                    else if (pi<y) {
                        Classification="MH";
                        tn="Inorganic silts, micaceous or dictomaceous fine sandy or silty soils, elastic silts";
                    }

                }
            }
            if (pi>=4 && pi<=7 && ll>16 &&ll<26 || (ll>26 && ll< 30 && pi>=y&& pi<=7)){
                Classification="CL-ML";
            }
            if (p4==0 && p200==0){
                Classification=" ";
                tn=" ";
            }


            if(p200>100 || p4>100 || pi>70) {
                if (p200 > 100)
                    editText1.setError("out of range");
                if (p4 > 100)
                    editText2.setError("out of range");
                if (pi >= 70)
                    editText5.setError("out of range");
            }
            else {
                    result.setText(String.valueOf(Classification));
                    typicalname.setText(String.valueOf(tn));
            }

Power Query / Power BI get look for data from another excel workbook

I am trying to combine worksheets from two different workbooks with Power Query and I have trouble doing that.

I do not want to merge the two workbooks.

I do not want to create relationships or "joints".

However, I want to get very specific information for one workbook which has only one column. The "ID" column.

The ID column has rows with letter tags : AB or BE. Following these letters, sepcific numeric ranges are associated. For both AB and BE, number ranges first from 0000 to 3000 and from 3000 to 6000.

I thus have the following possibilities: From AB0000 to AB3000 From AB3001 to AB6000 From BE0000 to BE3000 From BE3001 to AB6000

Each category match to the a specific item in my column geography, from the other workbook: From AB0000 to AB3000, it is ItalyZ From AB3001 to AB6000, it is ItalyB From BE0000 to BE3000, it is UKY From BE3001 to AB6000, it is UKM

I am thus trying to find the highest number associated to the first AB category, the second AB category, the first BE category, and the second.

I then want to "bring" this number in the other query and increment it each time that matching country is found in the other workbook. For example :

AB356 is the highest number in the first workbook.

Once the first "ItalyB" is found, the column besides writes "AB357". Once the second is "ItalyB" is found, the column besides write "AB358".

Here is the one columned worksheet: ![input

Here is the other worksheet with the various countries in geography: input

Here is an example of results: result

have one column (geography) with I think that this is something which I should work towards:

How to get last two observations from a dataset in SAS without using sort or First. and Last. or Do loop

Below code will solve for getting last 2 observations from the dataset without using loops, first & last dot concept or sorting.

data a;
set sashelp.cars nobs=_nobs_;/*create the temporary variable to store total no of obs*/
if _N_ ge _nobs_-1;/*Now compare the automatic variable _N_ to _nobs_*/
run;

Python - Pandas: IF statement based on column values

I am trying to develop an IF statement, which will - Run another python script, if there are values in [Column Name] which are equal to zero. - Else do nothing.

My original thought was to do something like

if df['column name'] == 0:

subprocess.call("python script.py", shall = True)

else:

print('No values of 0')

This gives me the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

If I try to specify any of these I am not really getting what I want.

To be specific I want the script to iterate over the values of a specific column and see if any of these values are = 0 and if they are I want to run another script which sends me an email warning.

Sorry if this has already been explained elsewhere but i cannot find it.

I am on Python 3.7.5 and using pandas.

Thank you for the help

Why does the function not work when the bar value is zero

function function1() {
document.getElementById("progress1");
progress1.value -= 25
}

function gameOver() {
if (document.getElementById("progress1").getAttribute("value") === 0) {
alert("GameOver")
}else {
}
}

gameOver();
<button onclick="function1()" id="button1">Click Me !</button>
<progress id="progress1" value="50" max="100"></progress>

I want to run the gameOver function when the bar value is 0 but it doesn't respond

Flutter set icon using if condition

i want to set the icon after an if condition , like if the condition is true i will set an icon else i will set another icon . my question is can i use it if statements in flutter widgets ? and if yes how can i use with the icon here , here is my code :


               if(this.iconName == 'green'){
                 Icon(Icons.verified_user, color: Colors.green),
               }else{
                 Icon(Icons.verified_user, color: Colors.blueAccent),
               }

Isolate an IF statement?

I would like to make sure that the "||" statement block is not applicable for this if statement :

if exist "%BackupDest%\%%~nI\%Desktop%\filename*.doc" (
ren "%BackupDest%\%%~nI\%Desktop%\filename*.doc" "newname*.doc"
)

Is there a way to isolate it from the rest of the code without having to interfere with the "||" statement block and without having to add a 2nd "||" statement block ?

I tried to add the if statement right after :

) || (
echo       Access refused ^(check permissions^)
)

But it executes the "||" statement block if any error occurs. Same thing if I remove the IF statement and leave the REN command only.

Here is the whole code :

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

set BackupDest=D:\backup

for /f "tokens=*" %%I in ('dir /a:d-h /b "%HomeDrive%\users\*" ^| findstr /x /i /l /v /g:"%~dp0exclude_users.txt"') do if exist "%BackupDest%\%%I\" (

    echo -----------------------------------------
    echo      Processing user : %%I
    echo -----------------------------------------
    echo

    :: checking write permissions
    copy /y nul "%BackupDest%\%%I\.writable" >nul 2>&1 &&
    (
        del "%BackupDest%\%%I\.writable"

        xcopy "%%I\Desktop" "%BackupDest%\%%I\Desktop\" /e /i /y
        xcopy "%%I\Documents" "%BackupDest%\%%I\Documents\" /e /i /y

        :: renaming some files
        if exist "%BackupDest%\%%~nI\%Desktop%\filename*.doc" (
            ren "%BackupDest%\%%~nI\%Desktop%\filename*.doc" "newname*.doc"
        )

    ) || (
        echo       Access refused ^(check permissions^)
    )
)

pause
exit

Any help would be very helpful.

Thanks.

How to write IF functions in Python when the condition requires the input to be a special character?

I'm trying to build a sample calculator in Python. It's expected output for calculate(2, 3, -) should be -1.

However, I have a hard time defining the operator.

if operator == +: will return a syntax error, but when I do if operator == '+': I need to write something like calcuate(3, 4, '+') to work.

Here are

def calculate(x, y, operator):
    if operator == '+':
        print (x + y)
    elif operator == '-':
        print (x - y)
    elif operator == '*':
        print (x * y)
    elif operator == '/':
        print (x / y)

Is it possible for me to get rid of the required apostrophes?

samedi 28 mars 2020

How can I print a string based on a boolean variable? JavaScript

I'm having trouble finding online how to use the variable I set as a boolean: var solved = false. As you can see I'm setting the boolean as false at first. But then, when I open the IF and ELSE IF, If the two conditions are met, the boolean becomes true: solved = true. What I want to know is how to use that new value of the boolean (true) to print a response with this setup:

if (solved) {
   console.log(suspect + " did it in the " + room + " with the " + weapon);
}

Or well if thats all wrong, then can you tell how to do it please!

CODE

var weapon = "";
var solved = false;

if ((room = "dining room") && (suspect = "Mr. Parkes")){
    weapon = "knife";
    solved = true;
} else if ((room = "gallery") && (suspect = "Ms. Van Cleve")) {
    weapon = "trophy";
    solved = true;
} else if ((room = "billiards room") && (suspect = "Mrs. Spark")) {
    weapon = "pool stick";
    solved = true;
} else if ((room = "ballroom") && (suspect = "Mr.Kalehoff")) {
    weapon = "poison"
    solved = true
} else {
    console.log("Wrong suspect or room");
}

if (solved) {
    console.log(suspect + " did it in the " + room + " with the " + weapon);
}

Add a condition to the if statement in my code?

is there a way to add at the end of the formula of mc_callAsia an else 0??

for j in range (1,10):
  for k in range (len(K)) :  
    mc_callAsia = np.asarray([(i-K[k]) for i in dictimoyennes["moyenneAsia" + str (j)] if (i-K[k])>0])
    payoffAsia = (1/(1+r[k])**T)*sum(mc_callAsia)/10000
    payoffsAsia = np.append(payoffsAsia, [payoffAsia])

The goal would be to keep all the values so either it's positive or 0. I've tried to do it like this

for j in range (1 ,10):
  for k in range (len(K)) : 
    for i in range (1, 10000):
        payoffss= max(dictimoyennes["moyenneAsia" + str (j)][i] - K[k],0) 
        payoffssAsia = np.append(payoffssAsia, [payoffss])

but it loops forever...

Thank you in advance

Logical Error while getting input from the user using String [duplicate]

I am required to write a Menu program that will display an error message and prompt user to enter the options again when user enter any value other than 0 to 6. It works for the first time when user enter "1" to calculate integers, but after that the calculation is done, the screens prints the output of the menu and user cannot enter any input at this time. Only allowed to enter input again for the third time.

Here are the output of the console:

Welcome to Programming Design and Implementation, Workshop 3

What would you like to do?

  1. Sum of 2 Integers
  2. Convert Temperature
  3. Convert a Character's case
  4. Print the ASCII equivalent of a Character
  5. Check if 2 Integers are Divisible
  6. Split Date into its components
  7. Exit

Please enter a value: 1 Please enter two integers 2 1 The sum of the two integers is: 3

Welcome to Programming Design and Implementation, Workshop 3

What would you like to do?

  1. Sum of 2 Integers
  2. Convert Temperature
  3. Convert a Character's case
  4. Print the ASCII equivalent of a Character
  5. Check if 2 Integers are Divisible
  6. Split Date into its components
  7. Exit

Please enter a value: Welcome to Programming Design and Implementation, Workshop 3

What would you like to do?

  1. Sum of 2 Integers
  2. Convert Temperature
  3. Convert a Character's case
  4. Print the ASCII equivalent of a Character
  5. Check if 2 Integers are Divisible
  6. Split Date into its components
  7. Exit

Please enter a value:

enter code here
String prompt = "Please enter a value: ";
String errorMsg1 = "Error: the value must be between <0> and <6>";
Scanner read = new Scanner(System.in);
String opt = "";
do // loop through the Menu until user enter zero to exit
    {
        System.out.println("Welcome to Programming Design and Implementation, Workshop 3");
        System.out.println();
        System.out.println("What would you like to do? ");
        System.out.println("> 1. Sum of 2 Integers ");
        System.out.println("> 2. Convert Temperature");
        System.out.println("> 3. Convert a Character's case");
        System.out.println("> 4. Print the ASCII equivalent of a Character");
        System.out.println("> 5. Check if 2 Integers are Divisible");
        System.out.println("> 6. Split Date into its components");
        System.out.println("> 7. Exit");
        System.out.println();
        System.out.print(prompt);
        opt = read.nextLine();

        if(opt.equals("1"))
            {
                int n1 = 0 , n2 = 0 , sum = 0;
                System.out.println("Please enter two integers");
                n1 = read.nextInt();
                n2 = read.nextInt();
                sum = n1 + n2;
                System.out.print("The sum of the two integers is: " + sum);
                System.out.println();
                System.out.println();
            } // take two integers and sum them up, after that output the answer

    } while(!opt.equals("7")); // stop the loop when option (opt) input by the user is 0
}

As seen from the console, the program will automatically print second menu screen without taking input from the user and jump straight to the third menu screen. Users are only allowed to input again in here

Forced to use switch statement to test for conditions

My professor gave us a seemingly straightforward homework assignment, but with one frustrating twist: we cannot use if/else if/else statements and we must use a switch statement instead. The homework problem is as follows:

Write a program that will read in the number of credit hours completed by a student at a university. Based on the number of credit hours completed, classify the student as a freshman, sophomore, junior, or senior (freshman: hours < 32, sophomore: 32 <= hours < 64, junior: 64<= hours < 96, senior: 96 <= hours). Don't use if/else if/else statements. You must use switch statements.

I know how to write this program using if statements but I have no idea how to write this with a switch statement. From what I've read, switch statements aren't supposed to be used in this way, yet here I am... Please do not answer telling me to use if statements, because I can't!

How could I define the seasons of the year in Python? [closed]

I have numeric values that refer to months of the year. ie january=1 february=2... How could I define a function that returns these month values to the season of the year? Is it some kind of 'if' function?

Thank you

please help me with the looping in order to compare in rows and columns

i have a google spreadsheet for attendance purpose. i want to make mark attendance for the Roll No taken as an input from the user(which is not an issue). the confusion is, how do i make a condition in the google's appscript where the attendance is marked by comparing the rollno by the entries in the rows and columns.

the sheet looks like this for eg.

the dates will be added in the coloumn by using this function(idk if it will work or not)

//CREATING NEW COLUMNS EVERYDAY AUTOMATICALLY

*function trig(){

var builder = ScriptApp.newTrigger("addcol").timeBased().everyDays(1);

var trigger = builder.create(); }

function addcol(){

var ss = SpreadsheetApp.getActiveSpreadsheet();

var sheet = ss.getSheetByName('ATTENDANCE'); var cname = builder.atDate(year, month, day)

var column = eventRange.getLastColumn() + 1;

sheet.insertColumnAfter(column).setName(cname);

sheet.getRange("E1").setValue(new Date()).setNumberFormat('d/M/yyyy');

var col = [];

for(var n=0 ; n

col.getLastColumn().push(['0']);

//the coloumns will automatically be filled by 0 and later overwritten by 1 if its marked

}

s.getRange('N:N').setValues(col);

}*

//===================================================

im taking input of the rollno. from user through android studio(and im getting the result here to gsheets for sure). but now for the prossessing part, what do i do in order to check the rollno. and mark the attendance in the coloumn?

S.S

Only the first if statement is returning (if / else if / else)

function getDrinkByProfession(param){
if (param = "Jabroni"){
return "Patron Tequila";
} else if (param = "School Counselor"){
return "Anything with Alcohol";
} else if (param = "Programmer"){
return "Hipster Craft Beer";
} else if (param = "Bike Gang Member"){
return "Moonshine";
} else if (param = "Politician"){
return "Your tax dollars";
} else if (param = "Rapper"){
return "Cristal";
} else {
return "Beer";
}
}

The input to this function (param) should return the suitable drink for each customer, with an else statement to cover any exceptions.

When this code is tested only the first if statement returns correctly and all other inputs to the function return "Patron tequila" (the first if statement's return value).

Long "if...continue" chains vs "if...else" chains in Javascript? [closed]

I couldn't find this question already on stack overflow (if it exists please point me in the right direction):

I have a long chain of if...continue statements that unfortunately don't transfer to a switch statement:

while (thing is true)
    if (condition 1) {
        ...do something; continue;
    }
    if (condition 2) {
        ...do something; continue;
    }
    ...
    if (condition 10) {
        ...do something; continue;
    }
}

Is there any difference (performance-wise or "good style"-wise) between this and making a long if-else chain?

while (thing is true)
    if (condition 1) {
        ...do something;
    }
    else if (condition 2) {
        ...do something;
    }
    ...
    else if (condition 10) {
        ...do something;
    }
}

Strange issue combining IF and CASE in TSQL query

Here is an issue that seems like it should be a simple solve but I have been working on it some time and cannot figure out why I cannot seem to combine CASE in one area of the query and IF in another.

Does anyone see what is going on here? I have an old data set that needs to be converted to work with new tables. The data is pulled from WDDX and put in a temp table. That's all working properly.

Here is where I am running into trouble. When it's simply CASE, everything works fine, but when I add IF to grab a value, it tells me:

"Incorrect syntax near the keyword 'IF'. Msg 156, Level 15, State 1, Procedure OldSysDataConv Incorrect syntax near the keyword 'THEN'.

Code is:

 SELECT VarName, 
 CASE 
   WHEN (CHARINDEX('XXXX', VarName) > 0 and SUBSTRING(VarName, CHARINDEX('XXXX', VarName), len(VarName)) like '%XXXX%') or SUBSTRING(VarName, CHARINDEX('ZZZZ', VarName), len(VarName)) like '%ZZZZ%' then

    left(replace(left(replace(VarName, 'XXXX', ''), len(VarName)-4), 'ZZZZ', ''), (len(VarName)-5))
else
    null
END as DetailName,
IF CHARINDEX('ZZZZ', VarName) > 0 THEN
    right(VarName, 1)
END
 as DetailValue,

How do you replace missing values with 0 for cases meeting specific conditions in R?

Background:

I am working with a large dataset that contains longitudinal data on gambling behavior of 195,318 participants. The data is based on complete tracking of electronic gambling behavior within a gambling operator. Gambling behavior data is aggregated on a monthly level, a total of 70 months. I have an ID variable seperating participants, a time variable (months), as well as numerous gambling behavior variables such as active days played for given month, bets placed for given month, total losses for given month, etc. Participants vary in when they've been active gambling. One participant may have gambled at month 2, 3, 4, and 7, another participant at 3, 5, and 7, and a third at 23, 24, 48, 65 etc. As such, there are considerable amounts of "missing values". However, because every instance of gambling is tracked, missing in this data set means that the person did not gamble. In other words, missing equals 0.

Problem/goal:

I want to impute 0 for missing values ("NA"). However I only want to do so under specific circumstances. Specifically I want to impute 0 for missing values within what I define as a participant's "active period" and leave everything else as is.

A participant's active period is every month between their first active month gambling and their last month gambling. For example, for a participant that gambled at month 2, 3, 4, and 7 I want to impute 0 at month 5 and 6. Every other month, i.e. 1 and 9 to 70, I want to stay as NA. I am struggling to write code that achieves this. I'm new to R.

Example data frame and code

Below is example code that produces a data frame that illustrates key characteristics described in my problem. In this code there's only 2 participants, 1 gambling behavior variable and 10 time points ("waves"). I've included a data frame in "long format" and "wide format" because I'm unsure which one would would be most helpful/informative. A time variable is included in the "long format". My actual data set is in long format, but I am familiar with how to switch between the two.

# Example variables and data frame in long form
  # Includes id variable, time variable and example variable
id <- c(1, 1, 1, 1, 2, 2, 2)
time <- c(2, 3, 4, 7, 3, 5, 7)
daysPlayed <- c(2, 2, 3, 3, 2, 2, 2)
dfLong <- data.frame(id = id, time = time, daysPlayed = daysPlayed)

Created on 2020-03-28 by the reprex package (v0.3.0)

# Example variables and data frame in wide form
  # Includes id variable, days played in given month 
id <- c(1, 2)
daysPlayed.1 <- c(NA, NA)
daysPlayed.2 <- c(2, NA)
daysPlayed.3 <- c(2, 2)
daysPlayed.4 <- c(3, NA)
daysPlayed.5 <- c(NA, 2)
daysPlayed.6 <- c(NA, NA)
daysPlayed.7 <- c(3, 2)
daysPlayed.8 <- c(NA, NA)
daysPlayed.9 <- c(NA, NA)
daysPlayed.10 <- c(NA, NA)
dfWide <- data.frame(id=id, daysPlayed.1 = daysPlayed.1, daysPlayed.2 = daysPlayed.2,
                 daysPlayed.3 = daysPlayed.3, daysPlayed.4 = daysPlayed.4,
                 daysPlayed.5 = daysPlayed.5, daysPlayed.6 = daysPlayed.6,
                 daysPlayed.7 = daysPlayed.7, daysPlayed.8 = daysPlayed.8,
                 daysPlayed.9 = daysPlayed.9, daysPlayed.10 = daysPlayed.10)

Created on 2020-03-28 by the reprex package (v0.3.0)

SCSS: Check if the element has the attribute

I need to check if the element has an attribute for the styles to apply on mobile devices(or in responsive mode). For example:

<tr>
    <td>Some text here</td>
    <td data-content="Hello there">Other text here</td>
    <td data-content="Hi there">Final text here</td>
</tr>

Browser:

------------------------------------------------------
| Some text here | Other text here | Final text here |
------------------------------------------------------

Mobile devices (Required output):

--------------------------------
| Some text here               |
| Hello there: Other text here | 
| Hi there: Final text here    |
--------------------------------

SCSS:

tr {
    td {
        @if (&[data-content]) {
            &:before {
                content: attr(data-content) ":";
            }

            float: left;
            font-size: 12px;
            font-weight: bold;
            margin: 0 5px 0 0;
            text-transform: uppercase;
        }
    }
}

Mobile devices (Current output):

--------------------------------
| : Some text here             |
| Hello there: Other text here | 
| Hi there: Final text here    |
--------------------------------

Please tell me the mechanism of this code [closed]

function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }
var element = multiply([1,5,5,5,5,], 3);
console.log(element); //output: 1*5*5 = 25;

How this multiplication occurs? Please tell me the details. Thank you.

How can I find how many conditions that I would expect from search box with filtering options

I am trying to implement a search box with a number of filtering option I would like to count how many possible conditions that I would have. for example I have two search boxes with options to search by title or search by location or search by both and also I have two options display results based on the last 24 hour posted results or within 3 days. Some of the conditions for instance could be that search location is empty where the rest is not and another example would be that the option 24 hours is on where the rest is not. the attempted solution for this is as below but what I am looking for is the accurate way of counting all of these conditions.

 public ActionResult SearchResult(int? page, string searchTitle = "" , string searchLocation = "", string last24="",string last3Days="")
        {      
            setUpApi(searchTitle, searchLocation);
            var result = new List<AllJobModel>();
            DateTime now = DateTime.Now;
            var time = now.AddHours(-24).ToString("dd/MM/yyyy").ToString();
            var time2 = now.AddHours(-48).ToString("dd/MM/yyyy").ToString();
            var time3 = now.AddHours(-72).ToString("dd/MM/yyyy").ToString();
            var timesNow = now.ToString("dd/MM/yyyy").ToString();
            if ((!string.IsNullOrEmpty(searchTitle) || !string.IsNullOrEmpty(searchLocation)) && (!string.IsNullOrEmpty(last24) || !string.IsNullOrEmpty(last3Days)))
            {
                setUpApi(searchTitle, searchLocation);
                if(!string.IsNullOrEmpty(last24))
                {
                    time = now.AddHours(-24).ToString("dd/MM/yyyy").ToString();
                    result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation) && a.PostedDate == timesNow ||
                    a.PostedDate.Equals(time)).ToList();
                }
                else if(!string.IsNullOrEmpty(last3Days))
                {
                  time2 = now.AddHours(-48).ToString("dd/MM/yyyy").ToString();
               result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation) && a.PostedDate == timesNow ||
              a.PostedDate.Equals(time3) || a.PostedDate == time2 || a.PostedDate == time).ToList();
                }

            }else if(!string.IsNullOrEmpty(searchTitle) || !string.IsNullOrEmpty(searchLocation) && (string.IsNullOrEmpty(last24) && string.IsNullOrWhiteSpace(last3Days)))
            {
                result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation)).ToList();
            }
            else if ((string.IsNullOrEmpty(searchTitle) || string.IsNullOrEmpty(searchLocation)) && (!string.IsNullOrEmpty(last24) || !string.IsNullOrEmpty(last3Days)))
            {
                if(!string.IsNullOrEmpty(last24) && !string.IsNullOrEmpty(searchTitle))
                {
                    result = db.AllJobModel.Where(a => a.PostedDate.Equals(time) && a.JobTitle == searchTitle).ToList();
                }else if(!string.IsNullOrEmpty(last24) && !string.IsNullOrEmpty(searchLocation))
                {
                    result = db.AllJobModel.Where(a => a.PostedDate.Equals(time) && a.locationName == searchLocation).ToList();
                }
                else if(!string.IsNullOrEmpty(last3Days) && !string.IsNullOrEmpty(searchTitle))
                {
                    result = db.AllJobModel.Where(a => a.JobTitle == searchTitle && a.PostedDate.Equals(time) || a.PostedDate == time2 || a.PostedDate == time3 || a.PostedDate == timesNow).ToList();
                }else if(!string.IsNullOrEmpty(last3Days) && !string.IsNullOrEmpty(searchLocation))
                {
                    result = db.AllJobModel.Where(a => a.locationName == searchLocation && a.PostedDate.Equals(time) || a.PostedDate == time2 || a.PostedDate == time3 || a.PostedDate == timesNow).ToList();
                }else if(!string.IsNullOrEmpty(last3Days))
                {
                    result = db.AllJobModel.Where(a => a.PostedDate.Equals(time) || a.PostedDate == time2 || a.PostedDate == time3 || a.PostedDate == timesNow).ToList();
                }else if(!string.IsNullOrEmpty(last24))
                {
                    result = db.AllJobModel.Where(a => a.PostedDate == time).ToList();
                }
            }
            else
            {
                result = (from app in db.AllJobModel select app).ToList();
            }
            return View(result.ToList().ToPagedList(page ?? 1, 5));
        }

How to Create Two Columns from One Column in SQL with an IF Statement

I have a table that has 3 columns. Value, condition and day. I would like to SELECT two columns from column Value. One which is average value of t.value grouped by t.condition 1 and another one which is an average value of t.value grouped by t.condition 2. I would then like to group them all by day and condition.

Table

Result should look like this table.

expected result

I have tried case when, if and CTEs. However, they all failed. The if statement work for fulfilling one condition but seeing that condition is binary, the if function i tried did not work. I have considered creating two tables and then joining on day. That would work I would assume. Would there be an easier way of doing this?

Thank you!

Apply more that two conditions to pandas series with lambda and dict

I want to add new categorical features based on some conditions.

If we have only two conditions, let's say we want to check if variable is positive or not we can simply:

df.my_var.apply(lambda x: 'positive' if x>0 else 'negative')

How we can profit Python dict syntax when we have more that two cases, something like:

df.my_var.apply(lambda x: {x<0: 'negative, 0<x<1e+10: 'good', 1e+10<x: 'too_much'}.get(x))

Counting valleys from a sequence of steps where each step is either 'U' or 'D'. What is the time complexity of this solution?

Given a sequence of up and down steps. Find and return the number of valleys in the given sequence. The sequence always starts and ends at the sea level, and each step up or down represent one unit change in altitude.

  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Example: If the path is 'DDUUUUDD', first we enter a valley two units deep.Then we climb onto a mountain two units high.Finally we return to the sea level. Therefore we return one.

Question: Is the time complexity of the given solution O(n / 2) or O(n), and how does an if statement change the complexity of an algorithm ?

Solution:

def countingValleys(n, s):

altitude = 0
prev_a = 0
v_count = 0

for i in range(1, n, 2):
    if s[i] == s[i-1]:
        if s[i] == 'D':
            altitude -= 2
            prev_a = altitude + 1
        else:
            altitude += 2
            prev_a = altitude - 1
    else:
        if s[i] == 'D':
            prev_a = altitude + 1
        else:
            prev_a = altitude - 1

    if altitude == 0 and prev_a == -1:
        v_count += 1

return v_count