vendredi 31 juillet 2020

Trying to define strings in an if statment in C++

I want to have a gender system in what I'm coding, so in dialogue there are pronouns, but since the strings are defined in an if statement they come up blank. Is there a better way to do this?

int gender;
string pronoun;
string pronoun1;
string pronoun2;
string pronouns3;
string namingGender;

cout << "Please enter your gender \n1. Male \n2. Female \n3. Other" << endl;
cin >> gender;
if (gender == 1) {
    string namingGender = " saucy sir";
    string pronoun = " he ";
    string pronoun1 = " him ";
    string pronoun2 = " his ";
    string pronoun3 = " he's ";
    cout << "Have fun playing Insert-Name-Here!" << endl;
}
else if (gender == 2) {
    string namingGender = " manseva madam";
    string pronous = " she ";
    string pronou1 = " her ";
    string pronoun2 = " her ";
    string pronoun3 = " she's ";
    cout << "Have fun playing Insert-Name-Here!" << endl;
}
else if (gender == 3) {
    string nammingGender = " majestic mate";
    string pronoun = " they ";
    string pronoun1 = " them ";
    string pronoun2 = " their ";
    string pronoun3 = " they're ";
    cout << "Have fun playing Insert-Name-Here!" << endl;
}
else {
    cout << "You  did not enter 1 2 or 3...guess your other than" << endl;
    string nammingGender = " majestic mate";
    string pronoun = " they ";
    string pronoun1 = " them ";
    string pronoun2 = " their ";
    string pronoun3 = " they're ";
    cout << "Have fun playing Insert-Name-Here!" << endl;
}
    
cout << "By the way, what is your name... " << namingGender << "?" << endl;
cin >> playerName;

JAVASCRIPT only the first function is working on my window.onscroll function

I am new to javascript and I am trying to make both of these functions run at different times depending on the scroll position but only the first function 'myFunction1' is running. Please help.

<script>
 

window.onscroll = function redblob() {myFunction()

function myFunction() {
  if (document.body.scrollTop > 250 && document.body.scrollTop < 1200 || 
  document.documentElement.scrollTop > 250  && document.documentElement.scrollTop < 1200  ) {
    document.getElementById("redblob").classList.add('scale-transition');
  } 

 
  else {
    document.getElementById("redblob").classList.remove('scale-transition');
  }
  
  
}

function myFunction2() {
  if (document.body.scrollTop > 1200 && document.body.scrollTop < 1700 || 
  document.documentElement.scrollTop > 1200  && document.documentElement.scrollTop < 1700  ) {
    document.getElementById("blueblob").classList.add('scale-transition');
 
  } 

 
  else {
    document.getElementById("blueblob").classList.remove('scale-transition');
 
  }
  
  
}
};
  
</script>

How to create an inline conditional assignment in Objective-C?

My Pet class has 2 properties: BOOL isHungry and NSNumber *age. I want to put the properties of Pet myPet into NSMutableDictionary *myMap.

This is my code is Java. I am trying to write an equivalent in Objective-C

myMap.put("isHungry", myPet == null ? null : myPet.isHungry);
myMap.put("age", myPet == null ? null : myPet.age);

This is my current Objective-C version:

[myMap addEntriesFromDictionary:@{
    @"isHungry" : myPet ? myPet.isHungry : (NSInteger)[NSNull null],
    @"age" : myPet ? myPet.age : [NSNull null],
}];

The error for the second line is the following:

Incompatible operand types ('int' and 'NSNull * _Nonnull')

The compiler stopped complaining about the first line when I added (NSInteger). If I put the same on the second line, the error goes away, but the compiler complains about the first line again:

Collection element of type 'long' is not an Objective-C object

I am a noob in Obj-C and I am totally lost. I would also like to know the best practice for Obj-C.

How to check a column in a data table for duplicates within a if statement in R

I have data table named quarter_earnings with the following columns: client_name, store_name, store_key, q1_sales, q2_sales, q3_sales, q4_sales. All businesses have 4 rows total (1 per quarter) per store_name.

We want to be able to check if there are duplicated store_names within a client_name grouping. If there are no duplicates, we will be filtering a graph and labeling it using the store_name values. If there are duplicated store_names within a client, we will be filtering on store_key and using a sort of fusion of the store_name and store_key value in the labels.

There is some additional complicated reasoning behind the logic of separating these two populations out, so I'm not going to be simplifying the problem by just consistently doing it one way. I know how to set up the graphs based on each situation, but I'm struggling with the loop that checks for duplicates. How would this be written?

Below was my initial thought, which is not working:

for(client_name in quarter_earnings){
  for(store_name in quarter_earnings){
    if(n_occur$Freq > 1){
      t$lab = store_name, '' store_key
    }
    else{
      t$lab = store_name
    }
  }
}

What am I doing wrong?

Python: Trouble looping through spreadsheet of application data to pull out info that meets parameters

I'm working on a midterm project for my grad class using a situation that I've had to deal with for my job which is sorting through CARES Act rental assistance applications.

My goal is to have applications that meet certain parameters be "sent" to two different departments (in this case I plan on doing TXT reports) and the rest to be filtered out further and sorted into more categories.

Right now I have the first part set as a lot of nested if/elif statements. My issue is that it's only reporting back one application. What do I need to use to have the code run through the entire list and report it all back either in a TXT file or in the shell?

So far I've only been working on the first part that ends at print (listFEA), so the other parts I haven't focused on yet.

I have tried opening a report as well, but didn't include it in this code because it didn't work.

    if caresValues [15] > "0":
        if caresValues [17] != "Yes":
            if caresValues [8] == "0":
                for i in caresValues:
                    listFEA.append(i)
                    print (listFEA)                    
        elif caresValues [18] != "Yes":
            if caresValues [8] != "0":
                print ("Refer to General Emergency Assistance.")
    if caresValues [15] == "0":
        print caresValues
                
else:
    print ("Refer to community provider.")```

Trying to calculate even odd without math operators

w= int(input('enter a num:'))
even= []
for x in range (0, 999999999999999999999999999999999999999999999999, 2):
    even.append(x)
    if w in even:
        print ('the num is even')
        break
else:
    print ('the num is odd')

R: Cross reference vector with list, HELP: append new vector based on positive hits

I have a vector A and a list B of vectors ls1, ls2 and ls3. I aim to combine the vectors in list B that contain one or more of the entries of A into a new vector (new_v).

A <- c("cat", "dog", "bird")
A

B <- list(v1 = c("mike", "fred", "paul"), v2 = c("mouse", "cat", "frog"), v3 = c("bird", "cow", "snake"))
B

new_list <- c()

for(i in names(B)){
  
  v <- A %in% B[[i]]
  print(v)
  
  if (TRUE %in% v){
    
    append(new_v, unlist(B[i])) ## doesn't do what I want
    
  }
}
print(new_v)

The result I was hoping for:

>dput(new_v)
c("mouse", "cat", "frog", "bird", "cow", "snake")

Prevent that people type anything else then [Y or N] [duplicate]

I need to make something that can prevent that people type anything else then [Y or N] (Maby an if statement and a loop)

while(true)
{

//The main program is up here

Console.WriteLine("Do you want to play again? [Y or N]");

string answer = Console.ReadLine().ToUpper();

if (answer == "Y")
{
continue;
}
else if (answer == "N")
{
return;
}

//maybe here

}

Lisp Macro Multiple Tasks

i have a question about lisp macros. I want to check a condition and if it' true to run a few things not only one. The same for the false way. Can anybody please help??

(defmacro test (condition (&rest then) (&rest else))
  `(if ,condition (progn ,@then) (progn ,@else)))

         (test (= 4 3)
            (print "YES") (print "TRUE")
              (print "NO") (print "FALSE"))

What is the problem with my Python if statement? [duplicate]

I can't figure out why my code here will not run. Can someone tell me if my if statement is wrong somehow?

I've tried using " instead of ' But I don't think it's making any difference. Also tried a number of various ways to write this such as if input() == ('Run') or ('run') or if input() == 'run' etc, nothing will work.

decide == input()
if decide == ('Run') or ('run')
    print("Ha, you are a coward.")

How to display multiple dropdown list using javscript with if else statement?

Hi Friends, I am in the beginning stage in javascript, Trying to create a small web application in javascript but, unable to print the drop-down list output Please help me to fix the issue

<html> <body>
<p>SELECT THE STATE: </p>
<select id="select2"> 
<option value="regiona">TAMILNADU</option>
<option value="regionb">ANDHRA PRADESH</option>
</select></p>
<span class="output1"></span>


<p>SELECT THE ROUTER TYPE: 
<select id="select1"> 
<option value="accessa">ASR9K</option>
<option value="accessa">ASR920</option>
</select></p> 
<span class="output"></span>

<button onclick="apply()"> APPLY</button> 

<script type="text/javascript"> 
function apply() { 
selectElement = document.querySelector('#select1','#select2'); 
var output = selectElement.value;
var output1 = selectElement.value;  
document.querySelector('.output','.output1').textContent = output,output1;
if (output === 'accessa' || output1 === 'regiona' ){ document.write('<h1 style ="color: #ff0000;">TAMILNADU</h1>');}

else if (output === 'accessa' || output1 === 'regionb' ){ document.write('<h1 style ="color: #ff0000;">ANDHRA PRADESH</h1>');}

}
</script>

</body> </html> 

Add to a variable each time a radio is checked?

