samedi 31 juillet 2021

Python why does this lines cause an error? [closed]

Can someone explain the solution to project euler 68? I have found many code examples onlşne but still I can't undersand why we are doing what we are doing.

JS Question: How do I make my level 0 flow to level 1 in my chat prompt

I'm working on a message chat flow diagram where you input answers and it'll give you a reply working through the chart. However, I can't get my first level to connect with my second level. I can type in "name" and it will return correctly, but when I type in yes to answer then Do you like ice cream question. I get an undefined reply. Any help is greatly appreciated.

let level = 0;
let path;

const getReply = (userInput) => {
if (level === 0) {
level = 1;
if (userInput === "name") {
path = "name";
return "Hello, name. Do you have like ice cream?";
}
}


if (level === 1) {
level = 2;
if (path === "yes") {
if (userInput === "yes") {
  return "Great, what flavour do you like?";
 }
 }

How do I get if stamens to run in Java 11?

I am new to Java 11. I have a little experience with Java 8, but I am pretty much re-learning everything. I was trying to prompt for a Username and then password if the username was correct but Main won't run anything in the if statement. It asks for the username and then after typing the username whether wrong or right the program just ends. Cant figure this out. I tried changing variables and declaring them differently but I just started making it worse.This picture shows the code for my program

JS -- levels wont flow from one to the other in my work-tree of if this then return this message

I'm working on a tree/branch flow diagram where you input answers and it'll give you a reply working through the chart. However, I can't get my first level to connect with my second level. I can type in "name" and it will return correctly, but when I type in yes to answer then Do you like ice cream question. I get an undefined reply. Any help greatly appreciated.

let level = 0;
let path;

const getReply = (userInput) => {
if (level === 0) {
level = 1;
if (userInput === "name") {
  path = "name";
  return "Hello, name. Do you have like ice cream?";
}
}


if (level === 1) {
  level = 2;
  if (path === "yes") {
    if (userInput === "yes") {
      return "Great, what flavour do you like?";
  }
}

If is not workin (beginner

I found out a lot, but this one kills my sleep.

I want to plot a sma only when ShowSMA is true. It plots fine but when I add (if ShowSMA) gives me an error. I think I tried all. Now its 3:30 and I have to give up. What's wrong there?

ShowSMA = input(title="Show SMA", type=input.bool, defval=1)

sma = sma(smaSource, smaLength)

// Plot SMA 200 if ShowSMA = 1

if ShowSMA

plot ( sma, color=close[1] > sma and close > sma ? color.green : color.red, linewidth=2 )

Recursive function that removes all odd numbers in a string; how to include negative symbol

Basically what the title says. It takes a string, removes all odd numbers in the string via recursion, and returns a modified string. For example, "54364" becomes "464", "4234" becomes "424", etc.

def removeOddDigits(inString):
#base case
    if inString == "":
        return inString
    else:
#if it's an even number keep it
        if int(inString[0]) % 2 == 0:
            return str(inString[0]) + str(removeOddDigits(inString[1:]))
        else:
#if it's an odd number skip it
            return removeOddDigits(inString[1:])
        
        
print(removeOddDigits(input("Enter String:")))

For the most part the code works as suspected, but I also want it to also include negative numbers. The problem is that it's only comparing int values, and the "-" character results in an invalid literal error. And I cannot use type() != int comparison either because it's all consisted of strings. Is there a way to bypass this so that it not only keeps even digits but also non-numerical characters?

How do I extract the last name from each cell in a name column and assign it to name array?

I think i've got a good start, but I'm having a tough time taking this to the finish line. Could someone help me out?

I have a name column(G) in my spreadsheet. I want to pull the only the last name out of each cell and assign it to an array called name_array.

I know that my If function is working because if I set each name_cell to the LastName variable it substitutes only the lastname in each cell of the column, but I cannot figure out how to assign that to the array.

Here is my code thus far. Can someone please help me out and point out what I'm missing?

Sub create_namear()

Dim name_array() As Variant
Dim name_range As Range
Dim name_cell As Range
Dim n As Long
Set name_range = ActiveSheet.Range("G2:G" & Range("G" & Rows.Count).End(xlUp).Row)
ReDim name_array(name_range.Cells.Count)

For Each name_cell In name_range.Cells
    Dim Lastname As String
            If InStr(name_cell, " ") > 0 Then
            Lastname = Split(name_cell, " ")(1)
            End If
    name_array(n) = lastname.value
    n = n + 1
Next name_cell

Debug.Print name_array(1)

End Sub

Name Column

How to fix a Javascript conditional statement that is wrongly setting everything as the first one [closed]

I'm having an issue making this conditional statement work successfully.

I want to take off "-10" from the height for "Event 3", a sprite on my map, and have managed to do that successfully. But what I'm struggling with is successfully making every other Event on the map have "+10".

The code below works in that it takes -10 from the height of $gameMap.event(3) like I want, but all the other Events also have -10 for some reason, instead of +10.

var ev3 = $gameMap.event(3);

if (ev3) {
  x = ev3.screenX(); 
  y = ev3.screenY();
  y -= ev3.spriteHeight()-10;
} else {
  var ev = $gameMap.event(eventId);
  if (ev) {
    x = ev.screenX(); 
    y = ev.screenY();
    y -= ev.spriteHeight()+10;
  }
}

I definitely have done something wrong in this code as the -10 is only meant to be specifically for $gameMap.event(3).

I'm a bit embarrassed as I'm assuming this will be a very easy thing to solve, and I'd love to figure out where I went wrong so a code noob like me can learn from this for next time. Thanks in advance to anyone who is kind enough to help me.

Several conditions and color change matplotlib and pandas df

I need to plot a barchat and to apply a color according to the "Attribute" column of my dataframe

enter image description here

x axis = Shares
y axis = Price

fig, ax = plt.subplots()
ax.barh(df['Share'],df['Price'], align='center')
ax.set_xlabel('Shares')
ax.set_ylabel('Price')
ax.set_title('Bar Chart & Colors')
plt.show()

Thanks for your help !

Else condition error with previous candle as output

Below is the code:

 bearishDynamicRSISumCarry = if bearishDynamicRSISum == 1 
        1
    else if bullishDynamicRSIsum == 1
        0
    else
        bearishDynamicRSISumCarry[1]

getting an error "undeclare identifier bearishDynamicRSISumCarry

Python: Determining period of the day based on hour using a for loop and conditionals

I would like to name the period of the day based on hourly information to my dataframe.

For this, I am attempting the following:

day_period = []

for index,row in df.iterrows():
        
    hour_series = row["hour"]
    
    # Morning = 04:00-10:00
    #if hour_series >= 4 and hour_series < 10:
    if 4 >= hour_series < 10:
        day_period_str = "Morning"
        day_period.append(day_period_str)
    
    # Day = 10:00-16:00
    #if hour_series >= 10 and hour_series < 16:
    if 10 >= hour_series < 16:
        day_period_str = "Day"
        day_period.append(day_period_str)
        
    # Evening = 16:00-22:00
    #if hour_series >= 16 and hour_series < 22:
    if 16 >= hour_series < 22:
        day_period_str = "Evening"
        day_period.append(day_period_str)
        
    # Night = 22:00-04:00
    #if hour_series >= 22 and hour_series < 4:
    if 22 >= hour_series < 4:
        day_period_str = "Night"
        day_period.append(day_period_str)

However, when double-checking if the length of my day_period list is the same as that of my dataframe (df)... they differ and they shouldn't. I can't spot the mistake. How can I fix the code?

len(day_period)
>21882

len(df)
>25696

Here's a preview of the data:

    timestamp               latitude    longitude   hour    weekday
0   2021-06-09 08:12:18.000 57.728867   11.949463   8   Wednesday
1   2021-06-09 08:12:18.000 57.728954   11.949368   8   Wednesday
2   2021-06-09 08:12:18.587 57.728867   11.949463   8   Wednesday
3   2021-06-09 08:12:18.716 57.728954   11.949368   8   Wednesday
4   2021-06-09 08:12:33.000 57.728905   11.949309   8   Wednesday

My end goal is to then append this list to the dataframe.

PHP - If statement not working properly in foreach loop

I am getting array in foreach loop,There are two keys "sequence"(unique,not repeated) and "asset_type"(can duplicate/same) and i want to check condition of every "sequence" with every "asset_type",So how can i do this ?

For example,Here is my current array

Array
(
    [id] => 78
    [sequence] => 1
    [asset_type] => 8
)
(
    [id] => 3
    [sequence] => 2
    [asset_type] => 11
)
(
    [id] => 3
    [sequence] => 3
    [asset_type] => 25
)

And here is my code which is working fine but this is too long,I am checking every "sequence" with every "asset_type", is there another way for do this ?

foreach ($feed as $key => $fd) {
    $total = count($fd);
    switch (true) {
    /*case 1 here */
         case ($fd['sequence'] == "1"):
            $asset_type = $fd['asset_type'];
            //showing articles (start)
            if ($fd['sequence'] == "1" && $fd['asset_type'] == "1") {
                    // showing html here
            }
            if ($fd['sequence'] == "1" && $fd['asset_type'] == "2") {
                    // showing html here
            }
            ... and so on ....to sequence 1 and asset_type ="n" (last asset type)
    /*case 2 here */
         case ($fd['sequence'] == "2"):
            $asset_type = $fd['asset_type'];
            //showing articles (start)
            if ($fd['sequence'] == "2" && $fd['asset_type'] == "1") {
                    // showing html here
            }
            if ($fd['sequence'] == "2" && $fd['asset_type'] == "2") {
                    // showing html here
            }
            ... and so on ....to sequence 1 and asset_type ="n" (last asset type)       
            
}           

What Am I Doing Wrong - If Else Swift

This is my code. I asked for help previously but got no response but I think I have fixed it. Essentially, want to disable a button if the count is higher than a specific number. I am printing out the count and it is correct however when I implement it in a if else statement, it is not working.

What am i doing wrong? Any help would be greatly appreciated! Thanks.

      func checkPurchase() {
        
        guard let uid = Auth.auth().currentUser?.uid else { return }
        
        Database.database().reference().child("users").child(uid).child("Posts").observe(DataEventType.value, with: { (snapshot) in
          print(snapshot.childrenCount)
          let imagesPurchase = snapshot.childrenCount
            print(imagesPurchase)
            
            Purchases.shared.purchaserInfo { [weak self] info, error in
                
                guard let info = info, error == nil else { return }
                                        
                if info.entitlements.all["Premium"]?.isActive == false && snapshot.childrenCount < 0 {
                    DispatchQueue.main.async {
                        self?.AddPicture.isEnabled = false
                    }
                } else {
                    print("Hi")
                }
            
        }
        
        }
        )
        }
        
 

why my code does not show the desired output when p_no > 10

p_no = input("Enter your 10 digit phone number: ")
if p_no in "1234567890":
    if len(p_no) == 10:
        print("ok")
        pass
    elif len(p_no) < 10:
        print()
        print("The number of digits in the phone number is less than 10.")
        print("Please retry")
    elif len(p_no) > 10:
        print()
        print("The number of digits in the phone number is more than 10.")
        print("Please retry")
else:
    print()
    print("Please retry using numbers (0-9)")

Nested else statement on bash script

For some reason, the first else statement is throwing a syntax error and I don't know why

#! /usr/bin/bash
    clear
    read -p "Enter the file you want to append the date to" FILENAME

if [ -f $FILENAME ]
then
    if [ -w $FILENAME ]
        echo "`date +"%d-%m-%Y"`" >> $FILENAME
    else    # FOR SOME REASON THIS ELSE STATEMENT IS THROWING AN ERROR
        echo "$FILENAME cannot be written to"
    fi
    
else
    touch $FILENAME
    echo "`date +"%d-%m-%Y"`" >> $FILENAME
fi 

vendredi 30 juillet 2021

Can I add IF clause to TRY & EXCEPT clause

Please pardon me if I make any formatting issues here!

I am creating 2 variables, namely the mean and variance. Still working on the "variance" variable so please ignore that part.

Here's the background: The mean and variance are int inputs. The mean can be of any value, on the other hand, the variance will need to be of value greater than 1. And whenever, the input prompts, and the users hit enter straightaway (without any inputs), the mean and variance will be 0 and 1 respectively.

I have attempted the question and want to integrate both the TRY & EXCEPT clause with the IF clause because to check of ValueError and to automatically stop the program if the users hit enter without any values...

I am not sure if this is doable, can anyone advise, please... Many thanks!

Here's my code:

mean = 0
variance = 1

valid_input = False
while valid_input == False:
    try:
        mean = int(input("Please enter the mean value: "))
        if mean == "":
            valid_input = True
            break
    except ValueError:
        print("Please enter a numeric value!")
    else:
        valid_input = True
print (mean, variance)

Dynamic redirection in expressjs

Am using Keycloak for sso which serves multiple idp autentication and using Express js as my middleware. Here am stuck with dynamic redirection, when i try to login using first tenant credentials am getting preferred-username as empid@domain1.com where as when i try to login with second tenant am getting empid@domain2.com

My query here is how to redirect to different pages based on this preferred_username obtained from response. Example: When i login using 1st tenant i should get redirected to https://example1.com and for second tenant i should get redirected to https://example2.com. How to make it work using if condition? Any help is appreciated. Example code is attached for reference

     var express = require('express');
     var session = require('express-session');
     var bodyParser = require('body-parser');
     var Keycloak = require('keycloak-connect');
     var cors = require('cors');

     app.use(bodyParser.json());

     app.use(cors());

     var memoryStore = new session.MemoryStore();

     app.use(session({
     secret: 'some secret',
     resave: false,
     saveUninitialized: true,
     store: memoryStore
     }));

     var keycloak = new Keycloak({
     store: memoryStore
     });

     app.use(keycloak.middleware({
     logout: '/logout',
     admin: '/'
     }));

     app.get('/Example1', function (req, res) {
     res.redirect('https://example1.com')
     });

     app.get('/Example2', keycloak.protect('realm:user'), function (req, res) {
     res.redirect('https://example2.com')
     console.log(req.kauth.grant.access_token.content.preferred_username)
     });

    app.use('*', function (req, res) {
    res.send('Not found!');
    });

Output of for combined loop and nested if is not coming out as intended for pandas

From a Pandas dataframe, I am trying to get an output of dates and its corresponding holiday type (eg: 25-Dec-2021 & Christmas) printed. However, the output only works as intended for one of them.

The dataframe holiday_sales_4 is as follows:

    Date        Weekly_Sales
0   2010-02-12  True
1   2010-09-10  False
2   2010-11-26  True
3   2010-12-31  False
4   2011-02-11  True
5   2011-09-09  False
6   2011-11-25  True
7   2011-12-30  False
8   2012-02-10  True
9   2012-09-07  True

and i'm trying with this code:

for i in range(0, len(holiday_sales_4)):
    comparison=holiday_sales_4.iloc[i]['Weekly_Sales']
    if comparison == True:
        date_of_true=holiday_sales_4.iloc[i]['Date'].strftime('%d-%b-%y')
        if (date_of_true==datetime.datetime(2010, 2, 12) or 
            date_of_true==datetime.datetime(2011, 2, 11) or 
            date_of_true==datetime.datetime(2012, 2, 10) or 
            date_of_true==datetime.datetime(2013, 2, 18)):
            return_holiday="Superbowl"
        elif (date_of_true==datetime.datetime(2010, 9, 10) or 
              date_of_true==datetime.datetime(2011, 9, 11) or 
              date_of_true==datetime.datetime(2012, 9, 12) or 
              date_of_true==datetime.datetime(2013, 9, 13)):
            return_holiday="Labour Day"
        elif (date_of_true==datetime.datetime(2010, 11, 26) or 
              date_of_true==datetime.datetime(2011, 11, 25) or 
              date_of_true==datetime.datetime(2012, 11, 23) or 
              date_of_true==datetime.datetime(2013, 11, 29)):
            return_holiday="Thanksgiving"
        elif (date_of_true==datetime.datetime(2010, 12, 31) or 
              date_of_true==datetime.datetime(2011, 12, 30) or 
              date_of_true==datetime.datetime(2012, 12, 28) or 
              date_of_true==datetime.datetime(2013, 12, 27)):
            return_holiday="Christmas"
            
        print(date_of_true)
        print(return_holiday,'test')

The output seems to iterate the loop/if condition correctly for date_of_true, but not for return_holiday:

The dates of holidays where Weekly Sales are greater than the mean sales of the non-holiday season are: 

12-Feb-10
07-Sep-12 test
26-Nov-10
07-Sep-12 test
11-Feb-11
07-Sep-12 test
25-Nov-11
07-Sep-12 test
10-Feb-12
07-Sep-12 test
07-Sep-12
07-Sep-12 test

Im new to coding, so iim sure the solution is simple, but I can't find it!

How to integrate control mechanism for 2 variables with couple of criteria to take note

There are 2 input variables (x and y). X & Y MUST be of numeric value. X can be of any value between negative infinity to positive infinity. On the other hand, Y has to be of value greater than 1.

If the user presses enter without entering any value, x and y will automatically be assigned 0 and 1 respectively.

Can't write more than one else if statement [closed]

So, I wrote a program. But I get an token error 'else'. I think I wrote everything correctly.

I tried to write just an else, but it is the same here.

if (averageDolphinsScore > averageKoalasScore && averageDolphinsScore >= 100) {
console.log(`Dolphins wins with ${averageDolphinsScore} points.`);
} else if (averageDolphinsScore < averageKoalasScore && averageKoalasScore >= 100); {
console.log(`Koalas wins with ${averageKoalasScore} points.`);
} else if (averageDolphinsScore === averageKoalasScore && averageKoalasScore >= 100) {
console.log(`It's a tie.`);
}

If cell is empty, paste, Else, go to next blank cell and paste

Basically I just need excel to verify if Cell A1 is empty.

If A1 is empty, paste starting in A1. If A1 is not empty, go down to the next blank cell in Column A, and paste there.

I am receiving an error : Application-defined or object-defined error on the Else part of the code.

If IsEmpty("A1") Then
    Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Else
    Range("A1").End(xlDown).Offset(1, 0).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End If

I try to make an app open from my app with a condition, someone to help me fix it? [closed]

estoy tratando de usar este código pero no funciona, ¿me pueden ayudar? click en el link para el codigo. my prolem is using the "if"

Cant loop the process in certain area - python

I'm new to python & getting stuck in this... My code does some simple stuff, it requests an API endpoint and fetches the user name from the response, and makes a table as input we take mobile number .after a successful search it will give us the option to search again. the problem I faced when the invalid mobile number was given as input the code exit, the invalid response content-length is 160 so we can easily figure out the invalid request by the content-length, so i store the response content-length in z3 varibale . is there any way to check if the content-length is equal to 160 it will print data not found and give us chance to search again. if content-length is less than 160 it will fetch the data which I have written in my code

Here is the code :

from rich.console import Console
from rich.table import Table
from rich import print
import requests

p = True

while p == True:

    num = input ("Enter the mobile number :")
    x = num
    data = {'account_type': '11' ,'account_no': x } 

    cookies = {'token': '121212ad2122sdsd2323asas12312'}
    response = requests.post('https://pytest.com/api/user/get_user_info/', data , cookies=cookies) 

    z1 = response.json()
    z2 = response.headers
    z3 = z2["Content-Length"]
    z4 = z1["data"]
    z5 = z4["acc_title"]

    table = Table(title="[+] Found [+]", style="bold")
    table.add_column("Name", justify="right", style="cyan", no_wrap=True)
    table.add_row( z5 )
    console = Console()
    console.print(table)
    
    answer = input("want to search again? ")
    if answer == "yes":
            continue
    else:
        exit()

Need your help Thanks

Show Partial View Based on Ajax Link

I am trying to show two partial views in the same div based on two ajax action links. If a user clicks "Process'", then the div renders the process_partial_view. If the user clicks "Logs", the the div renders the log_partial view.

I cannot seem to differentiate the ajax link that is click and show the appropriate view in an if statement. I have also tried using variables in tempdata. Any help would be greatly appreciated.

        <td>
                            @Html.ActionLink(linkText: "Edit", actionName: "Edit_Application", controllerName: "GenericBO", routeValues: new { id = item.App_ID }, htmlAttributes: null)
                            |
                            @Ajax.ActionLink("Process'", "Show_Process_Main_View", new { id = item.App_ID }, new AjaxOptions { UpdateTargetId = "result" }, TempData["view_partial"] = "Process")
                            |
                            @Ajax.ActionLink("Logs", "Show_Logs_Main_View", new { id = item.App_ID }, new AjaxOptions { UpdateTargetId = "result" },TempData["view_partial"] = "Log")

                        </td>

      <div class="col-lg-7 ">

    <div id="result" style=" margin: 3.5%; width:auto;">
        <h1>@TempData["view_partial"].ToString()</h1>
        <p></p>
        @if (TempData["view_partial"].ToString() == "Log")
        {
       
            { Html.Partial("Show_Logs_Main_View"); }
        }
        else if (TempData["view_partial"].ToString() == "Process")
        {
            { Html.Partial("Show_Process_Main_View"); }
        }
        <h1>@TempData["view_partial"].ToString()</h1>

    </div>

</div 

Is there an alternative to if statements?

I'm making a password generator with JavaScript and it works by getting a number from an input and it generates a password with the length that it got from the input. I added three checkboxes in HTML which represent caps, numbers and symbols. If you leave the checkboxes unchecked, it will generate the password using only lowercase letters, but if you mark the caps checkbox, it will use both lowercase and uppercase letters to create the password and it works the same way with the other checkboxes.

To evaluate which checkboxes were checked I had to use plenty of if statements, here is my code:

if (document.getElementById('caps').checked === true && 
        document.getElementById('numbers').checked === false && 
        document.getElementById('symbols').checked === false) 
    {
        const charsArray = lowercase.concat(caps);
        
        password = GeneratePassword(passwordLength, charsArray);
    } 
    else if (document.getElementById('caps').checked === false && 
            document.getElementById('numbers').checked === true && 
            document.getElementById('symbols').checked === false)
    {
        const charsArray = lowercase.concat(numbers);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === false && 
            document.getElementById('numbers').checked === false && 
            document.getElementById('symbols').checked === true)
    {
        const charsArray = lowercase.concat(symbols);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === true && 
            document.getElementById('numbers').checked === true && 
            document.getElementById('symbols').checked === false)
    {
        const charsArray = lowercase.concat(caps).concat(numbers);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === true && 
            document.getElementById('numbers').checked === true && 
            document.getElementById('symbols').checked === true)
    {
        const charsArray = lowercase.concat(caps).concat(numbers).concat(symbols);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === false && 
            document.getElementById('numbers').checked === true && 
            document.getElementById('symbols').checked === true)
    {
        const charsArray = lowercase.concat(numbers).concat(symbols);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === true && 
            document.getElementById('numbers').checked === false && 
            document.getElementById('symbols').checked === true)
    {
        const charsArray = lowercase.concat(caps).concat(symbols);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else if (document.getElementById('caps').checked === true && 
            document.getElementById('numbers').checked === true && 
            document.getElementById('symbols').checked === false)
    {
        const charsArray = lowercase.concat(caps);

        password = GeneratePassword(passwordLength, charsArray);
    }
    else {
        password = GeneratePassword(passwordLength, lowercase);
    }

As you can see, it is very repetitive. I know that one of the fundamentals for writing good code is DRY, so I wanted to know if there is another way to do this without making it so repetitive. I know switch is an alternative to if statements but I think that wouldn't solve the repetitive issue.

If anybody can provide any help I will appreciate it very much :)

ReactJs: How to check my props and other values correctly in an if statement?

I am trying to follow and create the right order in my if statement for my error, isloading and template values.

I recieve errors through: const [error, doRetry] = useTemplates();

isLoading through: const isLoading = !templates;

and my templates through a prop "templates" which are mapped here:

{templates.map((item) => (
                    <TemplateCard
                        id={item._id}
                        title={item.text}
                        description={item.description}
                        img={item.imgURL}
                        classNameToAdd={styles.cardContainer}
                        key={item.order}
                        onSelectCard={onSelected}
                        onDeselectCard={onDeselected}
                    />
                ))}

I return my values here:

return (
        <div style={sideScrollContainer}>
        <SideScrollContainer>{test}</SideScrollContainer>
        </div>

What would be the correct way of organizing my if statement in order to:

  1. If I recieve an error show the error
  2. If no templates are shown yet show the loader.
  3. If there are no errors and templates are not loading show the templates.

I did it this way but it is not working, can someone enlighten me please?

let test;
    if (error) {
        actionButtonClassName = `${styles.actionActive}`;
        test = (
            <div style={loader}>
                <span style={pStyle}>
                    <Trans>errorProduced</Trans>
                </span>
                <MenuButton
                    style={actionButton}
                    className={`${styles.actionActive}`}
                    onClick={doRetry}
                    classNameOnPressed={styles.onPressed}
                >
                    <Trans>Retry</Trans>
                </MenuButton>
            </div>
        );
    } else if (isLoading) {
        test = (
            <div style={loader}>
                <i className="fa fa-circle-o-notch fa-spin fa-2x fa-fw"></i>
            </div>
        );
    } else if (templates) {
        test = (
            <div style={templateCards}>
                {templates.map((item) => (
                    <TemplateCard
                        id={item._id}
                        title={item.text}
                        description={item.description}
                        img={item.imgURL}
                        classNameToAdd={styles.cardContainer}
                        key={item.order}
                        onSelectCard={onSelected}
                        onDeselectCard={onDeselected}
                    />
                ))}
            </div>
        );
    }

This is my useTemplates file.

const useTemplates = () => {
    const [result, setResult] = useState<[TemplateWithId[]?, Error?, Function?]>([]);
    // used to retringer the useEffect
    const [forceRerenderFlag, getForceRerenderFlag] = useState(true);

    const doRetry = () => {
        // changes the value so that useEffect retriggers
        getForceRerenderFlag(!forceRerenderFlag);
    };

    useEffect(() => {
        Meteor.call(
            GET_PUBLIC_TEMPLATES,
            i18n.locale,
            (error?: Error, result?: TemplateWithId[]) => {
                // returns the results sorted by template.order field
                if (result)
                    result.sort((templateA, templateB) => templateA.order - templateB.order);

                setResult([result, error, doRetry]);
            },
        );
    }, [forceRerenderFlag]);

    return result;
};

export default useTemplates;

Whole template file.

import React, { useState } from "react";
import TemplateCard from "/imports/cuadds/client/components/modals/templates/TemplateCard";
import MenuButton from "/imports/cuadds/client/components/common/menubutton/MenuButton";
import useWindowResponsiveValues from "/imports/cuadds/client/components/common/hooks/useWindowResponsiveValues";
import {
    DESKTOP_NARROW,
    TABLET,
    PHONE_WIDE,
    PHONE,
} from "/imports/cuadds/client/components/pages/onboarding/AspectRatios";
import SideScrollContainer from "/imports/cuadds/client/components/common/scrollContainer/SideScrollContainer";
import { t, Trans } from "@lingui/macro";
import useTemplates from "./useTemplates";
import { ROOT_ITEM_ACCESSED } from "/imports/cuadds/constants/onboardingLevels";
import styles from "./styles/templatepage.m.css";

type Props = {
    trainingLevel: number | undefined;
    templates?: TemplateWithId[];
    onOnboardingComplete: Function;
};

const MIN_NUM_OF_OPTIONS = 3;

const TemplateList = ({ trainingLevel, templates, onOnboardingComplete }: Props) => {
    const { aspectRatio, vmin } = useWindowResponsiveValues();
    const [error, doRetry] = useTemplates();

    let [selectedTemplatesIds, setSelectedTemplatesIds] = useState<string[]>([]);
    const isLoading = !templates;

    const onSelected = (id: string) => {
        const index = selectedTemplatesIds.indexOf(id);

        if (index === -1) {
            selectedTemplatesIds = [...selectedTemplatesIds, id];
            setSelectedTemplatesIds(selectedTemplatesIds);
        }
    };

    const onDeselected = (id: string) => {
        const index = selectedTemplatesIds.indexOf(id);

        if (index !== -1) {
            selectedTemplatesIds = selectedTemplatesIds.slice();
            selectedTemplatesIds.splice(index, 1);
            setSelectedTemplatesIds(selectedTemplatesIds);
        }
    };

    const actionButton = {
        fontSize: 2.8 * vmin,
        height: 6 * vmin,
        paddingBottom: 0.4 * vmin,
        width: 45 * vmin,
        borderRadius: 1 * vmin,
        fontWeight: 600,
    };

    const pStyle = {
        fontSize: 2.8 * vmin,
        color: "#3b3b3b",
    };

    const sideScrollContainer = {
        width: "100vw",
        marginTop: 2 * vmin,
        marginBottom: 3.2 * vmin,
    };

    const templateCards: React.CSSProperties = {
        whiteSpace: "nowrap",
        paddingTop: 0.5 * vmin,
        paddingBottom: 4 * vmin,
        marginTop: 2 * vmin,
        marginBottom: -1 * vmin,
        display: "inline-flex",
    };

    const loader: React.CSSProperties = {
        color: "#C5C5C5",
        fontSize: 22,
        height: 28.5 * vmin,
        padding: 1.5 * vmin,
        margin: "11px 0",
    };

    if (aspectRatio < DESKTOP_NARROW && aspectRatio >= TABLET) {
        actionButton.fontSize = 2.9 * vmin;
        actionButton.paddingBottom = 0.3 * vmin;
        loader.height = 31 * vmin;
    } else if (aspectRatio < TABLET && aspectRatio >= PHONE_WIDE) {
        actionButton.fontSize = 3.7 * vmin;
        actionButton.width = 60 * vmin;
        actionButton.height = 7.5 * vmin;
        actionButton.paddingBottom = 0.3 * vmin;
        loader.height = 40 * vmin;
    } else if (aspectRatio < PHONE_WIDE && aspectRatio >= PHONE) {
        actionButton.fontSize = 4.1 * vmin;
        actionButton.width = 68 * vmin;
        actionButton.height = 9 * vmin;
        actionButton.paddingBottom = 0.4 * vmin;

        templateCards.marginBottom = 1 * vmin;

        loader.height = 46 * vmin;
        loader.padding = 1.6 * vmin;
    } else if (aspectRatio < PHONE) {
        actionButton.fontSize = 4.8 * vmin;
        actionButton.width = 78 * vmin;
        actionButton.height = 11 * vmin;
        actionButton.paddingBottom = 0.5 * vmin;

        templateCards.marginBottom = 1.7 * vmin;

        loader.height = 59.2 * vmin;
        loader.padding = 2.2 * vmin;
    }

    const numOfTemplates = templates ? templates.length : 0;
    // makes sure we have enough templates to be over the minimum, otherise the user get's stuck
    const minNumOfOptions =
        numOfTemplates < MIN_NUM_OF_OPTIONS ? numOfTemplates : MIN_NUM_OF_OPTIONS;

    const firstTimeOnOnboarding =
        trainingLevel !== undefined ? trainingLevel < ROOT_ITEM_ACCESSED : true;

    let buttonText;
    if (firstTimeOnOnboarding) {
        if (selectedTemplatesIds.length < minNumOfOptions) {
            buttonText =
                t`SelectMore` + " (" + (minNumOfOptions - selectedTemplatesIds.length) + ")";
        } else {
            buttonText =
                t`SelectDone` +
                " " +
                // don't show the number if there's only one, otherwise it says "...your 1 cuadds!"
                (selectedTemplatesIds.length > 1 ? selectedTemplatesIds.length + " " : "") +
                "cuadds!";
        }
    } else {
        // if the user is re-watching the onboarding, don't force them to select templates
        buttonText = t`AlreadyDone`;
    }

    let actionButtonClassName;
    /**
     * if it's loading or on their first time onboarding the user didn't select enough templates.
     * If it's not the first time onboarding, the user is re-watching it, so we don't want to force
     * them to select templates, they should be able to continue directly.
     */
    if (isLoading || (firstTimeOnOnboarding && selectedTemplatesIds.length < minNumOfOptions)) {
        // shows the button in gray and inactive
        actionButtonClassName = `${styles.actionInactive}`;
    } else {
        // shows the button in blue and active
        actionButtonClassName = `${styles.actionActive}`;
    }

    let test;
    if (!error) {
        console.log("error");
        actionButtonClassName = `${styles.actionActive}`;
        test = (
            <div style={loader}>
                <span style={pStyle}>
                    <Trans>errorProduced</Trans>
                </span>
                <MenuButton
                    style={actionButton}
                    className={`${styles.actionActive}`}
                    onClick={doRetry}
                    classNameOnPressed={styles.onPressed}
                >
                    <Trans>Retry</Trans>
                </MenuButton>
            </div>
        );
    } else if (isLoading) {
        console.log("loading");
        test = (
            <div style={loader}>
                <i className="fa fa-circle-o-notch fa-spin fa-2x fa-fw"></i>
            </div>
        );
    } else {
        test = (
            <div style={templateCards}>
                {templates.map((item) => (
                    <TemplateCard
                        id={item._id}
                        title={item.text}
                        description={item.description}
                        img={item.imgURL}
                        classNameToAdd={styles.cardContainer}
                        key={item.order}
                        onSelectCard={onSelected}
                        onDeselectCard={onDeselected}
                    />
                ))}
            </div>
        );
    }

    const onActionButtonClick = () => {
        onOnboardingComplete(selectedTemplatesIds);
    };

    return (
        <>
            <div style={sideScrollContainer}>
                <SideScrollContainer>{test}</SideScrollContainer>
            </div>
            <MenuButton
                onClick={onActionButtonClick}
                style={actionButton}
                className={actionButtonClassName}
                classNameOnPressed={styles.onPressed}
            >
                {buttonText}
            </MenuButton>
        </>
    );
};

export default TemplateList;

Python - To make sure that clients receive accurate monthly invoices based on verifications checks that have been processed

A kind of homework for python from my college. Question is below:-

A company is looking to build a billing system in order to ensure that all of their clients receive accurate monthly-invoices that is based on verifications (or "checks") that's processed.

You have two tables in the following structure:

| Check type              | Price | Currency |
|-------------------------|-------|----------|
| document_photo          | 0.5   | USD      |
| document_video          | 0.9   | USD      |
| facial_similarity_photo | 0.3   | USD      |
| facial_similarity_video | 0.8   | USD      |
| right_to_work           | 1.25  | USD      |
 
| client   | Check Type              | Result    |
|----------|-------------------------|-----------|
| ABC Bank | facial_similarity_video | pass      |
| ABC Bank | facial_similarity_video | fail      |
| XYCoin   | document_photo          | bad_input |
| XYCoin   | facial_similarity_photo | pass      |
| XYCoin   | document_photo          | pass      |
 

Given the following input, calculate an invoice for a given vendors. To simplify the problem, you don't have to focus on any specific time period:

Input:
pricing = [{"check_type": "document_photo", "price":0.5, "currency":"USD"},
    {"check_type": "document_video", "price":0.9, "currency":"USD"},
    {"check_type": "facial_similarity_photo", "price":0.3, "currency":"USD"},
    {"check_type": "facial_similarity_video", "price":0.8, "currency":"USD"},
    {"check_type": "right_to_work", "price":1.25, "currency":"USD"}]
 
checks = [{"client": "ABC Bank", "check_type": "facial_similarity_video", "result": "pass"},
    {"client": "ABC Bank", "check_type": "facial_similarity_video", "result": "fail"},
    {"client": "XYCoin", "check_type": "document_photo", "result": "bad_input"},
    {"client": "XYCoin", "check_type": "facial_similarity_photo", "result": "pass"},
    {"client": "XYCoin", "check_type": "document_photo", "result": "pass"}]    


  Test cases:     
    calculate_invoice("ABC Bank") == 1.6    
    calculate_invoice("XYCoin") == 0.8 

Define thresholds based on different categories with RowSum

I have this code to categorize people with 3 or more columns out of range, the threshold would be 1015:

cols <- 2:17
df$Myo <- ifelse(rowSums(df[cols] > 1015, na.rm = TRUE) >= 3, 'Yes', 'No')

I would need to trick this code into 2 other codes:

  • one code that has a different threshold for by sex (theshold of 1004 for female (df$sex==F) and 986 by male (df$sex==M).

  • Other code that selects based on 4 thresholds:

a) first threshold would be males (df$sex==M) living in sweden (df$country==S), this theshold would be 900

b) second threshold would be females (df$sex==F) living in sweden (df$country==S), this theshold would be 1016

c) first threshold would be males (df$sex==M) living in iceland (df$country==I), this theshold would be 800

d) second threshold would be females (df$sex==F) living in iceland (df$country==I), this theshold would be 1000.

Thanks!!

flutter - if then else - variable made local only

As you can see in the code below, I want to check if a string has a ? in his name. If yes, I remove it. My problem is that the variable 'nameOfFileOnlyCleaned' stay local and is empty after the if else. Thank you for your help.

 String nameOfFile = list_attachments_Of_Reference[j].toString().split('/').last;

      if (nameOfFile.contains('?')) { //Removes everything after first '?'
        String nameOfFileOnlyCleaned = nameOfFile.substring(0, nameOfFile.indexOf('?'));
      } else{
        String nameOfFileOnlyCleaned = nameOfFile;
      }

//Here my variable 'nameOfFileOnlyCleaned' is empty. 
This is a problem because the value should be used later 
in the code. Do you know why I have this issue please? 
Many thanks.

      String extensionFile = nameOfFileOnlyCleaned.split('.').last;
      
      String url_Of_File = list_attachments_Of_Reference[j].toString();

Error in string comparison in if condition in bash shell

I need to read some properties from a config file and execute some commands if the properties match certain values. But when I try to compare the value with a string in if condition, it doesn't work.

Below is a small version of what I am trying to do.

#!/bin/bash
source config.file

echo "mode: $mode"

if [ "$mode" = "slow" ];
then 
echo "Mode is slow"
fi

The config file looks like this.

###config###
mode=slow
user=admin
password=pwd
###end###

The echo statement prints the values as "slow" but the if condition is never satisfied. What am I doing wrong?

I want to write two for loops in one for loop with an if condition. How do I do this? (Python) [closed]

I want to write this code with 1 for loop and if statement........................................................................................................................................................................................................................................................................................................................................................... ........................................................................................................................................................................How do I do this?.......................................................................................................................

 import numpy as np  
 import math   

 nlayerL = 1.5 # These are some variable 
 nlayerH = 2.4
 nsub = 1.56028
 lamda = 500e-9
 twopi = 2*math.pi


for i in range(0,101):      # First loop
    laythic = i
    sigmalayer = (twopi*laythic*1e-9*nlayerL)/lamda

    m1 = np.array([[math.cos(sigmalayer),(1j/nlayerL)*math.sin(sigmalayer)],
                   [(1j*nlayerL)*math.sin(sigmalayer),math.cos(sigmalayer)]])


    b = m1[0][0] + m1[0][1]*nsub
    c = m1[1][0] + m1[1][1]*nsub
    y = c/b

    print(y.real)

for k in range(0,101):    #* Second loop
    laythic = k
    sigmalayer = (twopi*laythic*1e-9*nlayerH)/lamda

    m2 = np.array([[math.cos(sigmalayer),(1j/nlayerH)*math.sin(sigmalayer)],
                   [(1j*nlayerH)*math.sin(sigmalayer),math.cos(sigmalayer)]])

    m3 = np.matmul(m2,m1)


    b = m3[0][0] + m3[0][1]*nsub
    c = m3[1][0] + m3[1][1]*nsub 
    y = c/b

    print(y.real)

I want to write this code with 1 for loop and if statement.......................................................................................................................................................................................................................................................................................................................................................... ...................................................................................................................................................................................How do I do this?.......................................................................................................................

why my discord.py bot is sending messages to wrong messages?

when I send a message like f then it should send message as f instead of that it sends me hello emoji idk why. Can anyone explain me why is that happening? Here is that faulty piece of code:-

@client.event
async def on_message(message):
  msg = message.content

  if message.author.id == 860161020681388093:
    pass
    
  elif "hello" or "hi" == msg:
    await message.channel.send("<a:hello:869245119780491275>")

  elif "f" == msg:
    await message.channel.send("f")

  elif "pog" in msg:
    await message.channel.send("<:NN_Poggers:852865363926450177>")

  else:
    pass

I don't know how to explain it clearly.

Here is the output in discord

How come this JQuery loop doesn't change CSS with elements less than 4

Why doesn't this script loop trough every ul.products element and count li.product element and then change it's css(background to yellow).

When I change < to > then background color changes to all elements. So far I know that the problem is with this script checking every parent elements ul.products but is able to count li.product.

$(document).ready(function(){
   $('ul.products').each(function() {
       
        if($('li.product').length < 4){
   $("li.product").css("background-color", "yellow");
}

   });
});

EXAMPLE

https://jsfiddle.net/p9rsuhx3/2/

R plotly(): hovertemplate with conditional content

I have a sunburst diagram and would like to show some hoverinfo since the labels are quite long. The code is basically

fig <- plot_ly(ids=df$KtoID,
               text= df$label_5,
               labels = df$label_4,
               parents = df$parent_ID,
               values = df$value_2020,
               type = 'sunburst',
               maxdepth=2,
               insidetextorientation="horizontal",
               branchvalues = 'total',
               hovertemplate = paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}'), 
               textinfo="text")

For each element I would like to include the information about the share of parent element in %. This works fine, if I use

hovertemplate = paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}')

resulting in hoverinfo of Element with parent, that shows "Anteil an [parent] x %"

But for the root Element, since there is no parent, I get the following hoverinfor for root element "Anteil an null 100,0 %".

So for the root element I would like to just show the first part including label and value.

So far I tried an if else expression.

hovertemplate = if (any(is.na(df[,parent]))) {paste('%{label}','<br>%{value} EUR<extra></extra>')} else {paste('%{label}','<br>%{value} EUR<extra></extra>','<br>Anteil an %{parent}','%{percentParent: .1%}')},

That didn't work.

Also, I found a similar topic here, but don't know how to use it.

Does anybody have an idea, how to modify the hoverinfo like I need it?

jeudi 29 juillet 2021

How apply a function in data frame with if/ lessthan statement in R?

I have a data frame looks like the following:

df<- data.frame(
  X1 = seq(from = 7, to = 25, by = 2),
  X2 = c(7,  10 ,11, 12, 16, 17, 20, 24, 2, 30),
  X3 = 2:11
)

I want to substitute column X3 with the following logic

if X1 lees than x2 then X3=0

am trying to write a simple if statement but my IDLE only reads the first part of my code and not the if statement if statement

am trying to write a simple if statement but my IDLE only reads the first part of my code and not the if statement

  age=int(input("Enter your age"))
if age>=18:
  print("Congratulations you are eligible to vote")

Issue with foreach, if, else php

I have been trying to add else to my foreach loop where it shows categories and subcategories. But if there is no categories available then I want it to show a text where it tells that there is no categories or products in categories.

Right now it shows the text that there is no products in categories anyways even if there is some categories shown.

<?php

  $taxonomy     = 'product_cat';
  $orderby      = 'menu_order';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 1;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 
      echo '<ul>';
      echo '<div class="category"><h1>CATEGORIES</h1></div>';
 
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id; 
        
         echo '<li class="parentcategory">';
        echo '<a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
        echo '</li>';
        

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo '<li class="subcategory">';
                echo  '<a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>' ;
                echo '</li>';
            }   
        } 
    }    
