mercredi 31 juillet 2019

An if condition gets ignored

This bit of the code is supposed to check if the password length is good, butif the password length is greater than or equals 16, it skips the if condition and doesnt print the sentence.

/* This bit of the coe just checks the length of the password */
if(Password.length() >= 8) {
    if(Password.length() <= 10) {
        System.out.println("Medium length of password");
        }
    }else if(Password.length() < 8) {
        System.out.println("Bruv youre asking to be hacked");
    }else if(i >= 10) {
        if(Password.length() <= 13) {
            System.out.println("Good password length");
            }
            /* The part that fails */
            else if(Password.length() >= 16) {
                System.out.println("Great password length");
            }

    } ```

/* The code should output "Great password length" if the password length is greater than or equal to 16 but it doesnt output anything if it's greater han or equal ot 16 */

Is there a limit to "else" in Javascript?

I have a code in which I need to use around 90 "else" and when I arrive at about 30 I start showing the blank code ... I have reviewed the keys "{}" and they are correctly located, but it still shows me the blank code ...

enter image description here

What could it be? I hope you can help me, thank you very much.

Scalable if statements conditions

I was wondering about the possibility of creating an if statement that is more scalable. In the case we have a condition that one variable can possibly be one of many different values for the if statement to be satisfied, I have tried these such formats:

This is the default answer.

if (variable == 23
    || variable == 52 
    || variable == 58 
    || variable == 62 
    || variable == 93)
{ 
    some function
} 

This is what I imagined would work as a newb to C.

if (variable == (23,52,58,62,93) 
{
    some function
}

However, using the comma method I get a warning such that

warning: expression result unused [-Wunused-value]

Does anyone have a possible way to make an if statement of one variable with multiple possible conditions to be written without copy and pasting the variable name each time?

how can i print the value or equation that is performing in an if statement

If I have an if statement that says

                       if f1_date == f2_date:    
                           if f2_number > f1_number:
                               print('WIN')
                               continue
                           elif f2_number <= f1_number:
                               print('lose')

can I print the part of the statement that says if f2_number > f1_number, so for example, if there's a row where f1_number = 1000 and f2_number = 2000 then is there a way to print out just 1000 or 2000 > 1000?

Handling letter cases in c#

In my program I'm using an if-statement to check if a character from a string is a letter or not. I'm using the following if-statement:

if (('A'<= character && character >= 'Z') || ('a' <= character && character >= 'z'))

The if-statement, as far as I know is true for all lower case letters and true for all upper case letters. I want it to be true for all letters. I'm not sure how character codes work in c#, could that be why it's not working?

VLOOKUP multiple columns for different months

I am trying to VLOOKUP a value with multiple columns. So I have a chart with ZIP codes, states, and an avg, min, max, std dev, etc for every month of the year.
Here is an example of one month for reference:

enter image description here

Next, I want to basically make a chart like so. In the AVG column I want to VLOOKUP the zip code, match it to the month and have it display the avg value (from the table above) for the correct month.

enter image description here

Is there any way to do this? Here is what I have tried thus far (the sheet with the first image is sheet 1, image 2 is sheet 2)

VLOOKUP(Sheet2!A2,Sheet1!A2:Z100,if((Sheet2!B3=2, vlookup(Sheet2!A2, Sheet1!A2:Z100,3),"")))

I am not really sure how to change the part where it goes to column 3 so that it will change for each month.

How to index match a condition set in a cell

I am trying to avoid having a multiple if formula by index matching a table instead, however what i need to match is the actual condition and a string.

Lookup table:

+---+------------------+-------------------+-------+
|   |        A         |         B         |   C   |
+---+------------------+-------------------+-------+
| 1 | Current to Prior | Portfolio Comment | Error |
| 2 | =0               | ""                | 1     |
| 3 | <>0              | ""                | -1    |
| 4 | >0               | OK – Losses       | 0     |
| 5 | <0               | OK – Losses       | 1     |
| 6 | <0               | OK – New Sales    | 0     |
| 7 | >0               | OK – New Sales    | 1     |
+---+------------------+-------------------+-------+

  • Column A: Lookup Condition
  • Column B: Lookup string
  • Column C: Return value

Data example with correct hard coded output (column C):

+---+------------------+-------------------+-------+
|   |        A         |         B         |   C   |
+---+------------------+-------------------+-------+
| 1 | Current to Prior | Portfolio comment | Error |
| 2 | 0                |                   | 1     |
| 3 | -100             | OK – Losses       | 1     |
| 4 | 50               |                   | -1    |
| 5 | 200              | OK – Losses       | 0     |
| 6 | 0                |                   | 1     |
| 7 | -400             | OK – New Sales    | 0     |
| 8 | 0                |                   | 1     |
+---+------------------+-------------------+-------+

  • Column A: Data value
  • Column B: Data string
  • Column C: Output formula

I need a formula that matches the data value with the lookup condition, the data string with the lookup string and outputs the return value.

Using Formulas in GoogleSheets for multiple cells

If I have the title "Comm" in Cell A, then I want Cell C1 to be whatever Date Cell B has + 14 days. If I have "Recruit" in Cell A, then I want Cell C1 to be whatever Date Cell B has + 30 days.

pasted in cell C1 =if(A1="Comm","B1+14,"")")

The result was False - what I need is a date +14 days from Cell B's entry.

Iterate over a nested dictionary to produce a tuple list that matches tables with the same key

I want to make a tuple list (table1, table2, Key) from a nested dictionary. I will need to match tables that have the same primary key and match tables that have the same foreign key.

I've used .items and .print(), but it doesn't give me what I want and I can't save those results as a list.

This is the code for the nested dictionary that I have to iterate over:

tables = {}
for table in table_list:
    tables[table] = {}
    tables[table]['cols'] = df_is_columns[df_is_columns.TABLE_NAME == table]['COLUMN_NAME'].tolist()
    has_constraint = False
    PK_tmp = df_is_constraints_cols[(df_is_constraints_cols.TABLE_NAME == table) &  (df_is_constraints_cols['CONSTRAINT_NAME'].str.startswith('PK'))][['CONSTRAINT_NAME', 'COLUMN_NAME']].to_dict('list')
    if(len(PK_tmp['CONSTRAINT_NAME'])):
        has_constraint = True
        tables[table]['constraints'] = {}
        tables[table]['constraints']['Primary'] = PK_tmp
    FK_tmp = df_is_constraints_cols[(df_is_constraints_cols.TABLE_NAME == table) & (df_is_constraints_cols['CONSTRAINT_NAME'].str.startswith('FK'))][['CONSTRAINT_NAME','COLUMN_NAME']].to_dict('list')
    if(len(FK_tmp['CONSTRAINT_NAME'])):
        if not has_constraint:
            tables[table]['constraints'] = {}
        tables[table]['constraints']['Foreign'] = FK_tmp

I run into errors when a Key has a "Primary", but no "Foreign" and other similar situations.

Alternatives to Iferror(index(Match))

I have data set up in week format and each week there are incoming values and outgoing values like inventory changes. I have the data in two sheets and I pull them into a third sheet that has proper formatting. I need to keep the future values matched with the weeks that they are coming in but I need all values from the past to add up in one cell.

I have tried using an iferror(Index(Match)) code and it has worked very well to get the future data into the right location, however the reference dates are started with today date so there is nowhere for the past due dates to match to.

Range("F8").Select
    ActiveCell.FormulaR1C1 = _
        "=IFERROR(INDEX(-'OnHand & PartReq & Supply'!C10,MATCH(LOB!R6C,'OnHand & PartReq & Supply'!C4,0)),0)"
    Range("F9").Select
    ActiveCell.FormulaR1C1 = _
        "=IFERROR(INDEX('OnHand & PartReq & Supply'!C14,MATCH(LOB!R6C,'OnHand & PartReq & Supply'!C4,0)),0)"

Is there a way to use this code or a code like it, but to put all data that was in the past added together in the same cell.

Is there a way of displaying backordered items on a Netsuite advanced PDF Packing Slip (freemarker)?

Basiscally we have a freemarker form (netsuite calls it Advanced PDF) for a Packing List. It displays the items shipped, with quantity ordered, quantity shipped, and quantity backordered - easy. Keep in mind, it needs to respect previous shipments, so it doesn't displays items already fulfilled. The problem is, in the process of excluding previous shipments, it excludes backordered items which haven't been shipped yet, and we would like these to display as X ordered, 0 shipped, X backordered.

Have a look at the segment below - so far I've tried adding an #elseif for when quantitybackorder+quantitycommitted gt 0, but this literally repeats each line on the fulfillment by the number of lines on the order, which is strange (ie. 8 lines ordered, 2 fulfilled- those 2 will repeat 8 times each, with each set of data on its own line)

<#if record.item?has_content>
            <table class="itemtable"><!-- start items -->
            <#list record.item as item>
                <#if item_index==0>
                    <thead>
                        <tr>
                            <th colspan="5" style="align: left;"><span style="font-size:12px;">Item Number</span></th>
                            <th colspan="12" style="align: left;"><span style="font-size:12px;">Item Description</span></th>
                            <th colspan="3"><span style="font-size:12px;">Ordered</span></th>
                            <th colspan="3"><span style="font-size:12px;">Backorder</span></th>
                            <th colspan="3"><span style="font-size:12px;">Shipped</span></th>
                            <th colspan="2"><span style="font-size:12px;">Unit</span></th>
                        </tr>
                    </thead>
                </#if>
                <#list salesorder.item as tranline>
                    <#if tranline.custcol_item_code==item.item>
                            <tr>
                                <td colspan="5"><p style="text-align: left;">${item.item}</p></td>
                                <td colspan="12"><p style="text-align: left;"><span style="font-weight: bold; line-height: 18px;">${item.description}</span><br /><em>${tranline.custcol_extra_details}</em></p></td>
                                <td colspan="3" style="align: center;">${tranline.quantity}</td>
                                <td colspan="3" style="align: center;">${tranline.quantitybackordered+tranline.quantitycommitted}</td>
                                <td colspan="3" style="align: center;">${item.quantity}</td>
                                <td colspan="2" style="align: center;">${tranline.units}</td>
                            </tr>
                    </#if>
                </#list>
            </#list>
    <!-- end items --></table>
</#if>

Does anyone have any idea how I can allow for backordered items here, or looking at it another way, just exclude the already fulfilled items leaving current fulfillment and backorders? Thanks very much for your help!

Google Sheet Function with IF statement to add 1/0 column

I want to query a number of rows from one sheet into another sheet, and to the right of this row add a column based on one of the queried columns. Meaning that if column C is "Il", I want to add a column to show 0, otherwise 1 (the samples below will make it clearer.

I have tried doing this with Query and Arrayformula, without query, with Filter and importrange. An example of what I tried:

=query(Data!A1:AG,"Select D, E, J, E-J, Q, AG " & IF(AG="Il",0, 1),1)

Raw data sample:

Captured Amount Fee     Country
 TRUE    336    10.04   NZ
 TRUE    37     1.37    GB
 TRUE    150    4.65    US
 TRUE    45     1.61    US
 TRUE    20     0.88    IL

What I would want as a result:

Amount  Fee     Country  Sort
 336    10.04   NZ       1
 37     1.37    GB       1
 150    4.65    US       1
 45     1.61    US       1
 20     0.88    IL       0

Forcing length of txt box or variable

I have some javascript code. I want to put in some error checking but don't know where to start. I want, if the contents of val1 is not exactly 21 characters in length, to stop the script, or better still give a message box to the fact. Or maybe it is possible to force the input box to containing 21 characters? Sorry if its a silly question but I am new to this and still learning.

I set the size of the input box to 21 but this only increase the dimension so its still possible to enter more or less characters than this. I thought maybe some sort of if statement might do it but dont know how to do this and my attempts have been unsuccessful.

<script type='text/javascript'>
function screenshot(){
  html2canvas(document.body).then(function(canvas) {

    // Get base64URL
    var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
    var val1 = $('#datepicker').val();

    // AJAX request
    $.ajax({
       url: 'ajaxfile.php',
       type: 'post',
       //data: {image: base64URL, name: datepicker},
       data: {image: base64URL, datepicker: val1},
       success: function(data){
       console.log('Upload successfully');
       }
    });
  });
}
</script>

No matter what I tried it stopped the script working altogether, even when val1 was 21 characters.

how to extract and change the date in date field if a specific condition is met

I've a dataframe as under

season  date
9090-2019fall   1/1/00
9879-2018fall   2/2/01
9801-2018spring 3/3/03
7868-2017fall   4/4/04
5765-2020fall   5/5/05

I'm tying to extract the year from the season column and then change the date in the date column where year < todays year The new date should be the first day in the month of may for the extracted year

I came across a solution to do it manually for each year

This is where I've gotten so far

df$date<-ifelse(grepl('2019fall', df$season, paste0('2019-05-01'),df$date)

Is there a way to have it run it in a loop instead of doing it manually ?

My expected result is as under

season  date
9090-2019fall   5/1/19
9879-2018fall   5/1/18
9801-2018spring 3/3/03
7868-2017fall   5/1/17
5765-2020fall   5/5/05

to replace if-else statements with loop in python

Using regular expression as global constant and have to check the regular expression regCheck in processloop fucntion also converting if -else statement with any loops( by removing "elif" since changed by loop)

`````````````````regex``````````````