Using only Javascript, I am trying to get 1 to be added to one of my variables (countA countB or countC) each time a radio btn is checked depending of what id a radio btn has. For some reason, my code will not run. What have I done wrong? HTML:

    <input type = "radio" class="a" name="radio" id="1"> 1 <br>
            <input type="radio" class="b" name="radio" id="2"> 2<br>
            <input type="radio" class="c" name="radio" id="3"> 3 <br>
        </div><br>       
            <input type="radio" class="a" name="radio" id="4"> 4<br>
            <input type="radio" class = "b" name="radio" id="5"> 5<br>
            <input type="radio" class="c" name="radio" id="6"> 6<br>
        </div><br>       
            <input type="radio" class="a" name="radio" id="7"> 7 <br>
            <input type="radio" class="b" name="radio" id="8"> 8 <br>
            <input type="radio" class="c" name="radio" id="9"> okay. 9<br>
        </div><br>
            <input type="radio" class="a" name="radio" id="10"> 10<br>
            <input type="radio" class="b" name="radio" id="11"> 11<br>
            <input type="radio" class="c" name="radio" id="12"> 12<br>
        </div><br>       
            <input type="radio" class="a" name="radio" id="13">13<br>
            <input type="radio" class="b" name="radio" id="14"> 14<br>
            <input type="radio" class="c" name="radio" id="15"> 15 <br>
        </div><br>
<p id="testp"></p>

JAVASCRIPT:

 var countA = 0
            var countB = 0
            var countC = 0 
            
            function check() {
                var radios = document.getElementsByTagName("input").length
                var selector = document.getElementsByTagName("input")
                for (var i = 0; i < radios; i++) {
                    if (selector[i].checked) {
                        if (selector[i].getAttribute("id") == 1 || selector[i].getAttribute("id") == 4 || selector[i].getAttribute("id") == 7 || selector[i].getAttribute("id") == 10 ||
                        selector[i].getAttribute("id") == 13) {
                            countA++
                        }
                        if (selector[i].getAttribute("id") == 2 || (selector[i].getAttribute("id") == 5 selector[i].getAttribute("id") == 8 || selector[i].getAttribute("id") == 11 ||
                        selector[i].getAttribute("id") == 14) {
                            countB++
                        }
                        if (selector[i].getAttribute("id") == 3 || selector[i].getAttribute("id") == 6 || selector[i].getAttribute("id") == 9 || selector[i].getAttribute("id") == 12 ||
                        selector[i].getAttribute("id") == 15) {
                            countC++
                            }
                
                                            
                                                }
                document.getElementById("testp").innerHTML = "Count A: " + countA + "Count B: " + countB + "Count C: " + countC
                            }
}

Asking user whether he/she wants to play again but typing yes just repeats this question again rather starting again

It is a number guessing game

Explanation

At first it asks the user to enter a number between 1 to 50 Then if the number is correct then you win else you have to try again (The winning number is random offcourse)You also have limited guesses

The problem is mentioned below the code Here is my code:)

import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:    
    while not number_enter:
        try:
            ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
            print(f"TOTAL GUESSES = {guesses_left}")
            break
        except ValueError:
            print("INVALID INPUT!!")
            continue
    while not game_over: 
        if ask==winning_num:
            print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
            print("DO YOU WANT TO PLAY AGAIN?")
            while True:
                ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
                ask1 = ask1.lower()
                if ask1=='yes':
                    print("YOU CHOSE TO PLAY AGAIN")
                    game_over = False
                    break
                elif ask1=="no":
                    print("THANK YOU FOR PLAYING THIS GAME")
                    game_over = True
                    end_game = True
                    break
                else:
                    print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
                    continue
            

        elif ask>winning_num:
            print("TOO HIGH!!")
            guesses+=1
            guesses_left-=1
            while True:
                try:
                    ask = int(input("TRY AGAIN: "))
                    print(f"GUESSES LEFT = {guesses_left}")
                    break
                except ValueError:
                    print("INVALID INPUT!!")
                    continue
            if guesses_left==1:
                print("ONLY ONE GUESS LEFT!!")
                continue
            elif guesses_left==0:
                print("YOU LOSE!!")
                break
        elif ask<winning_num:
             print("TOO LOW!!")
             guesses+=1
             guesses_left-=1
             while True:
                 try:
                     ask = int(input("TRY AGAIN: "))
                     print(f"GUESSES LEFT = {guesses_left}")
                     break
                 except ValueError:
                     print("INVALID INPUT!!")
                     continue
             if guesses_left==1:
                 print("ONLY ONE GUESS LEFT!!")
                 continue
             elif guesses_left==0:
                 print("YOU LOSE!!")
                 break
                

The problem is when the game ends It asks whether we want to play again But if we type "Yes" it again asks the same "Do you want to play again" However typing "No" works fine and the program ends

Conditional values

I'm having trouble with some data, and I think it's easy to solve. I have a subset like this:

data <- data.frame("treat" = 1:10, "value" = c(12,32,41,0,12,13,11,0,12,0))

And what I need is a third column that returns to me the value "1" when the value on second column is different from 0, and returns "0" when the value on the second column is equal 0. Like this:

data$param <- c(1,1,1,0,1,1,1,0,1,0)

I tried to do this with the function if() and else() but I don't get it.

How to add character before string based on condition

I'm trying to add one or more character before a string if a condition (membership sold) has been met. The example:

Huurders verbijsterd over verduistering 596.00... 3 Horeca-echtpaar Bas en Beaudine over verwoeste... 2 Nieuwe coronabesmettingen in Hillegom: ’Wak... 2 Monsters en demonen komen tot leven op dak Koe... 2 Hoofddorp krijgt een stadspark in het centrum,... 2

What I'm trying to achieve is to add an asterix before each string (headliner), corresponding to the amount of sales. I've tried many variations of code including the one below. df['article_title'] = '*' + df['article_title'] if df[df['Transactions'] == 1] else df['article_title']

Quite frankly: I can't seem to execute this quite simple command. Hopefully this community can help me :)

Swift: switch vs if-else statement to examine a random integer

I'm about to learn the Swift programming language. I just wrote a function that generates a random integer in a range of 0...2. Afterwards the function returns an enum type conditionally.

I'd like to prefer to use the case statement but I don't like the default case which returns an arbitrary enum. Omitting the default case not work since switch is not able to know how much cases will occur. Even though the default case would never happen I don't consider this to be a clean solution.

Which solution would you prefer respectively consider to be the cleanest solution - please elaborate.

If-else solution:

    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        if randomSelection == 0 {
            return .rock
        } else if randomSelection == 1 {
            return .paper
        } else if randomSelection == 2 {
            return .scissor
        }
    }

Switch solution:

    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        switch randomSelection {
        case 0: return .rock
        case 1: return .paper
        case 2: return .scissor
        default: return .rock
        }
    }

Best regards

If Radio box is selected, switch between two clicking methods

So i have this code here, and it quite literally doesn't work and i just don't know why. It doesn't click, doesn't print out anything. My goal is to make the buttons function as switches between two methods of clicking. Right mouse button clicks, and Left mouse button clicks. Can anyone tell me why this doesn't function?