else {
          echo '<li>';
          echo '<p>';
          echo 'Currently there is no categories made';
          echo ' or any products in the categories';
          echo '</p>';
          echo '</li>';

   } 
}

 echo '</ul>';
 
?>

enter image description here

OpenCV C++ How to set an if statement condition for every four numbers [duplicate]

currently I am writing a program that will perform an equation for every 4 values that are obtained. I currently have it working when the first 4 values are given, but I am trying to expand it to let you perform the equation as long as you want. However, I am having trouble coming up with a conditional statement to do this.. I remember doing this in the past by checking if the number of values divided by 4 equals a whole number, but I don't remember how.

if (event == EVENT_LBUTTONDOWN && (data->leftMouseClicked < 4)) {
        circle(data->img, Point(x, y), 1, Scalar(0, 0, 255), 3); // draw entered point
        data->enteredPoints[data->leftMouseClicked][0] = x;
        data->enteredPoints[data->leftMouseClicked][1] = y;
        ++(data->leftMouseClicked);

This is a snippet of some of my code that collects the values by the user clicking a spot on an image. I am planning on using data->leftMouseClicked as the value to check, similarly to what is used in the current if statement I have, which is below.

if (data->leftMouseClicked == 4) { // draw curve if all 4 points were entered

Any help changing this would be much appreciated.

Conditional assignment of value - is ifelse() the best when condition and intended return value don't have same features? [R]

I want to conditionally assign a value to a variable. For example, I want to create an alphabet variable and assign to it letters if a certain letter is lowercase, or assign to it LETTERS if a certain letter is uppercase.

The first thought was to use <- and ifelse(). However, this is not working in my case:

> alphabet <- ifelse("B" %in% letters, letters, LETTERS)
> alphabet
[1] "A"

In fact I saw that, with reference to ifelse(test, yes, no), the function description says: "ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no [...]". In the Value section, it specifies a bit more: "A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no. [...]".

Ok - I realised that I can use assign() instead of <- and the value is assigned correctly to the variable:

> ifelse("B" %in% letters, assign("alphabet", letters), assign("alphabet", LETTERS))
[1] "A"
> alphabet
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

However, as per the output above, ifelse() still returns the first character from the chosen set of letters.

I am not happy with this, because...

  1. ... the fact that my code is returning something that I don't need, and...
  2. ... the fact that ifelse() wouldn't actually even work with <- ...

make me wonder whether there is a better way to do this.

Is there a preferred / more efficient / better-etiquette or in any way more appropriate option to assign a value conditionally as in this case, or should I just ignore what is bothering me?

Click event and conditional statements

How do I create a click event in a group of links that checks if a link is already open and closes it while opening the new link in vanilla JavaScript

const heroList = document.querySelectorAll('.hero-list');
const navList = document.querySelectorAll('.nav-list');


for (let i = 0; i < heroList.length; i++) {
  
  heroList[i].addEventListener("click", function() {  
    navList[i].classList.toggle('show-list');
    heroList[i].addEventListener('click', function() {
      if(navList[i].classList.contains('show-list') == true) {
      navList[i].classList.remove('show-list')
     } else {
       navList[i].classList.add('show-list');
     }})
    
  })
 };

Expand RegexMatch To Test Against An Entire Range Of Cells - Google Sheets

In Google Sheets, I'm trying to essentially make an address book which I then want to use as a means of working out who is associated with each row in my data spreadsheet.

From looking around, I seemed to find that the best way to do the actual search would be to use the following formula

=ARRAYFORMULA(IF(REGEXMATCH($C$2:C, 'Address Book'!$A$2:A), 'Address Book'!$A$2:B ))

So my interpretation of this formula was that it is saying that for each row of column C, if it contains ANY of the values that are in Column A of the address book sheet, then show column A AND column B from the relevant row of the address book sheet.

However, I think the issue is actually that it is only looking at one row of the address book sheet as the formula only works if both the address book record and the data record use the same row number on their respective sheets. How can I expand this formula to make sure that it checks all of the values in column A of the address book sheet?

Why is my if statement being skipped and how to stop if statements conflicting each other?

I am creating a programme that uses DC motors to change gears on a bike. I have one DC motor for the rear set of gears ie 1-9 and I have a DC motor for the middle gears ie 1-3. The problem I have is that when I'm switching from gear 9 to gear 8, I press a button and the motor just keeps running forever.

This is my gear nine function:

void GearNine() {   //CHANGE FROM GEAR 9-10, or 10-9
  int target = 888;   // TARGET FOR GEAR 10

  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  //  buttonState2 = digitalRead(buttonPin2);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    //if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      
      //Turn on motor A
      MotorA_Forwards();
      MotorB_Backwards();
     }
  }
  if (pos >= 838) {   //GO TO GEAR 1 ON MOTOR 1
      MotorAOff();   //TURN MOTOR OFF
  }
  if (pos2 <= 50){   //GO TO GEAR 1 ON MOTOR 2
      MotorBOff();   //TURN MOTOR OFF
      buttonPushCounter2++; //ADD TO GEAR COUNTER
  }
  
  
  
//      delay(50);
  lastButtonState = buttonState;
    Serial.print(" Motor target: ");
    Serial.print(target);
    Serial.print(" pos1: ");
    Serial.print(pos);
    Serial.print(" pos2: ");
    Serial.print(pos2);
    Serial.print(" Gear: ");
    Serial.print(buttonPushCounter2);
    Serial.println();


        buttonState2 = digitalRead(buttonPin2);

  // compare the buttonState to its previous state
  if (buttonState2 != lastButtonState2) {
    //if the state has changed, increment the counter
    if (buttonState2 == HIGH) {
      
      // if the current state is HIGH then the button went from off to on:
      //Turn on motor B
      MotorB_Backwards();

      if (pos2 <= 7050) {   // WAS IN GEAR 9 BUT GO BACK TO GEAR 8
        MotorBOff();
        buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 9, NOW 8
      }
    }
  }
//  if (pos2 <= 7050) {   // WAS IN GEAR 2 BUT GO BACK TO GEAR 1
//  MotorBOff();
//  buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 2, NOW 1
//  }
  
  lastButtonState2 = buttonState2;
  lastButtonState = buttonState;
    
    Serial.print(" Motor target: ");
    Serial.print(target);
    Serial.print(" pos1: ");
    Serial.print(pos);
    Serial.print(" pos2: ");
    Serial.print(pos2);
    Serial.print(" Gear: ");
    Serial.print(buttonPushCounter2);
    Serial.println();

}