regSingle = r'[ACGU]\d+[ACGU]&[ACGU]-?\d+[ACGU]'
regMulti = 'regSingle(|regSingle)*'
regAlt = 'regMulti(,regMulti)*'
regCheck = '^\s* regAlt \s*$' 

````````````````````````


```````````````````conversion of ifelse into loop``````````````
def processLoop():
    for index, record in enumerate(sRNAGene):
        mutation = sRNAGene[record].get("mutation")
if ("|" in mutation):   
            print("\n\n Multiple Evaluations using : \t", mutation)
            multiEval = mutation.split("|")
            for index , element in enumerate(multiEval):
                part_1, part_2, = element.split('&', 1)    
                boolsRNA(part_1, sRNAGene[record].get("fasta") ,sRNAGene[record].get("name"))
                boolsGene(part_2, sRNAGene[record].get("gene").get("Sequence") ,sRNAGene[record].get("gene").get("name"))
                sys.exit()
                complementBase(part_2, part_1)

        elif ("," in mutation):   
            print("\n\n Mutation with Bar ',' : \t", mutation)
         else:
             part_1, part_2 = mutation.split('&', 1)
             boolsRNA(part_1, sRNAGene[record].get("fasta") ,sRNAGene[record].get("name"))
             boolsGene(part_2, sRNAGene[record].get("gene").get("Sequence") ,sRNAGene[record].get("gene").get("name"))
             sys.exit()
           complementBase(part_2, part_1)



How Do I Make My If Statement Run Correctly?

Below is my code. By the prompt "Do you enjoy fiction books?" the code is not working surrounding the if other == true statement (if no is entered). Any help would be appreciated!! I am unsure what part of the if statement needs to be fixed and I would really like to see this program working as I am 15 and the hours I have put into it is a lot!

<!DOCTYPE html>
<html>
<head>
    <title>Chatbot Charlie</title>
    <meta name='generator' content='notepad++'/>
</head>
<body>
<script>
var FantasyArray = ["A Song Of Ice And Fire by George R.R. Martin","The Lion, The Witch, and The Wardrobe by C.S. Lewis","American Gods by Neil Gaiman", "Good Omens by Terry Pratchett & Neil Gaiman",];
var ScienceFictionArray = ["1984 by George Orwell","Brave New World by Aldous Huxley","The Three Body Problem by Cixin Liu", "Ender's Game by Orson Scott Card",];
var RomanceArray = ["Pride and Prejudice by Jane Austen","Outlander by Diana Gabaldon","The Mister by E.L. James", "The Notebook by Nicholas Sparks",];
var ActionArray = ["City of Bones by Cassandra Clare","The Hunger Games by Suzanne Collins","Divergent by Veronica Roth","The Lightning Thief by Rick Riordan",];
var MysteryArray = ["Big Sky by Kate Atkinson","The Girl With The Dragon Tattoo by Steig Larsson","Gone Girl by Gillian Flynn", "In The Woods by Tana French",];
var OtherArray = ["Think And Grow Rich by Napoleon Hill", "The 4 Hour Work Week by Tim Ferriss","The Secret by Rhona Byrne", "10% Happier by Dan Harris", "Edmonds Cookbook by Edmonds Cooking", "Going Paleo by Pete Evans", "Fresh Start Feel Good by Nadia Lim", "Homegrown Kitchen by Nicola Galloway", "How Not To Die by Gene Stone and Michael Greger", "Intuitive Eating by Evelyn Tribole",];

alert("Welcome To Chatbot Charlie. Here we will help you find a storybook to read!");}

function getRndFromArray(arrayName){                                
return arrayName[Math.floor(Math.random()*arrayName.length)]; 
}   
    var strng = prompt("Do you like reading? Yes or No?") ; // first question asking if you like reading or not 
    var likesreading = strng.includes("Yes"); //string include "yes" true or false
    var dislikesreading = strng.includes("No"); //string include "no" true or false         

if (likesreading == true) // if string includes yes and therefore says you like reading then...
{
var likesreadingArray = [                                                                                                                       
"So do I!",
"I do enjoy reading too, wish I had more time to do it",
"I do like reading",];

alert("You do like reading! "+getRndFromArray(likesreadingArray)); //get random reply from array which adds to alert
}   

        else if (dislikesreading == true)   //if string includes no and therefore says you like reading then...
        {
        var dislikesreadingArray = [
        "Oh okay, you must have other hobbies. I'm sure reading could become one of yours!",
        "I used to dislike it too.",
        "Maybe you just haven't read a good book yet",];
        alert("You don't like reading! "+getRndFromArray(dislikesreadingArray));    //get random reply from array which adds to alert
        }

            else //if no option is inputed this set of code will run
            {
            alert("A lot of people are undecided on this too! Definitely depends on what book you are reading")
}
var again;
do {
  var strng = prompt(
    "Do you enjoy fiction books? Yes or No?");
  var fiction = strng.includes("Yes");
  var other = strng.includes("No");

  if (fiction == true) {
    var strng = prompt(
      "What genre do you prefer from the following? Fantasy, Science Fiction, Rommance, Action, Mystery"
    );
    var fantasy = strng.includes("Fantasy");
    var sciencefiction = strng.includes("Science Fiction");
    var romance = strng.includes("Romance");
    var action = strng.includes("Action");
    var mystery = strng.includes("Mystery");
    if (fantasy == true) {
      alert("I think you will enjoy " + getRndFromArray(FantasyArray));
    } else if (sciencefiction == true) {
      alert("I think you will enjoy " + getRndFromArray(ScienceFictionArray));
    } else if (romance == true) {
      alert("I think you will enjoy " + getRndFromArray(RomanceArray));
    } else if (action == true) {
      alert("I think you will enjoy " + getRndFromArray(ActionArray));
    } else if (mystery == true); {
      alert("I think you will enjoy " + getRndFromArray(MysteryArray));
    }

if(other == true) {
      alert("Read " +getRndFromArray(OtherArray));}


     //if no option is inputed this set of code will run
      else {
        var again = prompt(
          "You have not told me whether you like fiction books. Would you like to try again? Yes or No?"
        );
      }
    } // prompt relating to do while loop
  }
} while (again === "Yes");

alert("Happy Reading!");}

</script>
</body>
</html>

mardi 30 juillet 2019

Multiplying by a decimal wont give me a decimal answer to feed back into my variable

Currently using Clion to work on a homework question. I believe i am using my if-statements correctly, as-well as the double and char but it doesn't seem to be giving me the outcome i seek. The question asks: • Buy one get one half off promotion: the lower price item is half price. • If the customer is club card member, additional 10% off. • Tax is added.

I have tried to move brackets around. I have declared the .90 to a set variable and tried multiplying that but still always gives me the same answer. I think it has something to do with my if-statemets.

'

cout<<"Enter price of first item: ";
cin>>price1;
cout<<"Enter price of second item: ";
cin>>price2;

cout<<"Does customer have a club card? (Y/N): ";
cin>>clubCard;

cout<<"Enter tax rate, e.g. 5.5 for 5.5% tax: ";
cin>>taxRate;

fullSubtotal = price1 + price2;
taxRate /= 100;
taxRate += 1;

if (price1 > price2) {
    price2 /= 2.00;
    basePrice = price1 + price2;
    if (clubCard == 'y' || clubCard == 'Y') {
        cardPrice = basePrice * .90;
       finalPrice = taxRate * cardPrice;
    }
    else (clubCard == 'n' || clubCard == 'N'); {
        cardPrice = basePrice;
        finalPrice = taxRate * cardPrice;
    }
}
else {
    price1 /= 2.00;
    basePrice = price1 + price2;
    if ((clubCard == 'y') || (clubCard == 'Y')) {
        cardPrice = basePrice * .90;
        finalPrice = taxRate * cardPrice;
    }
    else ((clubCard == 'n') || (clubCard == 'N')); {
        cardPrice = basePrice;
        finalPrice = taxRate * cardPrice;
    }
}

cout<<"Base price: "<<fullSubtotal<<endl;
cout<<"Price after discounts: "<<cardPrice<<endl;
cout<<"Total price: "<<finalPrice<<endl;

return 0;

}`

Each time i enter the values for each price( 10 and 20), it gives me the correct fullSubtotal, but when i seek the corresponding cardPrice for that route (if-statement), it gives me 25. With a total price (including tax) to be 27.0625. I was expecting the output to be, cardPrice: 22.5 with finalPrice: 24.35625

Display text if image is not available