if (rbRightClickRadioButton.isSelected()) {
            System.out.println("RMB Clicker");

            Robot clicker = null;
            try {
                clicker = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
            clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
            clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);

            Thread.sleep(delay);

            try {
                clicker = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
            clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
            clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);

        } else if (rbRightClickRadioButton.isSelected()) {
            System.out.println("LMB Clicker");

            Robot clicker = null;
            try {
                clicker = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
            clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
            clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);

            Thread.sleep(delay);

            try {
                clicker = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
            clicker.mousePress(InputEvent.BUTTON2_DOWN_MASK);
            clicker.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);

Java is asking to return a value even when the value is returned in the if-else ladder

I was trying to code AVL tree in java and something has just shaken my understanding of basic programming. Why does Java force me to return a value when I already have a return statement in the else block of the if-else ladder. I tried debugging and it works as expected, it never goes to the returns statement outside the if-else blocks. I have been working on java and never realized this. I am not even sure if this was always there or is it something new? I also read a few blogs which say that you don't have to return a value if you have returned it from the else block.

The error which I get is I skip the last return statement.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    This method must return a result of type AVLNode

https://javahungry.blogspot.com/2019/12/missing-return-statement-in-java.html checkout the last example on this link.

public class AVL 
{
    AVLNode root;
    
    private AVLNode insert ( AVLNode current,int val)
    {
        if ( current == null)
        {
            return new AVLNode(val, 0, null, null);
        }
        else if ( val < current.val)
        {
            current.left = insert ( current.left, val);
        }
        else if ( val > current.val)
        {
            current.right = insert ( current.right, val);
        }
        else
        {
            return current;
        }
        return current;     // I don't want to return you ////      
    }


public void  add ( int val)
    {
        this.root = insert ( this.root, val);
    }

Sharepoint workflow if else statement not working

My if else statement not working.. No matter i choose approved or rejected. it will flow to Execution stage. Any ideas?

enter image description here

Why second ifelse not evaluated in R and why if else does not vectorize?

Consider the following df:

structure(list(GID7173723 = c("A", "T", "G", "A", "G"), GID4878677 = c("G", 
"C", "G", "A", "G"), GID88208 = c("A", "T", "G", "A", "G"), GID346403 = c("A", 
"T", "G", "A", "G"), GID268825 = c("G", "C", "G", "A", "G")), row.names = c(NA, 
5L), class = "data.frame")

Here is how it looks:

  GID7173723 GID4878677 GID88208 GID346403 GID268825
1          A          G        A         A         G
2          T          C        T         T         C
3          G          G        G         G         G
4          A          A        A         A         A
5          G          G        G         G         G

Now consider two vectors:

ref <- c("A", "T", "G", "A", "G")
alt <- c("G", "C", "T", "C", "A")

And the function:

f = function(x){
  ifelse(x==ref,2,x)
  ifelse(x==alt,0,x)
}

When I run sapply just the second ifelse evaluates:

sapply(dfn,f)

     GID7173723 GID4878677 GID88208 GID346403 GID268825
[1,] "A"        "0"        "A"      "A"       "0"      
[2,] "T"        "0"        "T"      "T"       "0"      
[3,] "G"        "G"        "G"      "G"       "G"      
[4,] "A"        "A"        "A"      "A"       "A"      
[5,] "G"        "G"        "G"      "G"       "G"    

If I run something like that:

f = function(x){
  if (x==ref) {return(2)
    
  }
  else if (x==alt) {return(0)
    
  }
  else {
    return(x)
  }
} 

I get the warning message:

sapply(dfn,f)

Warning messages:
1: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
2: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
3: In if (x == alt) { :
  the condition has length > 1 and only the first element will be used
4: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
5: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
6: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
7: In if (x == alt) { :
  the condition has length > 1 and only the first element will be used

I believe the latter function is due to the nature of if else to not vectorize. I really would like to solve this problem without using neither for loops nor sweep but only with if else statements followed by the apply family functions.

jeudi 30 juillet 2020

Total paid amount repeating in every row CodeIgniter

The total paid amount for particular fees type is repeating for every row, need a solution to overcome from this logic.please refer image below
Controller -

public function issueAdvance($company_id){
        if($this->session->userdata("is_active") == 1){

          $seedIssue =$this->seed_issue_model->selectFarmer($company_id);
          $singlefarmer =$this->seed_issue_model->selectIssueDates($company_id);
          $crops = $this->seed_issue_model->get_crop_data(); //Crop
          $pc_code = $this->seed_issue_model->get_pc_data(); //Production-Code
          $advance_amount =$this->advance_model->getLoanData($company_id);
          $paid_installments = $this->advance_model->paidInstallments($company_id);
         // echo '<pre>'; print_r($paid_installments); echo ("</pre>"); exit();
          if ($this->input->server('REQUEST_METHOD') == "GET") {
                $data = array(
                  "page_content" => "advance/view_advance_issue",
                  "singleFarmer" =>$singlefarmer,
                  "issueSeed"  =>$seedIssue,
                  "crop_result" =>$crops,
                  "pc_result" =>$pc_code,
                  "farmer_loan" =>$advance_amount,
                   "paid_installments" =>$paid_installments
                );
                $this->load->view("layout/main_layout",$data);
            }
            else{
            }
        }
    }

Model -

public function getLoanData($company_id){
      $query = 
       $this->db->select(
                        'a1.farmer_id,b1.advance_id,b1.balance_id,a1.amount,a1.check_no,a1.given_date,a1.due_date,b1.reason,b1.season,b1.mode,b1.balance')
        ->from('tbl_advance as a1')
        ->join('tbl_balance as b1', 'b1.advance_id=a1.advance_id')
        ->where("a1.farmer_id", $company_id)
        ->order_by('a1.given_date', 'desc')
        ->get();
        $result = $query->result();
        
        return $result;
    }
    
    
    public function paidInstallments($company_id){
            $query = 
                $this->db->select('a1.farmer_id,b1.advance_id,b1.balance_id,a1.amount,a1.check_no,a1.given_date,a1.due_date,b1.reason,b1.season,b1.mode,b1.balance,p1.amount_paid,p1.amount_discount,p1.paying_date,p1.payment_id,p1.payment_mode,p1.description,p1.balance_id')
                ->from('tbl_pay_amount as p1')
                ->join('tbl_balance as b1', 'p1.balance_id=b1.balance_id')
                ->join('tbl_advance as a1', 'b1.advance_id=a1.advance_id') 
                ->where("a1.farmer_id", $company_id)
                ->get();
                $result = $query->result();
                return $result;
        }

View Part -

<tbody>
                                    <?php
                                        $total_amount = 0;
                                        $total_discount_amount = 0;
                                        $total_balance_amount = 0;
                                        $total_paid_amount = 0;
                                        
                                        foreach ($farmer_loan as $key => $balance) {
                                            $discount_amount = 0;
                                            $paid_amount = 0;
                                            $total_amount = $total_amount + $balance->amount;
                                    }
                                       foreach ($paid_installments as $key => $kvalue) {
                                            if($kvalue->advance_id == $balance->advance_id )
                                                        continue;
                                                $discount_amount = $discount_amount + $kvalue->amount_discount;
                                                $paid_amount = $paid_amount + $kvalue->amount_paid;
                                        }
                                        foreach ($farmer_loan as $index => $value) {
                                    ?>

                                    <?php
                                            $balance_amount = $value->balance;
                                            $total_balance_amount = $total_balance_amount + $balance_amount;
                                            $total_discount_amount = $total_discount_amount + $discount_amount;
                                            $total_paid_amount = $total_paid_amount + $paid_amount;

                                            if ($balance_amount > 0) {
                                    ?>
                                            <tr class="danger font12">
                                        <?php
                                            } else {
                                        ?>
                                            <tr class="dark-gray">
                                        <?php
                                            }
                                        ?>
                                        <td><input class="checkbox" type="checkbox" name="fee_checkbox"
                                                data-advance_id="<?php echo $value->advance_id ?>"
                                                data-balance_id="<?php echo $value->balance_id ?>"
                                                data-farmer_id="<?php echo $value->farmer_id ?>"></td>
                                        <td><?php echo $value->check_no ?></td>
                                        <td><?php echo $value->amount ?></td>
                                        <td><?php echo $value->reason ?></td>
                                        <td><?php echo $value->season ?></td>
                                        <td> </td>
                                        <td></td>
                                        <td align="left" class="text text-left width85">
                                            <?php
                                                if ($balance_amount == 0) { ?>
                                                    <span class="label label-success">Paid</span>
                                                <?php
                                                    } else if (((int)$value->balance)==(int)($value->amount)) { ?>
                                                <span class="label label-danger">Unpaid</span>
                                                <?php
                                                    } else { ?>
                                                <span class="label label-warning">Partial</span>
                                                <?php
                                                    } ?>
                                         </td>

                                        <td></td>
                                        <td><?php echo $value->due_date ?></td>
                                        <td class="text text-center">
                                            <?php echo (number_format($discount_amount, 2, '.', '')); ?></td>
                                        <td class="text text-center">
                                            <?php echo (number_format($paid_amount, 2, '.', '')); ?></td>
                                        <td class="text text-right">
                                            <?php $display_none = "ss-none";
                                                if ($balance_amount > 0) {
                                                    $display_none = "";
                                                    echo (number_format($balance_amount, 2, '.', ''));
                                                }
                                                ?>
                                        </td>   
                                        <td><?php echo $value->given_date ?></td>

                                        <td>
                                            <div class="btn-group pull-right amount">
                                                <?php if ($paid_amount != $value->balance ){ ?>
                                                    <button type="button"
                                                    data-advance_id="<?php echo $value->advance_id; ?>"
                                                    data-balance_id="<?php echo $value->balance_id; ?>"
                                                    data-farmer_id="<?php echo $value->farmer_id; ?>"
                                                    data.title="Collect Amount"
                                                    class="btn btn-xs btn-default myCollectFeeBtn <?php echo $display_none; ?>"
                                                     data-toggle="modal"
                                                    data-target="#myFeesModal">
                                                    <i class="fa fa-plus"></i></button>
                                                <?php if($paid_amount == 0.00){ ?>
                                                    <button type="button"
                                                    data-advance_id="<?php echo $value->advance_id; ?>"
                                                    data-balance_id="<?php echo $value->balance_id; ?>"
                                                    data-farmer_id="<?php echo $value->farmer_id; ?>"
                                                    class="btn btn-xs btn-default myCollectFeeBtn <?php echo $display_none; ?>"
                                                    title="Edit Row" data-toggle="modal" data-target="#myFeeModal">
                                                    <i class="fa fa-pencil"></i></button>
                                                    <button class="btn btn-xs btn-default"
                                                    data-advance_id="<?php echo $value->advance_id; ?>"
                                                    data-balance_id="<?php echo $value->balance_id; ?>"
                                                    data-farmer_id="<?php echo $value->farmer_id; ?>"
                                                    title="Delete Row">
                                                    <i class="fa fa-remove"></i> </button>
                                                <?php 
                                                }
                                                ?>
                                                <?php
                                                    } else { ?>
                                                        <button class="btn btn-xs btn-default"
                                                    data-advance_id="<?php echo $value->advance_id; ?>"
                                                    data-balance_id="<?php echo $value->balance_id; ?>"
                                                    data-farmer_id="<?php echo $value->farmer_id; ?>"
                                                    title="Print Row">
                                                    <i class="fa fa-print"></i> </button>
                                                <?php
                                                    }
                                                ?>
                                            </div>
                                        </td>

                                    </tr>
                                         
                                    <?php
                                                foreach ($paid_installments as $index => $pvalue) {

                                                    if($value->advance_id != $pvalue->advance_id )
                                                        continue;
                                                    ?>

                                                        <tr class="white-td" id="">
                                                            <td align="left"></td>
                                                            <td align="left"></td>
                                                            <td align="left"></td>
                                                            <td align="left"></td>
                                                            <td align="left"></td>
                                                            <td class="text text-left">
                                                                <a href="#" data-toggle="popover" class="detail_popover" > <?php echo $pvalue->payment_id; ?></a>
                                                                <div class="fee_detail_popover" style="display: none">
                                                                    <?php
                                                                    if ($pvalue->description == "") {
                                                                        ?>
                                                                        <p class="text text-danger">No Description</p>
                                                                        <?php
                                                                    } else {
                                                                        ?>
                                                                        <p class="text text-info"><?php echo $pvalue->description; ?></p>
                                                                        <?php
                                                                    }
                                                                    ?>
                                                                </div>
                                                            </td>
                                                            <td class="text text-left"><?php echo $pvalue->paying_date; ?>
                                                            </td>
                                                            <td></td>
                                                            <td class="text text-left"><?php echo $pvalue->payment_mode; ?></td>
                                                            <td></td>

                                                            <td class="text text-right"><?php echo (number_format($pvalue->amount_discount, 2, '.', '')); ?></td>
                                                            
                                                            <td class="text text-right"><?php echo (number_format($pvalue->amount_paid, 2, '.', '')); ?></td>
                                                            <td></td>
                                                            <td></td>
                                                            <td class="text text-right">
                                                            <div class="btn-group pull-right">

                                                                <button class="btn btn-xs btn-default printInv"
                                                                data-advance_id="<?php echo $pvalue->advance_id; ?>"
                                                                data-balance_id="<?php echo $pvalue->balance_id; ?>"
                                                                data-farmer_id="<?php echo $pvalue->farmer_id; ?>"
                                                                title="Print Invoice">
                                                                <i class="fa fa-print"></i> </button>
                                                            </div>
                                                        </td>
                                                    </tr>     
                                                <?php
                                                    }
                                                ?>
                                    <?php
                                        }
                                    ?>

When amount to be paid for a particular fees type, the paid amount repeating in every other unpaid rows,it need to be update in only paid row, thanks in advance.example image

Multiple logical operaters doesn't support [closed]

How to get alternative for the following code

If( condition && condition || condition && condition)
{


}

.equals Method is not working in if Condition

App does not showing the chatting messages in the physical device when i replace if condition in onDataChanged() method when ever i remove the if condtion in onDataChanged messages are showing but the message is sent to all user not a perticular user

Please do somthing bro i need your help

THIS IS LOGCAT ERROR

2020-07-31 07:58:07.077 26146-26201/com.example.dotchat E/ActivityThread: Failed to find provider info for cn.teddymobile.free.anteater.den.provider
2020-07-31 07:58:07.721 26146-26193/com.example.dotchat E/Parcel: Reading a NULL string not supported here.
2020-07-31 07:58:08.593 26146-26146/com.example.dotchat E/Parcel: Reading a NULL string not supported here.
2020-07-31 07:58:11.863 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:11.864 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:18.571 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:18.571 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:18.787 26146-26146/com.example.dotchat E/Parcel: Reading a NULL string not supported here.
2020-07-31 07:58:19.943 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:19.943 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout
2020-07-31 07:58:24.037 26146-26146/com.example.dotchat E/RecyclerView: No adapter attached; skipping layout

THIS IS MessageActivity.JAVA FILE

package com.example.dotchat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dotchat.Adapter.MessageAdapter;
import com.example.dotchat.Model.Chat;
import com.example.dotchat.Model.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;

public class MessageActivity extends AppCompatActivity {

    CircleImageView profile_image;
    TextView username;
    DatabaseReference reference;

    ImageButton btn_send;
    EditText text_send;

    MessageAdapter messageAdapter;
    List<Chat> mchat;

    RecyclerView recyclerView;

    FirebaseUser fuser;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        recyclerView =findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getApplicationContext());
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);

        profile_image=findViewById(R.id.profile_image);
        username=findViewById(R.id.username);
        btn_send=findViewById(R.id.btn_send);
        text_send=findViewById(R.id.text_send);

        intent=getIntent();
        final String userid=intent.getStringExtra("userid");
        fuser= FirebaseAuth.getInstance().getCurrentUser();

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg=text_send.getText().toString();
                if(!msg.equals("")){
                    sendMessage(fuser.getUid(),userid,msg);
                } else {
                    Toast.makeText(MessageActivity.this,"You can't send Empty message",Toast.LENGTH_SHORT).show();
                }
                text_send.setText("");
            }
        });

        assert userid != null;
        reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user=dataSnapshot.getValue(User.class);
                assert user != null;
                username.setText(user.getUsername());
                profile_image.setImageResource(R.mipmap.ic_launcher);

                readMesagges(fuser.getUid(),userid,user.getImageURl());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

    private void sendMessage(String sender,String receiver,String message){

        DatabaseReference reference=FirebaseDatabase.getInstance().getReference();
        HashMap<String, Object> hashMap =new HashMap<>();
        hashMap.put("sender",sender);
        hashMap.put("recever",receiver);
        hashMap.put("message",message);

        reference.child("Chats").push().setValue(hashMap);

    }

    private void readMesagges(final String  myid, final String userid, final String imageurl){
        mchat=new ArrayList<>();

        reference=FirebaseDatabase.getInstance().getReference("Chats");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mchat.clear();
                for (DataSnapshot snapshot:dataSnapshot.getChildren()){
                    Chat chat=snapshot.getValue(Chat.class);
                    assert chat != null;
                    if(myid.equals(chat.getReceiver()) && userid.equals(chat.getSender()) ||
                            userid.equals(chat.getReceiver()) && myid.equals(chat.getSender())){
                        mchat.add(chat);

                    }

                    messageAdapter =new MessageAdapter(MessageActivity.this,mchat,imageurl);
                    recyclerView.setAdapter(messageAdapter);


                }


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

IN THIS METHOD IF CONDITION IS NOT WORKING(messages are not Showing in the physical device) WHEN EVER I REMOVE THE IF CONDITON NO ERROR SHOWING BUT MESSAGE WILL GOING TO ALL USERS NOT SELCTED RECEIVER

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mchat.clear();
                for (DataSnapshot snapshot:dataSnapshot.getChildren()){
                    Chat chat=snapshot.getValue(Chat.class);
                    assert chat != null;
                    if(myid.equals(chat.getReceiver()) && userid.equals(chat.getSender()) ||
                            userid.equals(chat.getReceiver()) && myid.equals(chat.getSender())){
                        mchat.add(chat);

                    }

                    messageAdapter =new MessageAdapter(MessageActivity.this,mchat,imageurl);
                    recyclerView.setAdapter(messageAdapter);


                }


            }