As you can see near the bottom I have these lines of code to make the gear run back down to gear 8 after the line of code that says MotorB_Backwards();:

if (pos2 <= 7050) {   // WAS IN GEAR 9 BUT GO BACK TO GEAR 8
        MotorBOff();
        buttonPushCounter2--;  //MINUS 1 FROM GEAR COUNTER: WAS 9, NOW 8
      }

If I have these lines of code here, the motor won't stop running if the button is pressed. Where as If I have the code where I have commented it out below these lines, then the if statement conflicts with this if statement which is slightly above in the code:

  }
  if (pos >= 838) {   //GO TO GEAR 2
      MotorAOff();   //TURN MOTOR OFF
  }
  if (pos2 <= 50){
      MotorBOff();
      buttonPushCounter2++;
  }

The reason it conflicts with these if statements is that if I want to go to gear 10. Motor A will go to pos 838 but motor B wont go down to pos2 of 50, instead it will stop at pos2 of 7050, because these if statements conflict with each other. So basically I'm not sure if my if statement is correct or if I'm putting it in the correct place or even wondering if there is a better way of doing this. Much appreciated for anyone's help. Thank you.

How to correctly use IF AND in Excel

Here is an example of the workbook I have:

Single cell (G2): "Aug Wk2"

And here is the table I am working with called "Table1"

