mardi 31 août 2021

CodeIgniter - SQL sentence IF then WHERE?

Currently I am capable of doing WHERE sentences in CodeIgniter as follows:

$builder = $db->table('mytable');
$builder->select(*);
$builder->where('age >='.$params['some-param']);

What I need to do, is a WHERE statement that only applies if an IF statement is true. Something like:

(IF gender = 'Male', apply these rows the following where) $builder->where('age >='.$params['some-param']);
(IF gender = 'Female', apply these other rows, this where and not the first one) $builder->where('age >='.$params['some-other-param']);

I have no clue of how to achieve this. Any orientation will be appreciated.

How do I subtract a number with an if statement

This is my code

import sys
import click


def Seats():
    global seats
    seats = 168
    print("\nThe current seating capacity is {}\n".format(seats))


def Restart():
    while True:
        restart = click.confirm('\nWould you like to subtract 1 from seats?',
                                default=True)

        if restart == True:
            x = seats - 1
            Seats()
        elif restart == False:
            print("\nOk, see you next time!\n")
            sys.exit()


Seats()
Restart()

I want to ask the user "Would you like to subtract 1 from seats?" and then subtract one from seats variable and then repeat until the users inputs n.

My condition for the if statement are not being evaluated

if webtablerowscount > enterlistscount and alertcount >= 2 and 8.225 < 8.11 and askPrice < tp1 or askPrice < tp2 and tickercountenterlist == tickercountcloselist:
    print('enterposition')
    enterlists.append([ticker, alertprice, alertcount])
    positionslists.append([ticker, askPrice, tp1, tp2])
else:
    print('do not enter')

I am trying to get this if statement to work. It still prints enter position even though 8.225<8.11.

IF statement for multiple date ranges

I built a tracker for my platoon to manage numerous training dates based on completion. Each sheet tracks different things and I'm trying to make a coversheet that pulls data from each sheet to give an overall snap shot. I'm trying to create and IF formula for if any of the dates in a certain row are over due, it reports as over do. I can do it with 1 or 2 but not with 14 different dates. Is this possible?

If / Statements with Strings (Java). No matter the method I try, It would say that the If statement is true when its not [duplicate]

There was code before this but to explain the section I'm having troubles with I cut out the rest. I've also tried an if/then else statement and it still didn't work.

    String fav_lang;
    System.out.println("\nEnough about me. What's your favourite language? (just don't say Python)");
    fav_lang = scan.next ( ); 

    String p = new String ("python");
    //add new a line here.
    if (fav_lang == p) {
        System.out.println("\nWow, that sucks, you should seek help.");
    }
    if (fav_lang != p) {
        System.out.println( "\n"+ fav_lang + ", that's great! Nice chatting with you " + full_name + ". I have to log off now. See ya!");
    }

How to check multiple parameters without a mess of 'if' statements?

I'm writing a program for myself that makes a meal plan. I want to make the meal plan customizable, so I have this method:

def getRestrictedMeals(meals):
    restrictions = []
    mealsR = []