I'm coding a custom SharePoint Item_XX.html template which is feeding in data from my SharePoint custom list. I'm not sure how to 'break up' script though. How do I use an if-else statement where the output displays html?

You'll see I'm trying to say: If there is LogoSrc data, add the data to the image src. Otherwise display text (dtaa from the title field)

<script> if (!LogoSrc==null){ </script>
    <img src="_#= $htmlEncode(LogoSrc) =#_" />
<script> } else { </script>
    <p style="font-size: 13pt; font-family: 'Malgun Gothic', Arial, sans-serif; color: #000000; font-weight: 700;">_#= Title =#_</p>
<script> } </script>

Problem with logic when usng if statements

I am writing a small program to accept a name and a score. The program will store data in vectors. Then the program will print the name and score of each entry. Then the program should be able to search for a stored name, and if found display the name and corresponding score, if not found it should display a "not found" message. The program works great, up until the point where a name is entered to be searched, if the name is stored, it will print the name and score correctly. If the name is not found, it will display "not found" correctly as well. The problem is if the name is found, the program will also display the "not found" message as well as the name and score. I am not sure where my logic is flawed.

I have tried using else if, I have tried separate loops, I have tried putting the if statement in the same loop. I have tried using a break statement. Nothing I try will remove the "not found" message when a record is found. Since this is just a program to help me learn, it isn't that big of a deal, however I would like to understand what is going wrong to help me learn more, and to fix this annoying issue.

#include<iostream>
#include<vector>
#include<string>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
vector<string> listOfNames{};
vector<int> listOfScores{};
string name = " ";
int score = 0;

int main()
{
    cout << "Please enter a name followed by a score: \n";
        cout << "Press enter when finished\n";
    cout << "To quit enter NoName 0\n";     
    while (cin >> name >> score && name != "NoName")
    {
        for (int i = 0; i < listOfNames.size(); ++i)
        {
            if (name == listOfNames[i])
            {
                cout << "error name is a duplicate: \n";
            }
        }
            listOfNames.push_back(name);
            listOfScores.push_back(score);      
    }
        cout << "\nlist of names and scores entered\n";
    for (int i = 0; i < listOfNames.size(); ++i)
    {
        cout << listOfNames[i] << ',' << listOfScores[i] << "\n";
    }
    cout <<"Please enter a name to search for\n";
    string searchName = " ";
    cin >> searchName;
    for (int i = 0; i < listOfNames.size(); ++i)
    {
        if (searchName == listOfNames[i])
        {
     cout << listOfNames[i] << ',' << listOfScores[i]<< "\n";
        break;          
            }   
        }

    for (int i = 0; i < listOfNames.size(); ++i)
    {       
        if (searchName != listOfNames[i])
        {
            cout << "Not found\n";
            break;
        }
    }       
    keep_window_open();

    return 0;
}

If the user enters John 22 and Tim 28, it will print the list, then when a user searched for a name, if the name is not found, it will print "Not found", however if the name is found, it will print the name and score, as it should, but the next line it prints is "Not found". This line should only print if the record is not found.

How to populate a VLOOKUP with a dynamic range in Google Sheets?

I have a file that needs to look up the team name (on a tab called "Parse") of an employee on a tab called "Roster". This can be done with a simple array Vlookup, however, the issue is that each week, we add a row to the Roster tab because employees sometimes move around.

I have already done the majority of legwork by using a MAX/FILTER/COLUMN, LEN formula to determine what the last column is in the Roster tab. I have also created a range that will provide me with the actual range needed for the VLookup. For example: If the last column in Roster is "G", I already have a formula that populates "'Roster'!A2:G", which is the range I would need for my Vlookup. If the last row in Roster is "P", then the formula shows "'Roster'!A2:P".

The formula that gives me the range, as I described in the examples, lives in cell F2 on the Parse tab.

So the hard part is done. All I need to know now is, when writing my Vlookup, how can I have the formula reference the actual contents of cell F2 in the Parse tab instead of thinking the lookup range is cell F2. Here's a visual:

Cell F2 in the Parse tab reads: 'Roster'!A2:G (because as of now, column G is the last column with data. this is correct).

My VLookup is VLOOKUP($A2,$F$2,7,FALSE). However, I want my Vlookup to say VLOOKUP($A2,'Roster'!A2:G,7,FALSE).

Is it possible to have the formula reference what is IN cell F2 instead of referencing just "F2"?

I hope this made sense. It's the end of my workday and I'm very tired.

Why is my code getting rid of rows when I subtract?

So I have some code that looks at two data frames and subtracts a column value named "Intensity" for certain Compositions of molecules. However for instance if the molecule is not in the other data frame, it completely gets rid of that row for some reason not too sure why.

blankdata3 and data3 are my two dataframes that I am subtracting. So I am subtracting a molecules's Intensity such as

(data3 - blankdata3) = datasubtracted


#This is my code that subtracts the molecule's Intensity based on if they have the same Composition. 

datasubtracted <- blankdata3 %>% left_join(select(data3, Intensity, Composition), by ="Composition") %>%
mutate(Intensity = ifelse (is.na(Intensity.y), -Intensity.x, Intensity.y - Intensity.x)) %>%
select(-Intensity.y, -Intensity.x ) %>%
bind_rows(anti_join(data3, blankdata3, by = "Composition") %>%
          mutate( Intensity = -Intensity))

#Example of data3 is below
#Composition Intensity
#C2H6O       100000
#C2H4O2      43000

#Example of blankdata3 is below
#Composition Intensity
#C2H6O       60000
#C3H8        53000

#When I run the code it gives me something like this (datasubtracted)
#Composition Intensity
#C2H6O       40000

#I expect to see this. I want compounds from data3 to carry over to datasubtracted untouched since there is nothing to subtract with. Basically subtracting a molecule by zero.
#Composition Intensity
#C2H6O       40000
#C2H4O2      43000


The code completely gets rid of molecules from data3 if they are not found in blankdata3 when the code runs, which I do not want.

Simple if-else failing test case [on hold]

This is a HackerRank problem and about as simple as it gets. But it's failing when test case is 4. Says expected output is "Not Weird." Isn't this covered by that first elif statement?

I have no idea what else to try.

if n % 2 == 1:
    print("Weird")
elif n % 2 == 0 and n >= 2 and n <= 5:
    print("Not weird")
elif n % 2 == 0 and n >= 6 and n <= 20:
    print("Weird")
else: 
    print("Not Weird")

How to list number of keys in dictionary with exclusions

Interested in the "total" output to reflect the count of new keys matching the criteria in the if statement. If you would also be able to provide instruction on how to show how many keys weren't returned as a result of the if statement that would be helpful.

d = {1:0.3246, 2:3.222, 3:3344, 2:0.3444, 5:1.09, 6:222.3}


for key in list(d)[:4]:
    if key == 2:
        continue
    print(key, d[key])
keyresults = key
print('Total unique keys found:', keyresults)

Expected results:

1 0.3246
3 3344
5 1.09
Total unique keys found: 3
Total unique keys not found: 2

Actual results:

1 0.3246
3 3344
5 1.09
Total unique keys found: 5

How do i make sure that the ID of object im adding to array doesn't exist without getting nullpointerexception?

I have an assignment where i am to create a program that manages CDs. I am using switch statement and in the first switch case I have to add a CD to the array but only if a CD with the same ID doesn't already exist in the array.