Project Name Actual Compl Date Week of Month Active/Planned
FirstProj Sept 5 Sept Wk1 Planned
SecondProj Aug 5 Aug Wk1 Planned
ThirdProj Aug Wk2 Active
SecondProj Aug 5 Aug Wk1 Planned

So, what I would like to do here, is have the Table1[Active/Planned] column dynamically update between "Active" or "Planned". Here are my conditions:

IF Table1[Week Of Month] = G2 AND Table1[Actual Completion Date] IS BLANK then set cell to "Active" ELSE set cells to "Planned".

I've tried using a function like this:

=IF(AND(Table1[Week of Month] = G2,ISBLANK(Table1[Actual Completion Date])), "Active", "Planned")

but it only seems to fill one cell rather than going through the whole column. I'd appreciate any guidance, thank you!

Python how to use if statement for dynamic column header

I have many csv files to be read by python and use pivot_table, but one of columns may not contain the same content for each csv file. After I use a fixed If Statement to execute a function, there will be an error.

For example, here's my code:

import pandas as pd
import numpy as np

dic = {
"Category": ['Math', 'Math', 'Math', 'Math', 'Math', 'Math', 'History', 'History','History','History','History','History','Physics','Physics','Physics','Physics','Physics','Physics'], 
"Name": ['John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee'],
"Scores": [59,64,50,33,80,20,30,44,65,66,78,80,94,56,55,61,12,11]}