In the method, I ask the user questions that customize the code and I save their answer in a list (The getRestHelp method just saves some answers as boolean.):

    print("Would you like only foods you aren't allergic to?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only healthy foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only Gluten Free foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("Would you like only Vegitarian foods?")
    print("1. Yes")
    print("2. No")
    user = int(input("Please choose an option: "))
    print()
    restrictions.append(getRestHelp(user))

    print("What is the longest cook time you want?")
    print("Please enter 1000 for any cook time.")
    user = int(input())
    restrictions.append(user)

Next I grab the information from each meal:

facts = []
for x in meals:
    facts.append(x.getAllergy())
    facts.append(x.getHealthy())
    facts.append(x.getGluten())
    facts.append(x.getVegitarian())
    facts.append(x.getCookTime())

This is where I'm stuck. I know I need to compare the lists the add the meal to mealR if it meets the restrictions, but I'm not sure how to do that without getting into a mess of 'if' statements. I can't make sure the lists match each other because if the user answers 'No' to a question, then any meal can be added.

If the user input is Allergies = No and Healthy = Yes, I want to avoid something like this (because I would have to go deeper and deeper for each parameter):

if(restrictions[0] == 0):
    if(restrictions[1] == 0):
        # I would continue going here for other parameters.
    else:
        if(x.getHealthy()):
            # I would continue going here for other parameters.
            mealsR[i] = x
            i+=1

    else:
       if(!x.getAllergy()):
           # I would continue going here for other parameters.

"Argument is of length zero" error in if argument - comparing two values in a vector

My code looks like this:

min_max <- function(n) {
  # n is the length of the given vector
  vecc <- rep(0, length = n)
  for (i in 1:n) {
    v <- as.integer(readline(prompt = "Insert number: "))
    vecc[i] <- v
    print(typeof(v[i]))
  }
  vecc <- as.integer(vecc)
  for (i in 1:n - 1) {
    print(vecc[i])
    if (vecc[i] > vecc[i + 1]) {
      aux <- vecc[i]
      vecc[i] <- vecc[i + 1]
      vecc[i + 1] <- aux
    }
  }

  print(vecc[1])
  print(vecc[n])
}
min_max(4)

And the result is an error

"argument is of length zero"

I am new to the R language and I really don't know how to solve this. I tried giving the vector using c() and then using the min, max functions and this is a way to solve the problem itself, but what should I do when I have to compare/ sort values of a given vector?

Excel Wildcard If statement for two columns?

I'm not sure what excel function to use.

I have two columns 'asset tag' and 'computer name'. Both unique values. The asset tag has a name like '11111' the computer name has a name like 'AA-11111-BB'.

I need a formula to output every asset that is also in the computer name column into its own column.

As you see the asset tags name is inside the computer name between characters.

I don't know how to tie these two columns together when their names are not exactly the same.

IS the a wildcard if statement formula for two columns to accomplish this. Please see my screenshot as well.

Screenshot of spreadsheet

Try to make score table for tic tac toe game

Hello I am new to javascript, Currently, I am creating a tic tac toe game with javascript and I want to add a score table for the game and I tried many ways but I didn't find the best way to do it pls give me some idea to do it

How to assign a new event for a second enter press

I have a phonebook, where you can add contact name and number, with click or enter press. I made Edit and a Delete button, the delete button works fine, also the Edit button, but I want when I press the Edit button and modify the value I want to be able to save it with pressing the enter not only by clicking save. A little help would be appreciated.

I tried out a few things this is the closest I got, here I can save the item by pressing enter, but it will create another table row as I already have an event assigned to enter and that fires as well

let form = document.querySelector('.form');
let inputMessage = document.getElementById('inputMessage');
let table = document.querySelector('.book-table');
let tableBody = document.createElement('tbody');
let nameInput = document.getElementById('name');
let numberInput = document.getElementById('number');
let submitBtn = document.querySelector('.btn');
let editBtn = document.querySelector('.edit-btn');
let deleteBtn = document.querySelector('.delete-btn');



function addNumber() {
    if (nameInput.value != '' && numberInput.value != '') {
        let newRow = document.createElement('tr');
        let firstCol = document.createElement('td');
        let secondCol = document.createElement('td');
        let thirdCol = document.createElement('td');
        let fourthCol = document.createElement('td');
        let editBtn = document.createElement('button');
        let deleteBtn = document.createElement('button');
        firstCol.innerHTML = nameInput.value;
        secondCol.innerHTML = numberInput.value;
        firstCol.className = 'list-name';
        secondCol.className = 'list-number';
        editBtn.className = 'edit-btn';
        deleteBtn.className = 'delete-btn';
        editBtn.innerHTML = 'Edit';
        deleteBtn.innerHTML = 'Delete';
        table.appendChild(tableBody);
        tableBody.appendChild(newRow);
        newRow.appendChild(firstCol)
        newRow.appendChild(secondCol)
        newRow.appendChild(thirdCol);
        newRow.appendChild(fourthCol);
        thirdCol.appendChild(editBtn);
        fourthCol.appendChild(deleteBtn);
        nameInput.value = '';
        numberInput.value = '';
        inputMessage.style.visibility = 'visible';
        inputMessage.innerHTML = 'Contact Added Successfully';
        inputMessage.classList.add('message');
        inputMessage.classList.remove('error-message');
    } else {
        inputMessage.style.visibility = 'visible';
        inputMessage.innerHTML = 'Please fill out all required fields';
        inputMessage.classList.remove('message');
        inputMessage.classList.add('error-message');
    }
}

function editBook(e) {
    if (e.target && e.target.className == 'edit-btn') {
        e.target.innerHTML = 'Save';
        clickCount++;
        const td = e.target.parentNode.parentNode;
        // console.log(td);
        let editName = td.getElementsByTagName('td')[0];
        let editNumber = td.getElementsByTagName('td')[1];
        if (clickCount > 1) {
            // change HTML back to edit
            e.target.innerHTML = 'Edit';
            // set clickCount back to 0
            clickCount = 0;
        }
        // save the values from the input in the same table row
        let tmp = nameInput.value;
        // console.log(tmp, nameInput.value);
        nameInput.value = editName.innerHTML;
        // console.log(nameInput.value, editName.innerHtml);
        editName.innerHTML = tmp;
        // console.log(editName.innerHTML, tmp);
        let tmp2 = numberInput.value;
        numberInput.value = editNumber.innerHTML;
        editNumber.innerHTML = tmp2;
    }
}




let enterCount = 0;
numberInput.addEventListener('keydown', function (e) {
    let dynamicTd = document.getElementsByTagName('td');

    if (e.keyCode == 13) {
        if (numberInput.value != '' && nameInput.value != '' && enterCount < 1) {
            addNumber();
            enterCount++;
        } else if (editBtn.innerHTML = 'Save') {
            if (clickCount > 1) {
                dynamicTd[2].innerHTML = 'Edit';
                clickCount = 0;
            }
            let tmp = nameInput.value;
            nameInput.value = dynamicTd[0].innerHTML;
            dynamicTd[0].innerHTML = tmp;
            let tmp2 = numberInput.value;
            numberInput.value = dynamicTd[1].innerHTML;
            dynamicTd[1].innerHTML = tmp2;
            enterCount = 0;
        }

    }
});
<form action="" class="form">
            <label for="name">Name</label>
            <input type="text" id="name" name="name" required autocomplete="off">
            <label for="number">Phone</label>
            <input type="number" id="number" name="number" required>
        </form>

        <button type="submit" class="btn">Add Contact</button>
    </div>
    <!-- Add error and success message -->
    <div id="inputMessage" class="message">
    </div>
    <table class="book-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Phone Number</th>
                <th colspan="2">Action</th>
            </tr>
        </thead>

Problem with Form Validation and question about syntax

I am NOT a PHP Devleoper at all. I worked with basic if-else statements in Joomla years back but that's it.

I have this a long form (set up by a past employee) that basically takes the field input and writes it to a pdf doc and emails it to our client. The issue I'm having is that despite filling out every field, the script redirects me to an error page that is generated by the script.

I'm looking through the if else statements to make sure all of the fields it checks are correct and it looks like it all matches up. The form basically has a ton of if else blocks that check every section of form fields.

I've been looking at other people's code and was wondering if maybe it's a formatting issue with the if statements syntax.

Are the number and usage of the parenthesis in this line correct?

if((!isset($_POST['ocname2'])) || (!isset($_POST['ocage2'])) || (!isset($_POST['ocr2'])))

Is there a better way to handle the checking of these forms without so many if else statements and still have it pass the data on to the pdf writing script?

Here is entire section of if else code.

    // check that a form was submitted
    if(isset($_POST) && is_array($_POST) && count($_POST)){
        // we will use this array to pass to the createFDF function
        $data=array();
        
        // This displays all the data that was submitted. You can
        // remove this without effecting how the FDF data is generated.
        //echo'<pre>POST '; print_r($_POST);echo '</pre>';

        if(isset($_POST['FirstName'])){
            // the name field was submitted
           $pat='`[^a-z0-9\s]+$`i';
           if(empty($_POST['FirstName']) || preg_match($pat,$_POST['FirstName'])){
                // no value was submitted or something other than a
                // number, letter or space was included
                $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
                curl_exec($ch);  
                die('Invalid input for First Name field.');
            }else{
                // if this passed our tests, this is safe
                $data['FirstName']=$_POST['FirstName'];
                
                $data['FirstName']=strtolower($data['FirstName']);
            }
        }
        
        if(isset($_POST['LastName'])){
            // the name field was submitted
           $pat='`[^a-z0-9\s]+$`i';
           if(empty($_POST['LastName']) || preg_match($pat,$_POST['LastName'])){
                // no value was submitted or something other than a
                // number, letter or space was included
                $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
                curl_exec($ch);  
                die('Invalid input for Last Name field.');
            }else{
                // if this passed our tests, this is safe
                $data['LastName']=$_POST['LastName'];
                
                $data['LastName']=strtolower($data['LastName']);
            }
        }
        
        
            
//            if((!isset($_POST['Address'])) || (!isset($_POST['City'])) || (!isset($_POST['State'])) || (!isset($_POST['Zip'])) || (!isset($_POST['Telephone'])) || (!isset($_POST['FromName'])) || (!isset($_POST['FromTelephone'])) || (!isset($_POST['FromAddress'])) || (!isset($_POST['FromCity'])) || (!isset($_POST['FromState'])) || (!isset($_POST['FromZip']))) {
                // Why this? What if someone is spoofing form submissions
                // to see how your script works? Only allow the script to
                // continue with expected data, don't be lazy and insecure ;)
//                die('You did not form fully.');
//            }
            
//                        if(($_POST['Address'] == '') || ($_POST['City'] == '') || ($_POST['State'] == '') || ($_POST['Zip'] == '') || ($_POST['Telephone'] == '') || ($_POST['FromName'] == '') || (['FromTelephone'] == '') || ($_POST['FromAddress'] == '') || ($_POST['FromCity'] == '') || ($_POST['FromState'] == '') || ($_POST['FromZip'] == '')) {
//                // Why this? What if someone is spoofing form submissions
//                // to see how your script works? Only allow the script to
//                // continue with expected data, don't be lazy and insecure ;)
//                die('You did not form fully.');
//            }
            
            // Check your data for ALL FIELDS that you expect, ignore ones you
            // don't care about. This is just an example to illustrate, so I
            // won't check anymore, but I will add them blindly (you don't want
            // to do this in a production environment).
            
    //if((!isset($_POST['app'])) || (!isset($_POST['MiddleName'])) || (!isset($_POST['birthdate'])) || (!isset($_POST['ss'])) || (!isset($_POST['drlic'])))
    if((!isset($_POST['app'])) || (!isset($_POST['MiddleName'])) || (!isset($_POST['birthdate'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);  
        die('You did not form fully.');        
    }
    else
    {
        $data['app']=$_POST['app'];
        $data['MiddleName']=$_POST['MiddleName'];
        $data['birthdate']=$_POST['birthdate'];
       //$data['ss']=$_POST['ss'];
        //$data['drlic']=$_POST['drlic'];
        
        $data['app']=strtolower($data['app']);
        $data['MiddleName']=strtolower($data['MiddleName']);
        $data['birthdate']=strtolower($data['birthdate']);
        //$data['ss']=strtolower($data['ss']);
        //$data['drlic']=strtolower($data['drlic']);
    }
        
        
    //if((!isset($_POST['pastname'])) || (!isset($_POST['hphone'])) || (!isset($_POST['cphone'])) || (!isset($_POST['ss'])) || (!isset($_POST['email'])))
    if((!isset($_POST['pastname'])) || (!isset($_POST['hphone'])) || (!isset($_POST['cphone'])) || (!isset($_POST['email'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);  
        die('You did not form fully.');        
    }
    else
    {
        $data['pastname']=$_POST['pastname'];
        $data['hphone']=$_POST['hphone'];
        $data['cphone']=$_POST['cphone'];
        $data['email']=$_POST['email'];
        
        $data['pastname']=strtolower($data['pastname']);
        $data['hphone']=strtolower($data['hphone']);
        $data['cphone']=strtolower($data['cphone']);
        $data['email']=strtolower($data['email']);  
    }
    
    if((!isset($_POST['ocname1'])) || (!isset($_POST['ocage1'])) || (!isset($_POST['ocr1'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['ocname1']=$_POST['ocname1'];
        $data['ocage1']=$_POST['ocage1'];
        $data['ocr1']=$_POST['ocr1'];
        
        $data['ocname1']=strtolower($data['ocname1']);
        $data['ocage1']=strtolower($data['ocage1']);
        $data['ocr1']=strtolower($data['ocr1']);
    }
    
    if((!isset($_POST['ocname2'])) || (!isset($_POST['ocage2'])) || (!isset($_POST['ocr2'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['ocname2']=$_POST['ocname2'];
        $data['ocage2']=$_POST['ocage2'];
        $data['ocr2']=$_POST['ocr2'];
        
        $data['ocname2']=strtolower($data['ocname2']);
        $data['ocage2']=strtolower($data['ocage2']);
        $data['ocr2']=strtolower($data['ocr2']);
    }
    
    
    if((!isset($_POST['ocname3'])) || (!isset($_POST['ocage3'])) || (!isset($_POST['ocr3'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['ocname3']=$_POST['ocname3'];
        $data['ocage3']=$_POST['ocage3'];
        $data['ocr3']=$_POST['ocr3'];
        
        $data['ocname3']=strtolower($data['ocname3']);
        $data['ocage3']=strtolower($data['ocage3']);
        $data['ocr3']=strtolower($data['ocr3']);
    }
    
    if((!isset($_POST['crstreet'])) || (!isset($_POST['crcity'])) || (!isset($_POST['crstate'])) || (!isset($_POST['cramountpaid'])) || (!isset($_POST['crownerphone'])) || (!isset($_POST['crleaving'])) || (!isset($_POST['crrentpaid'])) || (!isset($_POST['crnotice'])) || (!isset($_POST['crmove'])) || (!isset($_POST['crbilled'])) || (!isset($_POST['crdate'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['crstreet']=$_POST['crstreet'];
        $data['crcity']=$_POST['crcity'];
        $data['crstate']=$_POST['crstate'];
        $data['cramountpaid']=$_POST['cramountpaid'];
        $data['crownerphone']=$_POST['crownerphone'];
        $data['crleaving']=$_POST['crleaving'];
        $data['crrentpaid']=$_POST['crrentpaid'];
        $data['crnotice']=$_POST['crnotice'];
        $data['crmove']=$_POST['crmove'];
        $data['crbilled']=$_POST['crbilled'];
        $data['crdate']=$_POST['crdate'];
        
        $data['crstreet']=strtolower($data['crstreet']);
        $data['crcity']=strtolower($data['crcity']);
        $data['crstate']=strtolower($data['crstate']);
        $data['cramountpaid']=strtolower($data['cramountpaid']);
        $data['crownerphone']=strtolower($data['crownerphone']);
        $data['crleaving']=strtolower($data['crleaving']);
        $data['crrentpaid']=strtolower($data['crrentpaid']);
        $data['crnotice']=strtolower($data['crnotice']);
        $data['crmove']=strtolower($data['crmove']);
        $data['crbilled']=strtolower($data['crbilled']);
        $data['crdate']=strtolower($data['crdate']);
    }
            
    if((!isset($_POST['prstreet'])) || (!isset($_POST['prcity'])) || (!isset($_POST['prstate'])) || (!isset($_POST['pramountpaid'])) || (!isset($_POST['prownerphone'])) || (!isset($_POST['prleaving'])) || (!isset($_POST['prrentpaid'])) || (!isset($_POST['prnotice'])) || (!isset($_POST['prmove'])) || (!isset($_POST['prbilled'])) || (!isset($_POST['prdate'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['prstreet']=$_POST['prstreet'];
        $data['prcity']=$_POST['prcity'];
        $data['prstate']=$_POST['prstate'];
        $data['pramountpaid']=$_POST['pramountpaid'];
        $data['prownerphone']=$_POST['prownerphone'];
        $data['prleaving']=$_POST['prleaving'];
        $data['prrentpaid']=$_POST['prrentpaid'];
        $data['prnotice']=$_POST['prnotice'];
        $data['prmove']=$_POST['prmove'];
        $data['prbilled']=$_POST['prbilled'];
        $data['prdate']=$_POST['prdate'];
        
        $data['prstreet']=strtolower($data['prstreet']);
        $data['prcity']=strtolower($data['prcity']);
        $data['prstate']=strtolower($data['prstate']);
        $data['pramountpaid']=strtolower($data['pramountpaid']);
        $data['prownerphone']=strtolower($data['prownerphone']);
        $data['prleaving']=strtolower($data['prleaving']);
        $data['prrentpaid']=strtolower($data['prrentpaid']);
        $data['prnotice']=strtolower($data['prnotice']);
        $data['prmove']=strtolower($data['prmove']);
        $data['prbilled']=strtolower($data['prbilled']);
        $data['prdate']=strtolower($data['prdate']);
    }
    
    if((!isset($_POST['pristreet'])) || (!isset($_POST['pricity'])) || (!isset($_POST['pristate'])) || (!isset($_POST['priamountpaid'])) || (!isset($_POST['priownerphone'])) || (!isset($_POST['prileaving'])) || (!isset($_POST['prirentpaid'])) || (!isset($_POST['prinotice'])) || (!isset($_POST['primove'])) || (!isset($_POST['pribilled'])) || (!isset($_POST['pridate'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['pristreet']=$_POST['pristreet'];
        $data['pricity']=$_POST['pricity'];
        $data['pristate']=$_POST['pristate'];
        $data['priamountpaid']=$_POST['priamountpaid'];
        $data['priownerphone']=$_POST['priownerphone'];
        $data['prileaving']=$_POST['prileaving'];
        $data['prirentpaid']=$_POST['prirentpaid'];
        $data['prinotice']=$_POST['prinotice'];
        $data['primove']=$_POST['primove'];
        $data['pribilled']=$_POST['pribilled'];
        $data['pridate']=$_POST['pridate'];
        
        $data['pristreet']=strtolower($data['pristreet']);
        $data['pricity']=strtolower($data['pricity']);
        $data['pristate']=strtolower($data['pristate']);
        $data['priamountpaid']=strtolower($data['priamountpaid']);
        $data['priownerphone']=strtolower($data['priownerphone']);
        $data['prileaving']=strtolower($data['prileaving']);
        $data['prirentpaid']=strtolower($data['prirentpaid']);
        $data['prinotice']=strtolower($data['prinotice']);
        $data['primove']=strtolower($data['primove']);
        $data['pribilled']=strtolower($data['pribilled']);
        $data['pridate']=strtolower($data['pridate']);
    }
    
    if((!isset($_POST['ceemployed'])) || (!isset($_POST['ceaddress'])) || (!isset($_POST['ceemployerphone'])) || (!isset($_POST['ceoccupation'])) || (!isset($_POST['cesupervisor'])) || (!isset($_POST['cemonthlygrosspay'])) || (!isset($_POST['cedateofemployment'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['ceemployed']=$_POST['ceemployed'];
        $data['ceaddress']=$_POST['ceaddress'];
        $data['ceemployerphone']=$_POST['ceemployerphone'];
        $data['ceoccupation']=$_POST['ceoccupation'];
        $data['cesupervisor']=$_POST['cesupervisor'];
        $data['cemonthlygrosspay']=$_POST['cemonthlygrosspay'];
        $data['cedateofemployment']=$_POST['cedateofemployment'];
        
        $data['ceemployed']=strtolower($data['ceemployed']);
        $data['ceaddress']=strtolower($data['ceaddress']);
        $data['ceemployerphone']=strtolower($data['ceemployerphone']);
        $data['ceoccupation']=strtolower($data['ceoccupation']);
        $data['cesupervisor']=strtolower($data['cesupervisor']);
        $data['cemonthlygrosspay']=strtolower($data['cemonthlygrosspay']);
        $data['cedateofemployment']=strtolower($data['cedateofemployment']);
    }
    
    if((!isset($_POST['preemployed'])) || (!isset($_POST['preaddress'])) || (!isset($_POST['preemployerphone'])) || (!isset($_POST['preoccupation'])) || (!isset($_POST['presupervisor'])) || (!isset($_POST['premonthlygrosspay'])) || (!isset($_POST['predateofemployment'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['preemployed']=$_POST['preemployed'];
        $data['preaddress']=$_POST['preaddress'];
        $data['preemployerphone']=$_POST['preemployerphone'];
        $data['preoccupation']=$_POST['preoccupation'];
        $data['presupervisor']=$_POST['presupervisor'];
        $data['premonthlygrosspay']=$_POST['premonthlygrosspay'];
        $data['predateofemployment']=$_POST['predateofemployment'];
        
        $data['preemployed']=strtolower($data['preemployed']);
        $data['preaddress']=strtolower($data['preaddress']);
        $data['preemployerphone']=strtolower($data['preemployerphone']);
        $data['preoccupation']=strtolower($data['preoccupation']);
        $data['presupervisor']=strtolower($data['presupervisor']);
        $data['premonthlygrosspay']=strtolower($data['premonthlygrosspay']);
        $data['predateofemployment']=strtolower($data['predateofemployment']);
    }
    
    if((!isset($_POST['prieemployed'])) || (!isset($_POST['prieaddress'])) || (!isset($_POST['prieemployerphone'])) || (!isset($_POST['prieoccupation'])) || (!isset($_POST['priesupervisor'])) || (!isset($_POST['priemonthlygrosspay'])) || (!isset($_POST['priedateofemployment'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['prieemployed']=$_POST['prieemployed'];
        $data['prieaddress']=$_POST['prieaddress'];
        $data['prieemployerphone']=$_POST['prieemployerphone'];
        $data['prieoccupation']=$_POST['prieoccupation'];
        $data['priesupervisor']=$_POST['priesupervisor'];
        $data['priemonthlygrosspay']=$_POST['priemonthlygrosspay'];
        $data['priedateofemployment']=$_POST['priedateofemployment'];
        
        $data['prieemployed']=strtolower($data['prieemployed']);
        $data['prieaddress']=strtolower($data['prieaddress']);
        $data['prieemployerphone']=strtolower($data['prieemployerphone']);
        $data['prieoccupation']=strtolower($data['prieoccupation']);
        $data['priesupervisor']=strtolower($data['priesupervisor']);
        $data['priemonthlygrosspay']=strtolower($data['priemonthlygrosspay']);
        $data['priedateofemployment']=strtolower($data['priedateofemployment']);
    }
            
    if((!isset($_POST['savingbank'])) || (!isset($_POST['savingdeposit'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['savingbank']=$_POST['savingbank'];
        $data['savingdeposit']=$_POST['savingdeposit'];
        
        $data['savingbank']=strtolower($data['savingbank']);
        $data['savingdeposit']=strtolower($data['savingdeposit']);
    }
    
    if((!isset($_POST['checkingbank'])) || (!isset($_POST['checkingdeposit'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['checkingbank']=$_POST['checkingbank'];
        $data['checkingdeposit']=$_POST['checkingdeposit'];
        
        $data['checkingbank']=strtolower($data['checkingbank']);
        $data['checkingdeposit']=strtolower($data['checkingdeposit']);
    }  
    
    if((!isset($_POST['creditinstitution'])) || (!isset($_POST['creditowed'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['creditinstitution']=$_POST['creditinstitution'];
        $data['creditowed']=$_POST['creditowed'];
        
        $data['creditinstitution']=strtolower($data['creditinstitution']);
        $data['creditowed']=strtolower($data['creditowed']);
    }

   if((!isset($_POST['loaninstitution'])) || (!isset($_POST['loanowed'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $data['loaninstitution']=$_POST['loaninstitution'];
        $data['loanowed']=$_POST['loanowed'];
        
        $data['loaninstitution']=strtolower($data['loaninstitution']);
        $data['loanowed']=strtolower($data['loanowed']);
    }      
        
    if((!isset($_POST['car1make'])) || (!isset($_POST['car1model'])) || (!isset($_POST['car1color'])) || (!isset($_POST['car1year'])))
    //if((!isset($_POST['car1make'])) || (!isset($_POST['car1model'])) || (!isset($_POST['car1color'])) || (!isset($_POST['car1year'])) || (!isset($_POST['car1licenseplate'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
            $data['car1make']=$_POST['car1make'];
            $data['car1model']=$_POST['car1model'];
            $data['car1color']=$_POST['car1color'];
            $data['car1year']=$_POST['car1year'];
            //$data['car1licenseplate']=$_POST['car1licenseplate'];
            
            $data['car1make']=strtolower($data['car1make']);
            $data['car1model']=strtolower($data['car1model']);
            $data['car1color']=strtolower($data['car1color']);
            $data['car1year']=strtolower($data['car1year']);
            //$data['car1licenseplate']=strtolower($data['car1licenseplate']);
    }

   // if((!isset($_POST['car2make'])) || (!isset($_POST['car2model'])) || (!isset($_POST['car2color'])) || (!isset($_POST['car2year'])) || (!isset($_POST['car2licenseplate'])))
    if((!isset($_POST['car2make'])) || (!isset($_POST['car2model'])) || (!isset($_POST['car2color'])) || (!isset($_POST['car2year'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
            $data['car2make']=$_POST['car2make'];
            $data['car2model']=$_POST['car2model'];
            $data['car2color']=$_POST['car2color'];
            $data['car2year']=$_POST['car2year'];
            //$data['car2licenseplate']=$_POST['car2licenseplate'];
            
            $data['car2make']=strtolower($data['car2make']);
            $data['car2model']=strtolower($data['car2model']);
            $data['car2color']=strtolower($data['car2color']);
            $data['car2year']=strtolower($data['car2year']);
            //$data['car2licenseplate']=strtolower($data['car2licenseplate']);
    }
    
    
    if((!isset($_POST['app2'])) || (!isset($_POST['dname'])) || (!isset($_POST['dstreet'])) || (!isset($_POST['dcity'])) || (!isset($_POST['dstate'])) || (!isset($_POST['dphone'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
            $data['app2']=$_POST['app2'];
            $data['dname']=$_POST['dname'];
            $data['dstreet']=$_POST['dstreet'];
            $data['dcity']=$_POST['dcity'];
            $data['dstate']=$_POST['dstate'];
            $data['dphone']=$_POST['dphone'];
            
            $data['app2']=strtolower($data['app2']);
            $data['dname']=strtolower($data['dname']);
            $data['dstreet']=strtolower($data['dstreet']);
            $data['dcity']=strtolower($data['dcity']);
            $data['dstate']=strtolower($data['dstate']);
            $data['dphone']=strtolower($data['dphone']);
    }
        
    if((!isset($_POST['lname'])) || (!isset($_POST['lstreet'])) || (!isset($_POST['lcity'])) || (!isset($_POST['lstate'])) || (!isset($_POST['lphone'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);  
        die('You did not form fully.');        
    }
    else
    {
            $data['lname']=$_POST['lname'];
            $data['lstreet']=$_POST['lstreet'];
            $data['lcity']=$_POST['lcity'];
            $data['lstate']=$_POST['lstate'];
            $data['lphone']=$_POST['lphone'];
            
            $data['lname']=strtolower($data['lname']);
            $data['lstreet']=strtolower($data['lstreet']);
            $data['lcity']=strtolower($data['lcity']);
            $data['lstate']=strtolower($data['lstate']);
            $data['lphone']=strtolower($data['lphone']);
    }
    
    if((!isset($_POST['rname'])) || (!isset($_POST['rstreet'])) || (!isset($_POST['rcity'])) || (!isset($_POST['rstate'])) || (!isset($_POST['rphone'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);  
        die('You did not form fully.');        
    }
    else
    {
            $data['rname']=$_POST['rname'];
            $data['rstreet']=$_POST['rstreet'];
            $data['rcity']=$_POST['rcity'];
            $data['rstate']=$_POST['rstate'];
            $data['rphone']=$_POST['rphone'];
            
            $data['rname']=strtolower($data['rname']);
            $data['rstreet']=strtolower($data['rstreet']);
            $data['rcity']=strtolower($data['rcity']);
            $data['rstate']=strtolower($data['rstate']);
            $data['rphone']=strtolower($data['rphone']);
    }  

    if((!isset($_POST['laterent'])) || (!isset($_POST['nonsmoking'])) || (!isset($_POST['renttime'])) || (!isset($_POST['bankruptcy'])) || (!isset($_POST['bankruptcywhen'])) || (!isset($_POST['movein'])) || (!isset($_POST['felony'])) || (!isset($_POST['evictionnotice'])) || (!isset($_POST['evictionwhen'])) || (!isset($_POST['pets'])))
    {
        $ch = curl_init("https://tarterbrothers.com/filled-form-incorrectly/");
        curl_exec($ch);
        die('You did not form fully.');        
    }
    else
    {
        $laterent=$_POST['laterent'];
        $data['nonsmoking']=$_POST['nonsmoking'];
        $data['renttime']=$_POST['renttime'];
        $bankruptcy=$_POST['bankruptcy'];
        $data['bankruptcywhen']=$_POST['bankruptcywhen'];
        $data['movein']=$_POST['movein'];            
        $felony=$_POST['felony'];
        $evictionnotice=$_POST['evictionnotice'];                        
        $data['evictionwhen']=$_POST['evictionwhen'];
        $data['pets']=$_POST['pets'];
        
        $laterent=strtolower($laterent);
        $data['nonsmoking']=strtolower($data['nonsmoking']);
        $data['renttime']=strtolower($data['renttime']);
        $bankruptcy=strtolower($bankruptcy);
        $data['bankruptcywhen']=strtolower($data['bankruptcywhen']);
        $data['movein']=strtolower($data['movein']);            
        $felony=strtolower($felony);
        $evictionnotice=strtolower($evictionnotice);                        
        $data['evictionwhen']=strtolower($data['evictionwhen']);
        $data['pets']=strtolower($data['pets']);
    }
        

if else javascript syntax generating error mediaQuery not applied [closed]

I want this running to be able to have different js functions loaded for different screen sizes (mainly for very large screens).

// Create a mediaQuery that targets viewports from at least 1900px wide
const mediaQuery = window.matchMedia('(min-width: 1900px)')
// Check if the media query is true
if (mediaQuery.matches) {
  // Then run this
  $(window).on("load", function() {
    AOS.init();
  })
  // else run this:
  else {
    $(window).on("scroll", function() {
      AOS.init();
    });
  };
}

After many hours of trying and testing, I still can not get the syntax right. What is my fault here? The error output is:

Uncaught SyntaxError: expected expression, got keyword 'else'app.js:231:2

Which is referring to the else part.

I know the syntax need to be like this:

 if (condition) {
      //  block of code to be executed if the condition is true
    } else {
      //  block of code to be executed if the condition is false
    }

But I can not get it right. Any advice on this thanks.

Ternary operator error: potential misuse of operator?

I'm trying to use a ternary operator and am still learning so I'm not entirely familiar with how they do what they do.

I have a line of code that is as follows:

c.GetType() != typeof(CheckBox)
? c.Text = settingValue 
: ((CheckBox)c).Checked = bool.Parse(settingValue);

The purpose of this line of code is to test if the control c is of type CheckBox and then either set the text of the control or change the Checked state of the control. But this line gives me a CS0201 error in VS.

I know I could alternatively use an If statement for this but I wanted to see if I could condense it into one line with a ternary operator. What am I missing?

How to check object type from request.body in Typescript?

I need to check the object type from the request body and then run approbiate function based on this type, I try do this in this way:

export interface SomeBodyType {
    id: string,
    name: string,
    [etc....]
}

export const someFunction = async (req: Request, res: Response) => {
    const { body } = req.body;

    if (body instanceof SomeBodyType) {
        //run function A
    } else {
        // run function B
    }
}

but it not work, cause my SomeBodyType return me error: only refers to a type, but is being used as a value here.,

so, how can i check the type of the body in this case?

thanks for any help!

//// EDIT:

thanks to @phn answer I create this generic function to check object types:

export const checkObjectType = <T>(body: T): boolean => {
    return (body as T) !== undefined;
}

please, take a look and comment if this function is good

Nested if else and is blank in excel

Column A,B and C are dates Condition:

If column A date is present use the same date. If date in A column is blank then use date from column B. If column B is blank then use date from column C.

C has the final date.

Redo inside if in Ruby?

I inherited this code from a former co-worker, and it's giving me Invalid redo (SyntaxError) on the redo. Was there an older version of Ruby where this would've worked? I've tried 3, 2.7, 2.5, and 2.3, all without success.

def check_rate_limit(client, x, spinner)
    if client.rate_limit.remaining <= x
        spinner.error('ERROR: Rate limit exceeded!')
        spinner = TTY::Spinner.new("[:spinner] Rate limit resets in #{client.rate_limit.resets_in + 10} seconds ...", format: :classic)
        spinner.auto_spin

        sleep(client.rate_limit.resets_in + 10) # additional 10 second cooldown

        spinner.success

        spinner = TTY::Spinner.new("[:spinner] Continuing ...", format: :classic)

        redo
    end
end

(Replacing if with while seems to do the trick, but my co-workers code ran before and I want to know why...)

What is the use of return inside an if else block that isn't inside a function body? [closed]

I came across a code in which return is used inside an if-else block. But the if-else block is not inside a function body; and it doesn't throw any error. So what is the use of using return inside if-else that is not inside a function body? (Specifically for Node.js)

if(true) {
  return 'foo';
}

Here is the demo. Thanks in advance!!!

How to compare current date with dates from API to display different ImageView if the date from API greater, less, or equal to current date in Kotlin

I am getting dates from API based on what the user posted to the API

what i am trying to do here is displaying different ImageView if the date from API is greater, less, or equal to the current date

i have this bind function:

fun bind(event: PlannerGet) {
        val stringzz = event.date
        val date = LocalDate.parse(stringzz, DateTimeFormatter.ISO_DATE)
        val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-uuuu")
        val sdf = SimpleDateFormat("dd-MMM-yyyy")
        val c = Calendar.getInstance()
        try {
            c.time = sdf.parse(currentDate("dd-MMM-yyyy"))
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        val _date: String = sdf.format(c.time)
        val gregorianDate: LocalDate = LocalDate.parse(_date, dateFormatter)
        val islamicDate: HijrahDate = HijrahDate.from(date)


        mTextHijri.text = islamicDate.format(dateFormatter).toString()
        mTextNote.text = "${event.note}"
        mTextTitle.text = "${event.title} at ${event.location}"
        mTextIndex.text = "${getTime(event.startTime!!)} - ${getTime(event.endTime!!)}"
        mTextDate.text = (date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)))
        mTextTimeEstimated.text = getEstimated(getTime(event.startTime), getTime(event.endTime))

        
    }

and it is working fine, i tried to add if condition to the function like this:

if(mTextDate.toString() < _date){
            mTick.setImageResource(R.drawable.tick)
        }
        else if (mTextDate.toString() > _date){
            mTick.setImageResource(R.drawable.ic_logopng)
        }
        else if (mTextDate.toString() == _date){
            mTick.setImageResource(R.drawable.blue_logo)
        }

and i already posted 3 different dates in the API to compare but i ended up with the same ImageView every time, what am i doing wrong here?

and i also tried to compare straight away from the data class (Data class below):

data class PlannerGet(
val date: String,
val endTime: String,
val id: Int,
val location: String,
val note: String,
val startTime: String,
val title: String
)

but i ended up with the same ImageView every time

any suggestion to make this work?

lundi 30 août 2021

Will the .lower function in an if statement interrupt the correct input?

Python3 noob here. In the below code I expect if I enter "window" for the choice1 input then it would move on to the input prompt for choice2. But what I get instead is the else statement at the bottom, "You fell into a spike pit as you entered the house! Game Over." What am I doing wrong? Thanks

choice1 = input('You are in front of the house, which way do you want to enter? Type "front door" or "window" and hit Enter \n')
if choice1.lower == "window":
    choice2 = input('You snuck in through a window. You come to the foyer and can take the staircase upstairs or down to the basement. Type "basement" or "upstairs" and hit Enter to proceed \n')
    if choice2.lower == "upstairs":
        choice3 = input("You go upstairs and are in a hallway with 3 doors to enter: 1 red, 1 green, 1 blue. Which color door do you choose? \n")
        if choice3.lower == "red":
            print("The room is full of poisonous snakes! Game over.")
        elif choice3.lower == "green":
            print("You found the lost trick-or-treaters and lead them out of the haunted house to safety. You win!")
        elif choice3.lower == "blue":
            print("You ended up in a warewolf's room. It eats you! Game over.")
        else:
            print("This door doesn't exist... Game over.")
    else:
        print("You encountered a witch who cast a spell turning you into a rat! Game Over.")
else:
    print("You fell into a spike pit as you entered the house! Game Over.")```

Cypress | Chai assertions executes outside if else condition. Assertions are mentioned inside if condition

I am writing a cypress custom command, which fetches a json response from an API end point. I am writing some assertions on the json response. However, I have a if-else condition to be executed. See below.

cy.getReportJson('84b636f4-c8f0-4aa4-bdeb-15abf811d432',user).then(report=> {
                    
                    if(services.request_criminal_record_check.include){
                        console.log('inside if')
                        cy.wait(30000)
                        expect(report.report_summary.rcmp_result.status).equal(data.expected_result.rcmp_result.status)
                        expect(report.report_summary.rcmp_result.overall_score).equal(data.expected_result.rcmp_result.overall_score)
                        expect(report.report_summary.rcmp_result.result).equal(data.expected_result.rcmp_result.result)
                    }
                })

When I run this code in a spec file, the Output I get is as follows.

enter image description here

As you can see, the assertions are running, before the wait command is triggered. I want cypress to wait for 30 seconds, so that the back-end runs its magic and generates a report and after 30 seconds, i wanna assert on the report json. Even the console.log is printed after the assertions are executed.

Is this something related to the async nature of Cypress?

I have a bug when I am sending an array of data from each client over a server

I am working on a web app that uses a genetic algorithm to enable the user to pick the evolution of shapes - when a user makes a choice, it sends an array of data over a server, which is then retrieved on the other end and converted into a shape. I have it set up so that it only sends data when a user makes a choice, however this occasionally creates a bug that results in nothing being processed. This is where the error is occurring in my code:

receiveFit(data) {
  this.receive = data;
  
  this.dataArray.push(this.receive);    
  
  this.population = clientCount;   

  if(this.dataArray.length >= this.population){
      
      // if you want to mix them all 
      
      let i = 0;
      let start = new DNA(this.dataArray[0].genes);
      for (let dna of this.dataArray) {
        if (i!=0) {
            let current = new DNA(this.dataArray[i].genes);
            start = start.crossover(current);
        }
        
        i+=1;
      }
      
      // in theory start now is an amalgamation of all of them

        this.fittest = new Fittest(start, width/2, height/2);
        this.glyph = new Glyphs(start);
        
        this.dataArray = [];
    } 

}

I am receiving an array of data from the server, which I am then pushing onto another array. this.population is a variable that is counting the amount of people on the server - I have written an if statement that says is the array of arrays is greater than or equal to the amount of clients, execute the code that combines all of the choices.

I believe the reason it misses choices is that the array doesn't always equate to the amount of clients if someone decides not to make a choice, however I cant figure out what to do to solve this. Any advice would be appreciated!

How to create IF statement to check for objects in a list inside JSON data?

This following datastructure is in JSON. I want to know how I can write an if statement to check if there are any objects inside the key causes_virtual. I have tried using both if len(api_response_article[0]['causes_virtual']) == 0: or if not api_response_article[0]['causes_virtual']: , however neither of these works. Could this be because there are dictionaries inside of a list

{
    "additional_info": "",
    "approved_at": null,
    "approved_by_id": null,
    "causes_virtual": [           # THIS SECTION
        {
            "id": 5408600,
            "models": [
                "Potatoes"
            ],
            "principals": "Some irrelevant text",
            "title": "We farm potatoes or something"
        }
    ],
    "created_at": "2021-03-03T01:13:04.477348+00:00",
    "created_by_id": 1019500
}

Any pointers would be helpful. Thanks in advanced!

Collectionview going to if condition but not being called else condition in Swift

I am using two collectionviews and calling them according to conditions

Initially, I want to show newCollectionview with newArray images.

code for collectionviews: with this code isEdit condition working perfectly.

But initially when I upload images from picker then in cellForItemAt else condition not being called and added images in newArray are also not showing in newCollectionView.

but when I coming from isEdit then if collectionView == newCollectionView is working but if it's not from isEdit then it's not calling, why?

Here numberOfItemsInSection is also calling.. but images not showing in row

struct ImagesModel{

public var image : String?
init(image: String?) {
    self.image = image
}
}


import UIKit

class BidPlaceVC: UIViewController, UITextViewDelegate {

var oldArray = [ImagesModel]()
var newArray = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    let layout = UICollectionViewFlowLayout()
    
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    layout.scrollDirection = .horizontal
    let width = UIScreen.main.bounds.width/4.1
    let height = width*1.1
    
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 5
    layout.itemSize = CGSize(width: width, height: 100)

    self.newCollectionView.collectionViewLayout = layout
    
    self.oldCollectionnview.collectionViewLayout = layout

    newCollectionView.reloadData()
    oldCollectionnview.reloadData()
 }
 
}

extension BidPlaceVC : UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    if isEdit {// here all conditions working
        if newArray.isEmpty{

        if collectionView == oldCollectionnview{

        return  oldArray.count
        }
        }
        else{
            if collectionView == oldCollectionnview{

            return  oldArray.count
            }
            if collectionView == newCollectionView{

            return  self.newArray.count
            }
        }
        
    }else {
        if collectionView == newCollectionView{

        return  self.newArray.count// is calling
        }
    }
    return newArray.count
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if isEdit{
        
        if newArray.isEmpty{
            if collectionView == oldCollectionnview{

              let cell = oldCollectionnview.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

               let img = "\(CommonUrl.bidsAttachment)\( self.oldArray[indexPath.item].image ?? "")"
               cell?.imgView.getImage(withUrl: img, placeHolder: #imageLiteral(resourceName: "home"), imgContentMode: .scaleAspectFill)
                return cell!
            }

        }
        else{
            
            if collectionView == oldCollectionnview{

                let cell = oldCollectionnview.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

               let img = "\(CommonUrl.bidsAttachment)\( self.oldArray[indexPath.item].image ?? "")"
               print("\(img)")
               cell?.imgView.getImage(withUrl: img, placeHolder: #imageLiteral(resourceName: "home"), imgContentMode: .scaleAspectFill)
                   return cell!
            }
             // if i come from isEdit then its calling.. and images showing in newCollectionView
            if collectionView == newCollectionView{

               let cell = newCollectionView.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

                cell?.imgView.image = self.newArray[indexPath.item]
              
                return cell!
                
            }
            
        }
      
        }
        //******* here is not being called ******
       else{
        
        if collectionView == newCollectionView{

           let cell = newCollectionView.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell
            print("first time \(self.newArray)")
            cell?.imgView.image = self.newArray[indexPath.item]
            
            return cell!
        }
    }
    return UICollectionViewCell()

}

}


extension BidPlaceVC : EasyImagePickerDelegate{

func didSelect(image: UIImage?, video: URL?, fileName: String?) {
    if let img = image{
        self.imageProfile = img
    
        self.newArray.append(img)
        print("added images \(newArray)")
        self.newCollectionView.reloadData()
    }
}
}

please do help to solve this issue

How to produce an if statement to output the respective row [duplicate]

I have been working on some r code for a while, in which I am printing out the rows that have repeated cells, for example:

dataframe
Peptide | Domain | Count | Terminal 
AT1G4561  TH541     5        N
AT1G4561  RE123     6        N
AT4G6789  RT990     2        C
ATM43312  TH324     1        N

I have produced for loops with nested if statements to run through this dataframe (about 60,000 rows long) to keep only those with repeated 'Peptide' names. For example the data kept and printed here would be:

Peptide |
AT1G4561
AT1G4561

I have used this code so far:

new_res <- list()
for (i in 1:nrow(dataframe)) {
  if(isTRUE(dataframe$Peptide[i+1] == dataframe$Peptide[i])) {
    output <- print(dataframe$Peptide[i+1])
    new_res[[i+1]] <- output
    output <- print(dataframe$Peptide[i])
    new_res[[i]] <- output
  }
}

This outputs all of the peptide names that appear more than once into the list new_res. However I want to output the entire row containing the respective peptides. So I would have this as an output instead of just the peptide names:

new_res
Peptide | Domain | Count | Terminal 
AT1G4561  TH541     5        N
AT1G4561  RE123     6        N

I've tried to get this to work but I haven't had any success so far. Please could someone help me to figure out how I could go about this? Thanks in advance.

Why does just assigning setTimeout to a variable simply executes the argument function, inside if statement in javascript? [duplicate]

I have a simple if statement with 'true' as condition now my code isI assigned a variable a the value of setTimeout but i dont want to execute it but javascript still executes it, Why?

if(true){
        var a = setTimeout(alert("hello world"), 3000);
    }

Nested IF in Google Sheets Issue

I have a column of dates, with IF formulas in two other columns. The first IF statement looks for the Max Date in the date list and simply prints TRUE when found.

The second IF statement is meant to print TRUE when the most recent date prior to the Max Date is found.

Originally, I had the following for this:

=IF(B2=WORKDAY(MAX(QQQ!B:B), -1),TRUE,FALSE)

On occasion, however, a day of data will not exist, so the statement must continue beyond Max Date - 1. For this, I tried:

=IF(B2=WORKDAY(MAX(QQQ!B:B), -1),TRUE,IF(B2=WORKDAY(MAX(QQQ!B:B), -2),TRUE,IF(B2=WORKDAY(MAX(QQQ!B:B), -3),TRUE,FALSE)))

The issue with this second approach is TRUE prints for Max Date -2 and Max Date -3, when both exist. I expected that the final condition would be skipped when Max Date - 2 exists, but that's not what occurs.

Any ideas on how this might be better handled are appreciated.

If statement- python [closed]

I have this question in my H.W: Write a program that displays the discount that is applied to the number of phone accessories (each priced at 2.75 ) purchased according to this table: Quantity Discount 10‐19 10% 20‐49 20% 50‐99 30% 100+ 40%

and I wrote this code but it keeps telling me that there's something wrong..
''''

    accessories=(float(input("Enter the number of accessories purchased: "))
if accessories < 10:
 

    print("no discount, sorry!")

elif accessories >= 10 and accessories <=19:
 DISCOUNT10=(accessories*2.75*90)/100
 print(DISCOUNT10)
elif accessories >=20 and accessories <=49: 
  DISCOUNT20=(accessories*2.75*80)/100
 print(DISCOUNT20)
elif accessories >= 50 and accessories <=99:  
  DISCOUNT30= (accessories*2.75*70)/100
 print(DISCOUNT30)
else accessories >=100:
  DISCOUNT40= (accessories*2.75*60)/100
 print(DISCOUNT40)

''' can anyone help me?

How to Check if php variable have numeric or from certain string characters using php? [duplicate]

I want if $pro_case is not either a numeric (any numeric) value or string from these names only the answer will be FALSE else must be TRUE response from this Code.

$pro_case = "Australia";
   if(!is_numeric($pro_case) || $pro_case != "Africa" ||  "Europe" || "North America" || "South 
    America" || "Australia"){
    echo FALSE;
   }else{
    echo TRUE;
  }

I only got FALSE response from this Code even Australia is in there.

EDIT: $pro_case must be either any numeric value or

"Africa" ||  "Europe" || "North America" || "South 
        America" || "Australia"

to get only TRUE answer.

I tried with in_array method but the problem is the numeric vale can be any number. What could be the problem?

'if' blocks is not compatible with return type of other block(s) (series[string]; void)

can you help me? i don't understand where is bug:

//@version=4
study("FOR break test")
string = ""
for _i = 1 to 7 
//{
    if abs(close - open) < 10000 
        break 
    else    
        string := string + tostring(_i, "00") + "•" + tostring(close[_i]/1000, "0000") + " \n"
//}
label.new(bar_index, 0, string, style = label.style_none, textcolor=color.red, size = size.normal, textalign = text.align_left)

Konstantin

After reading the excel file and maping it in the Array in react, Why the last value is always undefined

Sheet Property contains the whole ExcelSheet in JSON format. Dayofthemonth is the Array that contains the value in days (1,2,3....31), which has been mapped from the Sheet. It is working but the also an extra value of undefined in entering in the array after mapping. I have attached the ss of console.log.

I don't understand that where does this undefined value come from.

if anybody knows the Ans and solution, Kindly Help me.

   const GrossProfitView = ({ Sheet }) => {
  

  const Dayofthemonth = [...new Set(Sheet.map((each) => each.Dayofthemonth))];

 
  let DayofthemonthReport = [];
  let DayofthemonthChart = [];

  Dayofthemonth?.forEach((day) => {
    let Days = day;
    let Brokline = 0;
    let EastCostBeast = 0;
    let OneTeam = 0;
    let Thelvy = 0;
    let WestQueens = 0;
    let ThatdayGp = 0;

    Sheet?.forEach((each) => {
      let OverallGP = each.NetProfit;
      let SheetDayofmonth = each.Dayofthemonth;
      let District = each.District;
    
        if (SheetDayofmonth === Days) {
          ThatdayGp = OverallGP + ThatdayGp;

          if (District === "One team One Mission") {
            OneTeam = OverallGP + OneTeam;
          }
          if (District === "West Queens") {
            WestQueens = OverallGP + WestQueens;
          }
          if (District === "The Ivy League") {
            Thelvy = OverallGP + Thelvy;
          }
          if (District === "B.K.S.I") {
            Brokline = OverallGP + Brokline;
          }
          if (District === "East Coast Beasts") {
            EastCostBeast = OverallGP + EastCostBeast;
          }
        }
      
    });
    
    const ThatdayGpChart = {
      GP: Math.round(ThatdayGp),
      EastCostBeast: Math.round(EastCostBeast),
      Brokline: Math.round(Brokline),
      Thelvy: Math.round(Thelvy),
      WestQueens: Math.round(WestQueens),
      OneTeam: Math.round(OneTeam),
      Dayofthemonth: Days,
    };

    DayofthemonthReport.push(ThatdayGpRecord);
   
  });

ss enter image description here

How to use onEdit to copy the data to another google sheet file and overwrite the data if the ID is the same?

enter image description here

enter image description here

Hi everyone,

I want to copy the data from source sheet to destination sheet. When the data reached the destination sheet, the script able to loop through row 2 in destination sheet to see whether any same ID already existed. If the ID already existed in row 2, then it will overwrite the data in the column, if not, the script will find the last empty column based on row 2 and paste the data there.

So in the screenshot above, since there is no 1004 in destination sheet, then it will paste the data in column E.

This is my code:

function onEdit(e){
  var ss = SpreadsheetApp.getActiveSheet ();
  var targetfile = SpreadsheetApp.openById("11tpC8SNZ5XB35n7GON0St3ZQ37dIbM8UbXRjmkVAeJQ");
  var target_sheet = targetfile.getSheetByName("Sheet1");
  var target_range = target_sheet.getRange(3, ss.getLastColumn() + 1);
  
  if (e.range.columnStart == 3 && e.range.rowStart == 16){
    if (e.value == 'Submit'){
      var source_range = ss.getRange("C4:C14")
      source_range.copyTo(target_range);
      e.range.clearContent()
    } 
  } 
}

My current problems are:

  • The script is not working when I triggered it in cell C16 (couldn't find the reason)
  • I'm not sure how to add the checking for ID in destination sheet into my script.

This are my google files

Source sheet: https://docs.google.com/spreadsheets/d/12kKQKT2XSdPkJ46LSV9OiI167NKBdwKkpkOtOf_r_jI/edit#gid=0

Destination sheet: https://docs.google.com/spreadsheets/d/11tpC8SNZ5XB35n7GON0St3ZQ37dIbM8UbXRjmkVAeJQ/edit#gid=0

Hope to get some advice and help from expert. Any help will be greatly appreciated!

Why selection-statement allows using of ; expression-statement?

It allows the constructs like:

if (0);
if (0); else;

Why allowing of such constructs?

Can the simplification of the grammar be the reason?

How to use if condition in initState() method while using YouTube video player and simple video player? I am also using Provider package

I am using a Youtube video player to play youtube links and a simple video player to play uploaded videos. I want to use the if statement in the InitState method, because without using it, I am unable to play Youtube videos. (I basically want to play videos of both types). Can anyone please help using it? Below is my code.

class VideoBox extends StatefulWidget {
  @override
  _VideoBoxState createState() => _VideoBoxState();
}

class _VideoBoxState extends State<VideoBox> {
  YoutubePlayerController _controller;

  void runYoutubePlayer() {
    final testdata = Provider.of<VideosModel>(context, listen: false);

    _controller = YoutubePlayerController(
        initialVideoId: YoutubePlayer.convertUrlToId(testdata.link),
        flags: YoutubePlayerFlags(
          enableCaption: false,
          autoPlay: false,
          isLive: false,
        ));
  }

  @override
  void initState() {
    final testData = Provider.of<VideosModel>(context, listen: false);

    if (testData.link != null) {
      runYoutubePlayer();
    }

    super.initState();
  }

  @override
  void deactivate() {
    _controller.pause();
    super.deactivate();
  }

  @override
  void dispose() {
    _controller.dispose();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final testData = Provider.of<VideosModel>(context, listen: false);

    if (testData.video == null) {
      return YoutubePlayerBuilder(
        player: YoutubePlayer(
          controller: _controller,
        ),
        builder: (context, player) {
          return Container(
            height: 24.0.h,
            width: 100.0.w,
            child: player,
          );
        },
      );
    } else {
      return Container(
          height: 24.0.h,
          width: 100.0.w,
          child: VideoItem(
              'https://hospitality92.com/uploads/videos/' + testData.video));
    }
  }
}

the if requirement is simply skipped through in php [duplicate]

<script>
if (confirm("Are you sure you want to save this thing into the database?")) { 
  var jvalue = "LEVELISGOINGUP!";
  alert(jvalue);
} else {  
  var jvalue = "null";
  alert(jvalue);
}
</script>

<?php 
  $valueofjs = "" . "<script>document.writeln(jvalue)</script>";
  if($valueofjs == "LEVELISGOINGUP!"){
    echo 'it's work!';
  }
?>

I'm using a JS var for an if condition. the var name is jvalue and I convert it to PHP var $valueofjs.

I already trying to post the $valueofjs value by echo and it's working fine.

but when I'm using it as for if the condition it didn't work. it just passes through like the condition wasn't met.

Please help! Thank you.

BIGQUERY: IF table exists start query SQL

I want to execute my SQL command, if a certain table "t1" exists in the the dataset "d".

I tried:

IF (EXISTS (Select * From d.INFORMATION_SCHEMA.TABLES WHERE Table_Schema like 't1*')) Then ---DO Stuff---- Else Stop query and repeat in 1 hour;

The last part doesnt work. Syntax error: Expected ";" but got keyword END.

Thanks a lot.

Don't know what I did wrong with the logical operator "OR"

I don't find my mistake in the following formula

=if(AB207<=DATE(2019,8,1),(Z207*0.075),(Z207*0.15);OR if Date =(#N/A)(Z207*0.15))

I want the Formula to multiply the cell Z207 with 0.15 if the "value" is #N/A

Hope someone can help me

else condition Collectionview rows not showing in swift

I am using two collectionviews and showing and hiding them according to conditions

initially i want to show newCollectionview with newArray images

code for collectionviews: with this code isEdit condition working perfectly.. but inatially when i upload images from picker then in cellForItemAt else condition not calling and added images(newArray) are also not showing in newCollectionView

here numberOfItemsInSection else return self.newArray.count is calling and count showing but the images not showing in newCollectionView

struct ImagesModel{

public var image : String?
init(image: String?) {
    self.image = image
}
}


import UIKit

class BidPlaceVC: UIViewController, UITextViewDelegate {

var oldArray = [ImagesModel]()
var newArray = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    let layout = UICollectionViewFlowLayout()
    
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    layout.scrollDirection = .horizontal
    let width = UIScreen.main.bounds.width/4.1
    let height = width*1.1
    
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 5
    layout.itemSize = CGSize(width: width, height: 100)

    self.newCollectionView.collectionViewLayout = layout
    
    self.oldCollectionnview.collectionViewLayout = layout

    newCollectionView.reloadData()
    oldCollectionnview.reloadData()
 }

 func uploadServiceCall() {

    let param = ["service_request" : bserviceId!, "amount" : amountTf.text ?? "100", "no_of_hours" : "2", "description" : proposalTextView.text ?? ""] as [String : Any]
    var imgData = [Data]()
    for image in self.newArray {
        imgData.append(image.jpegData(compressionQuality: 0.5)!)
    }
    APIReqeustManager.sharedInstance.uploadMultipleImagesWithParam(url: CommonUrl.place_bid, imagesData: imgData, imageKey: "files", parameters: param, vc: self, loaderNeed: true, completionHandler: {(responseData) in
        DispatchQueue.main.async {
            self.newCollectionView.reloadData()
        }
}

}

extension BidPlaceVC : UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    if isEdit {
        if newArray.isEmpty{

        if collectionView == oldCollectionnview{

        return  oldArray.count
        }
        }
        else{
            if collectionView == oldCollectionnview{

            return  oldArray.count
            }
            if collectionView == newCollectionView{

            return  self.newArray.count
            }
        }
        
    }else {
        if collectionView == newCollectionView{

        return  self.newArray.count// is calling
        }
    }
    return newArray.count
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if isEdit{
        
        if newArray.isEmpty{
            if collectionView == oldCollectionnview{

              let cell = oldCollectionnview.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

               let img = "\(CommonUrl.bidsAttachment)\( self.oldArray[indexPath.item].image ?? "")"
               cell?.imgView.getImage(withUrl: img, placeHolder: #imageLiteral(resourceName: "home"), imgContentMode: .scaleAspectFill)
                return cell!
            }

        }
        else{
            
            if collectionView == oldCollectionnview{

                let cell = oldCollectionnview.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

               let img = "\(CommonUrl.bidsAttachment)\( self.oldArray[indexPath.item].image ?? "")"
               print("\(img)")
               cell?.imgView.getImage(withUrl: img, placeHolder: #imageLiteral(resourceName: "home"), imgContentMode: .scaleAspectFill)
                   return cell!
            }
             // if i come from isEdit then its calling.. and images showing in newCollectionView
            if collectionView == newCollectionView{

               let cell = newCollectionView.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell

                cell?.imgView.image = self.newArray[indexPath.item]
              
                return cell!
                
            }
            
        }
      
        }
        //******* here is not calling ******
       else{
        
        if collectionView == newCollectionView{

           let cell = newCollectionView.dequeueReusableCell(withReuseIdentifier: "FilesCollectionCell", for: indexPath) as? FilesCollectionCell
            print("first time \(self.newArray)")
            cell?.imgView.image = self.newArray[indexPath.item]
            
            return cell!
        }
    }
    return UICollectionViewCell()

}

}


extension BidPlaceVC : EasyImagePickerDelegate{

func didSelect(image: UIImage?, video: URL?, fileName: String?) {
    if let img = image{
        self.imageProfile = img
    
        self.newArray.append(img)
        print("added images \(newArray)")
        self.newCollectionView.reloadData()
    }
}
}

Is there a way to find the time elapsed from a datetime column in a dataframe based on a certain condition?

I have a data frame called actions. The columns are user_id, action_timestamp and action. The users are students who perform an action at a specific time given by the action_timestamp.

Which student has spent the longest uninterrupted session? (here a “session” is defined as a length of time where a student performs a series of actions with less than 10 minutes in between them; the “session” stop when the next action in the series has been performed 10 minutes or more after the last one, after which a new “session” starts)subset of df

The code I am trying:

new['diff']= new['action_timestamp'].diff().astype('timedelta64[m]')

for i in new['diff']:
    if not np.isnan:
        if (i <=10.0):
            new['session']= 1.0
        else:
            new['session']=0.0

new.loc[new['diff'] <= 10.0, 'session'] = 1.0 
new.loc[new['diff'] > 10.0, 'session'] = 0.0 

This does not prove to be the right answer. Any help would be much appreciated. Thank you.

Show image only if the image is loaded from the database

I have a problem. I am searching in a database to see if a picture exists. If the image is not present, a "No Image" image is set. If an image is available, the current image from the database is displayed.

What I would like to do now is to display a loading spinner, which should only be displayed if an image is available in the database and the image from the database is still loading.

I now have the following problem: when I load an image from the database, everything fits. However, as soon as I don't have an image from the database, "No Image" is displayed and the loading spinner is also displayed. How can I now say that only the loading spinner should be displayed if dataPic is not zero and the image has not yet loaded?

import React, { useEffect, useState, useRef } from 'react'
import axios from 'axios'
import { Spinner } from 'react-spinners-css';

import nophoto from '../../../data/images/nophoto.png'

const id = (window.location.pathname).split("-")[1];

function Team() {

    const [imgLoaded, setImgLoaded] = useState(false);  

    const [dataPic, setDataPic] = useState(null);
    const getPhoto = () => {
        axios
            .get(`${process.env.REACT_APP_API_URL}/photo-${id}`,

        )
            .then((res) => {
                if (res.status === 200) {
                    var parts = res.data.split(",");
                    var result = parts[parts.length - 1];
                    setDataPic(result);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    useEffect(() => {
        getPhoto();
    }, []);

    return (
        <div>
            {/*here ist the problem*/}
            {imgLoaded && dataPic === null ? null :
                <div>
                    <Spinner color="#5869FF" style= />
                    <p>Is loading...</p>
                </div>
            }
            {
                dataPic === null ?
                    <img src={nophoto} alt="hi"/>
                    :
                    <img src={`data:image/png;base64,${dataPic}`} alt="hi" onLoad={() => setImgLoaded(true)} />

            }


    )
}

export default Team

dimanche 29 août 2021

nested if loop in splunk

I would like to write in splunk a nested if loop: What I want to achieve

if buyer_from_France: 
   do eval percentage_fruits
   if percentage_fruits> 10:
        do summation
        if summation>20:
                   total_price
                   if total_price>$50:
                              do(trigger bonus coupon)

My current code (that works):

> | eventstats sum(buyers_fruits) AS total_buyers_fruits by location
> | stats sum(fruits) as buyers_fruits by location buyers 
> | eval percentage_fruits=fruits_bought/fruits_sold 
> | table fruits_bought fruits_sold buyers
> | where percentage_fruits > 10
> | sort - percentage_fruits

How do I complete the syntax/expression for the 2nd (summation) and consequently, 3rd (total price), 4th if-loop (trigger)?

VBA If Statement if Row is not Outlined

The below is used to control code depending on outline level of row. It is working except for when there is no outline level.

Is it correct to use OutlineLevel = 0 when no outlining? I cannot find any information on this.

If ActiveCell.Rows.OutlineLevel = 0 Then MsgBox "No group Selected", vbCritical, "Admin": Exit Sub
    
If ActiveCell.Rows.OutlineLevel = 2 Then MsgBox "Please Collapse group first", vbCritical, "Admin": Exit Sub
        
If ActiveCell.Rows.OutlineLevel = 1 Then

How To Prevent WordPress from automatically adding p tags on ONLY one page

I have one page on my WordPress website that has some custom code on it (I cannot use Gutenberg blocks, only the classic Text/Visual editor). This code does not work because WordPress keeps adding p tags everywhere.

I tried adding this code to my functions.php, but it does not work. Can anyone help me to understand why this code doesn't work and how to stop WordPress from auto-generating p tags on just this 1 page?

if($post->ID == 352331) {
    remove_filter( 'the_content', 'wpautop' );
}

What is the issue with the syntax error I am receiving? [closed]

I am having an issue when trying to work on a rock, paper, scissors game. I am getting an error:

Error: expected ';' before '{' token

I have looked over my code to the best of my ability, but I am not having any luck solving the issue. It is my second day learning, so I would appreciate any feedback.

#include <iostream>

using namespace std;

int rock = 1;
int paper = 2;
int scissors = 3;   

int main()
{
    cout << "Rock, paper, or scissors?: " << endl;
    cout << "1: Rock" << endl;
    cout << "2: Paper" << endl;
    cout << "3: Scissors" << endl;
    cout << "Enter your choice: ";
    int userChoice;
    cin >> userChoice;

    if(userChoice = 1){
        cout << "You choose rock";
    }
    else(userChoice = 2){
        cout << "You chose paper";
    }else(userChoice = 3){
        cout << "You chose scissors";
    }

And or operators in one line if statement [closed]

I have the following line of code which I would like to amend with one more condition,

file_names = [f for f in os.listdir(source_dir) if not f.startswith('.')]

so it would also NOT include directories; however, it does not seem to work:

file_names = [f for f in os.listdir(source_dir) if not f.startswith('.') and os.path.isdir]

Is there a way around to keep the expression in one line?

I'm using pure JavaScript but I continue to get errors that end with "is not a function". How do make it so I can detect words and reply accordingly?

I want to detect a specific word or multiple words within the user's entered text and reply accordingly. I plan to add more words to detect but for now I've been using this. My result is finalKey.contains is not a function.

<html>
<div>
  <p1 id="iOut">🧰</p1>
</div>
<div>
  <input id="uIn" value=""></input>
</div>
<button onclick="regis()">SUBMIT</button>

<script>
  var key = document.getElementById("uIn").value;
  var finalKey = key.toUpperCase();

  function regis() {
    if (finalKey.contains("Hi" || "H")) {
      document.getElementById("iOut").innerHTML = "HEY";

    } else if (finalKey.contains("Bye" || "Goodbye")) {
      document.getElementById("iOut").innerHTML = "Okay";

    } else {
      document.getElementById("iOut").innerHTML = "🧰 Try again";
    }
  }
</script>

</html>

If statement conditional is getting ignored in R

I have a dataframe(df) with 20,000 rows that looks like this:

     type letter
1     a     a
2     a     k
3     a     j
4     a     c
5     a     p
...  ...   ...
2523  i     v
2524  i     j
2525  i     k
2526  i     b
...  ...   ...
7900  a     p
7901  a     x
7902  a     c
...  ...   ...

I want to create a new column 'match' based on two conditions: (1) MATCH if type==a and letter==a, b, or c (2) MATCH if type==i and letter==i, j, or k

So I ran if statements:

a.letter=c("a", "b", "c")
i.letter=c("i", "j", "k")

if (df$type=="a") {
  df$match <- ifelse(df$letter %in% a.letter, "MATCH", "NO MATCH")
} else if (df$type=="i") {
   df$match <- ifelse(df$letter %in% i.letter, "MATCH", "NO MATCH")
}

My desired output is this:

     type letter match
1     a     a    MATCH
2     a     k    NO MATCH
3     a     j    NO MATCH
4     a     c    MATCH
5     a     p    NO MATCH
...  ...   ...   ...
2523  i     v    NO MATCH
2524  i     j    MATCH
2525  i     k    MATCH
2526  i     b    NO MATCH
...  ...   ...   ...
7900  a     p    NO MATCH
7901  a     x    NO MATCH
7902  a     c    MATCH
...  ...   ...

However, it seems like the second if statement is getting totally ignored. My current output looks like this:

     type letter match
1     a     a    MATCH
2     a     k    NO MATCH
3     a     j    NO MATCH
4     a     c    MATCH
5     a     p    NO MATCH
...  ...   ...   ...
2523  i     v    NO MATCH
2524  i     j    NO MATCH
2525  i     k    NO MATCH
2526  i     b    NO MATCH
...  ...   ...   ...
7900  a     p    NO MATCH
7901  a     x    NO MATCH
7902  a     c    MATCH
...  ...   ...

To troubleshoot, I tried testing with just one if statement and, oddly enough, it would work perfectly fine for the first conditional, but not the second conditional.

This works:

if (df$type=="a") {
 df$match <- 0
}

But this doesn't (no new column created):

if (df$type=="i") {
 df$match <- 0
}

Why would R not recognize my second conditional entirely?

Which is the best approach to handle nested conditional rendering?

I recently installed eslint-config-airbnb and decided to review a project by using their style guide. Since it is not advised to nest ternary operators I found myself converting the following block:

<div>
  { index === 0 ? <StatusButton big programmed statusText="Programmed" />
  : index === 1 ? <StatusButton big confirmed statusText="Confirmed" />
  : <StatusButton big soldOut statusText="Sold Out" />; }
</div>

Into:

<div>
    {(() => {
      if (index === 0) {
        return (
          <StatusButton
            big
            programmed
            statusText="Programmato"
          />
        );
      }
      if (index === 1) {
        return (
          <StatusButton big confirmed statusText="Confermato" />
        );
      }
      return <StatusButton big soldOut statusText="Sold Out" />;
    })()}
</div>

The reason of the rule no-nested-ternary is that the code should be more easier to read by using if, but honestly, I think that's not true. Since I have relatively little experience with JS I would like to understand your point of view. Thank you.

Why is my if statement not working javascript?

I've created an If statement to return a boolean if a word has to of the same consecutive letters, but my code is only returning false and idk why

const doubleLetters = word => {
   let letters = word.split('')

   for(let i = 0; i < letters.length; i++){
      if (letters[i] === letters[i + 1]){
         return true
      } else{
         return false
      }
   }
}

could someone assist me? I've compared my code to

function doubleLetters (word) {
   const letters = word.split('') 
   for (let index = 0; index < letters.length; index++) {
     
     if (letters[index] === letters[index + 1]) {
       return true
     }
   }
   return false
 }

which appears to be working correctly. It looks like my code, but maybe I'm missing something since mine is broken. Thanks in advance

What is the proper way to use if/else statements in my code to check CSV records that equal 'N/A'? [duplicate]

Some of the CSV's contain rare cases of data that I need to create cases for. I'm parsing the string values to doubles to perform checks but some files contain 'N/A' in the record. How do I correctly perform the check so that it doesn't Double.parseDouble a string. That is the error I'm getting.

public CSVRecord lowestHumidityInFile(CSVParser parser) {
    CSVRecord lowestSoFar = null;
    for (CSVRecord record : parser) { 
        if (lowestSoFar == null) {
            lowestSoFar = record;
        }
        //Otherwise
        else if (record.get("Humidity") != "N/A") {
            double currentHum = Double.parseDouble(record.get("Humidity"));
            double lowestHum = Double.parseDouble(lowestSoFar.get("Humidity"));
            if (currentHum < lowestHum) {
                lowestSoFar = record;
            }
        }
    }
    return lowestSoFar;
}
public CSVRecord lowestHumidityInManyFiles() {
    CSVRecord lowestSoFar = null;
    DirectoryResource dr = new DirectoryResource();
    for (File f : dr.selectedFiles()) {
        FileResource fr = new FileResource(f);
        CSVRecord currentHum = lowestHumidityInFile(fr.getCSVParser());
        if (lowestSoFar == null) {
            lowestSoFar = currentHum;
        }
        else if (currentHum.get("Humidity") != "N/A") {
            double currentHumidity = Double.parseDouble(currentHum.get("Humidity"));
            double lowestHumidity = Double.parseDouble(lowestSoFar.get("Humidity"));
            if (currentHumidity < lowestHumidity) {
                lowestSoFar = currentHum;
            }  
        }
    }
    return lowestSoFar;
}

public void testLowestHumidityInFile() {
    FileResource fr = new FileResource();
    CSVRecord lowest = lowestHumidityInFile(fr.getCSVParser());
    System.out.println("Lowest Humidity was " + lowest.get("Humidity") + " on " + lowest.get("DateUTC"));

}

public void testLowestHumidityInManyFiles() {

    CSVRecord lowestFiles = lowestHumidityInManyFiles();
    System.out.println("Lowest Humidity was " + lowestFiles.get("Humidity") + " at " + lowestFiles.get("DateUTC"));

}

How to check if modulus of 2 number is equal to 0 or not

Few days ago I wrote a program to check if a number have a square root with no decimal point. And I wrote a simple program code below:

#include <iostream>
#include <math.h>

int checkforFloat(int x, int y)
{
    //will return 0 if no remainder remains, other value meaning has remainder
    return x%y;
}

int main()
{
    while(true)
    {
        std::cout << "Enter number to check if it has square root: ";
        double squareNumber{};
        std::cin >> squareNumber;

        double squareRoot{sqrt(squareNumber)};

        if(checkforFloat(squareNumber, squareRoot)==0)
        {
            std::cout<<"The number you entered has a square root number, and that is " << squareRoot << '\n';
        }
        else if(checkforFloat(squareNumber, squareRoot)!=0)
        {
            std::cout<<"Sorry, " << squareNumber << " has no square root.\n";
        }
    }

    return 0;
}

and the output for this program looks like this:

Enter number to check if it has square root: 25
The number you entered has a square root number, and that is 5
Enter number to check if it has square root: 24
The number you entered has a square root number, and that is 4.89898
Enter number to check if it has square root: 225
The number you entered has a square root number, and that is 15
Enter number to check if it has square root: 226
Sorry, 226 has no square root.

As you can see, this line is not working properly (or I am unable to understand where is the problem) else if(checkforFloat(squareNumber, squareRoot)!=0) I don't know what's going on but the thing what is going wrong with this program is it prints the square rooted number even if the square root is floating point number. In the other hand if I use int not double as data type for variable squareNumber and squareRoot it doesn't work for me. I'm not sure if the problem is in the else if statement or not. I'm new to C++ so it's kinda hard for me to know what is going wrong.

PHP: HYPERPAY payment gateway options (Adding one more else if)

The website currently have 2 payment options (Mada, Visa/Master). I want to add ApplePay option.

The code is using ternary operator

I want to change it to a readable if/else statement but the result gives 500 error.

The old code (working):

$data = "entityId=" . ($request->payment_option == 'hyperpay_mada' ? env('HYPERPAY_MADA_ENTITY') ? env('HYPERPAY_VISA_ENTITY') : env('HYPERPAY_APPLEPAY_ENTITY') ).
            "&amount=" . str_replace(',','',number_format($order->grand_total,2)) .
            "&currency=SAR" .
            "&billing.city=" .$order->city.
            "&billing.state=" .$order->city.
            "&billing.postcode=0000".
            "&billing.country=SA".
            "&customer.givenName=" .$order->name.
            "&paymentType=DB" .
//            "&testMode=EXTERNAL" .
            "&customer.email=" . (!empty(session('shipping_info')['email']) && session('shipping_info')['email'] != 'null' && session('shipping_info')['email'] != null ? session('shipping_info')['email'] :'shopcustomer'. rand(10000, 99999).'@parduswear.com') .
            "&merchantTransactionId=" . uniqid();

What I am trying to do:

function paymentMethods() {
                if($request->payment_option == 'hyperpay_mada'){
                    env('HYPERPAY_MADA_ENTITY').
                } elseif($request->payment_option == 'hyperpay_visa'){
                    .env('HYPERPAY_VISA_ENTITY').
                } elseif($request->payment_option == 'hyperpay_applepay'){
                    env('HYPERPAY_APPLEPAY_ENTITY').
                }
            }
            
            $data = "entityId=" . paymentMethods() .
            "&amount=" . str_replace(',','',number_format($order->grand_total,2)) .
            "&currency=SAR" .
            "&billing.city=" .$order->city.
            "&billing.state=" .$order->city.
            "&billing.postcode=0000".
            "&billing.country=SA".
            "&customer.givenName=" .$order->name.
            "&paymentType=DB" .
//            "&testMode=EXTERNAL" .
            "&customer.email=" . (!empty(session('shipping_info')['email']) && session('shipping_info')['email'] != 'null' && session('shipping_info')['email'] != null ? session('shipping_info')['email'] :'shopcustomer'. rand(10000, 99999).'@parduswear.com') .
            "&merchantTransactionId=" . uniqid();

I tried also adding the if statement without creating a function yet gives me the same 500 error.

samedi 28 août 2021

How to use an if else function inside the server on a shiny app?

Hi again and thanks for reading me. I am working on an app with interactive graphics and I would like different graphics to be rendered for each case, but I am getting the following error:

Error : Can't access reactive value 'alumnos' outside of reactive consumer.
ℹ Do you need to wrap inside reactive() or observer()?

Anyone know what it could be? The app code is as follows:

library(readxl)
library(shiny)
library(echarts4r)
library(dplyr)
asistencias <- read_excel("/Users/jorge_hca/Desktop/nombres.xlsx", sheet = "Asistencias")
calificaciones <- read_excel("/Users/jorge_hca/Desktop/nombres.xlsx", sheet = "Calificaciones")


calificaciones <- calificaciones |> 
  mutate( `Promedio tareas` = rowMeans(calificaciones[2:(length(calificaciones)-3)  ]) )

calificaciones <- calificaciones |> 
  mutate( `Promedio examenes` = rowMeans( calificaciones[(length(calificaciones)-3):(length(calificaciones)-2)] ) )


calificaciones <- calificaciones |> 
  mutate(`Calificación final` = round( (`Promedio tareas`*0.3)+
                                    (`Promedio examenes`*0.7)+
                                    `Punto extra`, digits = 2 
                                        
                                        )
         )
calificaciones <- calificaciones |> 
  mutate(`Calificación actas` = round(`Calificación final`, digits = 0)
         )


lista <- data.frame(asistencias$Alumno)
lista <- rbind("Todos", lista)


ui <- fluidPage(
  
  selectInput("alumnos", "Selecciona a un alumno:",
              choices = lista$asistencias.Alumno
              ),
  echarts4rOutput("grafico")
)

server <- function(input, output){
  reactive({
    calificaciones <- calificaciones
  })
  output$grafico <- if (input$alumnos == "Todos"){
    renderEcharts4r(
      calificaciones() |> 
        e_charts() |> 
        e_histogram(`Calificación final`)
    )
  }else{
    renderEcharts4r(
      calificaciones() |> 
        e_charts() |> 
        e_histogram(calificaciones$`Tarea 2` )
    )
  }
  
}
shinyApp(ui, server)

Stuck On Adding Ability to Switch Player Turns in Tic-Tac-Toe Game

Trying to build the tic-tac-toe game and stuck on the part with the alternation of players. The player marks ('X' or 'O') are defined in the factory function that creates the players. I am able to get it to where the squares on the gameBoard can populate the appropriate mark, but I can't seem to figure out why it will not alternate between player 1 and player 2.

//Tic-Tac-Toe board pieces and DOM elements
let ticTacToeBoard = (function() {
  let topLeft = document.querySelector('#top-left')
  let topMid = document.querySelector('#top-mid')
  let topRight = document.querySelector('#top-right')
  let midLeft = document.querySelector('#mid-left')
  let midMid = document.querySelector('#mid-mid')
  let midRight = document.querySelector('#mid-right')
  let botLeft = document.querySelector('#bot-left')
  let botMid = document.querySelector('#bot-mid')
  let botRight = document.querySelector('#bot-right')
  let gameBoard = []


  let gridSquares = () => {
    gameBoard = [topLeft, topMid, topRight,
      midLeft, midMid, midRight,
      botLeft, botMid, botRight
    ]
    // let gridSquares = cacheDom
    // // let gridSquares = document.querySelectorAll('.game-square')
    // let squares = [...gridSquares]
    for (let square of gameBoard) {
      square.textContent = ''
    }
  }

  gridSquares()

  return {
    gridSquares,
    gameBoard
  }
})()
//Player factory function
const Player = function(name, move, marker) {

  const boardMove = () => {
    for (let place of ticTacToeBoard.gameBoard) {
      place.addEventListener('click', function(e) {
        e.target.textContent = marker
      })
    }
  }
  return {
    name,
    move,
    boardMove,
    marker
  }
}
//Logic that creates player moves for both players
let playerMoves = (function() {
  // let turn = true;
  const playerOne = Player('player-one', 1, 'X')
  const playerTwo = Player('player-two', 2, 'O')

  //Function that alternates players turns
  function markBoard() {
    let turn = true;
    if (turn === true) {
      return playerOne.boardMove()
      turn = false;
    } else if (turn === false) {
      return playerTwo.boardMove()
      turn = true;
    }
  }

  markBoard()


  return {
    playerOne,
    playerTwo,
    markBoard
  }

})()


let game = (function() {})()

Can't read if statement in c [duplicate]

I'm trying to write a program inwhich the user enters the name of a month and the program says if this month has 30, 31 or 28/29 days. Here's the code I'm trying, the problem is that it doesn't reach all the if statement.

#include <stdio.h>

int main() {
    char month;
    
    printf("Enter a month: ");
    scanf("%s", month);

    if (month == "january" || month=="march"|| month == "may" || month == "july" || month == "august" || month =="october" || month == "december")
        printf("This month has 31 days");
    else if (month=="february")
        printf("This month has 28/29 days");
    else if (month == "april" || month == "june" || month == "september" || month == "november")
        printf("This month has 30 days");
    else 
        printf("Enter a valid month");
    
  
    
    return 0;
}

Could someone please help?

Thank you in advance.