THIS IS Chat.java file

package com.example.dotchat.Model;

public class Chat {

    private String sender;
    private String receiver;
    private String message;

    public Chat(String sender, String receiver, String message) {
        this.sender = sender;
        this.receiver = receiver;
        this.message = message;
    }

    public Chat() {
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Mapbox multiple If statement in a Var

I'm trying to change Mapbox marker colors according to a column tag. I have 3 separate columns Apple, Banana, and Orange I would like to associate that tag with a different marker color. This is my code so far. As of now, no markers show on the map.

var marker = new mapboxgl.Marker;({
          if (row["Apple"]) {
            color: 'blue';
          }
          else if (row["Banana"]) { 
            color: 'orange';
          }
          else (row["Orange"]) {
          color: 'yellow';
        }
        })

Concatenate results from 2 or more conditions - Tableau

I'm developing a dashboard in Tableau but I have an issue which I don't know how to solve it. I need your help :D

My objective is to have a better visualization because we are working in a customer and contacts datacleansing and I need to validate each record of the database, I mean, some fields doesn't have to have special character like "! # $ % & /"

Previousy I created some calculated fields like these in order to validate if the mailing street address has or not the special character

[z Mailing Street !] = IF CONTAINS(MailingStreetField, '|' ) THEN 1 ELSE 0 END
[z Mailing Street #] = IF CONTAINS(MailingStreetField, '#' ) THEN 1 ELSE 0 END
[z Mailing Street $] = IF CONTAINS(MailingStreetField, '$' ) THEN 1 ELSE 0 END
[z Mailing Street %] = IF CONTAINS(MailingStreetField, '|' ) THEN 1 ELSE 0 END

After I created all the fields, I want to have something like this

|Mailing street contains $ + = >| 

So I created a new calculated field:

IF [z Mailing Street empty] = 1 THEN '|Mailing street vacío|' 
  ELSEIF [z Mailing Street] > 0 THEN
  '|Mailing street contains ' +
  IF [z Mailing Street !] = 1 THEN '! ' END +
  IF [z Mailing Street #] = 1 THEN '# ' END +
  IF [z Mailing Street $] = 1 THEN '$ ' END +
  IF [z Mailing Street %] = 1 THEN '% ' END +
  IF [z Mailing Street &] = 1 THEN '& ' END +
  IF [z Mailing Street (] = 1 THEN '( ' END +
  IF [z Mailing Street )] = 1 THEN ') ' END +
  IF [z Mailing Street ?] = 1 THEN '? ' END +
  IF [z Mailing Street @] = 1 THEN '@ ' END +
  IF [z Mailing Street \] = 1 THEN '\ ' END +
  IF [z Mailing Street £] = 1 THEN '£ ' END +
  IF [z Mailing Street €] = 1 THEN '€ ' END +
  IF [z Mailing Street +] = 1 THEN '+ ' END +
  IF [z Mailing Street <] = 1 THEN '< ' END +
  IF [z Mailing Street =] = 1 THEN '= ' END +
  IF [z Mailing Street >] = 1 THEN '> ' END +
  '|'
END

But at the end I got the result only if all the conditions are true, I mean, Tableau evaluates the sentences like this:

IF 
  Condition = True AND 
  Condition2 = True AND 
  Condition3= True 
  THEN Result 
END

Any feedback will be realy appreciated.

Thanks

Speed considerations of if/else statements in for loops

Are there any differences in the general compute time in the following two scenarios? I remember learning in school that you should have the if statement run more often than the else statement (if possible), but wasn't really given any reasoning as to why this would be the case.

Lets say for both situations, condition is more likely than not to be true (for example, condition is true 75% and false 25% of the time).

Scenario 1:

for(int i=0; i<10000; ++i) {
    if(condition) {
        //do something
    } else {
        //do something else
    }
}

Scenario 2:

for(int i=0; i<10000; ++i) {
    if(!condition) {
        //do something else
    } else {
        //do something
    }
}

I guess the question boils down to, are there any speed differences between checking the if condition, running the do something code, and then branching to the end of the if/else statement compared to branching at the beginning and then running the do something code?

Count the number of successively fulfilled conditions in Spreadsheet

Please help me to count the number of successively fulfilled conditions.

I have a table with different metrics and their values per month. I also have a target value and condition per each metric:

Metric  Month   Target  Value   Expected Result
Metric1 Jan18   3.00%   2.00%   1
Metric1 Feb18   3.00%   2.50%   2
Metric1 Mar18   3.00%   2.30%   3
Metric1 Apr18   3.00%   3.50%   0
Metric1 May18   3.00%   3.40%   0
Metric1 Jun18   3.00%   2.00%   1
Metric2 Jan18   90.00%  95.00%  1
Metric2 Feb18   90.00%  93.00%  2
Metric2 Mar18   90.00%  80.00%  0
Metric2 Apr18   90.00%  91.00%  1
Metric2 May18   90.00%  92.00%  2
Metric2 Jun18   90.00%  93.00%  3

I need to count the number of months the condition is continuously met. E.G. Metric 1 should be less than 3%, and metric 2 should be more than 90%. Please see the expected result in the table.

What is the best way to ask a string prompt into a number? [duplicate]

What I was able to find while looking through stackoverflow was that this is the best way to prompt a string and turn it into a number. Is this the best way? Thank you!

var age = prompt("Please enter your age:");
if (Number(age) < 18) {
  alert("");
}

ASP.NET MVC : change namespace in web.config under certain conditions?

I have in the main web.config file under the

<system.web.webPages.razor>

a line that calls for a particular resource

<add namespcae="***.resources.male"/>

Now I want to change this line to

<add namespcae="***.resources.female"/>

only if the user is identified as female.

It is possible to check whether the user is male or female through a condition in the web.config file?

(jquery) Defining website position in relate to elements on the page using window.pageYOffset. "If" statements does not work, why and how to fix it?

I'm trying to define position of window in relate to div's in my page so I'll be able to add & remove classes from menu items during scroll when window will enter certain position.

But first I have a simple question, well maybe more than one simple question ;). Why when I write if( /* smth */ > var1 + var2) adding two variables this way does not apply? Why does statement var fromTop = window.pageYOffset + var1; does not work, while var1 is outerHeight() of element?

Now to the the topic of question:

My jquery code looks like this:

   <script type="text/javascript">
        $(document).ready(function() {
           var headerheight = $("#main_header_div").outerHeight();
           var mainpageheight = $("#Strona_glowna").outerHeight();
           var offerheight = $("#Oferta").outerHeight();
           var aboutheight = $("#O_nas").outerHeight();
          
          
            $(window).scroll(function () {
            var fromTop = window.pageYOffset + 90;
             
              
              if(fromTop < mainpageheight ){
              alert("mainpage");
              } else if((fromTop > mainpageheight)&&(fromTop =< mainpageheight + offerheight)) {
              alert("offer");
              } else if((fromTop > mainpageheight + offerheight)&&(fromTop =< mainpageheight + 
              offerheight + aboutheight)) {
              alert("about");
              }
             
            });
        });
      
      
      
      </script>

I added these alerts becouse I didin't want to mess with adding/removing classes and css until this basic scrypt works.

So as you see the script should cause a popup alert when the window is in certain position but it doesn't, why and how to fix it?

for loop for finding prime numbers in python [duplicate]

I'm new to python. I have a medium level background in c++. I was using the official documentation to learn python and came across this example which prints the prime numbers. Here is the example I'm talking about -

data = list(range(2,10))

for item in data :
    for div in range(2,item) :
        if item % div == 0 :                 /*  
            print(item, "not a prime")           not the same if-else statement
            break
    else :                                       
        print(item, "prime")                 */

here is where I'm confused- As far as I know, you can only have a matching if-else statement in c++. But in this case if-else statements are different as if statement is under for div in range(2,item) and else statement is under for item in data.

any help is appreciated. Thanks

if else statement python using plot parameters in function

I have an if else statement in my function that is not wokring the way i want it to. Mind you I am still learning python and all things programming.

I have a function to define a plot. Idea is to create a large python repo for data analysis.

def plots_timeseries(time=[],cond=[], depth=[], temp=[]):
    #-----------
    # CONDUCTIVITY PLOT
    #-----------
    if cond == []:
        print('there is no cond value')
        pass
    else:
        fig, ax1 = plt.subplots(1)
        plt.scatter(time,depth,s=15,c=cond)
        plt.show()

The idea here is that if there is no data in the cond value, do pass to not show the plot. However ever time I run this, the plot shows, even thought there is no data for it.

When i call the function i put in plot_timeseries(time=time_data, depth=depth_data temp=temp_data)

my aim is for only the temp data in this example to show, not a cond graph with no variables.

what i have tried is

if cond != []:
        plotting code
        plt.show()
else:
        print('there is no cond data')
        pass

and

plotting code
if cond == []:
    print('no cond data')
    pass
else:
    plt.show()

to no avail.

note that there are 4 other plots in this function i would like to do the same thing. thanks for any insight this community can give me.

Using Strings in switch case [duplicate]

Can anyone explain

Java compiler generates more efficient byte code for String in switch statement than chained if-else-if statements

What does this mean?

It is written in Java Documentation.

chosing a function without if statement in python

Imagine having 200 functions, which represent 200 ways to solve a problem or calculate something like

def A():
   ...
   
def B():
   ...
.
.
.

and the method will be chosen as an input argument, meaning the user decides which method to use, giving this as an argument while running the program like "A" for function/method A. how to chose that function without if-checking the name of every single function in python.

Mutating a variable depending on year using r

I am trying to standardized a variable by a national average depending on the year to create a new variable that is a Z score. Here is an example dataset:

 DF:
 Var1   Var2
 240     2015
 210     2018
 206     2016
 248     2017
 235     2019
----etc

I am using the following code:

DF$NewZScore<- if (DF$Var2== "2015"){
  (DF$Var1 - 229)/20
} else if (DF$Var2== "2016"){
  ((DF$Var1 - 228)/21
  } else if (DF$Var2== "2017"){
  ((DF$Var1 - 229)/20
    } else if (DF$Var2== "2018"){
  ((DF$Var1 - 230)/19
  } else if (DF$Var2== "2019"){
  ((DF$Var1 - 231)/19
} else {
  + 1000
}

The years 2015 through 2019 are the years I am wanting, there are a few other years which I will filter out after (thus, the + 1000). This code is mutating Var1 by the 2015 criteria rather than mutating the variable by the year in Var2. Any help is appreciated!

else if condition not utilised properly with other if statements -JS

l have an issue with a else if or if statement in my code, whereby it does not do it's intended function. The intended function is that it should display "Ran out of lives" and then end. l have tried different ways of sorting the if statement but with no success, it always 'skipped it'.

This is a snippet of my code.

var now = new Date();

now.setSeconds(now.getSeconds() + 30);
alert(now)
for (lives = 0; lives < 3; lives++) {

  var guess = prompt("_ _ _");

  var currenttime = new Date();

  if (guess.toUpperCase() === "BOO" && currenttime < now) {
    alert("Right");
    break;
  } else if (guess.toUpperCase() === "HINT" && currenttime < now) {
    alert("Online or offline entertainment.");
  } else if (currenttime >= now) {
    alert("now ended \nGame over");
    lives = 3;
    break;
  } else if (lives >= 3) {
    alert("Ran out of lives")
  } else {
    alert("Wrong");
  }
}

How match two columns of different data table?

I have two data frames that I would like to match similar columns in both data frames and extract the value of another column in one of the data tables.

I have tried the below code but it doesn`t work:

Code:

output <- if (Data_1$Var1 %in% Data_2$Coor) {
      Data_2$binID
      } else if (Data_1$Var2 %in% Data_2$Coor) {
        Data_2$ID
      } else {NA}

Data_1:

                  Var1                    Var2       value
 chr22:17400000-17410000 chr22:16080000-16090000  139.939677
 chr22:17400000-17410000 chr22:26080000-26090000  256.945265
 chr22:33470000-33480000 chr22:16080000-16090000  134.432441

Data_2:

                    coor  ID
 chr22:17400000-17410000  1
 chr22:33470000-33480000  2
 chr22:16080000-16090000  3
 chr22:26080000-26090000  4

Output:

                     ID1                    ID2       value
                       1                      3   139.939677
                       1                      4   256.945265
                       2                      3   134.432441

Is the if-statement with a const condition optimized inside a for loop (c++)

Consider the following code:

void func(int a, size_t n)
{
  const bool cond = (a==2);
  if (cond){
    for (size_t i=0; i<n; i++){
      // do something small 1
      // continue by doing something else.
    }
  } else {
    for (size_t i=0; i<n; i++){
      // do something small 2
      // continue by doing something else.
    }
  }
}

In this code the // continue by doing something else. (which might be a large part and for some reason cannot be separated into a function) is repeated exactly the same. To avoid this repetition one can write:

void func(int a, size_t n)
{
  const bool cond = (a==2);
  for (size_t i=0; i<n; i++){
    if (cond){
      // do something small 1
    } else {
      // do something small 2
    }
    // continue by doing something else.
  }
}

Now we have an if-statement inside a (let's say very large) for-loop. But the condition of the if-statement (cond) is const and will not change. Would the compiler somehow optimize the code (like change it to the initial implementation)? Any tips? Thanks.

React function enter twice in if condition inside Map function

my function handleAddPoint receive data like this:

data = {colorid,counter}

I call this function from child component called "Qualificatif" who just push data based on a onChange event from a Select input.

Each time i change the value from my select input, the map function inside the function called handleAddPoint go twice in the if condition.

Can you help me ?

Here is the code:

export default class Questionnaire extends Component {

constructor(props){
    super(props)

    this.state ={
        colors:[
            {
                id:1,
                color:"yellow",
                point:0
            },
            {
                id:2,
                color:"green",
                point:0
            },
            {
                id:3,
                color:"red",
                point:0
            },
            {
                id:4,
                color:"blue",
                point:0
            },
        ],
    }

    this.handleAddPoint = this.handleAddPoint.bind(this)
}

handleAddPoint = (data) =>{
    console.log("Data questionnaire",data)
    this.setState(state => {
        state.colors.map(color => 
            {if(color.id === data.colorid)
                color.point += data.counter
                return color
            })
    })
    console.log("couleurs questionnaire",this.state.colors)
}

render() {
    return (
        <div className="questionnaire">
            <Qualificatif data={Q1data} handleaddpoint={this.handleAddPoint}/>
            <Qualificatif data={Q2data} handleaddpoint={this.handleAddPoint}/>
            <Classement data={Q3data} handleaddpoint={this.handleAddPoint}/>
            <Result data={this.state.colors}/>
        </div>
    )
}

}

mercredi 29 juillet 2020

Returning NoneType from If Else - Cant determine why

I'm brand new to coding (and stack overflow) and just starting out so I apologise for the really basic question.

I am struggling to figure out why this if-else block isn't working.

The determine_cost function is returning a NoneType when it should be returning a float and I believe it has something to do with the shipping_method variable, but even with intensive googling, I can't seem to find a solution or why it's returning that.

I have tried calling the function without using the input lines and it seems to work okay, which indicates that it could have something to do with the input, but I can't figure what I'm doing wrong.

Any help would be appreciated.

def ground_shipping(weight):
    flat_charge = 20.00
    if weight > 10:
        ppp = 4.75
    elif weight > 6:
        ppp = 4.00
    elif weight > 2:
        ppp = 3.00
    else:
        ppp = 1.50
    return flat_charge + ppp


def prem_ground_shipping(weight):
    return 125.00


def drone_shipping(weight):
    if weight > 10:
        ppp = 14.25
    elif weight > 6:
        ppp = 12.00
    elif weight > 2:
        ppp = 9.00
    else:
        ppp = 4.50
    return ppp


def determine_cost(shipping_method, weight):
    if 1 == shipping_method:
        cost = ground_shipping(weight)
        return cost
    elif 2 == shipping_method:
        cost = prem_ground_shipping(weight)
        return cost
    elif 3 == shipping_method:
        cost = drone_shipping(weight)
        return cost


weight = input("Welcome to Sals Shipping! This calculator will help us determine how much your shipping will "
               "cost. To begin, how much does your item weigh in kg?\n")
shipping_method = input('Thanks! Next, what method of delivery best suits you? Enter 1 for our Ground Shipping '
                        'option. 2 for our Premium Ground shipping. Or 3 for our new Drone Shipping option.\n')
cost = determine_cost(shipping_method, weight)
print("Your item will cost: $" + str(cost))

confuse replacing with React Hooks React Native

I was trying to make async await with if condition with React Hooks. This code below is before I was trying to made it become React Hooks:

async startService() {
        if (Platform.OS !== 'android') {
            console.log('Only Android platform is supported');
            return;
        }
        if (Platform.Version >= 26) {
            const channelConfig = {
                id: 'ForegroundServiceChannel',
                name: 'Notification Channel',
                description: 'Notification Channel for Foreground Service',
                enableVibration: true,
                importance: 2
            };
            await VIForegroundService.createNotificationChannel(channelConfig);
        }
    }

and I was trying to make it into React Hooks

 useEffect(() => {
    async function startService() {
      if (Platform.OS !== 'android') {
          console.log('Only Android platform is supported');
          return;
      }
      if (Platform.Version >= 26) {
          const channelConfig = {
              id: 'ForegroundServiceChannel',
              name: 'Notification Channel',
              description: 'Notification Channel for Foreground Service',
              enableVibration: false,
              importance: 2
          };
          await VIForegroundService.createNotificationChannel(channelConfig);
      }
      const notificationConfig = {
          id: 3456,
          title: 'Foreground Service',
          text: 'Foreground service is running',
          icon: 'ic_notification',
          priority: 0
      };
      if (Platform.Version >= 26) {
          notificationConfig.channelId = 'ForegroundServiceChannel';
      }
      await VIForegroundService.startService(notificationConfig);
  }startService();
  }, []);

and I was also trying to call it inside my jsx like this:

<Button onPress={() => this.startService()}>
      <Text>Tes</Text>
 </Button>

and it did not working, did I write it wrong?

How to code: "If (A is True) and (B is True when C is True)"

How do I code this if statement (let's say in c++):

if (condition1 == true and condition2 == true (when condition3 == true))
{
    // condition2 need to be true only when condition3 is true
}

Creating column using ifelse in R [duplicate]

I'm a little stuck with creating a new Layer column in the dataset below:

> head(Sites.merge)
     Echo_ID                 Layer Interval Lat_M         Lon_M          Target_depth_mean Depth_mean ADens
[1,] "20180919_PS-1105_BN_1" "0"   "14"     "26.28209994" "-97.04343251" "0"               " "        "0"  
[2,] "20180919_PS-1105_BN_1" "0"   "15"     "26.28205407" "-97.04343251" "0"               " "        "0"  
[3,] "20180919_PS-1105_BN_1" "0"   "16"     "26.2820098"  "-97.04343558" "0"               " "        "0"  
[4,] "20180919_PS-1105_BN_1" "0"   "17"     "26.28196587" "-97.04344517" "0"               " "        "0"  
[5,] "20180919_PS-1105_BN_1" "0"   "18"     "26.28192194" "-97.04346068" "0"               " "        "0"  
[6,] "20180919_PS-1105_BN_1" "0"   "19"     "26.28187837" "-97.04346667" "0"               " "        "0"  
 Echo_ID_Layer                   numID sum                Echo_max_depth_m S_type       DepthZone  
[1,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
[2,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
[3,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
[4,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
[5,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
[6,] "20180919_PS-1105_BN_1_Layer_0" "1"   "13.4396280406658" "16.79"          "Artificial" "Nearshore"
 Subregion midLayer school.depth newLayer schoolLayer
[1,] "South"   "1.679"  " "          "1"      " "        
[2,] "South"   "1.679"  " "          "1"      " "        
[3,] "South"   "1.679"  " "          "1"      " "        
[4,] "South"   "1.679"  " "          "1"      " "        
[5,] "South"   "1.679"  " "          "1"      " "        
[6,] "South"   "1.679"  " "          "1"      " "   

The current "Layer" column has some right values but most of them are wrong so I'm trying to essentially piece together a new Layer column using values from other columns that I have created:

#the first one doesn't work
Sites.merge$artLayer = ifelse(Sites.merge$Target_depth_mean == 0 & Sites.merge$school.depth == "NA", Sites.merge$Layer, Sites.merge$newLayer)
Sites.merge$schLayer = ifelse(Sites.merge$Depth_mean != "NA", Sites.merge$schoolLayer, Sites.merge$artLayer)
Sites.merge$Layer = ifelse(Sites.merge$S_type == "Artificial", Sites.merge$artLayer, Sites.merge$Layer)

In the ifelse statements below the "TRUE" statement works but the "FALSE" statement don't. Any help would be greatly appreciated. Thank you!

Python function (ifs and inputs) stops partway through, no error

I'm using a series of inputs and if statements to create a text game/ choose your own adventure where input decides what happens next within a function. I was testing part of a function, and there should be a total of four strings that print with an input prompt, but after the first two it just moves onto the cell after the function. No error message. I'm using Jupyter Notebook with the latest version of Python. Any help appreciated in making the full function run. (Please ignore the goofy text, sorry for errors this is my first question)

start = input('Welcome to Witness Protection, enter HELP if you need help')
def helper():
if start == 'HELP':
    answer= input('Woah. As you are walking to the FBI office, you see a glistening penny on the floor. Something about it looks strange. What do you do? Enter PICK to pick it up or WALK to keep walking')
    if answer == 'PICK':
        answer= input('You reach down and grasp the penny, and try to pull it. It doesn’t move. Enter TRY to try again or WALK AWAY to walk away')
    elif answer == 'WALK':
        print('You enter the building and make your way to the office of your agent, and sit down to wait for them.')
        if answer == 'TRY':
            answer= input('The penny clicks out of place and slides along a track between the paving slabs. One of the slabs slides open. Enter IN to climb in or PUT to put the penny back where it was')
        elif answer == 'WALK AWAY':
            print('You keep walking until you reach the FBI office. You make your way to the office of your agent, and sit down to wait for them.')
            if answer == 'IN':
                answer = input('A few metres down, you hit the floor, and see the opening above you close up. You find yourself in an ice cavern, surrounded by the bodies of slain ice dwarfs. Enter ON to walk on or BACK to back')
            elif answer == 'PUT':
                print('You move the penny back to where it was, and the slab slides back into place. You continue your walk towards the FBI offices, and wait for your agent in front of their desk')
                if answer == 'ON':
                    answer = input('You enter the realm of the evil wizard. He tells you he is thinking of giving up evil and asks you if you would like to join him in taking over the world and establishing a utopia. Enter YES for  \'Of course I will join you, let’s do this!\' Enter THINK for \'That’s a big decision, I need some time to think about it\' Enter NO for  \'Woah, sorry buddy, I’m just lost, I’m gonna have to bounce\'')
                elif answer == 'BACK':
                    print('You scramble back to the surface and try to forget what just happened. You continue towards FBI HQ, and wait for your agent at their desk')
if start == 'HELP':
helper()

I have checked that I am using the right input, changed elifs to ifs nothing else came to mind that could be the issue any help appreciated

Does conditional operator in cpp evaluate both operands?

https://leetcode.com/problems/decode-ways/

my solution:

class Solution {
public:
    int numDecodings(string s) {
        vector<int> dp(s.size(),0);
        
        for(int i=0;i<s.size();i++)
        {
            int x =0;
            if(s[i]-'0'>0 && s[i]-'0'<=9)
            {
                x = (i>0)? dp[i-1]:1;
            } 
            if(i!=0 && stoi(s.substr(i-1,2))<=26)
            {
                cout<<i<<" ";
                x = x + (i>=2 )? dp[i-2]:1;
            }    
            dp[i] =x;
        }
        return dp[s.size()-1];
       
    }
};

Running this code gives this error

Line 924: Char 34: runtime error: addition of unsigned offset to 0x602000000010 overflowed to 0x60200000000c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:34

My question is does the conditional operator evaluate dp[i-2] in (i>=2 )? dp[i-2]:1; even if the condition doesn't satisfy? Replacing it with a normal if-else solved my problem.

Dax formula to calculate 2 filters using IF statement

would be grateful for assistance with my problem, I have a table that contains locations/areas with daily inputs (one week range), however some of the locations inputs twice a day. I wanted to calculate sum of inputs and its percentage per week with the two conditions: locations with 1 input and the other having 2 inputs.

This follows a rating scale of 1 to 10. i.e. Location 1 - day1: 10 / d2: 0 / d3: 6 / d4: 8 / d5: 10 / d6: 0 / d7: 5 Location 2 - day1: 9 and 8 / d2: 5 / d3: 2 and 5 / d4: 6 / d5: 0 / d6: 10 and 9 / d7: 5 and 7

Thank you.

Why is the if statement not triggering when the target time is hit? [duplicate]

I cannot seem to figure out why the if statement in the call method will not trigger. When printing self.minutes(self.time) and target_time, they show the same values (before running the script I set target_time to the current time + 1 minute, so it is possible to trigger), but the if statement is not getting triggered.

from datetime import datetime
import time

class Time:
    def __init__(self):
        super().__init__()
        self.time = datetime.utcnow() 
    def update_time(self):
        self.time = datetime.utcnow() 
    def minutes(self, time):
        return str(time)[11:16] # Turn self.time datetime object into string as hh:mm format

class A(Time):
    def __init__(self):
        super().__init__()

    def call(self):
        target_time = "18:56" # Time that will trigger the if statement. Should be set to a time ahead of the current time.
        print(self.minutes(self.time), target_time)
        if self.minutes(self.time) is target_time:
            print("here") # See if statement is triggered
            
class B(A):
    def __init__(self):
        super().__init__()

    def runner(self):
        while(True): # Keep updating self.time and calling the call method 
            time.sleep(.2)
            self.update_time()
            self.call()

B().runner()

Determine differences between date stamps and reference dates

I’m working with a dataset of 191K obs that has individual records with date stamps throughout the period of 2014-2020. I have four reference dates (19 Sept 2014, 9 Sept 2016, 26 Oct 2017, 19 June 2019) that I need to determine the difference between each record’s date stamp. The rub is that I only need positive values for ‘difftime’: if the difference is <180 then the difference will be used; if the difference between dates is 180-365 days, then the value will be set to 180; if the difference >365 days, then NA; no negative values will be included.

Sample data

Date Difftime Notes: 11 Nov 2014 53 19 Sept 2014 used as reference 10 Jun 2015 180 19 Sept 2014 reference, but >180 5 Jan 2018 71 26 Oct 2017 reference 1 May 2019 NA No reference date within 365 days

In summary, a record’s date stamp needs to be compared to a relevant reference date (i.e., the closet, post-record date). I think I can do this in a number of individual ‘ifelse’ statements after creating separate variables for each of the reference dates, but I don’t want to clutter my dataset with more variables (even if I can remove them post-assessment). I’d appreciate any insights into how to code for this assessment. Thanks. Doug

For an application input do you have to code 1000s of if else statemetnts

I was building an application similar to an Amazon Alexa or Siri and I was designing the input system and realised I would have to run an if statement for every single command I've programmed in. Is there any way to reduce this or do I literally need to program 1000's of if statements

Modx *id isnot =`` and isnot=`` not working

Hi can someone help me with the correct code for this statement because it is not working for me.

[[*id:isnot=250 and isnot=252:then=[[$qc-wrap]]]]

Lua: How do you update a variable that's in an event?

The issue I'm running into is that my variable isn't updating after an event. Here is my code:

local AmountOfPlayers = #Players:GetPlayers() -- starts at zero
local minPlayers = 1


Players.PlayerAdded:Connect(function(Player) -- updates amount of players in server
    AmountOfPlayers = AmountOfPlayers + 1
end)

Players.PlayerRemoving:Connect(function(Player) -- updates amount of players in server
    AmountOfPlayers = AmountOfPlayers - 1
end)

Below, this if-statement is not running since AmountOfPlayers is not equal to minPlayers.

while intermission > 0 do
    if AmountOfPlayers >= minPlayers then
    print("SUCCESS")                
    end
end

I have a scope issue of the variable AmountOfPlayers. I'm not sure how to fix this, so any suggestions will be appreciated. Thank you for your help!

How to set a field will be change by if statement in models for Django?

I have a field in models that the True/False value will be affect by other field. May I know how to set it?

models.py:

class Product(models.Model):
  storage_amount = models.PositiveIntegerField()
  if storage_amount == 0 or None:
    out_of_storage_or_not = models.BooleanField(default=True)
  else:
    out_of_storage_or_not = models.BooleanField(default=False)

If... else condition in LUA language

I'm new to coding and I recently started to take my baby steps in LUA. I have a small problem so it would be very helpful if you can help me. In my code, I need to code that If x ~= 1 and x~=2 and x~=3 and x~=4 then (do something) end is there a faster way not to hardcode that part, not to type the whole thing from x~=1 to x~=4? Thank you!

How to replace IF statements for dictionary? (C#, Linq)

I have this equality comparer of a SampleObject:

    public bool Equals(SampleObject x, SampleObject y)
    {
        if (x == null)
        {
            return y == null;
        }

        if (y == null)
        {
            return false;
        }

        if (!string.Equals(x.SomeId, y.SomeId))
        {
            return false;
        }

        if (x.EventsList == null)
        {
            return y.EventsList == null;
        }

        if (y.EventsList == null)
        {
            return false;
        }

        return x.EventsList.OrderBy(e => e)
            .SequenceEqual(y.EventsList.OrderBy(e => e));
    }

What I would like to know is if there is a way to replace all those IF clauses for a dictionary?

Javascript if else repetition

I'm new to Javascript so please don't judge me... I have a code and I want to avoid repetition of the code, is there a way to do it otherwise?

if (dir_x > 0) {
    x++;
    if (dir_y > 0) {
        y++;
    } else {
        y--;
    }
} else {
    x--;
    if (dir_y > 0) {
        y++;
    } else {
        y--;
    }
}

How do I work an elseif statement into this footer? [duplicate]

I am trying to swap some content in a theme footer that is calling an option for a shortcode. I was able to get the if statement to replace when in the shop but there is only other area I'd like to have a third option, on the news page. Can I please get some help with this else if statement... It is only recognizing the Woocommerce instance and not the single News page...

<?php if ( ! $disable_prefooter && woodmart_get_opt( 'prefooter_area' ) ): ?>
    <div class="woodmart-prefooter">
        <div class="container">
            <?php if ( is_woocommerce() ): ?>
                    <?php echo do_shortcode( woodmart_get_opt( 'prefooter_area' ) ); ?>
            <?php elseif ( is_page( $page = 'News' ) ): ?>
                    <?php echo do_shortcode( '[html_block id="3542"]' ); ?>
            <?php else: ?>
                <?php echo do_shortcode( '[html_block id="3557"]' ) ?>
            <?php endif; ?>
        </div>
    </div>
<?php endif ?>

Is it possible to execute an IF/THEN statement using row number as the logical expression in google sheets?

I am trying to count the number of cells up to a specified row in google sheets. I want my function to basically compute "if row number is <= x, then count y". Not sure if this is possible.

Does anybody know how to change the color depending on stringname?

I try to change the color of an order-status-span-element to color red, if the order status is "Pending payment".
As soon as the status changes to "completed", the span text color should switch to green.
I tried to insert a proper if-statement, but I don't know which variable I need to go for.

<div class="order-status">
        <span>Order Status</span>
        <?php elseif ( 'order-status' === $column_id ) : ?>
        <?php echo '<span id="order-status-value">' . esc_html( wc_get_order_status_name( $order->get_status() ) ) . '<span>'; 
            if ( strcasecmp( wc_get_order_status_name( $order->get_status() ) == 0 ) :
                echo "This String works";
        ?>      
                <style type="text/css">
                    #order-status-value {
                        color: green;
                    }
                </style>
    </div>

Thank you in advance,
Chris

Matching seperate first name and surname columns to an id no

I really need your help. I'm sure it's an easy one for you techie people. I am trying to find the membership number in a spreadsheet. I have searched using vlookup to find it using email numbers first:

=VLOOKUP(E1,'Member list'!A3:Z426759,2,FALSE)

However, I don't know how to do it with 2 separate columns. I though it might be as simple as putting the two columns together:

=VLOOKUP(C1&D1,'Member list'!A2:Z426759,2,FALSE)

Obviously that did not work either. I'd be really grateful if anyone could help me.

Thanks Lisa

How to delete rows in a data.frame by a specific condition?

I tried to delete some rows in a data.frame but can't solve do problem. Can anyone help?

This is the data.frame

   subj trial fix type
1     a     1   1    K
2     a     1   2    T
3     a     1   3    T
4     a     2   1    K
5     a     2   2    K
6     a     2   3    T
7     b     1   1    T
8     b     1   2    K
9     b     1   3    K
10    b     2   1    K
11    b     2   2    T
12    b     2   3    T

and I want for each subj, in each trial the row where T appears for the first time. The result should look like this:

   subj trial fix type
2     a     1   2    T
6     a     2   3    T
7     b     1   1    T
11    b     2   2    T

Define new variable to take on 1 if next row of another variable fulfills condition

so I´m trying to set up my dataset for event-history analysis and for this I need to define a new column. My dataset is of the following form:

ID   Var1
1    10
1    20  
1    30  
1    10
2    4
2    5
2    10
2    5
3    1
3    15
3    20
3    9

And I want to get to the following form:

ID   Var1   Var2
1    10      0
1    20      0
1    30      1
1    10      0
2    4       0
2    5       0
2    10      0
2    5       0
3    1       0
3    15      0
3    20      1
3    9       0

So in words: I want the new variable to indicate, if the value of Var1 (with respect to the group) drops below 50% of the maximum value Var1 reaches for that group. Whether the last value is NA or 0 is not really of importance, although NA would make more sense from a theoretical perspective. I´ve tried using something like

DF$Var2 <- df %>%
  group_by(ID) %>%
  ifelse(df == ave(df$Var1,df$ID, FUN = max), 0,1)

to then lag it by 1, but it returns an error on an unused argument 1 in ifelse.

Thanks for your solutions!

mardi 28 juillet 2020

what does 0 mean? how can it have three items

I have trouble understanding these lines of codes:

return (0, user, computer)
return (-1, user, computer)

My question: what does 0, -1, and 1 mean? How can () have three items inside?

Thanks very very much!I'm a beginner. Much help is needed and appreaciated.

the original code is below: def play(): user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n") user = user.lower()

computer = random.choice(['r', 'p', 's'])

if user == computer:
    return (0, user, computer)         #?????????????????

# r > s, s > p, p > r
if is_win(user, computer):
    return (1, user, computer)

return (-1, user, computer)

Filter Results Via checked box in laravel

i am making a blog system and i am trying to include a feature where you can make posts visible and hidden. for this im trying to create a filter where i can show the hidden ones on the home page if a press a button. i have linked the checkbox to my database using this

        
        
        

and then linked to the postController with

$post->visible = $request->input('hide');

which stores the value in the database, seeing as it was either 1 or 0 i used the binary type in mysql now when displaying my blogposts i use this

@section('content')
<h1>Posts</h1>
<li><a href="/posts/create">Create Post</a></li>
@if(count($posts) > 1 || count($visible) == 0) //this was an attempt to fix the issue as if it's unhidden the value us 0 
    @foreach($posts as $post)
        <div class="well">
        <h3><a href= "/posts/"></a></h3>
        
            
        
        <small> Written on</small>
        </div>
        <div>
            <small>Expires on</small>

        </div>
    @endforeach
    
@else
    <p> No posts </p>
@endif


@endsection

could you see any way around this, ideally i would have button that refreshes the results between hidden and unhidden i tried this by making a completely new if statement that runs off a button but seeing as i cannot even sort it without the button in the if statement i didn't include the code. thanks in advance and sorry for any silly mistakes in code

How can I condition the parameter values in an ODE function? (deSolve, if-else)

I'm trying to create values conditioned for some parameters given the initial values of states. For example, if D state is D >= 60, the S value will be S=1800. Otherwise, if D state is D <60 the S value will be S=4800. I used function if-else into the ode function (AedesIbag_model). When I run ode with D=70 if-else doesn't switch S parameter value. So I have not achieved to do that this works well. I apologize if my English is not very good. Thank you for any help.

AedesIbag_model<-function(t, state, parameters) {
  with(as.list(c(state, parameters)), {
    dL = R*theta*S - mu_L*L - gamma_L*L - mu_w*L  
    dP = gamma_L*L - mu_P*P  - gamma_P*P - mu_w*P   
    dA = gamma_P*P - mu_A*A 
    dD = beta - alpha*D 
    if (D >= 60) { 
      S = 1800
      } else if (D < 60) {
        S = 4800
        } else if (D >= 10) {
          mu_w = 0.1
          } else if (D < 60) {
            mu_w = 0.1*100
          }
    
    return(list(c(dL, dP, dA, dD)))
  })
}

parameters  <- list(R = 0.24, theta = 10, S = 0,
                gamma_L = 0.2088, gamma_P = 0.384,
                beta = 10, mu_L = 0.0105, mu_P = 0.01041,
                mu_A = 0.091, mu_w = 0.1, alpha = 10
                )
state      <- c(L = 100, P = 60, A = 10, D = 70)
times       <- seq(0, 100, by = 0.1)

out_1 <- ode(y = state, times = times, func = AedesIbag_model, parms = parameters)
parameters

when I run my model. the parameters conditioned don't change the values. Look!!!

> parameters
$R
[1] 0.24

$theta
[1] 10

$S
[1] 0   #S value doesn't change

$gamma_L
[1] 0.2088

$gamma_P
[1] 0.384

$beta
[1] 10

$mu_L
[1] 0.0105

$mu_P
[1] 0.01041

$mu_A
[1] 0.091

$mu_w
[1] 0        #S value doesn't change

$alpha
[1] 10

I apologize if my English is not very good. Thank you for any help.

Python one line if else statement SyntaxError, the error is at the "else", what can be the problem?

def censor_string(txt, lst, char):
    return " ".join([char*len(i) for i in txt.split() if i in lst else i])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))

How compare field of two different models in Django

One of the main goals of project is control users done visits to customers. Available Customers, Employees and Appointment models.

  1. Make appointment to Customer and assign it to Employee on any future date.
  2. Employee can see appointment assigned to him and make visits.
  3. Need somehow see are appointments to customers done or not. See customers on custom date with made visits and not visited.

Need to see it in Django Admin.

model.py

class Customer(models.Model):
name = models.CharField(max_length=255,blank=True, null=True)
......

class Emplyee(models.Model):
name = models.CharField(max_length=255,blank=True, null=True)
......

class Visit(models.Model):
employee_name = models.ForeignKey(Employee, on_delete=models.CASCADE)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE)
visit_time = models.TimeField() visit_date = models.DateTimeField(auto_now_add=True)
note = models.TextField(blank=True, null=True)
......

class Appointment(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
appointment_date = models.DateTimeField(auto_now_add=True)
note = models.TextField(blank=True, null=True)

admin.py

class VisitAdmin(admin.ModelAdmin):
list_display = ('employee_name', 'customer_name','visit_time','visit_date')
admin.site.register(Visit, VisitAdmin)
......

class AppointmentAdmin(admin.ModelAdmin):
list_display = ('employee_name', 'customer_name','appointment_date','visit_done')
admin.site.register(Appointment, AppointmentAdmin)


// Need to write some def visit_done as a Boolean for example True/False that the visit to exact this Customer and Date and Employee was done or Not.

Angular [ngClass] convert one line if statement to multiple if

I found a [ngClass] solution for my project. The Code is

[ngClass]= (controlDir && controlDir.control && controlDir.control.touched) ? (!controlDir.control.valid) ? 'is-invalid' : 'is-valid' : null"

This code is work nicely. But I want to convert it to like this pattern.

[ngClass]="{'is-invalid': **statement**, 'is-valid': **statement**}"

How can i split this ?

Google Apps Script_populate multiple templates depending on google form data and then email pdf copies

Help greatly needed.

Using Google Form to gather data, in order to populate one of 2 Google doc templates, dependent on whether option 1 or 2 is chosen in the Google form. Populated template to be saved in "final" folder as a PDF, and then emailed to the email address submitted in the Google form.

Currently, I'm able to generate the correct PDF files in the correct folder and send the email to the correct address, but there is no attachment and just the words [Object object].

Before I included the if/else function, I was able to correctly send the email with attachment, which means that I've caused a problem with the if/else and naming of the generated pdfs. I just can't figure it out.

function autoFillGoogleDocFromForm(e) {
  //form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var email = e.values[3];
  var multiplechoice = e.values[4];

  if (multiplechoice == "Template 1") {
    //This section will complete template 1
    var file = DriveApp.getFileById("Template 1 ID");

    //Create copy of Template 1
    var folder = DriveApp.getFolderById("Templates folder ID")
    var copy = file.makeCopy(lastName + ',' + firstName, folder);

    //Open copy of Template 1 and replace key fields per form data
    var doc = DocumentApp.openById(copy.getId());
    var body = doc.getBody();
    body.replaceText('', firstName);
    body.replaceText('', lastName);
    doc.saveAndClose();
    Utilities.sleep(1500);
  } else {
    //This section will complete Template 2 by default
    var file = DriveApp.getFileById("Template 2 ID");

    //Create copy of Template 2
    var folder = DriveApp.getFolderById("Templates folder ID")
    var copy = file.makeCopy(lastName + ',' + firstName, folder);

    //Open copy of Template 1 and replace key fields per form data
    var doc = DocumentApp.openById(copy.getId());
    var body = doc.getBody();
    body.replaceText('', firstName);
    body.replaceText('', lastName);
    doc.saveAndClose();
    Utilities.sleep(1500);
  }

  //create pdf copy of completed template
  var pdffolder = DriveApp.getFolderById("Templates folder ID");
  var pdfFILE = DriveApp.getFileById(copy.getId()).getAs('application/pdf');
  pdfFILE.setName(copy.getName() + ".pdf");
  var theFolder = pdffolder;
  var theFile = DriveApp.createFile(pdfFILE);
  theFolder.addFile(theFile);
  Utilities.sleep(1500);

  var subject = "File attached";
  var attach = theFile;
  var pdfattach = attach.getAs(MimeType.PDF);

  MailApp.sendEmail(email, subject, {attachments: [pdfattach]});
  
  }