df = pd.DataFrame(dic)

df2=df.pivot_table(index= ['Name'], columns="Category", values=['Scores'])
 
df2.columns=df2.columns.droplevel(0)

if ((df2['History'] > 60) | (df2['Math'] > 70) | (df2['Physics'] > 50)).any():
     print (df2.loc[:, 'History'])

Above If Statement code works when the Category column in my csv file contains Math, History and Physics.

However, if the Category column in another csv file only have Math, History. The If Statement won't work. How can I solve the If statement to fit different scenario of dynamic column content?

For example below, this code won't work because there's no Physics in the column header.

import pandas as pd
import numpy as np

dic = {
"Category": ['Math', 'Math', 'Math', 'Math', 'Math', 'Math','Physics','Physics','Physics','Physics','Physics','Physics'], 
"Name": ['John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee','John', 'Mary', 'Scott','Kevin','Judy','Lee'],
"Scores": [59,64,50,33,80,20,30,44,65,66,78,80]}

df = pd.DataFrame(dic)

df2=df.pivot_table(index= ['Name'], columns="Category", values=['Scores'])
 
df2.columns=df2.columns.droplevel(0)

if ((df2['History'] > 60) | (df2['Math'] > 70) | (df2['Physics'] > 50)).any():
     print (df2.loc[:, 'History'])