I've tried with 

    if(CDid != null && !CDid.equals(CDid.getCdId){
           cdArray[counter] = cd_obj;
           counter++;
        }else{
             counter = cdArray.length-1;
             System.out.println("The array is full");
         }

I've also tried a for each loop before the if statement but nothing works. Either i get the nullpointer exception and/or the cd wont add to the array. I am not allowed to have any nullpointerexceptions in the code and I am stuck on this problem for 2 days now so im hoping someone out there can help me!

Sorry for any errors ive made this is my first time posting a question on Stacksoverflow

The following code is the CD Main class

public class Cd_main {

   public static void main(String[] args){
   boolean running = true;
   String CDid, CDgenre, CDartist, CDalbum, CDstorageSpot, CDtrackAmount, 
       CDstorageAmount CDprice, searchGenre, deleteCD  ;
   CD[] cdArray = new CD[25];  
   int counter = 0;

   int choice; 
   Scanner scanner = new Scanner(System.in);

   while(running){
          ............................
          ............................
          choice = scanner.nextInt();

          switch(choice){
           case 1:
               System.out.println("......");
               System.out.println("............");
               CDid = scanner.next();  
               CDgenre = scanner.next();   
               CDartist = scanner.next();
               CDalbum = scanner.next();
               CDstorageSpot= scanner.next();
               CDtrackAmount= scanner.next();
               CDstorageAmount = scanner.next();
               CDprice = scanner.next();

               CD cd_obj = new CD(CDid, CDgenre, CDartist, CDalbum, 
               CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);                  



              if(CDid.equalsIgnoreCase(cdArray[0].getCdId())){  
              cdArray[counter] = s_obj;
              counter++;
              }else{
                counter = cdArray.length-1;
                System.out.println("The array is full");
             }
            }
            break;

The CD class:

public class CD {

    public String cd_ID;
    public String genre;
    public String artist;
    public String album;
    public String storageSpot;
    public String trackAmount;
    public String storageAmount;
    public String price;

    public CD() {   
    }
       public CD(String cd_ID, String genre, String artist, String album, 
           String storageSpot, String trackAmount, String storageAmount, 
           String price){
           this.cd_ID = cd_ID;
           this.genre = genre;
           this.artist = artist;
           this.album = album;
           this.storageSpot = storageSpot;
           this.trackAmount = trackAmount;
           this.storageAmount = storageAmount;
           this.price = price;  
    }
    public String getCdId() {
        return this.cd_ID;
    }
    public void setCdId(String cd_ID) {
        this.cd_ID = cd_ID;
    }
    public String getGenre() {
        return this.genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }

    public String getArtist() {
        return this.artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getAlbum() {
        return this.album;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public String getStorageSpot() {
        return this.storageSpot;
    }

    public void setStorageSpot(String storageSpot) {
        this.storageSpot = storageSpot;
    }

    public String getTrackAmount() {
        return this.trackAmount;
    }

    public void setTrackAmount(String trackAmount) {
        this.trackAmount = trackAmount;
    }

    public String getStorageAmount() {
        return this.storageAmount;
    }

    public void setStorageAmount(String storageAmount) {
        this.storageAmount= storageAmount;
    }

    public String getPrice() {
        return this.price;
    }

    public void setPrice(String price){
        this.price = price;
    }

}

How to implement if else in jmeter

I need to implement below in jmeter

flag == 1

while (flag == 0) check status if status == successful Change the value of flag to 0 check status if status == failed Change the value of flag to 0 check status

if status == in progress Change the value of flag to 0 check status

if flag is 0 while loop should stop and user should go to next transaction

How to write if not in array statement as python in javascript? [duplicate]

This question already has an answer here:

 arr1=[6,4,2,8]
 arr2=[1,5,4,8,2]
 for n in arr2:
     if n not in arr1:
         arr1.append(n)
 print(arr1)

How to write the program in javascript? I m stuck in the if statement.

sql - if something then do this if nothing do nothing

I have a column with many nulls in table 1, but now and then there is a value. If there is a value, i want to go to table 2 and take the the corresponding value from there. This should create an extra column called user_original

CASE
    WHEN table1.user_changed IS NOT NULL THEN table2.user_original ELSE -- do nothing  
    END as user_original

I basically want to replace

is nothing

Is this correct ? hw can this be done? is there a better way?

MySQL self join return all rows

Per the example data below, I need a query that returns every row, where if the 'contingent_on' field is NULL, it is returned as NULL, but if it is not NULL it is returned with the 'ticket_name' corresponding to the 'primary_key' value.

I tried self join queries but could only get them to return the not NULL rows.

example table data:

primary_key | ticket_name | contingent_on

1 | site preparation | NULL

2 | tender process | NULL

3 | construction | 1

All rows should be returned, where the in the 'construction' row return, 'site preparation' is input in place of '1' in the 'contingent_on' field.

If an object exist, take an action in python

I'm very new to python and I'm trying to make an if then statement as the one used in Delphi. I looked at other posts about this but all the examples I've encountered are with "print". I have an object that I want to handle if appears, for example if object(name_mapping) exists then take action x and action y. Can somebody help me?

if (object_mapping) is not none:

If name from one sheet is found on another mark checkbox on 1st sheet

I'm looking for help with a script to where if the name in column E of the first sheet "July Log" is in Column C of second sheet "DT NEW" where column F has either "Booked or Funded" it will go back to the "July Log" and check the box in column D. Else do nothing.

I'm not a coder or scripter just trying to teach myself. I've done a lot just from searching but I've tried a few different routes on this one and no luck. Thanks for any help. Preferable broken down on an elementary level lol

July Log

DTNEW

lundi 29 juillet 2019

How do you exclude values when creating a string when setting up initial conditions?

I'm trying to combine columns in my data frame so that they give me a certain string. I have columns titled as "C", "H", "O", "N", and "S" as elements. Within those columns are listed the number of elements within that molecule, but I want to exclude some elements depending on their value. For example when there is no Oxygens the value is 0, so i want to exclude this when combining the elements to make a string.

#This is a portion of my data frame titled data4a
#C H O N S
#3 4 0 0 1
#7 5 4 1 0

#The code I have is 
data4a$NewComp = paste("C",data4a$Total.C,"H", data4a$NewH, "O", data4a$O, "N", data4a$N, "S", data4a$S, sep = "")

#This code gives me this
#C H O N S NewComp
#3 4 0 0 1 C3H4O0N0S1
#7 5 4 1 0 C7H5O4N1S0

#I expect to see something like this when I print my results
#C H O N S NewComp
#3 4 0 0 1 C3H4S1
#7 5 4 1 0 C7H5O4N

#I want values of zero to be excluded from the string created

Exit If Statement if returned value is not a boolean

I have a user input for a yes or no answer. I would like to construct a function in python 3 which I could pass the value like isTrue('yes) and then the function would return True and isTrue('no') would return False. I am aware that I could just use an if statement to see if the value is just yes or no, but for other reasons, I'd benefit from using a function like isTrue(). Creating the function isTrue() is very easy, but the part I am struggling with is how to handle a value that is not true, nor false, like maybe or IDK. Ideally, I'd like to have an if statement like so

if isTrue(userInput) '''Some code here that would run anther function if the value was not true or false''':
    print('Input was Ture')
else:
    print('Input was False')

Is there a way I could return a value that I could still have the same if statement structure, but detect if the value wasn't True or False without having to do something like this and somehow have it integrated with the True if statement?

if isTrue(userInput):
    print('Input was Ture')
else !isTrue(userInput):
    print('Input was False')
else:
    print('Invalid')

References changing in Google Sheets with new forms submissions

I have a google sheet that feeds from a google form and then I use the sheet to make views to show data and graphics on a google sites. I noticed that suddenly the graphics said 'No Data', and when I checked, it seemed that for some reason the ranges that feed such tables had changed their referenced cells to the newest row from the submitted forms instead of retaining the range even if it was fixed.

I have no idea why or how this happened, but it happened in different places and different formulas along the sheets, not on all but quite on many. Previously it was working fine.

This happened to formulas for 1 cell and column arrays alike. The change was merely that instead of using lets say L2:L, it changed the 2 for 54 so it ended like L54:L , even if it was fixed with $ .

For example: Originally $AA$2:$AA became $AA$54:$AA

NOTE: This has affected random sections and other columns that have the same formula may not be affected, regardless as if they refer the same columns or adjacent ones.

The following are examples of this change, where 54 should have been 2.

1: An array that works on an entire column.

    ={"Person";ArrayFormula(IF(LEN(A54:A), 'Responses'!AL54:AL&"" &                                 
    'Responses'!AK54:AK&
    " " & 'Responses'!AJ54:AJ&
    " " & 'Responses'!AI54:AI
    ,""))}

2: A mere count of responses that has a fixed range

    =COUNTIF('Responses'!$AY$54:$AY, "si")

And 3: A count for different values

    =countifs('Responses'!$AA$54:$AA,"Sí",
                'Responses'!$AD$54:$AD, "<>Rod",
                'Responses'!$AD$54:$AD, "<>Ato",
                'Responses'!$AD$54:$AD, "<>Ref",
                'Responses'!$AD$54:$AD, "<>Cua"
                )

There are no error messages.

I'm just trying to comprehend how this happened to avoid it happening again on further forms submissions (done by another person) and to correct this (hopefully not manually).

Checking loop for match most efficiently

I have a simple set up to find top scores. The goal is to order who received the highest scores and then give the top 3 bonus points.

Question: In part two below I am looping through the people and checking who got the top score. The issue is I need to do this 3 times for each name. The way I currently have the loop set up works but seems very redundant. Is this the correct way to do it?

   var allGrades = [
        {name: 'andrew', score: 80}, 
        {name: 'john', score: 90}, 
        {name: 'sam', score: 31}, 
        {name: 'frank', score: 50}, 
        {name: 'dave', score: 95},
        ]

    allGrades.sort(function(obj1, obj2) {
    return obj2.score - obj1.score;
     });

Part two. Giving the top 3 scoring people a bonus of 50/25/15 accordingly.

for (i = 1; i < 5; i++) {

if (allGrades[0].name == 'andrew'){
andrewGradeBonus = 50; 
if (allGrades[1].name == 'andrew'){
andrewGradeBonus = 25;
if (allGrades[2].name == 'andrew'){
andrewGradeBonus = 15;

if (allGrades[0].name == 'dave'){
daveGradeBonus = 50; 
if (allGrades[1].name == 'dave'){
daveGradeBonus = 25;
if (allGrades[2].name == 'dave'){
daveGradeBonus = 15;

continued for all names...

How to fit getElementById.style within a condition block?

Really need help to understand what is wrong in that piece of code. Basically, if the block has this specific parameter satisfied (in that case left: -1200px), then it does move. In the other case it should stay at its place.

Here it is for the js:

function getReg() {
    var u = document.getElementById('greetings')
    var v = document.getElementById('createaccount')
    if (v.style.left == "-1200px") {
        u.animate([{left: '100px'},{left: '-1200px'}], {duration: 1000, fill: "forwards", easing: "ease"});
        v.animate([{left: '-1200px'},{left: '100px'}], {duration: 1000, fill: "forwards", easing: "ease"});
    } else {
        u.animate([{left: '100px'},{left: '100px'}], {duration: 1000, fill: "forwards", easing: "ease"});
        v.animate([{left: '-1200px'},{left: '-1200px'}], {duration: 1000, fill: "forwards", easing: "ease"});
    }
}

Thank you very much in advance

Is there a way to fill in NA based on a single entry in one column and matches from another?

I am trying to fill in a column for a dataframe I am working with. As of now, each row is a sample, and multiple samples may be assigned the same individual ID. If this is the case, only the first row with the ID contains the sex type, the remaining rows are NA. For the analysis I am doing the sex needs to be filled in for everything.

I initially fixed this by just exporting it to excel and copying in the sex designation by hand, but this is tedious and I am going to have to do this over many iterations. I attempted to use for and if-else loops to accomplish this. While the loop did not give any errors, it also didn't change any of the sex designations.

deerid <- c(1,2,2,2,3,4,5,5,6,7,8,8,9,9,9)
deersx <- c("m", "f", NA, NA, "f", "m", "m", NA, "f", "f", "f", NA, "m", NA, NA)
samp2 <- as.data.frame(cbind(deerid, deersx))

for (i in 1:length(samp2)) {
  for (j in 1:length(samp2)) {
    if (samp2$deerid[i] == samp2$deerid[j]) {
      if (is.na(samp2$deersx[i]) == FALSE) {
        samp2$deersx[j] <- samp2$deersx[i]
      } else {
        if (is.na(samp2$deersx[j]) == FALSE) {
          samp2$deersx[i] <- samp2$deersx[j]
        } else {
          NA
        }
      }
     } else {
      NA
    }

This didn't change the sex column at all. I was hoping that the NA values in the deersx column would be changed to m or f, such that it would actually read: m, f, f, f, f, m, m, m, f, f, f, f, m, m

Thank you for any thoughts and suggestions.

SAS count unique observation by group

I am looking to figure out how many customers get their product from a certain store. The problem each prod_id can have up to 12 weeks of data for each customer. I am trying to use the data count function as i have heard proc SQL's count function is not accurate. with large datasets. I have tried a multitude of codes, some add up all of the obersvations for each customer while others like the one below remove all but the last observation.

proc sort data= have; BY Prod_ID cust; run;
Data want;
Set have;
by Prod_Id cust;
if (last.Prod_Id and last.cust);
    count= +1;
run;

data have

prod_id cust week  store
1       A    7/29  ABC
1       A    8/5   ABC
1       A    8/12  ABC
1       A    8/19  ABC
1       B    7/29  ABC
1       B    8/5   ABC
1       B    8/12  ABC
1       B    8/19  ABC
1       B    8/26  ABC
1       C    7/29  XYZ
1       C    8/5   XYZ
1       F    7/29  XYZ
1       F    8/5   XYZ   
2       A    7/29  ABC
2       A    8/5   ABC
2       A    8/12  ABC
2       A    8/19  EFG
2       C    7/29  EFG
2       C    8/5   EFG
2       C    8/12  EFG
2       C    8/19  EFG
2       C    8/26  EFG

data want

prod_id store count
1       ABC    2
1       XYZ    2
2       ABC    1
2       EFG    2

Control for matching parts of a string (with one or multiple words)

I'm looking for a method to flag rows in which a string, or parts of the string (which may have two words) in a DataFrame column A, appear in another column B.

Example data with desired outcome in column C:

A               B                                C
Looney Tunes    Better than the Looney Tunes     True
Looney Tunes    Show me some tunes               True
Deep Tech       New tech is here                 True
Deeptech        Deeptech is here                 True
Car Ambolage    Camambolage happened             True
Something       Some thing is here               True          
Something else  This does not relate             False
Space           I am in universe                 False

What is the best approach?

How do I create a large array using a deck of 52 cards, and sets of 2 cards as each element?

I would like to shuffle the deck, and then filter the array to return two cards. The two cards represent the two dealt cards from the original 52. The problem I am having is creating a loop, if statement, or switch statement that will speed up the process of filtering through all the combinations of two so that I may apply pictures to each possibility for a fluid representation of poker with markup.

I would like to keep my original deck as an array of 52, rather than splitting the suits and numbers. As that is my thought process from the beginning. I am using the Fisher-Yates shuffle algorithm to shuffle my original deck of cards.

let deck = ["2 Club","2 Spade","2 Diamond","2 Heart","3 Club","3 Spade","3 Diamond","3 Heart","4 Club","4 Spade","4 Diamond","4 Heart","5 Club","5 Spade","5 Diamond","5 Heart","6 Club","6 Spade","6 Diamond","6 Heart","7 Club","7 Spade","7 Diamond","7 Heart","8 Club","8 Spade","8 Diamond","8 Heart","9 Club","9 Spade","9 Diamond","9 Heart","10 Club","10 Spade","10 Diamond","10 Heart","Jack Club","Jack Spade","Jack Diamond","Jack Heart","Queen Club","Queen Spade","Queen Diamond","Queen Heart","King Club","King Spade","King Diamond","King Heart","Ace Club","Ace Spade","Ace Diamond","Ace Heart"];

let originaldeck = [...deck];

const shuffle = arr => arr.reduceRight((res, _, __, arr) => [...res, arr.splice(~~(Math.random() * arr.length), 1)[0]], []);

let PlayPoker = {

  setGameStart: function(classType) {
    this.dealPlayers(classType);
  },

  dealPlayers: function(classType) {
    let freshdeck01 = shuffle(deck);
    let p1Deal = freshdeck01.filter(function(value, index, arr) {
      return index < 2;
    });
    console.log(p1Deal);
  }
}

I have created one random set of two, but I need every possible set of two within an array, and set each element to the corresponding picture.(i.e. king hearts-queen heartspicture of the king of hearts called, and then the picture of queen of hearts called from markup within my cpu)

Python if statement retrieving "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I have 2 datasets, a list r and a dataframe df.

r = [1,1,1,1,1,1,1,1,2,2,2,2,2,1]

df

|----|----|----|----|----|----|----|----|----|----|
| d1 | d2 | d3 | d4 | d5 | d6 | d7 | d8 | d9 | d10|
|----|----|----|----|----|----|----|----|----|----|
|  0 |  0 |  1 |  0 |  0 |  1 |  1 |  0 |  1 |  1 |
|  1 |  0 |  1 |  1 |  0 |  0 |  1 |  1 |  1 |  1 |
|  1 |  1 |  0 |  1 |  1 |  0 |  1 |  0 |  0 |  0 |
|  0 |  0 |  0 |  1 |  0 |  1 |  1 |  1 |  1 |  1 |

I am trying to run an if statement that evaluates the selection of a random value from df vs r. However I get an error.

The post in this link kind of exposes the problem and I did tried the methods but doesn't seem to be working.

I tried to used the methods proposed in the link above and in the error (.any() , .all(), .bool()) but don't see to get it working.

df1 = df.sample(n=1)
if(df1 <= r):
    df
    r-=df

What is wrong in my code of custom tab of buddypress?

Good day! I am looking for a way to solve that a user who doesn´t have the "shop_manager" role doesn´t appear the custom tab "searches" in his profile. But the other roles can see it. Could you help me?

  $role = 'shop_manager';
  if ( 'shop_manager' =! $role ) {
    bp_core_remove_nav_item( 'busqueda' ); //name of slug 

  }
}
add_action( 'bp_actions', 'bpcodex_remove_member_tab_on_role' );```

i try to write a trigger that check the value if exists in table returns me a default value or a random value

i try to write a trigger after insert ,checks my values if exists return me a default value or random one else insert users value in table.

alter trigger [dbo].[changevalues] 
on [dbo].[products]
after insert
as
begin
    declare @productname nvarchar(20),@prodcutprice money
    select productname=@productname ,price=@prodcutprice
    from inserted
    if exists ( select * from products 
                where productname like @productname and price=@prodcutprice)
    begin 
        insert products
        values('fast',100)
    end
    else
    begin
    insert products
    values(@productname,@prodcutprice)
    end
end

i expect that the code returns me ('fast',100) but it return null in table

How to check for multiple cases based on label name?

I have a view controller that contains a collection view on multiple categories. Different data and details including photos related to that category are fetched. I do not know how to make a case of switch statement regarding this. Writing the same code over and over does not seem like a good idea.

I have at least 14 different cells to cover...

Heres what I got

// Fetch posts based on trend name/hashtag
 func fetchPosts() {
    if trendName == "Bike Shorts" {
            print("Fetching posts with the hashtag bikeshorts")

         HASHTAG_POST_REF.child("bikeshorts").observe(.childAdded) { (snapshot) in

                let postId = snapshot.key
                Database.fetchPost(with: postId, completion: { (post) in
                    self.posts.append(post)
                    self.collectionView?.reloadData()
                })


           }

    } else {
        if trendName == "Animal Prints" {
            self.trendDetails = "This is the label for animal prints"
            HASHTAG_POST_REF.child("animalprints").observe(.childAdded) { (snapshot) in

                let postId = snapshot.key
                Database.fetchPost(with: postId, completion: { (post) in
                    self.posts.append(post)
                    self.collectionView?.reloadData()
                })


            }
        }
    } else {
        if self.trendName == "Bermunda Shorts" {
            self.trendDetails = "This is the label for bermunda shorts"
            HASHTAG_POST_REF.child("bikeshorts").observe(.childAdded) { (snapshot) in

                let postId = snapshot.key
                Database.fetchPost(with: postId, completion: { (post) in
                    self.posts.append(post)
                    self.collectionView?.reloadData()
                })


            }
        }
    }


    }

dart alternate for a lot of if elseiif

I want to replace an URL String in Dart with another String. Example:

if (url == "http://www.example.com/1") {
home = "example";
} else if (url == "http://www.example.com/1") {
home = "another example";
}

Isn't there a better way with less code and maybe faster? I'd have to do this over 60 times..

dimanche 28 juillet 2019

Checking boolean variable from JQuery POST in PHP

I am new in PHP.

I have a variable in jquery called editMode set to false. I used $.post() in jquery to pass the variable in a php function. But when I check its value, the value is fine, but if statement does not function the way it's supposed to. Here is my code:

jQuery (just a snippet):

var editMode = false;
$(document).ready(function(){
    //some function that handles UI input that triggers editMode=true

    $("#form").submit(function(event){
      event.preventDefault();

      var fName = $("#firstname").val();
      var lName = $("#lastname").val();
      //... and the rest of post values coming from UI input

      $.post('includes/sql/register.php', {
         fName: fName,
         lName: lName,
         //... and the rest of post values coming from UI input
         editMode: editMode // this is where I post the value for editMode
      },
      //jQuery function to handle the result
});

In my register.php:

<?php
  if(isset($_POST['submit'])){
     $fName = mysqli_escape_string($conn,$_POST['fName']);
     $lName = mysqli_escape_string($conn,$_POST['lName']);
     //and other post values from UI input
     $editMode = $_POST['editMode'];

     if($editMode) {
        echo $editMode . ": edit"; //fires update query
     } else {
        echo  $editMode . "add"; //fires insert query
     }
  } 
?>

When testing the code, it returns the correct value of $editMode, but does not perform the if statement correctly. What I mean is, if $editMode is true, it echoes: true: edit, which is good. But when it's false, it echoes: false: edit. So it still performs the if clause, even if its value is now false. I also tried if($editMode === true) {//edit} else {//add}, and it does the opposite. Whether $editMode is true or false, it performs the else clause. Please enlighten me.

How to handle the if statement inside the each of ajax?

I am trying to load some JSON data from back-end and output them as the html table. With no luck, I got confused how to set if-else conditions inside the ajax each.

There are 3 types of status from my data list. So I was trying to show each of them a different button by that.

However, always get wrong results when I do ELSE. even if it looks fine! the code make no sense at all...

And doesn't "else if" exist?

$.each(data.list, function (i, item) {
                var giftCenter = 
                    '<tr>'+
                        '<td width="20%">'+ item.sn +'</td>'+
                        '<td width="20%">'+ item.create_time +'</td>'+
                        '<td width="20%" width="20%">'+ item.out_nick_name +'</td>'+
                        '<td><img class="gem" src="img/gem.png" alt="" /> '+ $numberFormat.format(item.amt) +'</th>'+
                        '<td width="20%" class="gift-operate">'+ item.status_name +'<button type="button" class="acceptBtn">YES</button><button type="button" class="cancelBtn">NO</button><button type="button" class="confirmBtn">CONFIRM</button></td>'+
                    '</tr>';
                $(".playGiftTab2 tbody").append(giftCenter);
                // none of these will show
                if(item.status == "2" || item.status == "-1" || item.status == "-2" || item.status == "-3"){
                    $(".acceptBtn, .cancelBtn, .confirmBtn").hide();
                }
                // only if 0 1
                else if(item.status == "0" || item.status == "1"){
                    $(".acceptBtn, .cancelBtn, .confirmBtn").show();
                    // receiver
                    if(item.is_giver == 0){
                            $(".confirmBtn").hide();
                            $(".acceptBtn").hide();
                            $(".cancelBtn").hide();
                    }
                    // giver
                    else if(item.is_giver == 1){
                        // status 0
                        if(item.status == "0"){
                            $(".confirmBtn").hide();
                            $(".acceptBtn").show();
                            $(".cancelBtn").show();
                        }
                        // status 1
                        else if(item.status == "1"){
                            $(".acceptBtn").hide();
                            $(".cancelBtn").hide();
                            $(".confirmBtn").show();
                        }   
                    }
                }
            });

Dynamically Change as.POSIXlt Value

In R, I am trying to read a file that has a timestamp, and update the timestamp based on the condition of another field. The below code works with no problem:

t <- data.frame(user = as.character(c("bshelton@email1.com", "lwong@email1.com")), 
                last_update = rep(as.POSIXlt(Sys.time(), tz = "America/Los_Angeles"), 2))
Sys.sleep(5)
t$last_update <- as.POSIXlt(ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update), origin = "1970-01-01")  
print(t)

The problem is when I read an existing file and try to dynamically change an as.POSIXlt value. The following code is producing the error that accompanies it in the code block afterwards:

t <- data.frame(user = as.character(c("bshelton@email1.com", "lwong2@email1.com")), 
                last_update = rep(as.POSIXlt(Sys.time(), tz = "America/Los_Angeles"), 2))

write.csv(t, "so_question.csv", row.names = FALSE)
t <- read.csv("so_question.csv")

t$last_update <- as.POSIXlt(t$last_update)
Sys.sleep(5)
t$last_update <- as.POSIXlt(ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update), origin = "1970-01-01")  

Error in as.POSIXlt.default(ifelse(t$user == "bshelton@email1.com", Sys.time(),  : 
  do not know how to convert 'ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update)' to class “POSIXlt”
In addition: Warning message:
In ans[!test & ok] <- rep(no, length.out = length(ans))[!test &  :
  number of items to replace is not a multiple of replacement length

Arrayformula to count X when C

I want to count the cells they have o! or %

I want to count them or v witch have in the front cell from the row an o! or %

="o!: "&count(arrayformula(and($D9:H$67="o!",(E8:E67=Or("v","m")))))&", %: "&count(arrayformula(and($D9:H$67="%",(E8:E67=OR("v","m")))))

but nothing works

How can I use the if statement on this char in C? [duplicate]

This question already has an answer here:

I am trying to make a simple calculator program in C using functions and I am trying to use the if statement to determine the user inputted char string.

The function works as intended, I tried to make it as 3 and 4 sized char and it did not work.

int a, b, ans;
char *userChoice;
while (1)
{
    sf("%d %d %s", &a, &b, &userChoice);
    if(userChoice == "add")
    {
        ans = add(a, b);
        pf("%d", ans);
    }
    else if (userChoice == "sub")
    {
        ans = sub(a, b);
        pf("%d", ans);
    }
}

No error messages, and no output. Same with no while loop.

How to change object once in a loop

I am trying to make it so the object X is the background and A is an object to be moved up or down, but once i use loop to change the A to X, the loop finds the a in the next line and does it once again, how do i make it so it only changes once and moves on?

newlist = ['X','X','A','X','X','X','X']

for i in range(len(newlist)):

    print(newlist[i])

    if newlist[i] == 'A':

        newlist[i] = 'X'

        newlist[i+1] = 'A'

this is what i tried,

It should show X X X A X X X from X X A X X X X

but right now it shows X X X A A A A

How to fix "Result values in '? :' expression have mismatching types'"

I want to render two different HStacks depending on a value later coming from a backend

let list: [ReminderModel] = [ReminderModel(text: "Buy Bananas", closed: true), ReminderModel(text: "Meet John", closed: false), ReminderModel(text: "MMhh", closed: false), ReminderModel(text: "4", closed: false), ReminderModel(text: "5", closed: false), ReminderModel(text: "6", closed: false)]
var current: Int = 0

struct ReminderList: View {
    var body: some View {
        VStack() {
            list.count%3 == 2 ?
                HStack() {
                    Reminder(closed: list[list.count-2].closed, text: list[list.count-2].text)
                    Reminder(closed: list[list.count-1].closed, text: list[list.count-1].text)
                }
                : //Here is the error
                HStack() {
                    Reminder(closed: list[list.count-1].closed, text: list[list.count-1].text)
            }
        }
    }
}

Error:

Result values in '? :' expression have mismatching types HStack<TupleView<(Reminder, Reminder)>> and HStack<Reminder>

error: control reaches end of non-void function [-Werror=return-type] } ^

The problem is basically about to generate a arithmetic expression from a given 'n' numbers , and the expression should be divisible by 101. we can only have +,-,* operators and expression is left associative.

I have tried all the available solution on , that are already mentioned on stack overflow, like closing the expressions with else and many more

bool calci(int a[],int n,int sum,int pos,char operato[],deque<int>&q,deque<char>&qc)
{

    if(sum%101==0)
    {   //cout<<"sum:"<<sum<<endl;
        return true;
    }

    else if(pos==n)
        {return false;}
    else
    {
    for(int k=0;k<3;k++)
    {  // cout<<"here for "<<a[pos]<<endl;
        sum=addto(sum,a[pos],operato[k]);
        qc.push_back(operato[k]);
        q.push_back(a[pos]);
        bool kyaagesemila=calci(a,n,sum,pos+1,operato,q,qc);
        if(kyaagesemila)
            {
                return true;
            }
        sum=removefrom(sum,a[pos],operato[k]);
        qc.pop_back();
        q.pop_back();
    }
    }
}

i am getting a compilation error

solution.cc:53:1: error: control reaches end of non-void function [-Werror=return-type]
 }
 ^
cc1plus: some warnings being treated as errors```


a program for the if else statement with nested loop and regex

  1. there are 2 function in the program. public and private function.

  2. $merge_list is the db, with $article[' '] the place in the db to be searched.

  3. there is a text file with a given list of words which needed to be excluded from the db.

  4. the private function is called in the public function for the processing.

  5. i have successfully written a program to do unset the given words from the text file,

  6. but when the words from the text file are 'au' or 'awa' a certain if else must be applied with this regex, '/\bau\b/si' .

  7. if any one could complete the program i would really be very thankful to you.

completion needed in the //if and else if part only.

if($ng_word == 'au') {
            //if the word is au
            preg_match_all('/\bau\b/si', $article['article_headline1'], $ng) ||
            preg_match_all('/\bau\b/si', $article['article_headline2'], $ng) ;

if (array_search('au', $ng) !==FALSE) {
               var_dump($ng);
            }

<?php
public function dc_check_ng_word(&$merge_list){ //$merge_list is the db
        $ng_file = explode("\n", file_get_contents(self::NG_FILE)); //the text file
        $ng_list = [];
        foreach($merge_list as $key => $article) {
            //nested loop
            foreach($ng_file as $ng_word) {
                if(!$this->ng_word_match($article, $ng_word)) { //see the private function below
                    $ng['keyword'] = $ng_word;
                    $ng['url'] = $article['url'];
                    $ng_list[] = $ng;
                    unset($merge_list[$key]); //erasing the $ngword from the $merge_list
                }

            }
        }
    }
    //the is a list of words in a text file but if the condition of 'au' and 'awa'  a different conditon need to be writtien.
    //ng word check function
    private function ng_word_match($article, $ng_word) {
        if($ng_word == 'au') {
            //if the word is 'au' 
            //i have tried with  preg_match_all('/\bau\b/si', $article['article_headline1'], $ng)

        }else if($ng_word == 'awa') {
            //if the word is 'awa'

        }else {
            // if other words
            if (preg_match('/'.$ng_word.'/', $article['article_headline1']) || //searching the ng word in the db
                preg_match('/'.$ng_word.'/', $article['article_headline2']) ||
                preg_match('/'.$ng_word.'/', $article['article_headline3']) ||
                preg_match('/'.$ng_word.'/', $article['article_headline4']) ||
                preg_match('/'.$ng_word.'/', $article['article_headline5']) ||
                preg_match('/'.$ng_word.'/', $article['article_sentence1']) ||
                preg_match('/'.$ng_word.'/', $article['article_sentence2']) ||
                preg_match('/'.$ng_word.'/', $article['article_sentence3']) ||
                preg_match('/'.$ng_word.'/', $article['article_sentence4']) ||
                preg_match('/'.$ng_word.'/', $article['article_sentence5']))
            {
                return false;
            }
        }
        return true;
    }
    ?>

//the if and else section is only the problem i couldn't solve

Ignore i And j’s same value in loop

I want to print feasible solutions by adding up the maximum combinations of 2 indexes for n indexes where no index’s value can be added to itself

Expected output for 4 indexes 1,2 1,3 1,4 2,1 2,3 2,4 3,1 3,2 3,4 4,1 4,2 4,3

Where I’m going wrong :: (Here’s my Code )

for(i=1;i<n;i++)
{
    for(j=1; j!=i && j<n; j++)
    {
        printf("%d,%d",i,j);
    }
}

samedi 27 juillet 2019

What's the difference between LEN and <>"" when searching for values?

I initially learned that if I want to see if a cell has any contents to use if(A1<>"",.... But as I receive more and more assistance on SO, it seems most people use if(LEN(A1),... Is there a difference? Did I learn the wrong information? Should I ever opt for one over the other or just always use LEN from now on?

How can I change javascript if statement to compare two words properly?

I wrote a function check() which compares two words - the given one (stored in json called from a local server) and the word from the input. If they differ, then the screen turns red, js adds one point to the "word_rank" in the json and does it untill the user enters the same word as the given one in the input. However my function thinks, that at the moment, when the given word appers on the screen the user already entered 'nothing' in the input/ As a result, even if the user types the write word, the json has already been changed at least one time (has "word_rank"+1). How do I correct it&

This is the actual example with full code: https://codepen.io/Ramzess/pen/JgbBEO

And this is the fuction:

function check() {
          var x, y, z;
          x = document.getElementById("span_text").textContent;
          y = document.getElementById("input").value;
          console.log(x, y, z);
          v = document.getElementById('btn');
          v.innerHTML = 'Check';
          if (x == 'START!' || x == y) {
            document.body.style.background = '#C0F200';
            document.getElementById('span').style.display = 'none';
            z = true;
            console.log(z);
            counter = (counter + 1) % arr.length;
            console.log(counter);
            v = document.getElementById('btn');
            v.innerHTML = 'Next';
            y = document.getElementById("input").value = '';
          } else {
            document.body.style.background = '#DB504A';
            document.getElementById('span').style.display = 'none';
            z = false;
            console.log(z);
            counter = (counter + 0) % arr.length;
            console.log(counter);
            y = document.getElementById("input").value = '';
            v = document.getElementById('btn');
            v.innerHTML = 'Try again';
            words[counter].word_rank++
            document.getElementById('json2').innerHTML = JSON.stringify(words[counter].word_rank);
            document.getElementById('json3').innerHTML = JSON.stringify(words[counter]);
              }
            }
            var m = document.getElementById('json1').innerHTML;
            console.log('m = ' + m);

        check();

I expect the function to initialize the checking session (when I see "START!") without turning the screen into red color and compare the given word from json with the word from input after the user typed something into it.

Thank you!

Bash ping command in if statement with square brackets does not work [duplicate]

This question already has an answer here:

This works:

if ! ping -q -c 1 -W 1 google.com > /dev/null; then
   echo "google not reachable"
fi

but this does not work:

if [ ! `ping -q -c 1 -W 1 google.com > /dev/null` ]; then
    echo "google not reachable"
fi

Why does the second statement not work? Is it not basically the same?

Can we implement preprocessor level decision-making in C and C++ by combining #if-#else if and macros with arguments?

I wish to implement preprocessor level 'loops' which use #if #else directives as decision making statements so that I can exponentiate a number (base) to a certain power without using any functions and then using the main() and printf() statements to only print the output. Is this possible in C or C++?

I've tried this and the following error occurs:'#' is not followed by a macro parameter

(In reality I've written the entire #define statement on ONE line(till #endif).So please ignore that.)

/* C program to exponentiate a number to a certain power without using functions.(Using main() and printf() to ONLY output the final result.) */

 #define exp(base,power) #if power exp(base * base,power-1) #else 
 #include<stdio.h> void main(){printf("the exponentiated form is:%d",base);} #endif

exp(2,3)

I've tried this and the following error occurs:'#' is not followed by a macro parameter

Euclid's algorithm shows wrong conclusion

Homework of mine is to create and Euclid's algorithm in java. The task binds me to use both while-loop and if statement. Futhermore - if statement has to be placed inside while-loop.

During this task i faced already infinity-loop problem, somehow manage to get pass it. Now my Euclid's algorithm is giving multiple answers (instead of one) and futhermore they are wrong...

I have searched a couple of topics over here, but none of answers shown in there gave me an answer. I tried to rewrite whole code, and also diffrent conditions for while-loop and if statement.

import java.lang.*;

class EuklidesAlgorithm {
    public static void main (String[] args) throws java.lang.Exception{
        int a = 25648;
        int b = 15468;

        while (a % b != 0 ){
            int modulo = a % b;
            if (modulo == 0){
                break;
            }else {
                modulo = a % b;
                System.out.println(" Checking for GCD");
                a = b;
                b = modulo;
            }
            System.out.println(" Number " + b + " is GDC of numbers(" + a + "," + b + ").");
        }
    }
}

I would like it to give a single answer what is GCD for a and b.

How to find the biggest number using only two-way branching

I need help in solving my C++ problem exercise. The problem is this, I have to input 3 numbers and output the biggest number but I only need to use the two-way branching (if else). Can you help me with this?

How to alter this script to add another condition

I have this piece of code which has been working great for me, however, I need a minor alteration to it and don't know how to proceed.

I would like for 'Multiple Use' to be added as another condition, alongside 'Yes' for the onEdit() to work.

function numberToLetter(number){
  // converts the column number to a letter
  var temp = "";
  var letter = "";
  while (number > 0){
    temp = (number - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    number = (number - temp - 1) / 26;
  }
  return letter;
}

function obtainFirstBlankRow() {  

  var sheet = SpreadsheetApp.getActive().getSheetByName('Aug2019');
  // search for first blank row
  var col = sheet.getRange('A:A');
  var vals = col.getValues();
  var count = 0;

  while (vals[count][0] != "") {
    count++;
  }
  return count + 1;
}

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSheet();

  if (ss.getName() == 'ProspectiveSites' && e.range.getColumn() == 26) {

    if (e.range.getValue() != 'Yes'){
      Logger.log('test');
      return;
    }

    var sourceSheet = SpreadsheetApp.getActive().getSheetByName('ProspectiveSites');
    var targetSheet = SpreadsheetApp.getActive().getSheetByName('Aug2019');

    //Logger.log('O' + e.getRow() + ':O' + e.getRow());
    Logger.log(e);
    Logger.log(e.range.getValue());
    var cell15 = sourceSheet.getRange('O' + e.range.getRow() + ':O' + e.range.getRow()).getValue();
    var cell24 = sourceSheet.getRange('X' + e.range.getRow() + ':X' + e.range.getRow()).getValue();
    Logger.log(cell15);
    Logger.log(cell24);

    var row = obtainFirstBlankRow();    
    targetSheet.getRange(row, 1).setValue(cell15);
    targetSheet.getRange(row, 2).setValue(cell24);
  }
}

vendredi 26 juillet 2019

How to Create a function that will return the sum of 2 integers?

I've encountered a simple question but failed to write the code. Grateful if you can help me.

The question: Create a function that will return the sum of 2 integers.

My code:

q1 <- function(a, b) {
  if (a == as.integer(a)) {
    if (b == as.integer(b)) {
      result1 <- a + b
    }
  }
} else {
  result1 <- NA
  result1
}

q1(3,6) - suppose it returns 9

q1(3.1,6) - suppose it returns NA

BTW, why can I not write the syntax in this way? if(is.integer(a) = TRUE){

How do I grab the first non-NA column matching a string if a certain column is NA

I haven't seen a similar question for this issue (it's pretty specific).

I have three people who can be chosen to give answers to questions about a patient. Only two of those three people are actually used for any particular patient (in my real data it's always two who are chosen, but among a pool of 10 people).

If the initial two people disagree, a third person is used (3rdOpinion) and that opinion overrides the others.

Therefore, the final result = the 3rd opinion result, UNLESS the initial two opinions are the same (i.e. 3rdOpinion is NA), in which case the final result is just the opinion given by the initial two people (i.e. the first non-NA value for that question for that patient)

So for example patient 1 question 1, Ben and Chris disagreed, so 3rdOpinion was used as the final result.

For question 2, patient 2, Adam and Chris both said "yes", so the final result is "yes" and the 3rd opinion wasn't used.

How can I code my data to give the last two columns, Question1_final and Question2_final?

#Code to reproduce the data with the desired last two columns:
Patient <- c("1","2","3")
Question1_Adam <- c(NA,"Yes","No")
Question2_Adam <- c(NA,"Yes","No")
Question1_Ben <- c("Yes",NA,"Unlikely")
Question2_Ben <- c("No",NA,"No")
Question1_Chris <- c("Probably","Probably",NA)
Question2_Chris <- c("Unlikely","Yes",NA)
Question1_3rdOpinion <- c("Probably","Yes","No")
Question2_3rdOpinion <- c("No",NA,NA)
Question1_final <- c("Probably","Yes","No")
Question2_final <- c("No","Yes","Unlikely")
df <- data.frame(Patient, Question1_Adam, Question2_Adam, Question1_Ben, Question2_Ben, Question1_Chris, Question2_Chris, Question1_3rdOpinion, Question2_3rdOpinion, Question1_final, Question2_final)

I figured I needed something like this, but not sure how to code the last part:

df <- transform(df, Q1_final = ifelse(!is.na(Question1_3rdOpinion), Question1_3rdOpinion, *here I would somehow grep the first non-NA question 1 value*))

If Statement Providing Wrong Output

I coded a banking program. I'm at the point where the user must enter their pin, and it must be compared to their pin which is taken from a text file. The problem is, I have an if statement, and the condition is met, but it keeps giving me an the statement as if it was not met.

I've tried switch statements and even using a boolean value, but it does not work

public String getPin(){
return pin;
}

    String pin2 = lbl_Pin.getText();
    System.out.println(pin2);
    System.out.println(getPin());

//Allows the user to select what they want to do after they enter the 
correct pin
if(pin2.equals(String.valueOf(getPin()))) {
btn_SelectLoan.setEnabled(true);
btn_SelectWithdraw.setEnabled(true);
btn_SelectDeposit.setEnabled(true);
btn_Balance.setEnabled(true);
lbl_Loan.setVisible(true);
lbl_Withdraw.setVisible(true);
lbl_Deposit.setVisible(true);
lbl_Balance.setVisible(true);

    }
//Displays invalid if the pin is not correct
else{
lbl_Pin.setText("Invalid");
    }
}                                         

I enter the correct pin, I am sure of this as I displayed the correct pin as well as the entered pin, and they are the same, but an invalid answer is provided

why other clauses after "IF" is not working, when nested in while loop finishes

hi I am trying to create very simple if else clause which has nested while loop like this.

    a = 10
    if a > 6:
        while a > 5: 
            a -= 1
            print("a in while loop")
    elif a == 5:
        print("a", a)
    else:
       print("Doing else")    

The issue is when while loop finished, it will not go elif nor else clause. I think I am missing something basic here. Could someone explain? I thought after while loop finished the code should check rest of the statements. Thanks in advance

Prints last last capital instead of first one

It prints last capital letter in the input not first and whenever there is no capital letter in the input it prints random capital letter and no capital statement, I don't know why it doesn't end with return statement.

void fun(char x[],int y)
{
   if(x[y - 2] >= 'A' && x[y - 2] <= 'Z')
   {
      printf("First capital letter in the given input is:%c\n",x[y-2]);
      return;
   }else
      fun(x,y -1);
   }
   //this part works
   if(y == -1)
   {
      printf("No capital letter found\n");
      return;
   }
}

int main()
{

  char x[200];
  fgets(x,200,stdin);
  int count = 0;
  while(x[count] != '\0')
      count++;

  fun(x,count);

  return 0;
}

If/else not working with event.target selector

I have three buttons. Clicking on one should do one thing, clicking on the second one should do another thing, etc.

When you click on any of the buttons I'm seeing the same message in the console, which I don't want. Is there something wrong with my if/else logic or is something else affecting the results?

index.js:

$(document).on("click", ".dtAddClass-rolesgrid", disp._newRole);

$(document).on("click", ".dtAddClass-srchgrid", disp._newRole);

$(document).on("click", ".dtAddClass-additionalsrchgrid", disp._newRole);

JS snippet:

_newRole(e) {
        $("#dialog-form fieldset > #activate-button").hide();
        $("#dialog-form fieldset > #deactivate-button").hide();
        dialog.dialog({ title: "Add New Search/Role Filled" });
        dialog.dialog("open");

        if ($(e.target.tagName === ".dtAddClass-rolesgrid")) {
            myClass._AddNewRoleFilled();
            console.log('this is rolesgrid') // clicking on any of the buttons only shows this message
        } else if 
            ($(e.target.tagName === ".dtAddClass-srchgrid")) {
            console.log('this is srchgrid');
        } else if 
            ($(e.target.tagName === ".dtAddClass-additionalsrchgrid")) {
            console.log('this is addtsrchgrid');
        } else {
            console.log('this is e: ' + e)
        }
    }

How the buttons were created:

        let _gridNew = _grid.substring(1);
        var table = $(_grid).DataTable({
            buttons: [
                {
                  text:      '<i class="fa fa-plus"></i>',
                  titleAttr: 'Add',
                  className: 'dtAddClass-' + _gridNew
                },

Is there karate a way in karate dsl to implement an if /then else if/then for schema validation

I want to to be able to check two conditions if they are true i.e in karate I have an array of data that I want to validate in the following way

if "Documentation": "ID" then "citizen": "YES"

else

if "Documentation": "Passport" then "citizen": "NO"

Here is the array data I want to validate

{
  "id": 7777,
  "name": "suzie",
  "surname": "Nedbank",
  "Documentation": "ID",
  "citizen": "YES",
},

tried approach:

* def Doc_type = function(x) { return x == "ID" || x == "Passport"}

* match response == 

{
"id": 7777,
"name": "suzie",
"surname": "Nedbank",
"Documentation": "#? Device_type(_)",
"citizen": "#($.Documentation == "ID" ? "citizen" : "YES" || $.Documentation == "Passport" ? "citizen" : "NO" )" 
}

error : net.minidev.json.parser.ParseException: Unexpected token | at position 154.

Auto Update a Multivalue Field

I am looking for a way to auto update a multivalue field based on what is in one record. If Record 1 fieldx= 2,3 Then Record 2 fieldx= 1

Record 3 fieldx= 1

And vice versa. I would also like to further edit each record without losing data. So if i want to add another value to record 2 field x then it should read 1,4 and not just 4(the new value)

Stuck in an if statement in a while loop. How do i exit?

i wrote the following code to iteratively build a matrix depending on the conditions met. But i'm stuck in the 2nd if statement. for some reason it doesnt move to else and prints the contents of my print statements over and over, infinitely.

vi= df['GroupId'][0]
G_df= pd.DataFrame(index=np.arange(0, v), columns=['j', 'vi']) 
G_df['j'][0] = 0
G_df['vi'][0] = 0
j=0
i=0
old_tweet_id=1
new_tweet_id=1
value= df['TFIDF_score'][0]

while(i<u):
    old_tweet_id=new_tweet_id
    while (old_tweet_id == new_tweet_id):
        if (j < v):
            new_js= [G_df.loc[G_df['vi'] == vi, 'j'].item()] 
            if new_js != 0:
                print('new_js',new_js)
                new_j= int(''.join(str(x) for x in new_js))
                print('new_j', new_j)
                B[i][new_j] = value         
                print('matrix', B)                
            else: 
                G_df.loc[-1]=[j,vi]
                B[i][j]=value
                vi = vi +1
                j=j+1
            if (j>=v):
                old_tweet_id =  u +10
            else:
                cc = df['tweet_id'][j:j + 1]
                dd = df['TFIDF_score'][j:j + 1]
                value = dd[j]
                new_tweet_id = cc[j]

    i = i + 1

I tried using break and also tried to empty the new_js and new_j variables just before the else line but that didn't work either. I'm sure I'm missing something but I can't place my finger on it.

Need to compare two strings with one variable

I have two variable as model_name and status. Need to check if model_name is either in model1 or model2 and status is in Failed then have to send mail to users with format 1 else the mail should be sent as the default format.

I tried If [[ $model_name = "model1" ]] -o [[ $model_name = "model2"]] -a [[$status = "Failed" ]] then format1 else Default format fi But this didnt worked and Default format mail is only getting send

jeudi 25 juillet 2019

R: dplyr: transmute where there is a match; else keep

I have a long data frame (about 10 mill. rows) with a unique key (which is a combination of columns) for each row and a vector of values.

I have a short data frame with unique key that matches a few of the keys in the long data frame. These matching keys identify replacement values, supplied in the value column of the second data frame. All the keys in the second data frame should match exactly one key in the first, though perhaps not in order. I want to efficiently produce a new data frame with values of the first where there is no match, and of the second where there is. I feel like there should be a join that does this, but I have not identified it.

df1 <- tibble(let = c("a", "b", "a", "b"), num = c(1, 1, 2, 2), val = c(.1, .2, .3, .4))
df1 <- tibble(let = c("a", "b"), num = c(1, 2), val = c(.5, .6))

df1 %>%
out <- transmute(let = let, num = num, unknown_fn(df2, by = c("let", "num"))

desired output:

let    num   val
"a"    1       .5
"a"    2       .2
"b"    1       .3
"b"    2       .6

How to iterate over rows and assign values to a new column

I have a dataframe with over 75k rows, having about 13 pre-existing columns. Now, I want to create a new column based on an if statement, such that:

if each row of a certain column has the same value as the next, then the value in the new column for that row would be 0 or 1.

The if statement checks for two equalities (columns are tags_list and gateway_id).

The below code snippet is what I have tried

for i in range(1,len(df_sort['date'])-1):

    if (df_sort.iloc[i]['tags_list'] == df_sort.iloc[i+1]['tags_list']) & (df_sort.iloc[i]['gateway_id'] == df_sort[i+1]['gateway_id']):
        df_sort.iloc[i]['Transit']=0
    else:
        df_sort.iloc[i]['Transit']=1

Getting a keyerror :2 in this case

PS: All of the columns have the same number of rows

multiple OR conditions in IF statement in javascript

I have a drop-down and depending on what is selected from the drop-down some of the UI fields will become un-visible to the user to fill. I have an IF statement with many different ORs and have the hard-coded value on the condition. I am very new to coding so I don't know what is the best way to do this. I want to have a clean and reusable code. Also the drop-down values are coming from the database and I did not know how to add to my IF without hard-coding them.
Any help will be appreciated.

if (value === 'Banana Factory' || value === 'Apple Factory ') {
      this.store1Visable = false;
    } else {
      this.store1Visable = true;
    }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory') {
      this.store2Visable = false;
    } else {
      this.store2Visable = true;
  }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory'
        || value === 'Banana Factory' || value === 'Grape Factory' || value === 'Peach Factory' || value === 'Kiwi Factory') {
      this.store3Visable = false;
    } else {
      this.store3Visable = true;
    }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory'
        || value === 'Banana Factory' || value === 'Grape Factory' || value === 'Peach Factory') {
      this.store4Visable = false;
    } else {
      this.store4Visable = true;
    }

I want my code to be clean and reusable to the point if something needs to be added it be an easy change.

Program stops loop when if statement is met

I cant get my if statement to actually print anything even when it should be true.

When I remove the if statement the program runs through the while loop until the end of the text file, however it will stop once the if statement condition is met. (I have the problematic if statement commented out for the sake of posting this)

#include <stdio.h>
int *file_int, *file_int2, *inv1,*inv2, *inv3, *inv4, *num;
int counter = 0;

int main(){
    FILE * in_file;
    in_file = fopen("beerinput.txt", "r");
    while (!feof(in_file)){
        counter +=1;
        printf("LOOP #%d\n", counter);
        fscanf(in_file, "%d\n", &file_int);
        printf("file_int = %d\n", file_int);

        fscanf(in_file, "%d\n", &file_int2);
        printf("file_int2 = %d\n", file_int2);
      /*if (file_int == 1){
            inv1 += *file_int2;
            printf("%d", inv1);
        }*/
}
}

Output when if statement is commented out: LOOP #1 file_int = 100 file_int2 = 300 LOOP #2 file_int = 500 file_int2 = 900 LOOP #3 file_int = 1 file_int2 = 200 LOOP #4 file_int = 2 file_int2 = 200 LOOP #5 file_int = 3 file_int2 = -100 LOOP #6 file_int = 4 file_int2 = 200 LOOP #7 file_int = 4 file_int2 = -200 LOOP #8 file_int = 3 file_int2 = -100 LOOP #9 file_int = 2 file_int2 = -300 LOOP #10 file_int = 1 file_int2 = -99 LOOP #11 file_int = -1 file_int2 = -99

VS. Output when the if statement isnt commented out: LOOP #1 file_int = 100 file_int2 = 300 LOOP #2 file_int = 500 file_int2 = 900 LOOP #3 file_int = 1 file_int2 = 200

How to add a class using less than from a range in input?

I'm having problems with my code. It's supposed to add a class called test to .js-volume when a range in an input is less than 30. It can work if the value in the input is exactly at 30 this.value == 30 but using less than or greater than doesn't work.

JS Code:

$(function() {
  $('.plyr-volume input').on('input',function(){
    if(parseInt(this.value > 30)) {
      $('.js-volume').addClass('test');
    } else {
      $('.js-volume').removeClass('test');
    }
  });
  $('.plyr__volume input').trigger('input');
})();

Demo - https://codepen.io/openbayou/pen/JQeEry

Which is better "nested if" or "if and multiple else if"?

Which code snippet has better performance?

Assuming that 'a' and 'b' are boolean variables.

First Code Snippet

if (a && b) {
    // path 1
} else if (a && !b) {
    // path 2
} else if (!a && b) {
    // path 3
} else {
    // path 4
}

Second Code Snippet

if (a) {
    if (b) {
        // path 1
    } else {
        // path 2
    }
} else {
    if (b) {
        // path 3
    } else {
        // path 4
    }
}

It seems that the second code snippet is doing less work but I don't know if nesting 'if conditions' have side-effects.

How can I make icon child and text child appear only if the items equal 1 or greater and make them invisible if they are 0

How can I make icon child and text child appear only if the items equal 1 or greater

I am trying to hide the minus button and the 0 (which shows how many items) if the total equals 0. So only show the minus icon and the total items only if it is 1 or greater and make them invisible if they are 0.

import 'package:flutter/material.dart';

class ClassName extends StatefulWidget {
@override
_ClassNameState createState() => _ClassNameState();
}

class _ClassNameState extends State<ClassName> {

int _counter = 0;

void _incrementCounter() {
setState(() {
  _counter++;
});
}

void _decrementCounter() {
setState(() {
  if (_counter != 0)
  _counter--;
});
}

@override
Widget build(BuildContext context) {
return SingleChildScrollView(
  child: Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(left: 7.0, top: 7.0),
              child: Container(
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  image: DecorationImage(fit: BoxFit.fill,image: 
AssetImage("image.png"))
                ),
              ),
            ),
            Text("Black t-shirt", style: 
TextStyle(fontWeight: FontWeight.bold),),
            Spacer(),
            Padding(
              padding: const EdgeInsets.only(top: 52.0),
              child: Column(
                children: <Widget>[
                  Text("£17.99", style: TextStyle(fontWeight: 
FontWeight.bold),),
                  SizedBox(height: 5.0,),
                  Row(
                    children: <Widget>[
                      IconButton(icon: 
Icon(Icons.remove_circle_outline, color: Colors.blue,), onPressed: 
_decrementCounter),
                      Text('$_counter'),
                      IconButton(icon: Icon(Icons.control_point, 
color: Colors.blue,), onPressed: _incrementCounter),
                    ],
                  )
                ],
              ),
            ),
          ],

if else inside for loop

I came across this post about an ifelse statement inside a for loop:

How to create new variables using loop and ifelse statement

var1 <- c(0,0,1,2)
var2 <- c(2,2,2,0)
var3 <- c(0,0,0,2)
var4 <- c(1,2,2,2)

df<-as.data.frame(cbind(var1,var2,var3,var4))
df

 var1 var2 var3 var4 
   0    2    0    1   
   0    2    0    2   
   1    2    0    2   
   2    0    2    2   

Based on the post the output would be:

  var1 var2 var3 var4 new
   0    2    0    1   1
   0    2    0    2   0
   1    2    0    2   1
   2    0    2    2   0

Because if in any element in one row there is 1 the corresponding row in the column (new) will be 1 else it will be 0

I wrote something like this:

for (i in 1:nrow(df)){
  if(mean(df[i,] == 1) == 0){
    df$new[i]<- 0}
  else{
    df$new[i]<- 1    
  }}

However, it is giving this output:

var1 var2 var3 var4 new
 0    2    0    1   1
 0    2    0    2   1
 1    2    0    2   1
 2    0    2    2   1

if I modify the code if(mean(df[i,] == 1) == 0) to if(mean(df[i] == 1) == 0) then it works, but in another cases, if I modify the data frame by including 1 at certain position then if(mean(df[i,] == 1) == 0) is correct and not if(mean(df[i] == 1) == 0).

Can anybody explain this behavior? and how can my loop could be modified to be correct all the times? Any explanation highly appreciated!