samedi 31 octobre 2020

no response to if statement

Im trying to check if a username is in a csv file, the "if string in line:" works as intended, but "if string not in line:" Dosent do anything when it should. Could anyone help me? Here is the code:

''' while True: import csv with open("IDs.csv") as file: reader = csv.reader(file) q = int(input("1) Create a new User ID \n2) Change a password \n3) Display all current User IDs \n4) Quit \n\nEnter Selection:")) if q == 1: while True: newID = input("Enter a new User ID:") for line in file: if newID in line: print ("That userID is already in use, please select another one") print (newID) for line in file: if newID not in line: userpass = input("Enter a password") '''

Hi a need to Create query to select most expensive PC without CD drive for makers who manufacture only PCs

i tried this query but the result its not what i need, i was thinking maybe with the if statement anyone can help me?

SELECT MAX(Price), COUNT(DISTINCT CD)
FROM PC
WHERE type = 'PC'
GROUP BY maker
HAVING COUNT(DISTINCT model)

So this are my tables

                                                        *PC*
SERIAL_NUMBER   MODEL   PRICE   SPEED   RAM HD  CD
1234221         d1      500     600    2048 600 hitachi

                                        
                                                       *Laptop*
SERIAL_NUMBER   MODEL   PRICE   SPEED   RAM HD  SCREEN
1234211         s-1     500     600    2048 600 15.6
1234212         s-2     600     600    4096 600 15.6
                                                       *Product*
MODEL   MAKER   TYPE
s-1  Hitachi     laptop
s-2  Hitachi     laptop
d1   Dell        pc
d2   Dell        pc
                                       *Storage*
STORAGE_ID  MODEL   SERIAL_NUMBER   TRANSFERED_TO
50          s-1      1234211           51

select a row with and excepcion

Hi i need to Create query to select most expensive PC without CD drive for makers who manufacture only PCs my tables are

+-----------------------------------------------------+
         PC

+-----------------------------------------------------+ SERIAL_NUMBER MODEL PRICE SPEED RAM HD CD 1234221 d1 500 600 2048 600 hitachi 1234222 d2 600 600 4096 600 - +---------------------------------------------------+ Laptop +---------------------------------------------------+ SERIAL_NUMBER MODEL PRICE SPEED RAM HD SCREEN 1234211 s-1 500 600 2048 600 15.6 1234212 s-2 600 600 4096 600 15.6 +---------------------------------------------------+ Product +---------------------------------------------------+ MODEL MAKER TYPE s-1 Hitachi laptop s-2 Hitachi laptop s-3 Hitachi laptop d1 Dell pc d2 Dell pc d3 Dell pc +---------------------------------------------------+ Storage +---------------------------------------------------+ STORAGE_ID MODEL SERIAL_NUMBER TRANSFERED_TO 50 s-1 1234211 51 50 s-2 1234212 51

C# Console Application that Outputs a category based on input

I have a task to develop a windows application that collects employee information: Name and Number of items sold as input and outputs a summary of information in a way that groups the employee based on the number of items sold (below 50 items, 50-99 items, 100-199 items and a level above 199 items) See below. Can you help me with this code fam

enter image description here

How do you use an IF/THEN statement to do a VLookUp statement down a range taking into account the error code?

I am trying to do a VLookUp through an IF/THEN statement.

My Excel formula would be:

    =If(F2=G2,Today(),Vlookup(A2,[Range],15,FALSE))

When that would give me an "n/a" error, I would the use the following formula:

    =IF(VALUE(LEFT(C2,1))>8,N2+28,N2+14))"

I am trying to combine these in a macro and cannot get the syntax worked out.

Here is what I am 'trying' so far:

    For RowNumber = Range("M" & Rows.Count).End(xlUp).Row To 2 Step -1
    With WS2
        If Range("F" & RowNumber).Value = Range("G" & RowNumber).Value Then Range("O" & RowNumber) = (Now) Else Range("O" & RowNumber) = MyStringVar1 = Application.WorksheetFunction.VLookup(Range("A" & RowNumber), WS4.Range("A2:V5000").Value, 15, False)"
        On Error GoTo 0
        If MyStringVar1 = "" Then Range("O" & RowNumber).Value = Range("O" & RowNumber).Value = "=IF(VALUE(LEFT(Range("C" & RowNumber).Value,1))>8,Range("N" & RowNumber).Value+28,Range("N" & RowNumber).Value+14))" Else Range("O" & RowNumber).Value = MyStringVar1
    End With
    Next RowNumber

How can I add Codeigniter datatable action button based on the database status?

I want to show action button based on my database status result value.

If the database status value is 1 then datatable action button should be lock icon.

Else if the database status value is 0, then datatable action button should be unlock icon.

kotlin - Problem with my if statement and operator

This is my goal : user click on minus button the amount decrease by one and there is a if statement to not allow the amount go lower than 0 .

This is my Code :

   var number = 0
        view.text_amount.visibility = View.GONE

        view.plus_btn.setOnClickListener {

            if (number == 5) {
                Toast.makeText(
                    requireContext(),
                    "Limit in order",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                view.text_amount.visibility = View.VISIBLE
                number++
                view.text_amount.text = number.toString()
            }
        }
        view.minus_btn.setOnClickListener {
            if (number <= 0) {
                view.text_amount.visibility = View.GONE
            } else {
                number--
                view.text_amount.text = number.toString()

            }

        }

there is problem with code : I don't want the amount be visible after getting to 0 . it's better experience when the amount is equal to 0 not be visible .

I think it has a simple solution but I can't see it . do you have any idea ?

if statement only affects the last image, how can it affect all?

I'm new to Javascript and our teacher wants us to use Javascript only, so even links etc. have to be created in there.

I made a link with the id 'mine':

  var linkMyCDS = document.createElement("a");
  linkMyCDS.className = "link";
  linkMyCDS.id = "mine";
  linkMyCDS.innerText = "my cds";
  headerContainer.append(linkMyCDS);

and I have a dataset where 'oneAlbum' represents each cd in the dataset. There is a part where I ask for each cd if it's 'in my posession' -> true or false.

Now I want to change the opacity of the images that are 'not in my posession' to 0.5. The problem is that it only changes the opacity of the last album in my array of albums.

  window.onclick = function(event){
    if(!event.target.matches('mine')){
      if(oneAlbum.in_my_possesion === false){
        albumCover.style.opacity = 0.5;
      }
    }
  }
}

I tried putting it in a for loop before, but it didn't change the outcome. I struggle a lot with for loops though.

Python matching partial strings in list elements between two lists

In my code I am trying to match the item from 'match' to the the strings in the 'data' list.

I want the code to look at the first word in 'match' list and if it matches with a string in the data 'list' then that will be added to another list. A second check I want to do is if the first 2 words in 'match' list match with the strings in data.

Currently my output is giving me only one instance of water12 - whereas both shoud have been picked up.

Please could someone let me know where I might be going wrong?