How to check if number lies within many ranges?

I have a list of numbers from 1 to 24

hour = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

I want to create four separate lists (a, b, c, d) based on respective conditions:

a = (22<= number <6)
b = (6<= number <9 or 12<= number <18)
c = (9<= number <12)
d = (18<= number <22

if condition is True then 1 else 0

Expected output:

enter image description here


I can create the a column but with rest of them I am facing issue,

My attempt:

import pandas as pd
df = pd.read_excel('mask.xlsx')
hour = df['Hours']
df['a'] = [1 if i>=22 or i<6 else 0 for i in hour]
b=[]
for i,j in zip(hour, df['a']):
    if i <= 6 and i < 9:
        if i<=12 and i<18:
            if j==0:
                b.append(1)
    else:
        b.append(0)
df['b'] = b

Error I'm getting:

ValueError: Length of values does not match length of index

Query results using odbc in python

import pyodbc as odbc

Driver = 'SQL Server'
server_name = ''
database_name = ''

conn = odbc.connect(f"""
    Driver=};
    Server={server_name};
    Database={database_name};
    UID=;
    PWD=;
                      """)


def sku_search():

    SKU_check = '''SELECT [ITEMSKU] FROM
    [StilettoXT].[dbo].[PRODDETAIL] WHERE
    ITEMSKU = (?)'''
    SKU_code = input('Please enter the SKU code: ')
    cursor = conn.cursor()
    cursor.execute(SKU_check, SKU_code)
    if cursor.fetchall() == []:
        print('Not Found')
    elif cursor.fetchall() != []:
        print('Found')


sku_search()

conn.close()

I'm having real difficulty trying to get the following code to work, specially the 'elif' part of the my if statement. If you run the script with an invalid SKU code that doesn't exists in that database, you get the print statement. If you run with a valid SKU code, nothing gets returned even though the cursor.fetchall() is not an empty list. If you swap the if and elif arguments round, you will only get a result for the 'if' part of the function. I can't understand why the 'elif' part returns nothing. If you query an invalid sku code, SQL will return a blank value. I've tried to reference this as None as well but the same issue. Any suggestions would be greatly appreciated!

Create yes/no column based on values in two other columns

I have a dataset that looks like this:

df <- structure(list(ID = 1:10, Region1 = c("Europe", "NA", 
"Asia", "NA", "Europe", "NA", "Africa", "NA", "Europe", "North America"), Region2 = c("NA", "Europe", 
"NA", "NA", "NA", "Europe", 
"NA", "NA", "NA", "NA"
)), 
class = "data.frame", row.names = c(NA, -10L))

I want to create a new column called EuropeYN which is either yes or no depending on whether EITHER of the region columns (region1 or region2) include "Europe". The final data should look like this:

df <- structure(list(ID = 1:10, Region1 = c("Europe", "NA", 
"Asia", "NA", "Europe", "NA", "Africa", "NA", "Europe", "North America"), Region2 = c("NA", "Europe", 
"NA", "NA", "NA", "Europe", 
"NA", "NA", "NA", "NA"
), EuropeYN = c("yes", "yes", "no", "no", "yes", "yes", "no", "no", "yes", "no")), 
class = "data.frame", row.names = c(NA, -10L))

I know how to do this if it was just checking to see if "Europe" appears in one column, but have no idea how to do this when checking across multiple columns. This is what I would do if it was just one column:

df$EuropeYN <- ifelse(grepl("Europe",df$region1), "yes", "no")

Any ideas on the best way to approach this?...

Cannot get If statements on RaycastHit2D to execute except for the top-most one

In my Unity 2D game, I have set up 3 different 2D Raycasts on the same GameObject for score-detection purposes with the help of boolean and if statements. The object in question today is a torus that is scrolling from right to left, which the player (the balloon) has to go through or avoid using up and down motion. The player gets more points when going through the torus as opposed to going around it.

The issue: Rayhit1 returns correctly when the player is detected inside the torus. But the code for Rayhit2 and Rayhit3 won't execute. Interestingly, if I put the code for Rayhit2 before Rayhit1, it would execute. Same is true for Rayhit3.

This is the "hit1" part for example:

if(!Rayhit1)
    {
         if(hit1.collider.name == "GameObject")
         {
              RayHit1 = true;
              score.value += 30;
         }
    }
if(!hit1)
    {
         RayHit1 = false;
    }

Snapshot of the game

Here are snippets of my code that concern the process of detecting score:

private bool RayHit1 = false;
private bool RayHit2 = false;
private bool RayHit3 = false;

void Update()
{
     int layer = 9;
     int layerMask = 1;
     RaycastHit2D hit1 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 72.0f), Vector2.up, 150.00f, layerMask);
     RaycastHit2D hit2 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y + 85.0f), Vector2.up, 600.00f, layerMask);
     RaycastHit2D hit3 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 85.0f), Vector2.down, 600.00f, layerMask);

if(!Rayhit1)
{
     if(hit1.collider.name == "GameObject")
     {
          RayHit1 = true; //boolean to true for just 1 frame so that the score does not add more than once
          score.value += 30;
     }
}
if(!hit1)
{
     RayHit1 = false; //reset boolean to false when Raycast returns nothing
}

if(!Rayhit2)
{
     if(hit2.collider.name == "GameObject")
     {
          RayHit2 = true;
          score.value += 10;
     }
}
if(!hit2)
{
     RayHit2 = false;
}

if(!Rayhit3)
{
     if(hit3.collider.name == "GameObject")
     {
          RayHit3 = true;
          score.value += 10;
     }
}
if(!hit3)
{
     RayHit3 = false;
}
 
}

Run query based on variable

In PG, I need to get results from a different query based on the value of a variable.

I tried something like this -

do $$
declare myVar int;
select <something> into myVar;
if myVar = 1 then
    select col1 from myTable;
else
    select col2 from myTable;
end if;
end $$;

This gives me:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.

Now, I can't do case because depending on myVar, myTable might have the column col1 or col2; not both. Using case will fail with "column does not exist" since it considers the whole statement and notices the non existing column.

I'm hoping IF-ELSE will help by avoiding the block with the incorrect (non-existing) column

challenge about corona as a practice exercise second part

So I have 3 tables, person, hospital and hospitalized (as child of these 2)

enter image description here

enter image description here

enter image description here

So the point here is create a record in hospitalized if the person has symptoms in a hospital if this one has capacity.

At this point I created an after trigger on 'person' table

> CREATE DEFINER=`root`@`localhost` TRIGGER `person_AFTER_INSERT` AFTER
> INSERT ON `person` FOR EACH ROW BEGIN     
> N
>         /*CHECK ID EXISTS OR NOT.*/           
>         declare personExists  int;
>         declare hospital_id int;
>         declare capacity int;
>         select count(idperson) from person into personExists;
>         select idhospital from hospital where capacity > 0 into hospital_id;                  
>         select capacity from hospital where capacity > 0 and idhospital = hospital_id into capacity;
>         if personExists > 0 then  
>           if symptoms = 'yes' then
>              if capacity > 0 then
>                 /*INSERT ROW */
>                 insert into hospitalized(`person_id`,`hospital_id`) VALUES(person_id,     hospital_id);
>               /*UPDATE CAPACITY IN THAT HOSPITAL*/
>               SET @i:=0;
>               update hospital set capacity= @i:=(@i-1) where idhospital = hospital_id;
>              end if;          
>           end if;         
>         end if;
>     END

I do not know what's wrong Thanks a lot

Create a new factor level (new row) based on data from other rows with conditional statements

df <- data.frame(PatientID = c("0002" ,"0002", "0005", "0005" ,"0009" ,"0009" ,"0018", "0018" ,"0039" ,"0039" , "0043" ,"0043", "0046", "0046" ,"0048" ,"0048"),
                 Timepoint= c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B",  "A", "B",  "A", "B", "A", "B"),
                 A = c(NA , 977.146 , NA , 964.315 ,NA , 952.311 , NA , 950.797 , 947.465 , 902.852 ,  985.124  ,NA , 930.141 ,1007.790 , 1027.110 , 999.414),
                 B = c(998.988 , NA , 998.680 , NA , 1020.560 ,  955.540 , 911.606 , 964.039   ,  988.087 , 902.367 , 959.338 ,1029.050 , 987.374 ,1066.400  ,957.512 , 917.597),
                 C = c( 987.140 , 961.810 , 929.466 , 978.166, 969.469 , 943.398  ,936.034,  965.292 , 996.404 , 920.610 , 967.047, 913.517 , 893.428 , 921.606 , 929.590  ,950.493), 
                 D = c( 961.810 , 929.466 , 978.166, 1005.820 , 925.752 , 969.469  ,943.398 ,  965.292 , 996.404 ,  967.047 ,  NA , 893.428 , 921.606 , 976.192 , 929.590 , 950.493),
                 E = c(1006.330, 1028.070 ,  954.274 ,1005.910  ,949.969 , 992.820 ,934.407 , 948.913 ,    961.375  ,955.296 , 961.128  ,998.119 ,1009.110 , 994.891 ,1000.170  ,982.763),
                 G= c(NA , 958.990 , 924.680 , 955.927 , NA , 949.384  ,973.348 , 984.392 , 943.894 , 961.468 , 995.368 , 994.997 ,  979.454 , 952.605 ,NA , 956.507), stringsAsFactors = F)

Based on this dataframe, I need to create an extra FACTOR level for the variable (df$TimePoint) that will be filled based on the following conditions - we have already factors A and B in that variable so lets say that we want to create factor level X :

  • For df$A. If df$Timepoint B is >999 then the factor X will be filled with the same value as df$Timepoint level B value, otherwise (if it is ≤999) then it will be filled with the value at df$timepoint A.

  • For df$B. If df$Timepoint B is >986, factor X will be == as df$Timepoint level B value, otherwise X will == df$timepoint A.

  • For df$C. If df$Timepoint B is >1000, factor X will be == as df$Timepoint level B value, otherwise X will == df$timepoint A.

  • For df$D. If df$Timepoint B is >1030, factor X will be == as df$Timepoint level B value, otherwise X will == df$timepoint A.

  • For df$E. If df$Timepoint B is >800, factor X will be == as df$Timepoint level B value, otherwise X will == df$timepoint A.

  • For df$G. If df$Timepoint B is >950, factor X will be == as df$Timepoint level B value, otherwise X will == df$timepoint A.

The new dataframe would look like this:

enter image description here

Thanks in advance! Best

Find inconsistent and consecutive objects from List in C#

I'm having trouble with getting a consecutive and nonconsecutive number from list. I'm sure it's pretty simple, but i can't get it.

If consecutiveNum=2, then if result from before last and last is equal, i need to throw an exception.

If nonConsecutiveNum=4, then if from 10 pieces there are 4 with same result, i need to throw an exception.

I'm trying with nested loops and couple checks, but i didn't succeeded at all. Same is for both cases, i tried a couple solutions with System.LINQ, but again i don't get the result i need.

Thanks in advance to all of you!

int consecutiveNum = 2;
int nonConsecutiveNum = 4;
int counter = 1;

var sensInfo = new ResultInfo()
                {
                    Product = CurrentLot.Info.Product,
                    Result = code
                };

 if (consecutiveNum > 0)
                    {
                        for (int i = ListSensors.Count + 1; i >= 0; i--)
                        { 
                            if (sensInfo.Result == ListSensors[i].Result)
                            {
                                counter++;
                                if (counter >= consecutiveNum)
                                {
                                    throw new Exception("Consecutive num");
                                }
                            }
                        }
                    }

if (nonConsecutiveNum > 0)
                    {
                        for (int i = 0; i < ListSensors.Count; i++)
                        {
                            for (int j = i + 2; j < ListSensors.Count - 2; j++)
                            {
                                if (ListSensors[i].Result == ListSensors[i+1].Result)
                                    continue;
                                if (ListSensors[i].Result == ListSensors[j].Result)
                                {
                                    counter++;
                                    if (counter >= nonConsecutiveNum)
                                    {
                                        throw new Exception("NonConsecutive num");
                                    }
                                }
                            }
                        }
                    }

How does If statements does work on computers?

Im just wondering what is the logic behind the "if" in programming, how its handled on cpu side, what stuff that computer does to compare two variables?

np where with two conditions and met first

I am trying to create a target variable based on 2 conditions. I have X values that are binary and X2 values that are also binary. My condition is whenver X changes from 1 to zero, we have one in y only if it is followed by a change from 0 to 1 in X2. If that was followed by a change from 0 to 1 in X then we don't do the change in the first place. I attached a picture from excel.

I also did the following to account for the change in X

df['X-prev']=df['X'].shift(1)
df['Change-X;]=np.where(df['X-prev']+df['X']==1,1,0)

however, this is not enough as I need to know which change came first after the X change. I attached a picture of the example.

Thanks a lot for all the contributions. Example

What mistake am I doing in my javascript code?

In the place of "math", user will write name of mathematical operation. I am trying to get user input and want to do user specified mathematical operation on selector 1 and selector 2. Is this js code perfect for that?

self.math = function(math, sel1, sel2){
        let inner = 0;
        switch (inner)
        {
          case (math = 'add') :
             text = sel1 + sel2;
            break;
          case (math = 'multiply') :
             text = sel2 * sel1;
            break;
          case (math = 'subtract') :
             text = sel1 - sel2;
            break;
          case (math = 'subReverse') :
             text = sel2 - sel1;
            break;
          case (math = 'div') :
             text = sel1 / sel2;
            break;
          case (math = 'divReverse') :
             text = sel2 / sel1;
            break;
        }
       self.innerText = text;
       return self;
    }

Ifelse(V>=80,"Above_Average","Average") in R printing extra spaces between last 2 outputs

I've a simple programming exercise in R, where I have to- Check each value of the vector V passed as a argument. If the marks are greater than or equal to 80 print Above_Average. If the marks are less than 80, print Average(in a single line).

Here's what I'm doing :-

conditional <- function(V)
{
ifelse(V>=80,"Above_Average","Average")
}
conditional(c(90,80,85,70,95))

output :-

[1] "Above_Average" "Above_Average" "Above_Average" "Average"       "Above_Average"

My concern is the extra space between last two outputs. Do you've any idea why I'm getting the extra space? And what is the solution for this?

mercredi 28 juillet 2021

R code for creating "if... then" statement for a range of values of two variables

I am trying to create an "if... then" statement in R in which two variables, G1 and G2, lie within a range of values in a given dataset. For example, if (200 > G1 > -100) and (200 > G2 > -100), then G = mean(G1,G2)

My code looks like this:

if(200 > G1 > -100 & 200 > G2 > -100) {G = mean(G1,G2)}

The error I'm getting reads: Error: unexpected '>' in " if(200 > G1 >"

Any help would be much appreciated! Thanks

I am new to Python,Help me with this

New

Geek has found a new job for himself, he is now a "password validator", he has to validate thousands of passwords in a day. A password is a string of characters which is valid only when it contains atleast one numerical character, atleast one lowercase english alphabet character and atleast one uppercase english alphabet character. Geek is too smart to do this job manually, so he decided to make a program to automate the process. Help him write a program which when given a string S (the password) prints "YES" if it is a valid password or "NO" otherwise. Input Format: 1. The first line of the input contains a single integer T denoting the number of test cases. 2. The first line of each test case contains a single string S. Output Format: For each test case, print "YES" or "NO" in a new line.

How to make variable equations inside conditionals work in jQuery?

I have been trying to make a tool that processes an input value via arithmetic equations depending on its value range.

After many iterations, being unable to declare variables within an if..else statement, and combing through online resources, I am completely stuck at the following, a bulky workaround which depends on having id'd every cell of the table I am outputting into.

Could there be any way I can make a sequence of formulas such as the ones at the bottom functional? Currently, the only part that works are the top three lines. Thank you so very much. (*゚ー゚)

  $('#submit').click(function(){
     
      var hc = $("#healthcare_cost").val();
      $("#cost2").text(hc);
      $("#cost").text(hc);

      var ai = $("#annual_income").val();
      var o = $("#0").val();
      var x = $("#25000").val();
      var xx = $("#50000").val();
      var xxx = $("#75000").val();
      var xxxx = $("#100000").val();
      var xxxxx = $("#200000").val();

      var yy = $("#3450").val();
      var yyy = $("#7695").val();
      var yyyy = $("#12275").val();
      var yyyyy = $("#33875").val();
    
        var xmr = $("#.138").val();
        var xxmr = $("#.169").val();
        var xxxmr = $("#.184").val();
        var xxxxmr = $("#.216").val();
        var xxxxxmr = $("#.246").val();
      
      if (ai<x){
          $("#mr").text(o);
          $("#tta").text((ai-o)*o+o);
          $("#er").text(((ai-o)*o+o)/ai);
          $("#yp").text(((ai-o)*o+o)*.2);
          $("#ner").text((((ai-o)*o+o)*.2)/ai);
      };
      
      else if (ai>=x && ai<xx){
            $("#mr").text(xmr);
          $("#tta").text((ai-x)*xmr+o);
          $("#er").text(((ai-x)*xmr+o)/ai);
          $("#yp").text(((ai-x)*xmr+o)*.2);
          $("#ner").text((((ai-x)*xmr+o)*.2)/ai);
  };
         else if (ai>=xx && ai<xxx){
            $("#mr").text(xxmr);
          $("#tta").text((ai-xx)*xxmr+y);
          $("#er").text(((ai-xx)*xxmr+y)/ai);
          $("#yp").text(((ai-xx)*xxmr+y)*.2);
          $("#ner").text((((ai-xx)*xxmr+y)*.2)/ai);
      };
         else (ai>=xx && ai<xxx){
            $("#mr").text(xxmr);
          $("#tta").text((ai-xx)*xxmr+y);
          $("#er").text(((ai-xx)*xxmr+y)/ai);
          $("#yp").text(((ai-xx)*xxmr+y)*.2);
          $("#ner").text((((ai-xx)*xxmr+y)*.2)/ai);
      };

});
});

How to add my isLoading constant to this conditional statement?

I added this constant

    const isLoading = !templates;

In order to Change the color of my button and prevent a click if my cards are still loading.

However, I dont know how to add my isLoading constant to this conditional statement.

<MenuButton
    className={
    !firstTimeOnOnboarding || selectedTemplatesIds.length >= minNumOfOptions
    ? `${styles.actionBlue}`: `${styles.actionNormal}`}>
    {buttonText}
</MenuButton>

I tried doing this but it doesnt work.

className={
!isLoading && !firstTimeOnOnboarding || selectedTemplatesIds.length >= minNumOfOptions ? `${styles.actionBlue}`: `${styles.actionNormal}`}

if in pandas data frame : TypeError: '<' not supported between instances of 'NoneType' and 'int'

I am lost in some simple pandas op.

I am getting the error: TypeError: '<' not supported between instances of 'NoneType' and 'int'

When evauating the following statement:

self.df.sma_s.iloc[-1] < self.df.sma_l.iloc[-1]

The weird thing is that my dataframe actually contains floats in those fiels.

Trying to debug, I did the following:

    self.df['sma_s'] = self.df.close.rolling(sma_s).mean()
    self.df['sma_l'] = self.df.close.rolling(sma_l).mean()

    self.current_position = self.check_positions()

    print('gonna check for trades')

    print(self.df.sma_s.iloc[-1])
    print(type(self.df.sma_s.iloc[-1]))

    print(self.df.sma_l.iloc[-1])
    print(type(self.df.sma_l.iloc[-1]))

    print('='*50)
    print(self.df.tail(5))

    over = self.df.sma_s.iloc[-1] > self.df.sma_l.iloc[-1]
    print(f'Over: {over}')

    under = self.df.sma_s.iloc[-1] < self.df.sma_l.iloc[-1]
    print(f'Under: {under}')

    if over and np.sign(self.current_position) != 1:
        self.close_position()
        trade = self.buy(self.qty)
        
    elif under and np.sign(self.current_position) != -1:
        self.close_position()
        trade = self.sell(self.qty)

The results are:

gonna check for trades
 1.1847966666666665 
<class 'numpy.float64'>
 1.1848311111111112 
<class 'numpy.float64'>
 
  date                      sma_s     sma_l   
2021-07-28 16:23:00-04:00  1.184852  1.184856
2021-07-28 16:24:00-04:00  1.184860  1.184863
2021-07-28 16:25:00-04:00  1.184847  1.184853
2021-07-28 16:26:00-04:00  1.184820  1.184837
2021-07-28 16:27:00-04:00  1.184797  1.184831
Over: False 
Under: True