match =['f helo','happy hellp','floral', 'alpha','12133','water12 puppies']
data=['f we are', 'hello there', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

lst=[]
for i in match:
    for j in data:
        if i.split()[0] in j:
            lst.append(j)
            data.remove(j)
            break
        if len(i) > 1:
            k= ' '.join(i.split()[:2])
            if k in j:
                lst.append(j) 
                data.remove(j)
                break
                
    else:
        lst.append(i + ' - not found')

print(lst)

Desired output:

output= [ 'f we are', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

Segmentation fault adding condition to if statement

I'am writing a program that performs the knight's tour. For now it does just the first move.

If I run it I can see the first move performed, however since the move is of one row and one column it's not an allowed move for knights in chess. To fix that I need to add the condition j != i into this if statement:

for( i = 1; i < 3; ++i ) {
    for( j = 1; j < 3; ++j ) { 
        if( r + i < 8 && c + i < 8 ) {
            ...
        }
    }
}

So that it becomes:

if( j != i && r + i < 8 && c + i < 8 )

But if I run the "fixed" program, the compiler gives me a segmentation fault for the line of the modified if. Any idea of what does it mean?

EDIT: I am posting the full program. When the program moves the knight, it sets the destination board[row][column] to 0 (zero)

For now I just tried starting from the top left corner. I know that the starting point is not set to zero and I noticed that the double for with the guilty if should start for both i and j = -2. Also there are repeated actions that I could wrap into a new function. However I am not here to fix these stuff. I just want to get rid of the segmentation fault.

Ps: in case it's relevant, I am writing and running the code into an app on my phone

#include <stdio.h>
#include <stdlib.h>

int board[8][8];

void euBoard( void );
void move( int r, int c );
int checkThat( int r, int c);
void printBoard( void );

int main() {



euBoard();

printBoard();

puts("");

move( 0, 0 );

printBoard();



return 0;
} // end main

void euBoard( void )
{
int i, j;

for( i = 0; i < 8; ++i ) {
    for( j = 0; j < 8; ++j ) { 
        if( i < 4 && j < 4 ) {
            board[i][j] = i + j + 2;
        }
        else if( i < 4 && j >= 4 ) {
            board[i][j] = i + 7 - j +2;
        }
        else if( i >= 4 && j < 4 ) {
            board[i][j] = 7 - i + j + 2;
        }
        else if( i >= 4 && j >= 4 ) {
            board[i][j] = 14 - i - j + 2;
        }
    }
}
} // end euBoard

void move( int r, int c )
{
int i, j;
int best = 9;
int possible[8][3];
int possCount = 0;
int bestPo[8];
int bestCount = 0;
int ct[8];
int ctCount = 0;
int ctBest = 9;
int ctBestCount = 0;
int ctBests[8];
int lucky;

for( i = 1; i < 3; ++i ) {
    for( j = 1; j < 3; ++j ) { 
        if( r + i < 8 && c + i < 8 ) {
            if( board[r+i][c+j] <= best ) {
                best = board[r+i][c+j];
                possible[possCount][0] = r + i;
                possible[possCount][1] = c + j;
                possible[possCount][2] = board[r+i][c+j];
                ++possCount;
            }
        } // end outer if
    }
}

for( i = 0; i <= possCount; ++i ) {
    if( possible[i][2] == best ) {
        bestPo[bestCount] = i;
        ++bestCount;
    }
}
if( bestCount == 1 ) {
    board[possible[bestPo[0]][0]][possible[bestPo[0]][1]] = 0;
}
else {
    for( i = 0; i <= bestCount; ++i ) {
        ct[ctCount] = checkThat( possible[bestPo[i]][0], possible[bestPo[i]][1] );
        if( ct[ctCount] < ctBest ) {
            ctBest = ct[ctCount];
        }
        ++ctCount;
    }
    for( i = 0; i <= ctCount; ++i ) {
        if( ct[i] == ctBest ) {
            ctBests[ctBestCount] = i;
            ++ctBestCount;
        }
    }
    if( ctBestCount == 1 ) {
        board[possible[bestPo[0]][0]][possible[bestPo[0]][1]] = 0;
    }
    else {
        lucky = rand() % ctCount;
        board[possible[lucky][0]][possible[lucky][1]] = 0;
    }
} // end outer else
} // end move

int checkThat( int r, int c)
{
int i, j;
int best = 9;
int possible[8][3];
int possCount = 0;
int bestPo[8];
int bestCount = 0;
int lucky;

for( i = 1; i < 3; ++i ) {
    for( j = 1; j < 3; ++j ) { 
        if( r + i < 8 && c + i < 8 ) {
            if( board[r+i][c+j] <= best ) {
                best = board[r+i][c+j];
                possible[possCount][0] = r + 1;
                possible[possCount][1] = c + j;
                possible[possCount][2] = board[r+i][c+j];
                ++possCount;
            }
        } // end outer if
    }
}

for( i = 0; i <= possCount; ++i ) {
    if( possible[i][2] == best ) {
        bestPo[bestCount] = i;
        ++bestCount;
    }
}
if( bestCount == 1 ) {
    return possible[bestPo[0]][2];
}
else {
    lucky = rand() % bestCount;
    return possible[bestPo[lucky]][2];
}
} // end checkThat

void printBoard( void )
{
int i, j;

for( i = 0; i < 8; ++i ) {
    for( j = 0; j < 8; ++j ) { 
        printf("%d ", board[i][j] );
    }
    puts("");
}
}

Noobie* calculate checksum of 4 digit Number

hey im pretty new to Python. I want to write a little Programm to calculate the Checksum of an 4-Digit Number with an Input() But If u type an 5 or higher digit number there should be an print('error') message. I dont know how to tell the programm to only allow 4 digit number inputs.

Python to C# code .How could be converted

I am trying to convert piece of Python code into C# but unfortunately I am stuck on a certain peace . How can I convert this part from Python code into C# code

if not (town in ("Bansko", "Borovets") and option in ("noEquipment", "withEquipment",)) and not (
        town in ("Varna", "Burgas") and option in ("noBreakfast", "withBreakfast")):
    print(f'Invalid input!')

How to get value from select in trigger mysql and use it for condition of IF

DELIMITER $$
CREATE TRIGGER cek
AFTER INSERT ON lapor_karya
FOR EACH ROW
BEGIN
SET @var = (SELECT COUNT(lapor_karya.ID_Lapor) FROM lapor_karya GROUP BY NEW.ID_Karya);
IF(@var > 10)
THEN
DELETE * FROM karya_pelajar WHERE ID_Karya=NEW.ID_Karya;
END IF;
END $$
DELIMITER ;

error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM karya_pelajar WHERE ID_Karya=NEW.ID_Karya;
END IF;
END' at line 9

I want to get value from lapor_karya table, and use this value for condition IF. If my value more than 10, then will execute query delete. But it's doesn't working

cant increment a variable inside if-statement properly. C++

for(int x=i; x<=j; x++) {
    int reverse = rev(x);
    
    if ((x - reverse)%k == 0)
    {
        days++;
    }  
}

If I include any print statement inside the loop i get the desired output otherwiese it it wrong. I don't want to include print statement.

Google Sheet - Delete rows if cells contain NO VALUES

I have an array A15:G63, what I would like to do is create a button called 'Clear'

The purpose of the button is:

  • Between A15:G63, if a cell has no values (usually the value input is a string) I would like to delete that row. It could be multiple rows.

For example: I enter the word 'HI' in A15:G55, nothing in A56:G59, and the word 'HELLO' in A60:G63. I would like to delete rows 56-59.

How do I do that?

Thanks all.

Convert Python code into C# . How can I do this

How can I transform this code java if not (town in ("Bansko", "Borovets") and option in ("noEquipment", "withEquipment",)) and not ( town in ("Varna", "Burgas") and option in ("noBreakfast", "withBreakfast")): print(f'Invalid input!') into c# code

MySQL pivot row into columns with in columns(using concat)

I have one MySQL tables:(how to use concat with in if(condition)) table :

CREATE TABLE `brute20` (
  `record_id` int(10) UNSIGNED NOT NULL,
  `mesure_id` int(10) UNSIGNED NOT NULL,
  `J_DATE` date NOT NULL,
  `J_TIME` time NOT NULL,
  `Value` varchar(10) NOT NULL,
   `qulity_code` char(1) NOT NULL,
   `added_date_time` datetime NOT NULL,
  `updated_last_column` datetime NOT NULL
);

I would like to get a table in the rows and columns as mesure_id. So far I was unable to get an output

Using this query:

set @var = null;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      **'sum(IF(mesure_id =', mesure_id,' , concat(Value,qulity_code), null)) as ','`',mesure_id,'`'**
    )
  ) INTO @var
 FROM brute20  where mesure_id IN ('1201','1203','1202');

-- select @var;


SET @var = CONCAT(' select J_DATE, J_TIME,  ',  @var, 
  ' FROM
  brute20  group by J_TIME ');
  
  -- select @var;
  
  PREPARE stmt FROM @var;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

but I would like to have instead something like:

enter image description here

The problem is that I cannot show correct value in mesure_id

Manipulating links in python [closed]

I am trying here to retrieve a list of urls in python.

I want to set an example of a url that should be retrieved.

Here is the code example:

if url != 'https://' + '  ' +'.example.com/':
       continue

If i want to include a prefix that consists of two letters in the blank space between the single quotes and if the retrieved url is not same as that example then ignore it.

Any help would be much appreciated!

Java if else in while loop

i had this problem where while looping, the output shows the loop but the invalid is also there. how do i separate the loop and the if...else statements?

below is the program code.

Scanner scan = new Scanner(System.in);
String option = new String("Y");

while (option.equalsIgnoreCase("Y")) {
    System.out.println("Good Morning!!");
    System.out.print("Do you want to continue [Y/N]: ");
    option = scan.nextLine();

    if (option.equalsIgnoreCase("N")) {
        break;

    } else {

        System.out.println("invalid");
    }
}

this is the output of the loop. the invalid is only supposed to show up when i put in a different letter other than y or n

Do you want to continue [Y/N]: y
invalid
Good Morning!!
Do you want to continue [Y/N]: y
invalid
Good Morning!!

and it was supposed to show like this

Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: n

vendredi 30 octobre 2020

R dplyr conditional mutate with group_by

I have a grouped data.frame and want to mutate a column conditionally checking all() of the certain column.

In this example, I have a simple data.frame with 3 columns; I am grouping by the column code and if the column B of that group is entirely of NA, I want to copy the values from column A and otherwise keep the original non NA values of B.

Input:

> example <- tibble::tribble(
  ~code, ~A, ~B,
  "1", 0.5, 0.7,
  "1", 0.5, 0.3,
  "1", 0.5, 0.25,
  "2", 0.2, NA,
  "2", 0.8, NA,
  "2", 0.5, NA
)
> example %>% dplyr::group_by(code)
# A tibble: 6 x 3
# Groups:   code [2]
  code      A     B
  <chr> <dbl> <dbl>
1 1       0.5  0.7 
2 1       0.5  0.3 
3 1       0.5  0.25
4 2       0.2 NA   
5 2       0.8 NA   
6 2       0.5 NA   

Desired output:

# A tibble: 6 x 3
  code      A     B
  <chr> <dbl> <dbl>
1 1       0.5  0.7 
2 1       0.5  0.3 
3 1       0.5  0.25
4 2       0.2  0.2 
5 2       0.8  0.8 
6 2       0.5  0.5 

I've tried using ifelse() and it can check the all(is.na(B)) but it doesn't attribute rowwise as standard behavior and just copy from the first value.

example %>% 
  dplyr::group_by(code) %>%
  dplyr::mutate(
    B = ifelse(all(is.na(B)), A, B)
  )
# A tibble: 6 x 3
# Groups:   code [2]
  code      A     B
  <chr> <dbl> <dbl>
1 1       0.5   0.7
2 1       0.5   0.7
3 1       0.5   0.7
4 2       0.2   0.2
5 2       0.8   0.2
6 2       0.5   0.2

attribuing fixed values is ok.

example %>% 
  dplyr::group_by(code) %>%
  dplyr::mutate(
    isBna = ifelse(all(is.na(B)), 'y', 'n')
  )
# A tibble: 6 x 4
# Groups:   code [2]
  code      A     B isBna
  <chr> <dbl> <dbl> <chr>
1 1       0.5  0.7  n    
2 1       0.5  0.3  n    
3 1       0.5  0.25 n    
4 2       0.2 NA    y    
5 2       0.8 NA    y    
6 2       0.5 NA    y      

and with the dplyr::if_else() it throws an error complaning that A and B is not fixed value.

example %>% 
  dplyr::group_by(code) %>%
  dplyr::mutate(
    B = if_else(all(is.na(B)), A, B)
  )
Error: Problem with `mutate()` input `B`.
x `true` must be length 1 (length of `condition`), not 3.
ℹ Input `B` is `if_else(all(is.na(B)), A, B)`.
ℹ The error occurred in group 1: code = "1".
Run `rlang::last_error()` to see where the error occurred.     

and my real case error is little different.

# sometime like this
Error: Problem with `mutate()` input `xx`.
x `false` must be a logical vector, not a double vector.

# and sometimes like this
Error: Problem with `mutate()` input `xx`.
x `false` must be length 1 (length of `condition`), not 12.

Is there any way to achieve my goal within chains of pipe%>%?
Thanks in advance.

Why R only excute my last if statement in for loop

I am new to R and I am trying to do for loop in R with if/else if statment The score data looks like this[Score data]Score data2

I want to create a new variable called Student2_Score where if only 1 score is missing than the Student2_Score = 0.5average of assignment1,2,3 +0.5average of assignment and the missing score is ignored and if more than 1 score is missing than the Student2_Score = NA

  Score$NA_count <- apply(Score, 1, function(x) sum(is.na(x[2:6])))
for (i in nrow(Score)) {
  if(Score$NA_count[i] > 1){Score$Student2_Score<-"NA"}
  else if (Score$NA_count[i] == 1 && is.na(Score$"1c"[i]) == T)
          {Score$Student2_Score<-((Score$"2c"+Score$"3c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if (Score$NA_count[i] == 1 && is.na(Score$"2c"[i]) == T)
    {Score$Student2_Score<-((Score$"1c"+Score$"3c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if (Score$NA_count[i] == 1 && is.na(Score$"3c"[i])== T)
    {Score$Student2_Score<-((Score$"1c"+Score$"2c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if  (Score$NA_count[i] == 0) 
    {Score$Student2_Score<-((Score$"2c"+Score$"1c"+Score$"3c")/3)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
}

But the Student2_Score I got for only 1 missing score is still NA, since like R only excute the last else if statement. I would appreciate any idea and help! Thanks:)

Combine IF with AND/OR python

Im trying to filter out some "words/characters" out of an python string. Here is my code:


if "MV" not in (str)network_name:
                        if "MOB" not in network_name:
                            if "MG" not in network_name:
                                if "RO" not in network_name:
                                    if "RQ" not in network_name:
                                        if "RM" not in network_name:
                                            if "RT" not in network_name:
                                                if "RC" not in network_name:
                                                    if "RW" not in network_name:
                                                        if "RU" not in network_name:
                                                            if "RA" not in network_name:
                                                                if "RH" not in network_name:
                                                                    print ('OK')

Is there an way to make an oneliner with all of the filters? Thanks in advance!

No value variation in returned column when using for loops and ifelse statements)

I have written a function (pre_post_comparision) that takes a set of columns containing survey responses, and uses a for loop and a series of ifelse statements to conditionally increment a score on a variable called bonus_points.

The objective of the function is to return the bonus_points column containing a user's score. bonus_points should range between 0 and 3.

When running the function using the full dataset, the returned score has no variation, with a score of 2 for each user. When running the function one row at a same, I am able to achieve variation in the bonus_points variable (i.e. bonus_points range between 0, 1, 2, 3).

What changes should I make to the function so that I am returning the correct bonus_points score?

To help, below is an example of my code and dataset.

Thanks in advance!

The pre_post_comparison function

SEA_VALUE_LUT <- function(df){
  for (i in 1:length(df)){
    df[,i][df[i] == 4] <- 5
    df[,i][df[i] == 3] <- 4
    df[,i][df[i] == 2] <- 3
    df[,i][df[i] == 0] <- 0
  }
  return(df)
}

pre_post_comparison <- function(df, cap){  
  df$bonus_points <- 0
  for(i in seq(from=1, to=length(df)-2, by = 2)){
    x <- as.data.frame(df[,i])
    y <- as.data.frame(df[,i+1])
    is_strength <- TRUE
    pairs_df <- cbind(x, y)
    pairs_df <- SEA_VALUE_LUT(pairs_df)
    colnames(pairs_df) <- c("cur_value", "pre_value")
    attach(pairs_df)
    ifelse(cur_value >=3, 
           ifelse(is_strength && pre_value == 5,
                  df$bonus_points <- df$bonus_points + 1,
                  ifelse(!is_strength && pre_value == 0, 
                         df$bonus_points <- df$bonus_points + 1,
                         ifelse(pre_value == 2 || pre_value == 3 || pre_value == 4, 
                                df$bonus_points <- df$bonus_points + 1, NA))), NA)
    detach(pairs_df)
  }

  df$bonus_points[df$bonus_points > cap] <- cap
  return(df$bonus_points)
}

Example data frame


+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+
| H.Response2.Attack | H.Response.Attack | H.Response2.Budget | H.Response.Budget | H.Response2.Cred | H.Response.Cred |
+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+
|                  4 |                 4 |                  4 |                 4 |                4 |               3 |
|                  4 |                 4 |                  3 |                 2 |                3 |               4 |
|                  4 |                 4 |                  3 |                 2 |                3 |               4 |
|                  4 |                 4 |                  4 |                 4 |                4 |               4 |
+--------------------+-------------------+--------------------+-------------------+------------------+-----------------+

How to check if any of the elements in a list can be found in the given string?

This is the way I'm doing it, but I'm wondering if there's a better way. When I google the problem it suggests using list comprehensions or any() method which either doesn't work for me or I'm misunderstanding them. But I gathered that they just give out boolean values - but I want to keep on using the matched URL if one of the phrases is located in it.

for URL in URLs
    if 'phrase1' in URL or 'phrase2' in URL or 'phrase3' in URL:
        get_subcategories(URL)               #Calling a function wit the matched URL 
        ...

PHP | If loop with multiple conditions

I have a problem with an if loop with more than one condition inside I bring an example to understand:

for example let's say we have 3 fields in the same database table

one

two

three

each of these 3 fields has 3 states

empty

on hold

ready

I want to see a statement only when all 3 are up ready

    <?php if($collaboratore_abilitato['one'] === 'ready'|| $collaboratore_abilitato['two'] === 'ready' || $collaboratore_abilitato['three'] === 'ready') :?>

<!-- SHOW CODE -->

<?php else: ?>

<!-- SHOW ANTOHER CODE -->


    <?php endif; ?>

and

$collaboratore_abilitato

it s a paramater for a while

my problem is that when I activate the 3 parameter it shows me the contents of show code and not of show another code

I don't understand why it should show me show another code only when the 3 statements are verified in ready

How to create automatic new field if character reaches x amount of characters

For a while I have been trying to work on a automatic adding field whenever it reaches a specific characters total which in my case would be the Discord embed (Discord-embed). For each field there is a limitation of 1020 characters and after that you need to add a new field to be able to post to discord. Else it will return an error saying that it has reached its number and it will not be posted to discord.

The code I have written right now is:

from discord_webhook import DiscordEmbed, DiscordWebhook

data = {
    '1': ' - (https://www.python.org/)',
    '2': ' - (https://en.wikipedia.org/wiki/Python_(programming_language))',
    '3': None,
    '4': ' - (https://sv.wikipedia.org/wiki/Python_(programspr%C3%A5k))',
    '5': None,
    '6': ' - (https://www.learnpython.org/)',
    '7': ' - (https://www.w3schools.com/python/python_intro.asp)',
    '8': None,
    '9': ' - (https://www.codecademy.com/learn/learn-python)',
    '10': ' - (https://www.programiz.com/python-programming)',
    '11': None
}

embed = DiscordEmbed(title="Test", description="test", color=10881109)

dict_keys = list(data.keys())
characterCount, i = 0, 0
for index, key in enumerate(dict_keys):

    if data[key]:
        if len(dict_keys[index] + data[key]) + characterCount > 20: #I put 20 just for test, should be 1020
            embed.add_embed_field(name='Info', value='\n'.join([dict_keys[index] + data[key]]))
            characterCount, i = len(dict_keys[index] + data[key]), index
        else:
            characterCount += len(dict_keys[index] + data[key])

    else:
        if len(dict_keys[index]) + characterCount > 20: # I put 20 just for test, should be 1020
            embed.add_embed_field(name='Info', value='\n'.join([dict_keys[index]]))
            characterCount, i = len(dict_keys[index]), index
        else:
            characterCount += len(dict_keys[index])

webhook = DiscordWebhook(url="https://discordapp.com/api/webhooks/633369105713332254/Rx_3-AjWajxIM8uKButDV6mp3ymO4B4Ja7dyuRkzSQlTgd8l-UA_mdiM9evExb8e9klF")
webhook.add_embed(embed)
response = webhook.execute()

And here is two things I had struggles first with, the first one would be the key-value where value doesn't contain any values. Which means we just want to print out the key.

But my main problem is that I have got stuck where Im at this point that I dont know how I can split the code so that every time it reaches 1020 total of characters, it should create a new field which is: embed.add_embed_field(name='Info', value='\n'.join([dict_keys[index] + data[key]])) <-- embed.add_embed_field is how you create a new embed.

What I would like it to show in the discord webhook is whenever it reaches over 1020 characters (And that can be tested if we add a long url instead of the numbers inside the ():

Info                                                                Info
1 - (https://www.python.org/)                                       7 - (https://www.w3schools.com/python/python_intro.asp)
2 - (https://en.wikipedia.org/wiki/Python_(programming_language))   8
3                                                                   9 - (https://www.codecademy.com/learn/learn-python)
4 - (https://sv.wikipedia.org/wiki/Python_(programspr%C3%A5k)       10 - (https://www.programiz.com/python-programming)
5                                                                   11
6 - (https://www.learnpython.org/)

but thats the outlook it should look once we reach over 1020 characters in one embed.

How am I able to do that?

Why wont the if-statement in my function run?

Ive searched all over this site for similar questions and haven't been able to find an answer to help me. With that being said, sorry if this was asked before and I missed it.

After the if statement (winner != null) fires and the gameWon() is called, the console.log works but then nothing happens with the if-statement in gameWon(). But if I call gameWon() myself in the console then the whole function runs properly.

Any idea why it works when I call it manually but not when checkWinner() calls it?

{
  checkWinner: function () {
    //check for left to right diaganol
    if (this.equalCheck(boardArr[0], boardArr[4], boardArr[8]))
      winner = boardArr[0];
    //check for right to left diagonal
    if (this.equalCheck(boardArr[6], boardArr[4], boardArr[2]))
      winner = boardArr[6];
    //check for vertical win
    if (this.equalCheck(boardArr[0], boardArr[3], boardArr[6]))
      winner = boardArr[0];
    else if (this.equalCheck(boardArr[1], boardArr[4], boardArr[7])) {
      winner = boardArr[1];
    } else if (this.equalCheck(boardArr[2], boardArr[5], boardArr[8])) {
      winner = boardArr[2];
    }
    //check for horizontal win
    if (this.equalCheck(boardArr[0], boardArr[1], boardArr[2]))
      winner = boardArr[0];
    else if (this.equalCheck(boardArr[3], boardArr[4], boardArr[5])) {
      winner = boardArr[3];
    } else if (this.equalCheck(boardArr[6], boardArr[7], boardArr[8])) {
      winner = boardArr[6];
    }
    if (winner != null) {
      this.gameWon(winner);
    }
  },

  gameWon: function () {
    console.log("WORKS");
    if (winner == "X") {
      this.scoreDiv.innerText = `${player1.name} won!!`;
    } else if (winner == "O") {
      this.scoreDiv.innerText = `${player2.name} won!!`;
    } else return;
  },
}

Can`t compare ArrayList values in Java

Im doing a Java course and in one exercise I have to create three ArrayLists, ask the user to fill the first two with Integers, and then compare both ArrayLists.

The values that don´t repeat are added to the third ArrayList. I already declared the ArrayLists, used Scanner to allow the user to fill the ArrayLists, and that part works.

The problem comes when I try to compare both ArrayLists. I get all sort of alerts in this line ("the if statement is redundant", "Integer values compared using == or !=","Flip operands of the binary operator", "Invert if").

I suspect that what I wrote after the if statement is not very clean, and that I could get some comments about that (Im not an expert in Java), but I do not understand the alerts that the IDE displays. The code compiles and runs just fine until it hits the nested loops. Please help! Thanks.

       //Checking for values that dont repeat
        for(int i=0;i<listVector1.size();i++){
            for(int j=0;j<listVector2.size();i++){
                if(listVector1.get(i)==listVector2.get(j)){//Im getting an alert here
                 repeats=true; //this boolean was previously declared
                 } else {
                  repeats=false;
                }
            if(repeats==false){
                int newValue=listVector1.get(i);
                listVector3.add(newValue);
            }
        }

        }

How to create IF condition in trigger mysql when condition is result of count table

Trigger in mysql

BEGIN

DECLARE jml INT;

SET jml = (SELECT COUNT(lapor_karya.ID_Lapor) FROM lapor_karya GROUP BY NEW.ID_Karya);

IF jml>10 THEN 

DELETE * FROM karya_pelajar WHERE ID_Karya=NEW.ID_Karya;

END IF;

END

Error

The following query has failed: "CREATE DEFINER=`root`@`localhost` TRIGGER `delete_karyabanned` AFTER INSERT ON `lapor_karya` FOR EACH ROW BEGIN DECLARE jml INT; SET jml = (SELECT COUNT(lapor_karya.ID_Lapor) FROM lapor_karya GROUP BY NEW.ID_Karya); IF jml>10 THEN DELETE * FROM karya_pelajar WHERE ID_Karya=NEW.ID_Karya; END IF; END"
MySQL menyatakan: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM karya_pelajar WHERE 

ID_Karya=NEW.ID_Karya; END IF; END' at line 9

I want to get count of my query, and then if the result of count is more than 10, it will execute query delete. But my code doesn't working. I use mysql database

Mysql IF statement Error on Nested if sentence

I am trying to create a procedure to update the stopTime field on my works table. The query I am using is:

update  mydb.works  set stopTime= 
(IF((SELECT table_name FROM information_schema.tables WHERE table_schema = 'mydb' AND table_name = 'results_24') is NULL, 
(select stampTime from mydb.works where id = 24), 
(IFNULL((select stampTime from mydb.results_24 order by id desc limit 1),
(select stampTime from mydb.works where id = 24))))) where id=24;

Shortly, the query should get the related results_ table stampTime as stopTime of works table's related entry. If there is no table or empty table, the stampTime at the works table is used.

My problem occurs when there is no results_ table I'm looking for. The statement should check if related results_* table exists and if not, it should get the stampTime from works table.

But it also executes the statement below (i.e: ELSE part)

IFNULL((select stampTime from mydb.results_24 order by id desc limit 1)

and I got the error (as expected)

ERROR 1146 (42S02): Table 'mydb.results_24' doesn't exist

I checked the parenthesis and commas multiple times. I think there is no mistake about it. What am I missing? It shouldn't execute the ELSE part, but it does. Why?

Thanks.

OS: Raspbian

Mysql version: Mysql Ver 15.1 Distrib 10.3.22-MariaDB, for debian-linux-gnueabihf (armv8l) using readline 5.2

Postman test script:Setting variables for Basic auth and setting a field in the next request based on the username password combination

1.In the first request I am generating token using basic Auth 2. In the next request, using the generated token ,I am sending a request payload where I want to set like if the username, password combination (in the first request) is suppose a and b, then I want my tradingAgent field to be suppose B, else C or other combinations How can I achieve this, I am new to postman and javascripting.

My second request looks like this

"sequence": "5533", "tradingAgent": "",

I understand in the pre-requisite script I have to write..but the below doesnt work..enter image description here var username = pm.environment.get("username"); if (username = ("a")) (password = ("b")) pm.environment.set("tradingAgent","B"); else pm.environment.set("tradingAgent","C");

MIPS If Statement Being Ignored

I have a word array of 1's and 0's that is 7x5. My code is supposed to branch whenever there's a 1 to display a certain graphic, however, I noticed that the statement is being ignored. Here's the code:

bge s1, 5, _increment_outer_loop

la a0, arena

mul t0, s0, 28 #i

mul t1, s1, 4 #j

add t1, t1, t0

add t2, a0, t1

beq t2, 1, _draw_arena

j _increment_inner_loop

Can anyone shine light on the problem? Thank you

I have already created a stored procedure query. Now I want to modify my query to get the output with conditions for feature column

select distinct(l.ID),
    l.labID as OrderLabid, l.name as InterfaceName,
    l.deleteFlag,
    (case when l.labID = 28 then 'Uni-directional'  
          when l.interfaceconfigured = 1 then 'Uni-directional' 
          when l.interfaceconfigured = 2 then 'Bi-Directional' 
          when l.interfaceconfigured = 3 then 'Uni with ereq' 
     end) as "Uni/Bi",
    l.resultlabid, 
    e.practid, e.ecwlabid, e.hublabid,
    cast (eu.url as varchar(255)) as HUB_URL, 
    stuff((select ' (-) ' + P.keyname + ':= ' + c.classtobeexecuted + ', ' + 'RegisteredServerId:= ' + cast(c.RegisteredServerId as varchar) 
           from xyz P 
           join ecwschtasks c on cast(p.ID as varchar) = cast(c.ecwschjobdatamapids as varchar) 
           where cast(P.keyvalue as varchar) = cast(eu.PractId as varchar) 
             and c.deleteflag = 0 
           for xml path('')), 1, 1, '') as 'Jobs',
    replace(replace(replace(replace(stuff((select ' (-) ' + 'Name:= ' + li.name,' ** Itemid:= ',li.itemId,' ** Value:= ',li.value  
                                           from def li 
                                           where li.labid = l.ID 
                                             and (li.name in ('OMG')) 
                                           for xml path('')), 1, 1, ''), '<value>', ''), '</value>', ''), '<itemid>',''), '</itemid>','') 'Feature',
from 
    ABC l 
join 
    ecwlabhub_spoke_mapping e on l.ID = e.ecwlabid 
left join 
    ecwlabhub_spoke_url eu on e.practid = eu.practid 
                           and eu.Type = 0 
left join 
    ecwschjobsdatamap ed on eu.practid = ed.keyvalue 
left join 
    ecwschtasks es on ed.Id = es.ecwschjobdatamapids 
where 
    l.deleteflag = 0 and l.labid > 0;

Execute a series of commands on each IP address in a file in bash

I am looking to analyse a log file for IP addresses which accessed a specific number of web pages in less than a specific time frame and append the IP addresses to a file.

The log file (output.csv) has been modified and uses the following format:

29/Oct/2020:07:41:42|111.111.111.111|200|/page-a/
29/Oct/2020:08:30:40|000.111.000.111|200|/page-a/ 
29/Oct/2020:08:30:44|000.111.000.111|200|/page-b/
29/Oct/2020:08:30:45|000.111.000.111|200|/page-c/
29/Oct/2020:08:30:47|000.111.000.111|200|/page-d/
29/Oct/2020:08:30:48|000.111.000.111|200|/page-e/

To get the time difference in seconds between a specific number of instances of an IP address, I used the following set of commands:

egrep "000.111.000.111" output.csv | awk 'BEGIN{FS="|"; ORS=" "} NR==1 || NR==5 {print $1,$2}' | sed -e 's/[\/:]/\ /g' -e 's/Jan/1/g' -e 's/Feb/2/g' -e 's/Mar/3/g' -e 's/Apr/4/g' -e 's/May/5/g' -e 's/Jun/6/g' -e 's/Jul/7/g' -e 's/Aug/8/g' -e 's/Sep/9/g' -e 's/Oct/10/g' -e 's/Nov/11/g' -e 's/Dec/12/g' | awk '{print $3,$2,$1,$4,$5,$6 "," $10,$9,$8,$11,$12,$13","$14}' | awk -F, '{d2=mktime($2);d1=mktime($1);print d2-d1, $3}'  | awk '{if($1<15)print $2}' >> file.txt

What this is supposed to achieve:

  • search for IP in output.csv
  • where possible, show the 1st and 5th line where this IP appears, printing the date/time & IP
  • remove separators "/" & ":" in date and time
  • change dates to a numerical format
  • reorder the date and time, and change format to read date/time, date/time, IP address
  • print the difference in sec between the first and second date/time on each line
  • append the IP address to file.txt if the time (in seconds) is less than 15.

If 5 pages are accessed in under 15 seconds by the given IP address, the command above appends the IP to a file.

I would like to run this command on every IP address in the file.

The desired result is a file with a list of IP addresses which all accessed the server at a rate of more than 5 pages in 14 seconds (timing can be adjusted).

What I have tried...

I attempted to use egrep -f with a list the IP addresses in the same sequence (a shot in the dark):

egrep -f ip-list output.csv | xargs

This failed miserably, as you might expect — with awk stating that it can not find a file with the name of the given IP address.

I also created a list of files for each set of IP addresses:

awk '{print >  "ip_"$1}' ip-list.txt

...but alas, I had no look iterating through them (I am a bit green at looping and bash scripting).

Apologies in advance if I have worded my question badly or if my attempts are somewhat primitive or inefficient.

Help would be most appreciated.

Thank you.

VBA forumula as a variable

I'm writing a VBA form which looks at a sheet of data and narrows down a selection based on drop boxes selected. The data sheet contains the options for each drop box under different headings eg

Drop box 1 - Please select your company -> narrows down contents of drop box 2

Drop Box 2 - Please select your department -> narrows down contents of drop box 3

Drop Box 3 - Do you wish to raise or approve -> narrows down to a selectable list

I have the above working, utilizing scripting dictionaries and a lot of nestled if statements, as per the below. Basically this populates the dictionary with any rows which match the relevant criteria.

Is there a neater way of doing this? It means reviewing the full criteria each time you get into the nestled if statement, so the 'If Not Dic.Exists(rCell.Value) And rCell.Value...' statement just gets longer and longer under each if statement.

I'm wondering if there is a way to have the componants of that line embedded as variables eg If Not Dic.Exists(rCell.Value) And rCell.Value <> "" And Statement1 And Statement2

where

Statement 1 = rCell.Offset(0, -2).Value = CompanySelect.Value
Statement 2 = rCell.Offset(0, 1).Value = "Display access"

I could then change the statements based on the different If values so if we were looking at display access it would be the above, but for approving it would be

Statement 1 = rCell.Offset(0, -2).Value = CompanySelect.Value
Statement 2 = rCell.Offset(0, 1).Value = "Approval"

Current code:

If CompanySelect.Value <> "" Then

If SAPDisplay.Value = False And SRMUse.Value = False And SAPEdit.Value = False Then
RoleSelector.RoleList.Clear
For Each rCell In ws.Range("C2", ws.Cells(Rows.Count, "C").End(xlUp))
    If Not Dic.Exists(rCell.Value) And rCell.Value <> "" And rCell.Offset(0, -2).Value = CompanySelect.Value And rCell.Offset(0, -2).Value = CompanySelect.Value Then
    Dic.Add rCell.Value, Nothing
    End If
Next rCell
For Each Key In Dic
    RoleSelector.RoleList.AddItem Key
Next
    Dic.RemoveAll

ElseIf SAPDisplay.Value = True Then
If SRMUse = False Then
    RoleSelector.RoleList.Clear
    For Each rCell In ws.Range("C2", ws.Cells(Rows.Count, "C").End(xlUp))
        If Not Dic.Exists(rCell.Value) And rCell.Value <> "" And rCell.Offset(0, -2).Value = CompanySelect.Value And rCell.Offset(0, -2).Value = CompanySelect.Value And rCell.Offset(0, 1).Value = "Display access" And rCell.Offset(0, 2).Value = "N/A" Then
            Dic.Add rCell.Value, Nothing
        End If
    Next rCell
    For Each Key In Dic
        RoleSelector.RoleList.AddItem Key
    Next
    Dic.RemoveAll

    ElseIf SRMUse = True Then

        If SRMDisplay.Value = False And SRMCreate.Value = False And SRMApprove.Value = False Then
        RoleSelector.RoleList.Clear
        For Each rCell In ws.Range("C2", ws.Cells(Rows.Count, "C").End(xlUp))
            If Not Dic.Exists(rCell.Value) And rCell.Value <> "" And rCell.Offset(0, -2).Value = CompanySelect.Value And rCell.Offset(0, -2).Value = CompanySelect.Value And rCell.Offset(0, 1).Value = "Display access" And rCell.Offset(0, 2).Value <> "N/A" Then
                Dic.Add rCell.Value, Nothing
            End If
            Next rCell
            For Each Key In Dic
            RoleSelector.RoleList.AddItem Key
            Next
            Dic.RemoveAll

How to conditionally select top value per group without comparing each value?

The data I have looks like:

  Group Gene      Score     direct_count   secondary_count 
    1   AQP11    0.5566507       4               5
    1   CLNS1A   0.2811747       0               2
    1   RSF1     0.5469924       3               6
    2   CFDP1    0.4186066       1               2
    2   CHST6    0.4295135       1               3
    3   ACE      0.634           1               1
    3   NOS2     0.6345          1               1

I am grouping the genes by the Group column then selecting the best gene per group based on conditions:

  1. Select the gene with the highest score if the score difference between the top scored gene and all others in the group is >0.05

  2. If the score difference between the top gene and any other genes in a group is <0.05 then select the gene with a higher direct_count only selecting between those genes with a <0.05 distance to the top scored gene per group

  3. If the direct_count is the same select the gene with the highest secondary_count

  4. If all counts are the same select all genes <0.05 distance to each other.

Output from example looking like:

 Group Gene      Score     direct_count   secondary_count 
    1   AQP11    0.5566507       4               5       #highest direct_count
    2   CHST6    0.4295135       1               3       #highest secondary_count after matching direct_count
    3   ACE      0.634           1               1       #ACE and NOS2 have matching counts
    3   NOS2     0.6345          1               1

Currently I try to code this with:

df<- setDT(df)
new_df <- df[, 
   {d = dist(Score, method = 'manhattan')
   if (any(d > 0.05)) 
     ind = which.max(d)
   else if (sum(max(direct_count) == direct_count) == 1L) 
     ind = which.max(direct_count)
   else if (sum(max(secondary_count) == secondary_count) == 1L) 
     ind = which.max(secondary_count)
   else 
     ind = which((outer(direct_count, direct_count, '==') & outer(secondary_count, secondary_count, '=='))[1, ])
   
   .SD[ind]
   }
   , by = Group]

However, I am struggling to adjust my first else if statement to account for my 2nd condition with only selecting between genes with a <0.05 distance to the top scored gene - currently it's comparing with all genes per group so even if a gene in that group has a 0.1 score but largest count columns its getting selected over a top scored gene at 0.7 for example if other genes in the group are 0.68 filling that <0.05 distance requirement.

Essentially I want my conditions 2 to 4 to only be considering the genes that are <0.05 distance to the top scored gene per group.

Input data:

structure(list(Group = c(1L, 1L, 1L, 2L, 2L, 3L, 3L), Gene = c("AQP11", 
"CLNS1A", "RSF1", "CFDP1", "CHST6", "ACE", "NOS2"), Score = c(0.5566507, 
0.2811747, 0.5269924, 0.4186066, 0.4295135, 0.634, 0.6345), direct_count = c(4L, 
0L, 3L, 1L, 1L, 1L, 1L), secondary_count = c(5L, 2L, 6L, 2L, 
3L, 1L, 1L)), row.names = c(NA, -7L), class = c("data.table", 
"data.frame"))

Edit:

The reason for my question is a problem with one specific group not doing as I expect:

structure(list(Group = c(2L, 2L, 2L, 2L, 2L), Gene = c("CFDP1", 
"CHST6", "RNU6-758P", "Gene1", "TMEM170A"), Score = c(0.551740109920502, 
0.598918557167053, 0.564491391181946, 0.567291617393494, 0.616708278656006
), direct_count = c(1, 1, 0, 0, 0), secondary_count = c(62, 
6, 1, 1, 2)), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x00000183dc6b1ef0>)

From this group Gene1 is being selected when it should actually be CHST6 and I can't find why.

Data looks like:

  Group Gene         Score      direct_count     secondary_count
1   2    CFDP1        0.5517401        1                  62
2   2    CHST6        0.5989186        1                   6
3   2    RNU6-758P    0.5644914        0                   1
4   2    Gene1        0.5672916        0                   1
5   2    TMEM170A     0.6167083        0                   2

CHST6 has the highest direct_count out of all genes <0.05 of the to the top scored gene in this group, yet Gene1 is being selected.

It keeps print sorry to hear that even if the input contains was fine or anything else . What can I do about it ? Please i would appreciate answers

Name=input("what's your name:")
print("Hello",Name, "I am Nexus . was designed by Ibrahim to keep you company")
Day=input("How was your day:")
if 'was not'in 'Day':
    print("sorry  to hear that")
elif 'was fine' in 'Day':
    print('ok')
else:
    print('sorry about that')

#I want the code to be able to print various responses to various questions . But it prints sorry to hear that even if Day contained was fine or a response not containing was not .

PHP MySQL If nothing changed, process the rest

I have an update info form. I want it to check if the new email is already taken. BUT if the email stays the same, then just update the rest of it. I have tried several IF statements, but nothing seems to work, it always says, "email already taken". So if someone could point me in a good direction, i would be greatly appreciative.

Here is a sample of the code:

$user_name = validate_text($_POST['user_name']);
        $user_email = validate_email($_POST['user_email']);
        $user_country = validate_text($_POST['user_country']);
        $user_state = validate_text($_POST['user_state']);

        $edit_id = $_SESSION['user_data']['id'];

        $db->query('SELECT * FROM users WHERE user_email = :user_email');
        $db->bind('user_email', $user_email, PDO::PARAM_STR);
        $check_user_email = $db->fetchSingle();

        if ($check_user_email > 0) {
            if ($check_user_email != $user_email) {
                setAlert('<div class="alert alert-danger text-center" role="alert">That Email is already in use</div>');
            } else {
                $db->query('UPDATE users SET user_name=:user_name, user_email=:user_email, user_country=:user_country, user_state=:user_state WHERE user_id=:user_id');

How to replace input within a loop

bool alphabeticString(string word)
{
for (int i = 0; i < word.length(); i++)
{

    if (isalpha(word[i])==true)
    {
        cout << word[i] << " is alphabetical\n";
        
    }
    
    if (isalpha(word[i])==false) {
        cout << "Please retry a character is not alphabetical\n";
        cin >> word;
    }

}
return true;
}

Trying to make the word variable become the new loop if a character isn't alphabetical

How to add && to onclick and if function in javascript? Thanks alot

So I have a code that looks like this

<button id="p1" onclick="p();" >p1</button>
<button id="p2" onclick="p();" >p2</button>
<p id="p3">2</p>

And then I would like to make a function that goes

function p(e){

    var p= document.getElementById("p3").innerHTML;

    if('p1'==e && p!=2){alert('yes');}

    if('p2'==e && p==2){alert('no');}

}

I don't know why it's just not working.

How to use if and && and onclick together in this case?

Please guide me further and in javascript only.

If condition then put value many times in java

I have two objects with many parameters. I need to compare it by each field and put information about what field is different

How to do it clean?

I'm not happy with something like that

if(<condition>) {
    list.add(object.getParam());
}
if(<condition>) {
    list.add(object.getParam());
}
if(<condition>) {
    list.add(object.getParam());
}
if(<condition>) {
    list.add(object.getParam());
}
(...)
   

Maybe there is cleaner way to do it by stream for example?

jeudi 29 octobre 2020

How to use if else conditions with overloaded constructor in java

Our prof give us an activity to create a overloaded constructor that stores blood type. I've already Created two (2) classes named BloodData (no class modifier) and RunBloodData (public). My problem is I don't how to apply the if else statements to this 2 objects in the main method, if the user does not input anything Hence, the values stored in the default constructor are displayed.

public class RunBloodData {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter blood type of patient: ");
String input1 = input.nextLine();
System.out.print("Enter the Rhesus Factor (+ or -): ");
String input2 = input.nextLine();

//How to use conditions in this 2 objects with agruments and w/out arguments?

BloodData bd = new BloodData(input1,input2);
bd.display();
System.out.println(" is added to the blood bank.");   

// if the user did not input values, the values stored in the default constructor should display this.
BloodData bd = new BloodData();
bd.display();
System.out.println(" is added to the blood bank.");


//constructor
class BloodData {
static String bloodType;
static String rhFactor;

public BloodData() {
bloodType = "O";
rhFactor = "+";   
}
public BloodData(String bt, String rh) {
bloodType = bt;
rhFactor = rh;
}static
public void display(){
System.out.print(bloodType+rhFactor);
  
 }
}
// this is the output of it
Enter blood type of patient: B
Enter the Rhesus Factor (+ or -): -
B- is added to the blood bank.
O+ is added to the blood bank.//this should not be displayed since the user input values. How to fix it?

This is a part of the instruction in the activity. --In the main method, add statements to ask the user to input the blood type and the Rhesus factor (+ or -). Instantiate a BloodData object name with arguments based on the user input. For example, BloodData bd new BloodData(inputl, input2); where input1 and input2 are String variables that stored what the user entered. If the user does not input anything, instantiate a BloodData object without an argument. Print the confirmation message by invoking the display method through the object you created For example, bd. disp1ay;

How to properly filter a df based on a condition in R?

I am trying to sample a dataset based on date class column, quarterly for "Active" and monthly for "Inactive"

Here's my code:

library(dplyr)
library(lubridate)
  
## data ##
                 
df <- structure(list( 
             mes = c("01/01/2000", "01/02/2000", "01/03/2000", 
"01/04/2000", "01/05/2000", "01/06/2000", "01/07/2000", "01/08/2000", 
"01/09/2000", "01/10/2000", "01/11/2000", "01/12/2000"),
              status = c("Active", "Inactive",
                         "Active", "Inactive",
                         "Active", "Inactive",
                         "Active", "Active",
                         "Inactive", "Active",
                         "Inactive", "Active")),
             class = "data.frame",
             row.names = c(NA, -12L))

## setting date class for "mes" column ##

df$mes <- as.Date(df$mes,
                  format = "%d/%m/%Y")

## sampling ##

sample_df <- df %>%  
  dplyr :: filter(status %in% "Active",
                  status %in% "Inactive") %>%
            dplyr :: filter_if(status == "Active",
            month(mes) %in% c(3,6,9,12),
            month(mes) %in% c(1,2,3,4,5,6,7,8,9,10,11,12))

Console output:

Error in is_logical(.p) : objeto 'status' no encontrado

Is there any other library that I could use to accomplish this task?

Page reading 2 different If-Statements as the same

I'm running into a pretty confusing situation here:

   if ((a.length == 0 || b === null)) {
        this.noNotif = true;
        console.log("1");
      }
      if (a.length > 0 || b === null) {
        this.newNotif = true;
        // this.noNotif = false;
        console.log("2");
      } else {
        if (a.length === b.length) {
          console.log("No New Notifications");
          this.noNotif = true;
        } else {
          console.log("New notifications");
          this.newNotif = true;
        }

Console logging a.length returns 0 and 'b' is null However, the issue is that somehow both of the first two if-statements' conditions are being met. noNotif and newNotif both display a Vue components and both are showing up currently.

Some background information about a & b

'a' is supposed to be data from an API that is fetched on page load. 'b' is supposed to be a localStorage object array

The first if-statement deals with a new user who has no API data or anything stored in LocalStorage

The second if-statement handles when the user does have data in the API, but nothing in LS yet.

The First nested if-statement is if the data from the API matches the LS data

The nested else-statement is if the API data is different (longer) than what's in LS

How to use an IF statement to change a variable in python

Hi im really new to coding so if this seems dumb sorry but I cannot firgure this out for the life of me maybe I just cant use this method?

propLW = float(propLength) * float(propWidth)
copyPropLW = float(propLength) * float(propWidth)
# VVV I could really use help on adding this surcharge im not sure how to do it VVV
if propLW >= overSqftSurcharge:
    print("Adding a $500 surcharge")
    propLWCost = copyPropLW + overSqftSurcharge
elif propLW <= overSqftSurcharge:
    print("No surcharge")
    

treeNumValue = float(treeNum) * float(treeCost)
grassPropLW = propLWCost * grassTypeCost
totalCost = baseLabour + float(treeNumValue) + float(grassPropLW)

Error: unexpected '}' in " }" for if, else if, else loop in R Studio [closed]

I am trying to bucket random uniform~(0,1) into buckets using an if/else if/else loop but keep receiving the unexpected '}' in " }" error. Below is my code:

u <- runif(100,0,1)
u <- as.matrix(u,nrow=100,ncol=1) #vector of uniforms
x <- as.matrix(rep(0,100),nrow=100,ncol=1)  #vector of zeroes
p1 <- 9/16
p2 <- 15/16
for(i in 1:100){ 
  if (u[i] <= p1) { (x[i] = 0) } #if u[i] is less than p1, assign value of 0
  else if (u[i] > p1 & u[i] <= p2)  {(x[i] = 1) } #if u[i] is in between p1 and p2, assign 
   value of 1
  else (u[i] > p2)  {(x[i] = 2)} #if u[i] is more than p2, assign value of 0
  }

If anyone can help me, I would appreciate it! I would like to be able to print(x) at the end to get a vector of 0, 1, 2s.

Selenium web driver statement not working within an if statement, but works fine outside of if statement, Python Selenium

Hi all I am working with selenium in python, I have the following code

a=26 #specifying the starting point 
b=73 #specifying the end point
x=a/25
print(x)
q=int(x)-1
p=b-a+1


if x<=1:
    school_urls = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//*[@id='rankings']/tbody/tr/th/a")]
    print(school_urls)
    for i in range(a-1,len(school_urls)):
        school_links.append(school_urls[i])
    while len(school_links)<p:
        next_elements=driver.find_elements_by_xpath("//*[@id='layout_1']/section/ol/li[8]/a")
        print(next_elements)
        next_page=next_elements[0]
        next_link=next_page.get_attribute('href')
        if next_link in next_links:
            break
        next_links.append(next_link)
        driver.get(next_link)
        school_urls = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//*[@id='rankings']/tbody/tr/th/a")]
        school_links=school_links+school_urls


this code chunk occurs after having navigated to a page via the code below

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
import mysql.connector as mysql
import re 

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(5)
driver.get("https://www.maxpreps.com/")
sign_in=driver.find_element_by_link_text('SIGN IN')
sign_in.click()
email=driver.find_element_by_id("ctl00_Navigation_Content_txtEmail")
email.send_keys('XXXXX')
password=driver.find_element_by_id("ctl00_Navigation_Content_txtPassword")
password.send_keys('XXXXX')
sign_in_submit=driver.find_element_by_id("ctl00_Navigation_Content_Button1")
sign_in_submit.click()
school_links=[]
next_links=[]

the problem is that the elements

school_urls = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//*[@id='rankings']/tbody/tr/th/a")]

next_elements=driver.find_elements_by_xpath("//*[@id='layout_1']/section/ol/li[8]/a")


are returned as empty lists when inside the if statement sometimes and sometimes the code works perfectly fine, but if I take them out of the if statement they work perfectly fine every time I run it. This is a very weird error to have, since the web elements are always present and an if statement should not have an impact on this. Any ideas?

a vba code to improve If-function in excel

I am using functions like the following function in excel a lot.

=if(A1<>"",1/A1,"")

but I got tired of writing the (A1<>"") part because there is lots of cells which I should check if they are empty or not. so I was thinking if I can write a vba code like " If " which gets some formula as input and then check for me if all the cells included in the formula have some conditions (like there is a number there or not, being zero and so on) then it saves me lots of time and also my formulas inserted are much more readable.but unfortunately I don't know how to get the formula as an input and how to look at the cells included in the formula. so, myfunction should be like this

=myfun(1/A1)

and then it checks for me if A1 is empty so it don't give me any result.

How to compare two requests values and print if new values found

Im currently coding a comprehension where I check for fruits in KG (as example) that are in stock in a webshop. The values can be between 1-10KG and that some of the values (KG) might not be in stock but could be restocked after a while.

What I have been trying to do is to print out if we find a restock. We should print it out and say that "There is a restock" and then continue to compere to see if there is more restock.

As for now I have done a mock-up data of what it could look like:

import random
import time

""" # Mock-up of a requests values that is being scraped"""
firstReq = []
for _ in range(random.randint(1, 5)):
    firstReq.append(random.randint(1, 10))

while True:
    """ # Mock-up of a requests values that is being scraped"""
    newReq = []  # I have created an example for random values - The meaning here is that I will later on scrape values through requests.
    for _ in range(random.randint(1, 5)):
        newReq.append(random.randint(1, 10))

    if len(newReq) > len(firstReq):
        print("New value has been uploaded to the page")
        newReq = firstReq

    else:
        print("There is more values in firstReq than in newReq")
        time.sleep(2)
        newReq = firstReq

However my concern is that I dont think comparing the length of found KG on the website could be a good way because an example could be if 2KG is already in stock. That means we have already 1 In-stock and we continue to see if there is new restock coming. (We don't care if it gets less in stock, only when restocked however!) and lets say that 2KG gets sold out but a 4KG gets restock, with the code I have done, this will still think there is 1 In-stock and I will then miss the 4KG restock.

I wonder how I can be able to print out whenever there has happend a restock for a value?

While does not go in the next block

I have been stuck on this problem for about 1 hour : I want my command while to access in the next block. Case is a class: cases is the object. I made a definition that say on some condition : my object case become NoneType. There is the condition if element_voisin == case to be sure that the element is still a case and not a NoneType. If it's still a case I want to access case.ajouter une mine voisine() but my program won't go in. If you need more information tell me! I relly want this to work please.

            for element in coordonnees_voisine:
                element_voisin = self.obtenir_case(element[0], element[1])              
                if element_voisin == case: 
                    case.ajouter_une_mine_voisine()
                else:
                    None

Multiple IF conditions inside filter

I want to filter a table (2d array) together with IF condition (depending on HTML select value) and use this code

transportRegFiltered = transportReg.filter(r => 
          {if(lugarDe.value == "TODOS"){return true} else {return (r[6] == lugarDe.value)}    
          })

with 1 condition it works but I need to have several ones. Smth like

transportRegFiltered = transportReg.filter(r => 
          {if(lugarDe.value == "TODOS"){return true} else {return (r[6] == lugarDe.value)} 
           if(lugarA.value == "TODOS"){return true} else {return (r[7] == lugarA.value)}
          }

How can I do it?

Multiple commands in a IF statement

Can you put multiple commands in a If command? What I have is looking to see if something is installed and if it is, send text to a file and change a variable. My example is lets say you want to see if edge is installed....

Set Edge=N
If  exist "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"  (
 echo Edge is installed >> C:\Temp\Message.txt
) Else (
echo Edge is Not installed >> C:\Temp\Message.txt
)

Where would I need to put the Set Edge=Y if it is installed?

How do I give a javascript alert if a user enters a restricted character? [closed]

I need to create a notification when a user tries to enter a restricted character on a form. I currently have it set so that they cannot enter any special characters except a hyphen or an underscore. I used a jQuery function I found and it won't even show the character if it is limited.

Users have been confused though because there is no alert. I would like to let them know that the key they pressed is not cool.

So far I have been able to use document.getElementById to isolate the input. I think that I can use an event listener for keypress to identify the special characters but I am not sure how to create that function. Then I assume I will use an if statement to insert a new element or html to display the message if they press a not cool key.

Am I on the right track? Any guidance or suggestions are greatly appreciated. I hope everyone is having a wonderful day :)

Cannot implictly convert type "int" to "bool"

using System;

namespace Codes
{
    class Program
    {
        static void Main(string[] args)
        {
            String name = RandomNames();
            Console.Write(name);
            Console.ReadKey();
        }

        public static string RandomNames()
        {
            Random numGen = new Random();
            string vowel = "aeiou";
            string conso = "bcdfghjklmnpqrstvwxyz";
            int nameLen = numGen.Next(4,10);

            string result = "";
            for (int i = 0; i < nameLen; i++) 
            {
                if (i % 2) 
                {
                    result += vowel[numGen.Next(0, 4)]; // 4 is final index of vowel.
                } 
                else 
                {
                    result += conso[numGen.Next(0, 20)]; // 20 is final index of consonants.
                }
            }
            return result;
        }
    }

it says the "i" in if statement cannot implictly convert type "int" to "bool" and I don't know whats the problem with that because it's already an int in for loop

Dictionary returning only the Last Item in List Value

I have 2 lists as inputs:

A = ['A', 'B', 'C', 'D', 'E']
sessionid = [1, 1, 3, 2, 2]

I want to use dictionary comprehension without importing any libraries to generate the following output, with the key as 'Session x' by using string formatting:

{'Session 1': ['A','B'], 'Session 2': ['D','E'], 'Session 3': ['C']}

I tried with this code:

dictb = {'Session {}'.format(session): [a if session not in dictb.keys() else [a]] for a,session in list(zip(A,sessionid))}

but it returns me this:

{'Session 1': ['B'], 'Session 3': ['C'], 'Session 2': ['E']}

I think there is a problem with if-else statement in the comprehension. How should I improve this?

how come the program doesn't tell me if the numbers are in ascending or descending order?

all the rest of the code works, but coming to the last point, that of the order of numbers, the code either tells me that it is in increasing form or it is neither. Could you help me understand why please?

#include <stdlib.h>
#include <stdio.h>

int main(){
int n;
int number;
int positive, negatives, null;
int even, odd;
int cont;
int rest;
int previous_number;
int increasing;
int decreasing;

increasing=1;
decreasing=1;
positive=0;
negative=0;
null=0;
even=0;
odd=0;

printf("insert a number\n");
scanf("%d",&n);

for(cont=1;cont<=n;cont++){
printf("insert a number\n");
scanf("%d",&number);

here the code works by checking if the number is positive, negative or null

if(number>0){
  positive++;
}else if(number<0){
  negatives++;
}else{
  null++;
}

here also seeing if it is even or odd rest=number%2;

if(rest==0){
  even=even+1;
}else{
  odd=odd+1;
}

and here the code doesn't work

if(number>previous_number){
  decreasing=0;
}else{
    if(number<previous_number){
  increasing=0;
}
  else{
    increasing=0;
    decreasing=0;
 }
 previous_number=number;
}

  

printf("the positive numbers are: %d \n",positive);
printf("the negative numbers are: %d \n",negative);
printf("the null numbers are: %d \n",null);
printf("the even numbers are: %d \n",even);
printf("the odd numbers are: %d \n",odd);
if (increasing==1){
  printf("the numbers are arranged in ascending order\n");
}else if(decrescente==1){
  printf("the numbers are arranged in descending order\n");
}else{
  printf("the numbers are arranged neither in increasing nor in decreasing order\n");
}
system("pause");
return 0;
}

how to search through array with if statement and loop in Java Scrpit?

How can I write code like this Python code:

array = [["item1", "item2"], [1, 2]]
x = ["item1", 3]
for i in range(len(array)):
    for j in range(len(x)):
        if x[j] in array[i]:
           # do something

with JavaScript?

I did write this code with JavaScript:

var arr = [["item1", "item2"], [1, 2]],
     x = ["item1", 3];

for (var i = 0; i <arr.length; i++) {
    for (var j = 0; j < x.length; j++) {
         if (x[j] in arr[i]) {
               // do something
          }
    }
}

But the code didn't give me the result I want.

How to use "if" function with DataGrid View [Repost for solution] [duplicate]

I've been searching with google/stackoverflow for a while, but I couldn't find proper answer for my problem.

I have to create simple program in VS Windows Forms (.net Framework). I have created few DataGridViews with showing exact data I need. I added buttons to "Add" to create new row, or "Remove" selected row. Now I need to change data in selected row with single button click. When I click "Add" button, new dialog window pop-up, where you choose from subclasses Car or Motorbike, then when you choose what to add, new dialog will pop-up, and there you fill proper information (like Manufacturer, or year of creation etc.)

When I want to "Edit" selected row, I want the app to directly go to dialog where you can change the data to new ones. I thought simple "if" could help me easily, but i cannot find the code to create it. My thought was something like this:

            F1Automobil f1 = new F1Automobil();
            F1Motorka f2 = new F1Motorka();
            int indCar = dgvVozovyPark.CurrentCell.RowIndex;
            if (/*index of selected row where subclass equals to "automobil" = true)
            {
                {
                    f1.Action = F1Automobil.ActionType.Edit;
                    f1.CarInstance = (Automobil)dgvVozovyPark.CurrentRow.DataBoundItem;
                    f1.ShowDialog();
                }
            else
                {
                    f2.Action = F1Motorka.ActionType.Edit;
                    f2.BikeInstance = (Motorka)dgvVozovyPark.CurrentRow.DataBoundItem;
                    f2.ShowDialog();
                }
            }

But VS shows me several mistakes. Could somebody please help, because i don't know what to do. I tried a lot of combinations like Database.Equals(something) = true, but none worked.

Also, I need help with other thing, so I will write it here, because I don't want to create new thread. I want to implement one if function for NumericUpDown. I will share code below:

        public void InitializeDate()
        {
            if (numMonth.Value.Equals(2) == true)
            {
                numDay.Maximum = 28;
            }
            else if (numMonth.Value.Equals(4 | 6 | 9 | 11) == true)
            {
                numDay.Maximum = 30;
            }
            else
            {
                numDay.Maximum = 31;
            }
        }

This code show no mistake or error, but it's not working properly. Could anyone help with this aswell ?

I would like to point out, that I never programmed as professional, and I am learning everything in school from distance learning for Bachelor degree, and I have no option to communicate with my teacher to discuss this problem. Thank you all very much for help in advance.

Edit:

namespace Semestrální_projekt___Půjčovna_vozidel
{
    [Serializable()]
    public class Vozidla
    {
        public string Vyrobce { get; set; }
        public string Model { get; set; }
        public int RokVyroby { get; set; }
        public int CenaVypujcky { get; set; }
        public int CenaProdejni { get; set; }
        public Vozidla(string vyrobce, string model, int rokVyroby, int cenaVypujcky, int cenaProdejni)
        {
            Vyrobce = vyrobce;
            Model = model;
            RokVyroby = rokVyroby;
            CenaVypujcky = cenaVypujcky;
            CenaProdejni = cenaProdejni;
        }
    }
        [Serializable()]
        public class Motorka: Vozidla
        {
            public int Kubatura { get; set; }
            public string Typ { get; set; }
            public Motorka(string vyrobce, string model, int rokVyroby, int cenaVypujcky, int cenaProdejni, int kubatura, string typ)
                :base (vyrobce, model, rokVyroby, cenaVypujcky, cenaProdejni)
            {
                Kubatura = kubatura;
                Typ = typ;
            }
        }
        [Serializable()]
        public class Automobil: Vozidla
        {
            public int ObsahMotoru { get; set; }
            public string Typ { get; set; }
            public string Prevodovka { get; set; }
            public int PocetMistSezeni { get; set; }
            public Automobil(string vyrobce, string model, int rokVyroby, int cenaVypujcky, int cenaProdejni, int obsahMotoru, string typ, string prevodovka,int pocetMistSezeni)
                :base(vyrobce, model, rokVyroby, cenaVypujcky, cenaProdejni)
            {
                ObsahMotoru = obsahMotoru;
                Typ = typ;
                Prevodovka = prevodovka;
                PocetMistSezeni = pocetMistSezeni;
            }
        }
    }

mercredi 28 octobre 2020

Where do I need to place the if statement?

I need to print this output:

Guess the price and win the prize!
Enter your guess:46000
Too high!
Enter your guess:45000
Too high!
Enter your guess:44000
Too high!
Enter your guess:43000
Too high!
Enter your guess:42000
Too low!
Enter your guess:42500
Too many guesses!

This is my code:

guess_count = 0
car_price = 42500 

print("Guess the price and win the prize!")
while guess_count <= 5:
   guess_count = guess_count + 1
   guess = int(input("Enter your guess:"))

  if guess == car_price:
    print("You won the car!")
  elif guess < car_price:
    print("Too low!")
  elif guess > car_price:
    print("Too high!")
  if guess_count > 5:
    print("Too many guesses!")

If I input 5 guesses, the code above gives me an output like this:

  Too low!
  Too many guesses!

When a user inputs more than 5 guesses, I just want to print:

  Too many guesses!

What do I need to fix?

Creating pizza ingredients java program

I am creating a java program which will ask a user questions regarding what ingredients/toppings they would like on a pizza. After getting the user input, the program will print an ingredients list. I just started writing the program so its not finished. What I am having trouble with is validating the user input. for instance If the choices are "a" or "b" and the user enters "c", im not sure how to make the program force the user to enter a proper choice. With the code I have so far, It just displays an error message such as "Invalid Selection. Please enter a or b" but just moves on to the next question. How do I make sure the user is choosing a proper option then loop back around if the user doesnt enter in a valid choice?

Heres what I have so far:

package pizza.program; import java.util.Scanner;

public class PizzaProgram { public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    
    String CrustType;
    String Sauce;
    String Cheese;
    String Ingredient1;
    

        
    System.out.println("_______________________________________________________");
    System.out.println("Please choose one crust option: ");
    System.out.println("\n");
    System.out.println("a. regular crust             b. gluten-free crust");
    System.out.println("\n");
    System.out.printf("Enter choice: ");
    CrustType= input.next();
    
    if(CrustType.equals("a")) {
        System.out.println("You chose: regular crust");
    }
    else if(CrustType.equals("b")) {
        System.out.println("You chose: gluten-free crust");
    }
    else {
        System.out.println("Invalid Selection. Please enter a or b");
        System.out.println("Enter choice: ");
        CrustType = input.next();
    }
    
    
    
    System.out.println("_______________________________________________________");
    System.out.println("Please choose one sauce option: ");
    System.out.println("\n");
    System.out.println("a. red sauce             b. no red sauce");
    System.out.println("\n");
    System.out.printf("Enter choice: ");
    Sauce= input.next();
    
    if(Sauce.equals("a")) {
        System.out.println("You chose: red sauce");
    }
    else if(Sauce.equals("b")) {
        System.out.println("You chose: no red sauce");
    }
    else {
        System.out.println("Invalid Input. Please enter a or b");
        System.out.println("Enter choice: ");
        Sauce = input.next();
    }
  
    
    
    System.out.println("_______________________________________________________");
    System.out.println("Would you like to add cheese to the pizza?  (Y/N): ");
    System.out.println("\n");
    System.out.printf("Enter choice: ");
    Cheese = input.next();
    
    if(Cheese.equals("Y")) {
        System.out.println("You chose to add cheese to the pizza.");
    }
    else if(Sauce.equals("N")) {
        System.out.println("You chose NOT to add cheese to the pizza.");
    }
    else {
        System.out.println("Invalid Input. Please enter Y or N");
        Cheese = input.next();
    }

    
    
    System.out.println("_______________________________________________________");
    System.out.println("Please choose one ingredient option: ");
    System.out.println("\n");
    System.out.println("a. diced onion          b. diced green pepper     c. pepperoni");
    System.out.println("d. sliced mushrooms     e. diced jalapenos        f. sardines");
    System.out.println("g. pineapple chunks     h. tofu                   i. ham chunks");
    System.out.println("j. dry red pepper       k. dry basil");
    System.out.println("\n");
    System.out.printf("Enter choice: ");
    Ingredient1 = input.next();
    
    if(Ingredient1.equals("Y")) {
        System.out.println("You chose to add cheese to the pizza.");
    }
    else if(Ingredient1.equals("N")) {
        System.out.println("You chose NOT to add cheese to the pizza.");
    }
    else {
        System.out.println("Invalid Input. Please enter Y or N");
        Ingredient1 = input.next();
    }
   
    
}

}

Use of numpy.select when conditions and hence choices are too many

I have just started using numpy.select() given specific conditions and choices list.

Currently my code looks like this:

conditions = [
    data['column_name'].values == mylist[0],
    data['column_name'].values == mylist[1],
    data['column_name'].values == mylist[2],
    data['column_name'].values == mylist[3],
    data['column_name'].values == mylist[4],
    data['column_name'].values == mylist[5],
    data['column_name'].values == mylist[6]
] 

    choices = [
    data['column_name'].multiply(data['xyz'])*mylist[0]*Price/another_list[0],
    data['column_name'].multiply(data['xyz'])*mylist[1]*Price/another_list[1],
    data['column_name'].multiply(data['xyz'])*mylist[2]*Price/another_list[2],
    data['column_name'].multiply(data['xyz'])*mylist[3]*Price/another_list[3],
    data['column_name'].multiply(data['xyz'])*mylist[4]*Price/another_list[4],
    data['column_name'].multiply(data['xyz'])*mylist[5]*Price/another_list[5],
    data['column_name'].multiply(data['xyz'])*mylist[6]*Price/another_list[6]
]

outcome = np.select(conditions, choices)

What I am trying to find out, is what if I had say 30 conditions and 30 different choices? Do I have to fill conditions and choices lists manually? Is there any shortcut similar to the one below?

conditions = [data['column_name'].values == mylist]

choices = [data['column_name'].multiply(data['xyz'])*mylist*Price/another_list]

outcome = np.select(conditions, choices)

I hope I passed the message, looking forward to your ideas. Thank you

Java while loop random crashes [duplicate]

I have a code where I basically run through an array by custom order. I have included a code snippet of what goes wrong for me. For some reason Java sometimes gives me an arrayoutofboundsexception on 8, but to my knowledge the if statement in the while loop and before it should prevent it from reaching 8. Can someone explain to me what might be the cause of the variable val reaching 8 from time to time.

int size = 16;
done = new boolean[size/2];
int val = (int)(Math.random()*255);
int a = 0;
if ((size/2)<val)
  val=0;
while (done[val+a]) {
  a++;
  if ((val+a) > (int)(size/2)){
    val=0;
    a=0;
  }
}
done[val+a]=true;

How do I put a conditional statement into a loop

I'm working on a for loop that has a range of 1 which is a list. I'm trying to insert a conditional statement into my for loop that uses the modulo operator. I'm receiving a Type Error unsupported operand type(s) for %: 'list' and 'int

I've tried to remove the % sign and setting it to zero. I tried to remove the condition and set it to a variable. I also tried setting the modulo into a list by using the brackets and placing my integer 3 in it but receive another Type Error unsupported operand type(s) for %: 'list' and 'list

for i in range (1):  
    a=money = money %3 == 0  
    b=money = money %3 == 1
    if a and b:
        print( money[i]*6.00, money[i]*7.00)
    elif a:
        print (money[i]*6.00) 
    else:
        print (money[i]*7)

My desire out put is to determine if my list is divisible by 3 or not so I can multiple the list by the price 6.00

How to use if statement to go to choice [closed]

I want to use an if statement to go to different code segments

This is my code.

System.out.println("Select Action:");
System.out.println("a. Create Student File");
System.out.println("b. Write to Student File");
System.out.println("c. Caculate Student Grades");
System.out.println("d. Caculate Student Fees");
Scanner option = new Scanner(System.in);
String action1 = option.nextLine();

String action2 = "a";
String action3 = "b";
String action4 = "c";
String action5 = "d";

Thanks in advance :)

How to refactor my code with if (condition) { return } [closed]

For example, i have several functions needing to check the age of a patient. They must return false if patient.age < 10 so i write :

if (patient.age < 10) {
  return false
}

How can i do to have these 3 lines above in one function call ? Is it possible ? I need to do that in javascript and java.

Thanks

write a program to find out whether a given post is talking about "harry" or not? [closed]

''' TOPIC:THIS IS AN EXERCISE OF IF-ELSE IN PYTHON

                                                  '''

TRY TO SOLVE THIS PROBLEM USING THE HELP OF IF-ELSE STATEMENT

Optimize little Woocommerce snippet code with IF .. ElseIF and such

Would you please help me out to optimize my little snippet I wrote to apply a discount after adding products in the cart with tech assigned shipping class and other products with no class specified for WordPress (Woocommerce) website. How can I optimize the if .. elseif and overall make it better. Also, is adding break a good practise? I'm a PHP newbie, but I'm currently learning and would like to improve my code. Porbably I can use something similar to switch? Any help and examples are greatly appreciated!

add_filter( 'woocommerce_package_rates', 'adjustment_in_rates_of_product_with_shipping_class', 12, 2 );

function adjustment_in_rates_of_product_with_shipping_class( $available_shipping_methods, $package ) {

   // Shipping class slug to be eligible for a discount when combined with no class products
    $shipping_class = array(
        'tech',
    );

   // Discount
    $discounteuro = 3.50;
    $discountgbp = 3.20;
    $discountusd = 4;
    $discountglobalusd = 5;

    // Enter the shipping method value
    $shipping_services = array(
       'flat_rate:5',
    );

    $shipping_class_exists = false;
    foreach(WC()->cart->get_cart_contents() as $key => $values) {
        if ( in_array($values['data']->get_shipping_class() , $shipping_class) ) {
            $shipping_class_exists = true;
            break;
        }
    }

    $shipping_class_no_exists = false;
    foreach(WC()->cart->get_cart_contents() as $key => $values) {
        if ( strlen($values['data']->get_shipping_class()) == 0 ) {
            $shipping_class_no_exists = true;
            break;
        }
    }

    if ($shipping_class_exists && $shipping_class_no_exists) {
        foreach ($available_shipping_methods as $key => $value) {
            if ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'EUR' ) {
                $available_shipping_methods[$key]->cost -= $discounteuro;
        break;
            }
        elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'GBP' ) {
                $available_shipping_methods[$key]->cost -= $discountgbp;
        break;
        }
        elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'USD' ) {
                $available_shipping_methods[$key]->cost -= $discountusd;
        break;
       }
        else {
            $available_shipping_methods[$key]->cost -= $discountglobalusd;   
        break;
       }
        }
    }

    return $available_shipping_methods;
}

Ifelse recoding data statement applied to many datasets

I have a long list of automatically generated ifelse statements for many columns and conditions in dataset:

dat$Q5_str<-ifelse(dat$Q8.4 =="Yes"| dat$Q9.3_6 =="Maybe" & dat$Q9.11=="Europe", dat$Q10_str) 
dat$Q5_otr<-ifelse(dat$Q20.4 =="Other"| dat$Q21.7_13 =="Other" & dat$Q23.11=="Other" ,dat$Q10_otr)
...
...

I need to to modify those code to apply statements not to single dataset, but to many datasets stored in list:

ldat<-list("RegionA"=dat1, "RegionB"=dat2)

So I'm looking for a solution to update (with regexp) initial syntaxes, to more generalized function:

MyIfElse(dataset=ldat, expr='dat$Q8.4 =="Yes"| dat$Q9.3_6 =="Maybe" & dat$Q9.11=="Europe", dat$Q10_str')

but then I need probably manually parse this long string and manage everything with regexp. Is there any better approach?

How do I create the IF Statement in Excel which can handle many conditions. My Example provided

As you can see in my picture. There is a table to the right.

  1. Cell D3 has the option to select 90.0, 95.0, 99.0, and 99.9
  2. Cell D4 is a % value
  3. Cell D5 I have: IF(AND(D3=90,3/D4<9),3,4) Obviously if the user selects 90 for D3, then I want to determine which 2 X choices either 3 or 4 from the table are used based on the value of Y which I get by the 3/D4. This statement is working 100% correct.

MY QUESTION, How do I add the other parts of the table to this same line of code for when D3 = 95, 99, and 99.9?

I try this: =IF(OR(AND(D3=90, 3/D4<9),3,4, IF(AND(D3=95,4/D4<16),4,5)))

Can someone please help. Thank you.

Picture from Excel

how to apply if else statement [closed]

Our prof give us an activity to create a overloaded constructor that stores blood type. My problem is I don't how to apply the if else statements to this 2 objects. If the user did not input values Hence, the values stored in the default constructor are displayed. This is only the part of the code where I only have problem with.

    BloodData bd = new BloodData(input1,input2);
    bd.display();
    System.out.println(" is added to the blood bank.");   

    // if the user did not input values, the values stored in the default constructor should display.
    BloodData bd = new BloodData();
    bd.display();
    System.out.println(" is added to the blood bank.");

What am I comparing when comparing 2 gameObjects?

In unity when I compare 2 gameObjects in a if statement. example: if(this.gameObject == pointerToThis.gameObject) what is it comparing and how does it know other GameObjects which are almost the same but, not the same are not the same objects?

How to pass params to the method if a user leaves few params empty and wants to omit?

I have one web service to which i need to send multiple params but it's upto user that he can leave few empty and few filled but the problem is that if we pass empty or null the web service returns nothing and the vendor is not modifying it.

so we need to do something on our end.

I have done this that i took one string varaible and then append this to the url.

   If String.IsNullOrEmpty(txtEqptType.Text) Then
                Dim command As String = "Equips?$filter= TypeID eq 'Safety'"
            ElseIf String.IsNullOrEmpty(txtEquipID.Text) Then
                Dim command As String = "Equips?$filter= EquipID eq 'FIRE EXT 150'"
            ElseIf String.IsNullOrEmpty(txtPlant.Text) Then
                Dim command As String = "Equips?$filter= Plant eq 'MfgSys'"
            ElseIf String.IsNullOrEmpty(txtDescription.Text) Then
                Dim command As String = "Equips?$filter= Description eq 'Fire Extinguisher 150_1'"
            End If

but what I need to achieve is that if one param is empty i.e. not filled, then it shouldn't be passed to the webservice in the query string. Is there any short and solid way? bcz If I do, i will have to write a lot of if else condtions.

startIndex cannot be larger than length of string.| But i can print the value

I have a problem with the .Substring() method, when a execute a Substring on a string, the compiler, tell me that there is an exeption BUT only in the IF condition, if i try to print the same Substring, magically, the compiler is happy and there's no error. I took set the string with a foreach loop because i'm reading a file

Error

    Unhandled exception. System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string. (Parameter 'startIndex')
   at System.String.Substring(Int32 startIndex, Int32 length)
   at RTFM_Defonseca.Program.readSpedizioni() in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 166
   at RTFM_Defonseca.Program.compatta() in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 181
   at RTFM_Defonseca.Program.Main(String[] args) in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 43 '

Code

            foreach (var line_collegamento in collegamenti_lines)
            {
                Console.WriteLine(line_collegamento.Substring(3, 20)); //THIS ACTUALLY DOESN'T HAVE PROBLEM
                if (line_collegamento.Substring(3, 20).Equals(codice_collegamento)) //LINE 166, ERROR HERE
                {
                    spedizione.BDA = line_collegamento.Substring(32, 15);
                    lista_spedizioni.Add(spedizione);
                }
            }

Output

Console.WriteLine(line_collegamento.Substring(3, 20))

00310463900043482   
00310463900043482   
00310463900043482
00310463900043482
00310463900043482

//
Console.WriteLine(line_collegamento.Substring(32,15));

00112145001    
00112145002
00112145003
00112145004
00112145005

Create variable based on two other variables

In Python, I would like to create a new variable c based on the value of a and b.

if a in ('GBP', 'AUD', 'CNY', 'NZD'):
    if b == '[00Y, 01Y]':
        c= '90'
    elif b == '[01Y, 02Y]':
        c = '85'
    elif b == '[02Y, 03Y]':
        c = '80'
    elif b == '[03Y, 04Y]':
        c = '75'
    elif b == '[04Y, 05Y]':
        c = '70'
elif a in ('EUR', 'USD', 'CHF', 'CAD', 'SGD', 'HKD', 'JPY'):
    if b == '[00Y, 01Y]':
        c = '95'
    elif b == '[01Y, 02Y]':
        c = '90'
    elif b == '[02Y, 03Y]':
        c = '85'
    elif b == '[03Y, 04Y]':
        c = '80'
    elif b == '[04Y, 05Y]':
        c = '75'
    elif b == '[05Y, 07Y]':
        c = '60'
    elif b == '[07Y, 10Y]':
        c = '55'

a and b are columns of a dataframe and I have to use apply to finally obtain what I desire.

Although this perfectly works, I think it is long code for such a small operation and I wonder if there is a more elegant way to do the same. I know the np.select condition but it forces me to repeat the condition on `a, which I find is not elegant either.

Thanks,

Javascript: Is there a difference in performances when using literals in conditional statements?

this is a very peculiar curiosity that I'm not apparently able to benchmark with significant results.

The following code blocks perform the same simple comparison, they differ only in the order that I use inside the condition:

Code1:

const val = true;
if (val === true) {
  console.log('this is a truism');
}

Code2:

const val = true;
if (true === val) {
  console.log('this is a truism');
}
  • Is there any performance difference?
  • Is one implementation better than the other for any reason?

Thank you guys! 🙏