But it still gives me the error:

TypeError: '<' not supported between instances of 'NoneType' and 'int'
    176 
--> 177         elif under and np.sign(self.current_position) != -1:
    178             self.close_position()
    179             trade = self.sell(self.qty)

TypeError: '<' not supported between instances of 'NoneType' and 'int'

How come, when I ask it to print,self.df.sma_s.iloc[-1] is a float64 and self.df.sma_s.iloc[-1] > self.df.sma_l.iloc[-1] it is a boolean, but when I evaluate it inside the "if" I get that error? It does not make any sense to me! any clues?

Thanks!!

If statement is always true regardless of condition

I think I have the same issue posted here: R Programming: Condition giving always TRUE but I do not know how to apply the answer to my situation.

The if statement below searches for a match in the major_allele column for REF and vice-versa. The problem is that it always evaluates to true as shown by the rows with astericks. The previous answer at the above link stated that ifelse always produces a vector so I am guessing that it is only looking at the first observation, evaluates to true and then moves to doing the same across all rows. However, I would like it to go row-by-row. Below new_gwas_a1 is created but from the REF column for all rows but it should be false for the rows with asterisk.

for (i in files){
rsid.tmp  <- read.table(i, header = TRUE, sep=" ", stringsAsFactors = 
FALSE, fill = TRUE)


rsid.tmp$new_gwas_a1 <-if((sapply(lapply(rsid.tmp$REF, grepl, 
x=rsid.tmp$major_allele),any))
                || (sapply(lapply(rsid.tmp$major_allele, grepl, 
x=rsid.tmp$REF),any)))
        {rsid.tmp$REF}

new_file <- sub("(\\.txt)$", "_updated\\1", i)
write.table(rsid.tmp, new_file, quote = FALSE, row.names = FALSE)


REF ALT minor_allele_frequency  minor_allele    major_allele     
new_gwas_a1
A   G   0.000219914 G   A   A
C   T   0.0144844   T   C   C
C   T   0.0445486   T   C   C
C   T   0.00647968  T   C   C
C   T   0.222656    T   C   C
**A G,T 0.12189     A   G   A
**A G,T 0.305252    A   G   A
C   T   0.00210762  T   C   C
C   A   0.00139373  A   C   C

I was also receiving this warning previously which hasn't shown again since but I wonder if the issue is related. Warning message: In if (sapply(lapply(rsid.tmp$REF, grepl, x = rsid.tmp$minor_allele), : the condition has length > 1 and only the first element will be used

I tried this same code directly in R and it seems to work. See below please

> a <- c("TGTGTGT")
> b <- c("AC")
> c <- c("A")
> d <- c("AGTGTG,ATGTGT")
> e <- c("TG")

> if((sapply(lapply(a, grepl, x=c),any)) || (sapply(lapply(c, grepl, 
x=a),any))) {print(Yes)}

> if((sapply(lapply(b, grepl, x=c),any)) || (sapply(lapply(c, grepl, 
x=b),any))) {print("Yes")}
[1] "Yes"

How do I take 2 columns, one for name and one for values, and spit out the unique number of amounts per unique name? Then make a list

I was given a list of property names and the number of bedrooms they offer, but the info was given like this: 0 value = studio

Property Bedrooms
Name1 1
Name1 2
Name1 3
Name2 0
Name2 1
Name2 4
Name3 1
Name3 2

I'm hoping to eventually get this information to spit out into a new sheet like so:

Property Bedrooms
Name1 1, 2, and 3 bedrooms
Name2 studio, 1, and 4 bedrooms
Name3 1 and 2 bedrooms

2nd table wouldn't show up correctly

I can get the numbers to populate in a new cell along with the word "bedroom" by using the join function, but I'm not finding much success getting conditional values to work for things like adding a comma after the second value if there's a third.

Any help, even just linking me to the right threads, videos, etc. would be greatly appreciated!

How would you check if a letter/number/symbol is in a string? (Python)

Sorry for asking a fairly simple question, but how would I make it so that if a certain letter/symbol/number would "activate" an if statement when the letter (for example "a") is in the element. If I make

thestring = ["a"]

(And then add the if statement ^^) Then it would work but if I add another letter or number next to it:

thestring = ["ab"]

(And then add the if statement ^^) It wouldn't work anymore. So essentially, how can I fix this?

Sample Code:

thestring = ["fvrbgea"]

if "a" in thestring:
  print("True")
Output: (Nothing here since there's not an else code I guess.)

How to produce an if statement to compare rows in R

I need to compare two rows next to each other in a column in a dataframe, if the data in both those rows matches, then save the most recent row, e.g.

Column: Animals

# 1  dog  row 1

# 2  cat  row 2

# 3  cat  row 3

It should compare dog and cat, then not save any data. So it won't save row 1 and 2.

But when it moves onto compare cat and cat, realise they are the same and save those rows. So save rows 2 and 3. As they are the same. I need to do this for lots of rows, iterating through to compare a big set of data.

I've tried to produce an if statement in which:

#  if(data$Animals[i] == data$Animals[i+1]) {
#    print(data$Animals[i])
#  }
# }

I want to save the printed output into a new dataframe, but I'm not sure how to go about it.

I'm new to R and learning, please help anyway you can, I'd appreciate it :)

Nesting "IF" Statements in Google Sheets to categorize numbers

I am trying to categorize numbers based on various levels of qualifications standards. For instance, Qualification "A" requires a number between 44.09 and 35.60. Qualification "B" requires a number between 35.59 and 29.30. Finally, qualification "C" requires a number at or less than 29.29. If the number is above the highest "A" qualification of 44.09, then an "X" should be displayed.

B2 happens to be the cell this formula is categorizing.

I have tried nesting "IF" statements in the following manner, however the formula incorrectly classifies the number.

=IF(44.09>=B2>35.59,"A", IF(35.59>=B2>29.29,"B", IF(B2<=29.29,"C","X")))

When I input "20" into "B2", the formula will classify it as "A", even though it should be "C".

Perhaps I have the "<>=" statements incorrectly stated, but I have tried fixing them to no avail. How can I change the formula to correctly classify these numbers?

Matching and returning values based on condition or ID

This seems like it should be fairly easy, but i'm having trouble with it.

Example: I have a dataframe with two columns IDs and perc_change. I want to know which unique IDs have had more than 30% change.

IDs <- c(1,1,2,1,1,2,2,2,3,2,3,4,5,6,3)
perc_change <- c(50,40,60,70,80,30,20,40,23,25,10,30,12,7,70)
df <- data.frame(IDs, perc_change)

So far:

if (df$perc_change > 30) {
unique(df$IDs)
} else {
}

This obviously doesn't work because it returns all unique IDs. Should I be be finding the index and then matching it or soemthing?

Thanks in advance!

How to create an if statement that runs if a function is used

currently I am creating a program in c++ that performs an equation if 4 points are given. However, I want to create a loop that stores the coordinates of the points as they are created. To do this, I want to the condition of the an if statement to be if a function is used. I was wondering how I could set this condition, as I am not sure how to indicate the function being used as true. The loop will automatically store the coordinates selected in the function into an array. My code can be found below, with onMouse being the function that I want to be used in the if statement condition. I was also wondering if this loop should be set in the main function or the onMouse function itself. Thanks for the help!

#include <iostream>
#include<opencv2/core/core.hpp> //Mat is defined there
#include<opencv2/imgproc/imgproc.hpp>  //resize an image
#include<opencv2/highgui/highgui.hpp> //input or output: imread(), imshow()

using namespace std;
using namespace cv;

Mat img;

void onMouse(int event, int x, int y, int flags, void* userdata)
{
    if (event == EVENT_LBUTTONDOWN)
    {
        printf("(%d, %d)\n", x, y);

        circle(img, Point(x, y), 1, Scalar(0, 0, 255), 3);
    }
}


int main(int argc, char** argv)
{
    cv::namedWindow("Spline");
    cv::setMouseCallback("Spline", onMouse);


    img.create(600, 800, CV_8UC3);
    img = Scalar(255, 255, 255);


    //Below are just matrices used for testing the spline function

    

    

    
    //Points manually inputted to be used for formula, will be deleted when loop is created


    double h_values[4][4] = { { 2, -2, 1, 1 }, { -3, 3, -2, -1 }, { 0, 0, 1, 0 }, { 1, 0, 0, 0 } };
    //Standard matrix that is used for spline formula, this will stay the same
    Mat Hermite = Mat(4, 4, CV_64FC1, h_values);

    //Points manually inputted, this is the part that will be replaced with a loop (last two rows are computed from a separate 
    //formula, which is why they are not directly on the last two points)
    double point_values[4][2] = { { 200, 350 }, { 220, 400 }, { 600, 300 }, { 390, 300 } };
    Mat Points = Mat(4, 2, CV_64FC1, point_values);

    //This is how you obtain the values for the final spline formula
    Mat Final = Hermite * Points;
    printf("Final matrix:\n");
    cout << Final << endl;
    
    //Just test points used to figure out spline function, used before the ablility to click to make a circle was found

        //Draw 1st point
    circle(img, Point(200, 350), 1, Scalar(0, 0, 255), 3);

    //Draw 2nd point
    circle(img, Point(220, 400), 1, Scalar(0, 0, 255), 3);

    circle(img, Point(400, 450), 1, Scalar(0, 0, 255), 3);

    circle(img, Point(350, 500), 1, Scalar(0, 0, 255), 3);

    //Draw the spline between 1st and 2nd points
    //Use a loop on t [0, 1], for different t values, compute x(t), y(t); then use circle() to draw it
    // x(t) = axt3 + bxt2 + cxt + dx                               
    // y(t) = ayt3 + byt2 + cyt + dy


    double ax = (int)(Final.at<double>(0, 0));
    double ay = (int)(Final.at<double>(0, 1));
    double bx = (int)(Final.at<double>(1, 0));
    double by = (int)(Final.at<double>(1, 1));
    double cx = (int)(Final.at<double>(2, 0));
    double cy = (int)(Final.at<double>(2, 1));
    double dx = (int)(Final.at<double>(3, 0));
    double dy = (int)(Final.at<double>(3, 1));

    printf("ax:\n");
    cout << ax << endl;
    printf("dx:\n");
    cout << dx << endl;


    //Formula used to draw spline spline

    for (double t = 0.0; t <= 1.0; t += 0.001)
    {
        int x = ax * t * t * t + bx * t * t + cx * t + dx;
        int y = ay * t * t * t + by * t * t + cy * t + dy;
        circle(img, Point(x, y), 1, Scalar(0, 0, 0), 1);
    }



    while (1)
    {

        imshow("Spline", img);
        char c = waitKey(1);
        if (c == 27)
            break;

    }


    return 1;


}