vendredi 31 mai 2019

Creating New Collumns in DataFrames under some condition (python pandas)

I'm trying to create a new collumn in my dataframe, but its values must follow some rule. For example, if the value of the variabe "Venda" is less than 200 then the Variable "Comissão" must be 0.

if (df['Venda']<200):
    df['Comissão']=0
    df['Direito a Bonus']='Não'
elif (df['Venda']>=200) & (df['Venda']<250):
    df['Comissão']=0.5*df['Venda']
    df['Direito a Bonus']='Sim'
else:
    df['Comissão']=0.7*df['Venda']
    df['Direito a Bonus']='Sim'

Running this code i keep gettin the error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Simple_Polygon isEqualateral();

Define a [public] function called "isEquilateral" which will return true if all of this polygon's sides are of equal length (otherwise it'll return false). Make sure that this function works no matter how many sides / vertices there are. I have a distance function in another class. that handles the distance between two points. Vertices is an array of points.

enter image description here

How to write if-statement and document.write in function?

I'm new to Java and I'm stuck with this task. The task is to aks a user his name and save it in var name and do the same for exam and save it in var exam. Then I have to check what grade did student got on the exam and depending on answer (1, 2, 3, 4 or 5) write a message (if student got a grade 1 the message should be "Student (name) got (grade) on (exam)." I need to do that in Croatian and we have different form of verb for male and female version, I wrote that in code. I'm sorry if it's not clear but I don't know how to explain better.


<html lang="hr">
<head>
<meta charset="UTF-8">
<title>Task</title>
</head>
<body>

    <form>

        <p>NAME</p>
        <input id="name" type="text" name="Name" size="40" maxlength="150">
        <p>EXAM</p>
        <input id="exam" type="text" name="Exam" size="40" maxlength="150">
        <p>GENDER</p>
        <input id="gender" type="text" name="Gender" size="40" maxlength="150">
        <p>GRADE</p>
        <input id="grade" type="number" name="Grade" size="40">
        <input class="document" type="submit" onclick="task();">
        <p id="task"> </p>

        </form>
    <script>


        function task(){
            var grade= document.getElementById(grade).value;
            var name= document.getElemenetById("name");
            var exam= document.getElemenetById("exam");
            var gradetxt= [];
            var gender= document.getElemenetById("gender");


            if (grade == 1) {
                ocjenatxt = "insufficient";
            } else if (grade == 2) {
                ocjenatxt = "sufficient";
            } else (grade == 3) {
                ocjenatxt = "good";
            } else (grade== 4) {
                ocjenatxt = "very good";
            } else (grade== 5) {
                ocjenatxt = "excellent";
            }
            if (gender== "f" && grade== 1) {
                document.write("Studentica " + name+  " je na ispitu " + exam+ " pala."); /*this is for grade 1 for female (insufficient)*/
                } else if (gender == "m" && grade== 1); {
                   document.write("Student " + name + " je na ispitu " + exam+ " pao.");  /*this is for grade 1 for male (insufficient)*/
                } else (gender == "m" && grade != 1) {
                   document.write("Student " + name +  " je na ispitu " + exam + " ostvario ocjenu " + gradetxt);  /*this is for grade 2-5 for male (it should be written in words not number)*/
                } else (gender == "f" && grade != 1) {
                   document.write("Studentica " + name + " je na ispitu " + exam + " ostvarila ocjenu " + gradetxt);  /*this is for grade 2-5 for female (it should be written in words not number)*/
                }


        </script>

    </body>
</html>```

How would you change multiple variables to false if their individual values are zero?

Context:

I'm working on a game in Unity and I have a piece of code which you can make destroy an object after it reaches or passes a certain point in the x or y-axes or after a set amount of time. In the script, I have a few safeguards for incorrectly filling out what values of time, x and y coordinates you would like the object to be destroyed at.

Quick Data Dictionary:

killPosX, float

killPosY, float

killPosT, float

killX, boolean

killY, boolean

killT, boolean

Code:

I would like to make my code a little more compact. Here is the original.

if (killPosX != 0) //x position you would like the object to be destroyed at
{
    killX = true; //make sure the value is set to true
}

if (killPosY != 0) //y position you would like the object to be destroyed at
{
    killY = true; //make sure the value is set to true
}

if (killPosT != 0) //position in time you would like the object to be destroyed at
{
    killT = true; //make sure the value is set to true
}

Is there some way in C# to turn this piece of code into something that might look like this:

if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}

Where the code would check if each value in the array [killPosX, killPosY, killPosT] were not equal to 0 individually (or something which would get the same job done)?

What is wrong with my Factorial Function logic?

I'm trying to get a factorial number in the JS console in Chrome.
Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.
Thank you very much for answers <3

var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};

Is my coding program malfunctioning? There should be no problems

I don't even know what the problem is. As far as I can see, there is no reason this should be happening. No matter what you input, badrating() always executes. Even negative numbers, or numbers larger than 10, or text.

rating=input("How do you rate my coding? (1-10)  ")
...
if rating=="1" or "2" or "3" or "4":
    badrating()
elif rating=="5" or "6" or "7":
    mehrating()
elif rating=="8" or "9" or "10":
    goodrating()

Confusion with scanf() or if()

I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it. After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that, but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

How do I fix the error in the first step of a circular VBA code

424 Error in the first step of my Macro. What is causing the issue?

Here is what I currently have.

Sub Macro1()
'
' Macro1 Macro 
'
' Keyboard Shortcut: Ctrl+Shift+P
'
    If Selection.Style = "Percent" Then
        Selction.Stlye = "Currency"
    ElseIf Selection.Style = "Currency" Then
        Selection.Style = "Normal"
    ElseIf Selection.Style = "Normal" Then
        Selection.Style = "Percent"
   End If
End Sub

The Elseif lines are working as intended. I can toggle from currency to normal to percent just fine and the way I intended. One I reach percent though I get a 424 error and the debugger highlights the line "Selection.Style = "Currency". I cannot figure out what is causing the error.

With If statement Page load error works, but page load success does not

When running If statement, upon page element not being present, page load fails and produces a correct error message, but when the element is present, both conditions run, success code operation as well as failure operation.

Tried await page.waitForSelector and await page.$(selector) both did not work and

await page.waitForSelector('#example').then(() => {
  console.log('SUCCESS');
}).catch(e => {
  console.log('FAIL');
});

if (await page.$('.SELECTOR') !== null)
console.log(success(await page.title() + ' SUCCESS LOAD 1 - URL Page Load'));  // console log   
// on success continue below
else
console.log(error(await page.title() + ' FAIL LOAD 1 - URL Page Load'));  // console log    
await page.screenshot({path: './screenshots/Fail_Load_1_PageDidNotLoad.jpeg'}); // screenshot
await page.evaluate(() => alert('FAIL LOAD 1 - URL Page Did Not Load'));  // pop up alert
await browser.close();  // release memory  
return process.exit(1); // exit process

How to correctly incorporate a THEN.

Why is only the If Statement Reached and not the else while the STATE.txt is acutally empty?

def checking():
    fp = open("STATE.txt", "w+")
    if "!" or "§" in fp.read():
        print(fp.read())
        read = fp.read()
        print(read)
    else:
        fp.close()
        no_entry()
    fp.close()


checking()

Output:

Process finished with exit code 0

Why is this Output Empty but my Code thinks its not?

Use files in a folder - exceptions VBA

I need to perform certain task over some excel files located in subfolders (which are inside a folder). This task must exclude all those file's names that contain letter "v".

I used file name length since the files I want to use have that length (file names with letter "V" have more that 28 characters). Here is my code.

Sub test()
Application.ScreenUpdating = False

Dim Fso As Object, objFolder As Object, objSubFolder As Object
Dim FromPath As String
Dim FileInFolder As Object

FromPath = "C:\Prueba"
Set Fso = CreateObject("Scripting.filesystemobject")
Set objFolder = Fso.GetFolder(FromPath)

For Each objSubFolder In objFolder.Subfolders

    Dim wbk As Workbook
    Dim Filename As String, File As Variant
    Path = objSubFolder.Path
    Filename = Dir(Path & "\*.xlsx")

    For Each File In objSubFolder.Files
        If Len(Filename) = 28 Then 
            Do something
            wbk.Close True
            Filename = Dir
        End If
     Next File
Next objSubFolder

ActiveWorkbook.Close savechanges:=True
    Application.DisplayAlerts = True

Application.ScreenUpdating = True
End Sub

This code works OK until it reaches a file with "V". It just stuck in that file (do nothing, which is good) and then goes to the next subfolder, ignoring all the remaining excel files.

I need some advice how to deal with this.

thx

If statement not giving the expected value

Hey all so I am trying to create a script using bash to hash each file in a folder, and check it hash value against a main file.

I already tried adding a ! within the if statement to see if that would help and I tested part of my code directly within the cygwin command line to see the direct output of the commands I am using to see if I could figure out my issue from that

Please note I do have this within a while read do loop

md5=$(md5sum "$p" | cut -c -32)

if [ $( echo $md5 | grep checkfile.xml ) ]
then
    echo "There is a match"
else 
    echo "There is no match"
    rm -v "$p"
fi

If it match do nothing If it don't match then delete the file

R not recognizing if statement in creating new column

I'm trying to create a new column based on if there is a direct character match across 3 columns of the same row. I then want to put a 1 in the new column if there is a match, or a 0 if there is no match. Here's the code I have:

   prodprov$var_match <- 0
    for(i in 1:nrow(prodprov)) {
     if(prodprov$var1[i] == prodprov$var2[i] |
     prodprov$var1[i] == prodprov$var3[i] ) {
     prodprov$var_match <- 1
     }
    }

But I get this error: Error in if (prodprov$var1[i] == prodprov$var2[i] | : missing value where TRUE/FALSE needed

Any ideas on how to fix this? All of these variables are the same data type (characters). Thanks in advance!

Difference between (int ret = 0; !ret && ret !=0)

What the difference between:

1) !ret
2) ret != 0

?

if (ret != 0 || stack[fd] == NULL || stack[fd][0] == '\0')
{
  if (!ret && *line)
    *line = NULL;
  return (ret);
}

How can I fix this batch file so that it does not error out on the IF statement?

I am pulling my hair out getting an error on this IF statement

IF %resultis%=="true" (

The batch file hits the pause right before it but right after that gets some error that goes by to fast for me to see what it is.

Here is the full script:

@Echo off
Echo "Adding Chrysaliser user to Users group and removing from Administrators"
REM net localgroup Users Chrysaliser /add
REM net localgroup Administrators Chrysaliser /delete

REM SET /P password= Enter ladmin user password: 
REM net user ladmin %password% /ADD
REM net localgroup Administrators ladmin /add

SET /P alaptop= Is this a laptop? (Y/N): 
echo %alaptop%
IF %alaptop%=="Y" (SET resultis="true")
IF %alaptop%=="y" (SET resultis="true")
pause
IF %resultis%=="true" (
    pause   
    SET /P password= Enter Lockedout user password: 
    pause
    net user Lockedout %password% /ADD
    net localgroup Users Lockedout /add
    net localgroup Administrators Chrysaliser /delete

)
Echo Getting install files
mkdir %SYSTEMDRIVE%\files
SET /P username= Enter your domain admin username: 
SET/P password= Enter your domain admin password:
net use \\server /user:%username% $password%
pause

How to create data.frame given the situations?

I am trying to create data.frame like in this picture i actually have a for loop before that df

I got the values i wanted in this second picture.

But when I tried to create data.frame, I faced error message ! what I have entered the error message.

And when W is null as well. null values

All I wanted to do is to produce this:

this

Where I think I will also be using for loops to ensure quantity ordered equals to previous demand.

please help me.. I just started learning. thank you!!

Conditional correlations using an IF statement - Python

I am trying to conduct an IF statement in order to evaluate conditional threshold correlations. The equation is as follows:

Threshold Correlation

I tried doing an IF statement, but it doesn't work. I kind of managed to do it with pandas, but it would be really a bad code.

p = np.arange(0.1,1,0.1)

r1 = log_r['AEX']; r2 = log_r['MBI10']
np.quantile(r1, p[0])

corrcoef = pd.Series()
if r1<np.quantile(r1,p[0]) & r2<np.quantile(r2,p[0]) & p[0]<0.5:
    corrcoef[0] = np.corrcoef(r1,r2) 

Alternatively, I did the following:

df = pd.DataFrame(pd.concat([log_r['AEX'],log_r['MBI10']],axis=1))
df['p0.1 AEX'] = (df['AEX'] < np.quantile(df['AEX'], p[0]))*df['AEX']    
df['p0.1 MBI10'] = (df['MBI10'] < np.quantile(df['MBI10'], p[0]))*df['MBI10']
np.corrcoef(df['p0.1 AEX'],df['p0.1 MBI10'])

This works, however it would be really messy since I would need to do this for not only p[0] but for the entire np.arange and also AEX and MBI10 are only 2/36 pairs that I have, so I am really looking for a more elegant solution to this. Thanks!

I am trying to get a correlation coefficient populated in the first row of corrcoef. I am getting the following error when I try to do the for loop:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

I can't save data input in my array, why?

I cant save my input in my array, so when i put all the answers in, and i want to se what i have in my array, all the spots are empty. This is whats happening since i put the if-statement there. If i remove the if-statement, the input will be saved in my array but it will miss the first input, so i will have 23 out of 24 answers.

Ive tried to write an else-statement aswell, but same problem with the one missing, same if i delete the whole if-statement.

    {


        if (numberOfBottles < 24)
        {
            Console.WriteLine("");
            Console.WriteLine("Write what sodas u want in the crate:"); // Skriver ut text och ber användaren skriva drycken. 

            int soda_input = 0;

            string chosenSoda = "";
            do
            {

                Console.WriteLine("1: Coca-cola"); // skriver ut alternativen för flaska
                Console.WriteLine("2: Fanta");
                Console.WriteLine("3: Pepsi");
                Console.WriteLine("4: Beer");
                Console.WriteLine("5: Redbull");
                Console.WriteLine("6: Cider");
                Console.WriteLine("7: Water");


                try
                {
                    soda_input = int.Parse(Console.ReadLine());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Just numbers, my friend");
                    continue;
                }

                if (chosenSoda == null)**
                {
                    crate[numberOfBottles] = chosenSoda; // lagrar svaren i min vektor
                } THIS IS THE IF-STATEMENT THAT IS MESSING EVERYTHING UP

                numberOfBottles++;  // för varje svar jag skriver så ökar det med 1 i vektorn hela vägen till 24

                switch (soda_input) // Skapar en meny, som skriver ut vilken dryck användaren väljer tills backen blir full.
                {

                    case 1:
                        chosenSoda = "Coca-Cola";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Coca-Cola");
                        Console.WriteLine("-------------------");
                        break;

                    case 2:
                        chosenSoda = "Fanta";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Fanta");
                        Console.WriteLine("-------------------");
                        break;

                    case 3:
                        chosenSoda = "Pepsi";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Pepsi");
                        Console.WriteLine("-------------------");
                        break;

                    case 4:
                        chosenSoda = "Öl";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Öl");
                        Console.WriteLine("-------------------");
                        break;

                    case 5:
                        chosenSoda = "Redbull";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Redbull");
                        Console.WriteLine("-------------------");
                        break;

                    case 6:
                        chosenSoda = "Cider";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Cider");
                        Console.WriteLine("-------------------");
                        break;

                    case 7:
                        chosenSoda = "Vatten";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Vatten");
                        Console.WriteLine("-------------------");
                        break;


                    default: // om man skriver siffror ovanför 1-7 så skrivs detta ut.
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Siffor mellan 1-7 min vän");
                        Console.WriteLine("-------------------");
                        break;
                }

            } while (numberOfBottles != 24);

        }
        else
            Console.WriteLine("");
        Console.WriteLine("The crate is full, choose some of the alteratives to check the crate:");
        Console.WriteLine("");


    }

EDIT: "Du valde, means U chose.. in swedish.

How to get add match?

what i did was if a team performance entry for the home team already exists, it should be updated if a team performance entry for the home team already does not exist, it should be added * same goes for the away team

and this is what i've tried

public void addMatchEntry(Match m) 
{
        boolean homeExist = false;
        boolean awayExist = false;

        for(int i = 0; i < tableEntries.size(); i++) {
            if(tableEntries.get(i).getName().equals(m.getHomeTeam()))
                homeExist = true;
            tableEntries.get(i).addMatchRecord(m);
            break;
        }
        if(homeExist == false)
            tableEntries.add(new TeamPerformance(m.getHomeTeam(), m.getHomeGoals(), m.getAwayGoals()));

        for(int i = 0; i < tableEntries.size(); i++) {
            if(tableEntries.get(i).getName().equals(m.getAwayTeam()))
                awayExist = true;
            tableEntries.get(i).addMatchRecord(m);
            break;
        }
        if(awayExist == false)
            tableEntries.add(new TeamPerformance(m.getAwayTeam(), m.getAwayGoals(), m.getHomeGoals()));

        Collections.sort(tableEntries, Collections.reverseOrder());
    }

How can I optimize this code to work even faster? Or can u suggest any alternative to replace this code with something that executes way faster?

So i categorize the sentiment scores by using our basic else if elif. but when sentences go above 400 or maybe even above 3k-4k. This starts to take a lot of time. So can you please suggest me something that does the same job but way faster?

for i in tqdm(range(len)):
    sent = dff['compound'][i]
    if(sent<=5 and sent>=3.0):
        dff['Sentiment'][i]='V.Positive'

    elif (sent<3.0 and sent>0.5):
        dff['Sentiment'][i]='Positive'

    elif (sent<0.5 and sent>-0.5):
        dff['Sentiment'][i]='Neutral'

    elif (sent<-0.5 and sent>=-3.0):
        dff['Sentiment'][i]='Negative'

    else:
        dff['Sentiment'][i]='V.Negative'

PS - I use TQDM library as a to see progress bar during execution. Any alternatives to this code ? or maybe optimize this code itself? Regardless it has to classify.

Unexpected "{" when many if's and if-else structures are mixed together?

When trying to write a function fromNdpTo10 that converts normalized double precision number (in memory) to decimal number, I get "unexpected '{' in:" error, but I should not get that error. I cared the opening and closing number of paranthesis, braces, brackets to be equal. Look:

SubstringHoldingLeading0s <- function(x) { 
  x <- formatC(x, flag="0", width=11, format="d") 
  substr(x, 1, 11) 
}
SubstringHoldingLeading0s(00100101101) # "00100101101"

from2to10 <- function(binaryNumber) {
  # Via SubstringHoldingLeading0s, the loss is prevented when converting string (holded as numeric) to character
  sapply(strsplit(SubstringHoldingLeading0s(binaryNumber), split = ""), function(x) sum(as.numeric(x) * 2^(rev(seq_along(x) - 1))))}
from2to10(00100101101) # 301

fromNdpTo10 <- function(NdpNumber) {
  NdpNumber <- as.character(NdpNumber)
  out <- list()

  # Handle special cases (0, Inf, -Inf)
  if (NdpNumber %in% c(
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0111111111110000000000000000000000000000000000000000000000000000",
    "1111111111110000000000000000000000000000000000000000000000000000")) {
    # special cases
    if (NdpNumber == "0000000000000000000000000000000000000000000000000000000000000000") { out <- "0" }
    if (NdpNumber == "0111111111110000000000000000000000000000000000000000000000000000") { out <- "Inf" }
    if (NdpNumber == "1111111111110000000000000000000000000000000000000000000000000000") { out <- "-Inf" }
  } else { # if NdpNumber not in special cases, begins

    signOfNumber <- "+" # initialization
    If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"
    } else { signOfNumber <- "-" }

    # From BiasedExponent to RealExponent (Biased Exponent=Real exponent +1023;  Real exponent=Biased Exponent-1023)
    BiasedExponent <- substr(NdpNumber, 2, 12)
    BiasedExponent <- from2to10(BiasedExponent)
    RealExponent <- BiasedExponent - 1023


    # Significand
    Significand <- substr(NdpNumber, 13, 64)
    Significand <- from2to10(Significand)

    out <- paste0(c(signOfNumber, Significand, "e", RealExponent), collapse = '')
  } # if NdpNumber not in special cases, ends

  out
}

The (unexpected for me) error is:

Error: unexpected '{' in:
"        signOfNumber <- "+" # initialization
        If (substr(NdpNumber, 1, 1) == 0) {"

The problem seems to be caused by many if's and if-else structures are mixed together. Any idea on how to solve the problem?

jeudi 30 mai 2019

Limiting the lenght of response with python requests

I'm setting up a Views that save data from an API into my database on a button click and I'm having a hard time trying to figure out how to limit the size of the requests response for product descriptions in the following way:

If the lenght of a description is higher than 2000, delete some of the letters at the end of it until it reaches the limit of 2000, but don't remove it completely from the request.

As of now, what I've been able to achieve is to completely remove the product infos if the lenght is higher than 2000 as you can see below.

My django views function:

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product
                Product.objects.get_or_create(
                    title=item['name'],
                    destination=item['city']['name'],
                    description=resp_2_data['contentListHtml'][0]['html'],
                    link=item['canonicalUrl'],
                    image=item['image']['url']
                )

    return render(request, "form.html")

But I remove way to much rows by doing this so I would like to know how can I fix this?

Please help.

Why does it always return true?

Beginner question, sorry if it's not the right place to ask Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!"); 
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

How to recode negative values in a set of variables based on if conditional statement in R?

R newbie here. I am currently trying to recode a set of variables in R, such that all negative values within them are recoded as positive values.

Please find simulated data below:

df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
                 measure1 = rnorm(11, mean = 0, sd = 1),
                 measure2 = rnorm(11, mean = 0, sd = 1),
                 measure3 = rnorm(11, mean = 0, sd = 1),
                 measure4 = rnorm(11, mean = 0, sd = 1))

This is the function I've written so far:

df[2:5] <- sapply(df[2:5], function(x) {
  if(x<0) {
  return(x*-1)
}  else {
   return(x)
    }
  })

although I recieve the following errors:

Warning messages:
1: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used

Any ideas on how to make this work?

Thanks!

How to change a range in a formula based on the loop iteration?

I have a formula in which I need to change certain cells based on the iteration.

for i = 1 to NbData
    Range(Cells(2, 10), Cells(Part1 + 1, 10)).FormulaR1C1 = _
    "=(IF(AND('Arbre Positions'!R2C2=""HQV Asy"",'Arbre Positions'!R2C3=1),VLOOKUP(RC[-8],'Static Asymmetry - 1'!C[3]:C[6],4,FALSE),IF(AND('Arbre Positions'!R2C2=""HQV Asy"",'Arbre Positions'!R2C3=2),VLOOKUP(RC[-8],'Static Asymmetry - 2'!C[3]:C[6],4,FALSE),IF(AND('Arbre Positions'!R2C2=""HQV Opp"",'Arbre Positions'!R2C3=1),VLOOKUP(RC[-8],'Static Opportunity - 1 '!C[3]:C[" & _
    "6],4,FALSE),IF(AND('Arbre Positions'!R2C2=""HQV Opp"",'Arbre Positions'!R2C3=2),VLOOKUP(RC[-8],'Static Opportunity - 2'!C[3]:C[6],4,FALSE),IF(AND('Arbre Positions'!R2C2=""HQV Sta"",'Arbre Positions'!R2C3=1),VLOOKUP(RC[-8],'Static Stability - 1'!C[3]:C[6],4,FALSE),IF(AND('Arbre Positions'!R2C2=""HQV Sta"",'Arbre Positions'!R2C3=2),VLOOKUP(RC[-8],'Static Stability - 2" & _
    "'!C[3]:C[6],4,FALSE),""Pas trouvé dans les feuilles Statics"")))))))"
Next i 

'Arbre Positions'!R2C2 and 'Arbre Positions'!R2C3 are the cells that should change for every iteration. So for the first it would be Row 2 and the next one row 3 ... as long as my loop continu.

So far I've tried to name the range 'Arbre Positions'!R2C2 and 'Arbre Positions'!R2C3 and then in the formula refere to the named range. Ex: Groupe = Sheet("Arbre Positions).Cells(1+i,2) But when the formula is written into the cell, the reference does'nt work anymore..

I also tried something like Arbre Positions'!R&i+1&C2.. But again it did'nt work...

Thank you for your help !

SharePoint 2010 List, Calculated Column, If-statement modification not working

I had a formula in a calculated column that worked just fine. I tried to revised the formula, reusing part of what worked before (in bold), but it keeps taking me to syntax error screen. The new formula is much simpler.

I've looked online, but can't find the issue.

Old formula:
=IF(AND(LEFT([EVENT TYPE],8)<>"Mtng (PM",LEFT([EVENT TYPE],8)<>"Mtng (eP",LEFT([EVENT TYPE],8)<>"Mtng (DS",LEFT([EVENT TYPE],8)<>"Mtng (#D"),"N/A for this row", IF(OR([(DC1) EDS?]="",[(DC2) Part Info]="",[(DC3) Part Innov]="",[(DC4) Other]=""),"Fill DC columns (1-4)",IF(OR(LEFT([(DC1) EDS?],1)<>"4",LEFT([(DC2) Part Info],1)<>"4",LEFT([(DC3) Part Innov],1)<>"4",LEFT([(DC4) Other],1)<>"4"),"Yes","No")))

New Formula (that throws error):
=IF(AND(LEFT([EVENT TYPE],8)<>"Mtng (PM",LEFT([EVENT TYPE],8)<>"Mtng (eP",LEFT([EVENT TYPE],8)<>"Mtng (DS",LEFT([EVENT TYPE],8)<>"Mtng (#D"), "N/A for this row", [Add to Data Collection Calendar?])

The syntax and condition in the revised formula (in bold) is straight out of the old formula. Instead of adding other If statements, I just want the formula to enter the contents of "Add to" column if condition is false.

The "Add to..." column is a choice column.
The "EVENT TYPE" column referred in condition is also a choice column. (This condition evaluates correctly in the old, longer formula).

I've tried to set the calculated column to simply "=[Add to Data Collection Calendar?]" to check if there's an issue with "Add to..." column, but that formula works and gets me the contents of "Add to..." column.

It's got to be something simple that I can't seem to find.

why doesn't my while loop work? Can someone tell me how the error message works?

How can I restart this codeblock? My idea is if you enter a character that will return an error message. What is the condition for the loop?

string r_operation;
Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
r_operation = Console.ReadLine();
-------------

while (?r_operation = Console.ReadLine())
{
Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
}


If/else in a For loop won't swap between if/else

I have an if/else inside of a for loop designed to swap between the two based on a changing user input. The input works fine, it can do either loop, the stuff I'm comparing to choose between if/else is working, it can do either path individually but not swap between the two. Basically, it should do one if it finds a letter in a list (the letter is definitely getting into the list) and if it doesn't it does the else. My CS teacher is stumped as am I.

I've ensured that the inputs are actually making it through, the comparison works when isolated but when actually attached. I've tried swapping my else/if, I've tried changing the index from != -1 to all manner of other things like > 0, < 0, and more

        public void printWord()
    {
        for (int i = 0; i < wordKey.length(); i++)
        {
            char curChar = wordKey.charAt(i);
            if(letterList.indexOf(curChar) < 0)
            {
                System.out.print("_" + " ");
            }
            else
            {
                System.out.print(curChar + " ");
                //if(win condition: every letter guessed)
            }

wordKey is just a string (in this case jazz) and letterList is an arraylist with individual letters. (its supposed to be user input which is why its an arraylist)

Either I get _ _ _ _ or j a z z (sample word) it will NOT swap between.

Why is if-function not working, using two strings?

I try to compare two strings (one coming from a database - sqlite3 - via object.get() and the other one is coming from a cell in a csv file) within an if-clause using python (PyCharm). I want to insert the data (around 13.000 listings) from the csv file into a database/table. Problem is that one "csv-column" contains values which should refer to a foreign key table (already created). I don't understand why the two strings are not equal, although they should be. Perhaps you guys can help me with this issue. Thanks, nicdreifuss

I used cmd, opend a pyhton manage.py shell, imported all models from models and imported the python file which contains the function (works fine). Then I ran the function and the problem is that the condition b11==b12 is always NOT true, although seem to be equal. Therefore I always get to else and get the return = Its not working.

I tried to import the data without the if-clause and it works just fine, but I have to make a selection of the foreign Key in the table depending on what the value is in column 3 (index[2]). So infact there will be a b2, b3, b4...

def bula():
    file = open("C:\\Users\\...\\...\\postalcodes.csv", "r")
    rows = file.readlines()

    b1 = Bundesland.objects.get(bundesland="Berlin")

    for i in range(len(rows)):
        fields = rows[i].split(";")

        b11 = str(b1.bundesland)
        b12 = str(fields[2])

        print(b11, b12)
        print(type(b11), type(b12))

        if b11 == b12:
            print("Its working")
            das = SPB(stadt=fields[0], plz=fields[1], bundesland=b1)
            das.save()

        else:
            print("Its not working")
            pass

from main.models import* #<<<--- import "SPB" model to get data from Foreign Key table from main.test import* #<<<---here is the function bula() #<<<--- run function

output is the following:

Berlin Berlin

Its not working Berlin Berlin

Its not working

expected would be output:

Berlin Berlin

Its working Berlin Berlin

Its working

Working on a Financial scraper for Income Statements

I have a couple of functions first function gets me a df of the S&P 500 list. I then have a second function that will try to scrape the data from Yahoo Finance. Then write it to a MySQL table. What happens is it breaks on a Timer that doesn't have any Income Statement data.

a lot of web searches to try and skip a ticker if there isn't any data.

'''python def SP500_Tickers(): df = pd.read_html('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies', header=0)[0] ticker = (df.Symbol) # print(ticker) return ticker def Income_Statement(): ticker = SP500_Tickers() mydb = mysql.connector.connect( host="localhost", user="invest", passwd="invest101", database="investing" )

mycursor = mydb.cursor()
today = date.today()
try:
    for tik in ticker:
        inc_state = pd.read_html('https://finance.yahoo.com/quote/' + tik + '/financials?p' + tik)

        if len(inc_state) < 1:
            pass
        else:
            # Dataframes Column 1
            IS_Date_C1 = inc_state[0][1][0]
            TotRevenue_C1 = inc_state[0][1][1]
            CostRevenue_C1 = inc_state[0][1][2]
            GrossProfit_C1 = inc_state[0][1][3]
            OE_RND_C1 = inc_state[0][1][5]
            OE_SellingAdmin_C1 = inc_state[0][1][6]
            OE_NonRecuring_C1 = inc_state[0][1][7]
            OE_Others_C1 = inc_state[0][1][8]
            OE_Total_C1 = inc_state[0][1][9]
            OperIncomeLoss_C1 = inc_state[0][1][10]
            TotOtherIncExp_C1 = inc_state[0][1][12]
            EarningBeforIntrestTax_C1 = inc_state[0][1][13]
            IntrestExpense_C1 = inc_state[0][1][14]
            IncomeB4Tax_C1 = inc_state[0][1][15]
            IncomeTaxExpense_C1 = inc_state[0][1][16]
            MinorityIntrest_C1 = inc_state[0][1][17]
            NetIncomeOps_C1 = inc_state[0][1][18]
            DiscontinuedOperations_C1 = inc_state[0][1][20]
            ExtraordinaryItems_C1 = inc_state[0][1][21]
            EffectAccountChange_C1 = inc_state[0][1][22]
            OtherItems_C1 = inc_state[0][1][23]
            NetIncome_C1 = inc_state[0][1][25]
            PreferredStock_C1 = inc_state[0][1][26]
            NetIncomeShares_C1 = inc_state[0][1][27]

            # Dataframes Column 2
            IS_Date_C2 = inc_state[0][2][0]
            TotRevenue_C2 = inc_state[0][2][1]
            CostRevenue_C2 = inc_state[0][2][2]
            GrossProfit_C2 = inc_state[0][2][3]
            OE_RND_C2 = inc_state[0][2][5]
            OE_SellingAdmin_C2 = inc_state[0][2][6]
            OE_NonRecuring_C2 = inc_state[0][2][7]
            OE_Others_C2 = inc_state[0][2][8]
            OE_Total_C2 = inc_state[0][2][9]
            OperIncomeLoss_C2 = inc_state[0][2][10]
            TotOtherIncExp_C2 = inc_state[0][2][12]
            EarningBeforIntrestTax_C2 = inc_state[0][2][13]
            IntrestExpense_C2 = inc_state[0][2][14]
            IncomeB4Tax_C2 = inc_state[0][2][15]
            IncomeTaxExpense_C2 = inc_state[0][2][16]
            MinorityIntrest_C2 = inc_state[0][2][17]
            NetIncomeOps_C2 = inc_state[0][2][18]
            DiscontinuedOperations_C2 = inc_state[0][2][20]
            ExtraordinaryItems_C2 = inc_state[0][2][21]
            EffectAccountChange_C2 = inc_state[0][2][22]
            OtherItems_C2 = inc_state[0][2][23]
            NetIncome_C2 = inc_state[0][2][25]
            PreferredStock_C2 = inc_state[0][2][26]
            NetIncomeShares_C2 = inc_state[0][2][27]

            # Dataframes Column 3
            IS_Date_C3 = inc_state[0][3][0]
            TotRevenue_C3 = inc_state[0][3][1]
            CostRevenue_C3 = inc_state[0][3][2]
            GrossProfit_C3 = inc_state[0][3][3]
            OE_RND_C3 = inc_state[0][3][5]
            OE_SellingAdmin_C3 = inc_state[0][3][6]
            OE_NonRecuring_C3 = inc_state[0][3][7]
            OE_Others_C3 = inc_state[0][3][8]
            OE_Total_C3 = inc_state[0][3][9]
            OperIncomeLoss_C3 = inc_state[0][3][10]
            TotOtherIncExp_C3 = inc_state[0][3][12]
            EarningBeforIntrestTax_C3 = inc_state[0][3][13]
            IntrestExpense_C3 = inc_state[0][3][14]
            IncomeB4Tax_C3 = inc_state[0][3][15]
            IncomeTaxExpense_C3 = inc_state[0][3][16]
            MinorityIntrest_C3 = inc_state[0][3][17]
            NetIncomeOps_C3 = inc_state[0][3][18]
            DiscontinuedOperations_C3 = inc_state[0][3][20]
            ExtraordinaryItems_C3 = inc_state[0][3][21]
            EffectAccountChange_C3 = inc_state[0][3][22]
            OtherItems_C3 = inc_state[0][3][23]
            NetIncome_C3 = inc_state[0][3][25]
            PreferredStock_C3 = inc_state[0][3][26]
            NetIncomeShares_C3 = inc_state[0][3][27]

            # Dataframes Column 4
            IS_Date_C4 = inc_state[0][4][0]
            TotRevenue_C4 = inc_state[0][4][1]
            CostRevenue_C4 = inc_state[0][4][2]
            GrossProfit_C4 = inc_state[0][4][3]
            OE_RND_C4 = inc_state[0][4][5]
            OE_SellingAdmin_C4 = inc_state[0][4][6]
            OE_NonRecuring_C4 = inc_state[0][4][7]
            OE_Others_C4 = inc_state[0][4][8]
            OE_Total_C4 = inc_state[0][4][9]
            OperIncomeLoss_C4 = inc_state[0][4][10]
            TotOtherIncExp_C4 = inc_state[0][4][12]
            EarningBeforIntrestTax_C4 = inc_state[0][4][13]
            IntrestExpense_C4 = inc_state[0][4][14]
            IncomeB4Tax_C4 = inc_state[0][4][15]
            IncomeTaxExpense_C4 = inc_state[0][4][16]
            MinorityIntrest_C4 = inc_state[0][4][17]
            NetIncomeOps_C4 = inc_state[0][4][18]
            DiscontinuedOperations_C4 = inc_state[0][4][20]
            ExtraordinaryItems_C4 = inc_state[0][4][21]
            EffectAccountChange_C4 = inc_state[0][4][22]
            OtherItems_C4 = inc_state[0][4][23]
            NetIncome_C4 = inc_state[0][4][25]
            PreferredStock_C4 = inc_state[0][4][26]
            NetIncomeShares_C4 = inc_state[0][4][27]

            print(tik)
            print(len(inc_state))
            print('Colunm 1')
            print(IS_Date_C1, TotRevenue_C1, CostRevenue_C1, GrossProfit_C1, OE_RND_C1, OE_SellingAdmin_C1, OE_NonRecuring_C1, OE_Others_C1, OE_Total_C1,
                  OperIncomeLoss_C1, TotOtherIncExp_C1, EarningBeforIntrestTax_C1, IntrestExpense_C1, IncomeB4Tax_C1, IncomeTaxExpense_C1,
                  MinorityIntrest_C1, NetIncomeOps_C1, DiscontinuedOperations_C1, ExtraordinaryItems_C1, EffectAccountChange_C1, OtherItems_C1,
                  NetIncome_C1, PreferredStock_C1, NetIncomeShares_C1)

            # print('Colunm 2')
            #
            # print(IS_Date_C2, TotRevenue_C2, CostRevenue_C2, GrossProfit_C2, OE_RND_C2, OE_SellingAdmin_C2, OE_NonRecuring_C2,
            #       OE_Others_C2, OE_Total_C2,
            #       OperIncomeLoss_C2, TotOtherIncExp_C2, EarningBeforIntrestTax_C2, IntrestExpense_C2, IncomeB4Tax_C2,
            #       IncomeTaxExpense_C2,
            #       MinorityIntrest_C2, NetIncomeOps_C2, DiscontinuedOperations_C2, ExtraordinaryItems_C2, EffectAccountChange_C2,
            #       OtherItems_C2,
            #       NetIncome_C2, PreferredStock_C2, NetIncomeShares_C2)

            # print('Colunm 3')
            #
            # print(IS_Date_C3, TotRevenue_C3, CostRevenue_C3, GrossProfit_C3, OE_RND_C3, OE_SellingAdmin_C3, OE_NonRecuring_C3,
            #       OE_Others_C3, OE_Total_C3,
            #       OperIncomeLoss_C3, TotOtherIncExp_C3, EarningBeforIntrestTax_C3, IntrestExpense_C3, IncomeB4Tax_C3,
            #       IncomeTaxExpense_C3,
            #       MinorityIntrest_C3, NetIncomeOps_C3, DiscontinuedOperations_C3, ExtraordinaryItems_C3, EffectAccountChange_C3,
            #       OtherItems_C3,
            #       NetIncome_C3, PreferredStock_C3, NetIncomeShares_C3)
            # print('Colunm 4')
            # print(IS_Date_C4, TotRevenue_C4, CostRevenue_C4, GrossProfit_C4, OE_RND_C4, OE_SellingAdmin_C4, OE_NonRecuring_C4,
            #       OE_Others_C4, OE_Total_C4,
            #       OperIncomeLoss_C4, TotOtherIncExp_C4, EarningBeforIntrestTax_C4, IntrestExpense_C4, IncomeB4Tax_C4,
            #       IncomeTaxExpense_C4,
            #       MinorityIntrest_C4, NetIncomeOps_C4, DiscontinuedOperations_C4, ExtraordinaryItems_C4, EffectAccountChange_C4,
            #       OtherItems_C4,
            #       NetIncome_C4, PreferredStock_C4, NetIncomeShares_C4)


            # mycursor.execute(
            #     "INSERT INTO IncomeStatement (Ticker, IS_Date, TotRevenue, CostRevenue, GrossProfit, OE_RND, OE_SellingAdmin, OE_NonRecuring, OE_Others, OE_Total, OperIncomeLoss, TotOtherIncExp, EarningBeforIntrestTax, IntrestExpense, IncomeB4Tax, IncomeTaxExpense, MinorityIntrest, NetIncomeOps, DiscontinuedOperations, ExtraordinaryItems, EffectAccountChange, OtherItems, NetIncome, PreferredStock, NetIncomeShares, Today ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (
            #     tik, IS_Date_C1, TotRevenue_C1, CostRevenue_C1, GrossProfit_C1, OE_RND_C1, OE_SellingAdmin_C1, OE_NonRecuring_C1, OE_Others_C1, OE_Total_C1, OperIncomeLoss_C1, TotOtherIncExp_C1, EarningBeforIntrestTax_C1, IntrestExpense_C1, IncomeB4Tax_C1, IncomeTaxExpense_C1, MinorityIntrest_C1, NetIncomeOps_C1, DiscontinuedOperations_C1, ExtraordinaryItems_C1, EffectAccountChange_C1, OtherItems_C1, NetIncome_C1, PreferredStock_C1, NetIncomeShares_C1, today))
            # mycursor.execute(
            #     "INSERT INTO IncomeStatement (Ticker, IS_Date, TotRevenue, CostRevenue, GrossProfit, OE_RND, OE_SellingAdmin, OE_NonRecuring, OE_Others, OE_Total, OperIncomeLoss, TotOtherIncExp, EarningBeforIntrestTax, IntrestExpense, IncomeB4Tax, IncomeTaxExpense, MinorityIntrest, NetIncomeOps, DiscontinuedOperations, ExtraordinaryItems, EffectAccountChange, OtherItems, NetIncome, PreferredStock, NetIncomeShares, Today ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (
            #         tik, IS_Date_C2, TotRevenue_C2, CostRevenue_C2, GrossProfit_C2, OE_RND_C2, OE_SellingAdmin_C2,
            #         OE_NonRecuring_C2, OE_Others_C2, OE_Total_C2, OperIncomeLoss_C2, TotOtherIncExp_C2,
            #         EarningBeforIntrestTax_C2, IntrestExpense_C2, IncomeB4Tax_C2, IncomeTaxExpense_C2, MinorityIntrest_C2,
            #         NetIncomeOps_C2, DiscontinuedOperations_C2, ExtraordinaryItems_C2, EffectAccountChange_C2, OtherItems_C2,
            #         NetIncome_C2, PreferredStock_C2, NetIncomeShares_C2, today))
            # mycursor.execute(
            #     "INSERT INTO IncomeStatement (Ticker, IS_Date, TotRevenue, CostRevenue, GrossProfit, OE_RND, OE_SellingAdmin, OE_NonRecuring, OE_Others, OE_Total, OperIncomeLoss, TotOtherIncExp, EarningBeforIntrestTax, IntrestExpense, IncomeB4Tax, IncomeTaxExpense, MinorityIntrest, NetIncomeOps, DiscontinuedOperations, ExtraordinaryItems, EffectAccountChange, OtherItems, NetIncome, PreferredStock, NetIncomeShares, Today ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (
            #         tik, IS_Date_C3, TotRevenue_C3, CostRevenue_C3, GrossProfit_C3, OE_RND_C3, OE_SellingAdmin_C3,
            #         OE_NonRecuring_C3, OE_Others_C3, OE_Total_C3, OperIncomeLoss_C3, TotOtherIncExp_C3,
            #         EarningBeforIntrestTax_C3, IntrestExpense_C3, IncomeB4Tax_C3, IncomeTaxExpense_C3, MinorityIntrest_C3,
            #         NetIncomeOps_C3, DiscontinuedOperations_C3, ExtraordinaryItems_C3, EffectAccountChange_C3, OtherItems_C3,
            #         NetIncome_C3, PreferredStock_C3, NetIncomeShares_C3, today))
            # mycursor.execute(
            #     "INSERT INTO IncomeStatement (Ticker, IS_Date, TotRevenue, CostRevenue, GrossProfit, OE_RND, OE_SellingAdmin, OE_NonRecuring, OE_Others, OE_Total, OperIncomeLoss, TotOtherIncExp, EarningBeforIntrestTax, IntrestExpense, IncomeB4Tax, IncomeTaxExpense, MinorityIntrest, NetIncomeOps, DiscontinuedOperations, ExtraordinaryItems, EffectAccountChange, OtherItems, NetIncome, PreferredStock, NetIncomeShares, Today ) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (
            #         tik, IS_Date_C4, TotRevenue_C4, CostRevenue_C4, GrossProfit_C4, OE_RND_C4, OE_SellingAdmin_C4,
            #         OE_NonRecuring_C4, OE_Others_C4, OE_Total_C4, OperIncomeLoss_C4, TotOtherIncExp_C4,
            #         EarningBeforIntrestTax_C4, IntrestExpense_C4, IncomeB4Tax_C4, IncomeTaxExpense_C4, MinorityIntrest_C4,
            #         NetIncomeOps_C4, DiscontinuedOperations_C4, ExtraordinaryItems_C4, EffectAccountChange_C4, OtherItems_C4,
            #         NetIncome_C4, PreferredStock_C4, NetIncomeShares_C4, today))
            #
            # mydb.commit()
except KeyboardInterrupt:
    pass

Income_Statement()

'''

I am trying to get the if statement to by pass the bad ticker and go on its merry way. Sorry code is ugly I am noob.

Is if statement in for loop faster than one by one if statements in Java?

I wonder that if I use a HashMap to collect the conditions and loop each one in one if statement can I reach higher performance rather than to write one by one if - else if statement?

In my opinion, one-by-one if-else, if statements may be faster because in for loop runs one more condition in each loop like, does the counter reach the target number? So actually each if statement, it runs 2 if statements. Of course inside of the statements different but if we talk about just statement performance, I think one-by-one type would be better?

How can I restart my following codeblock?

I would like to restart my codeblock after error message. How can I do this? Please give me an example.

Console.Write("\tBitte geben Sie ihre erste Zahl ein: ");
if (!double.TryParse(Console.ReadLine(), out zahl1))
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen an!");

Excel IF statement to find specific actions against a record

The Excel consists of two columns 'Person Number' and 'Action Code'. There can be multiple occurrences of a 'Person Number' for first occurrence the 'Action Code' needs to be 'HIRE' rest occurrences needs to be 'ASG_CHANGE'. Brief Summary Image

Used below code to get the 'Expected Action Code' but got'Invalid Code Output' instead.

=IF($A2:$A3=$A3,"HIRE","ASG_CHANGE")

How to efficiently check whether a vector of numbers is in an interval defined by a data frame

I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1 in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}

Thanks!

How to compare request.get result in if else statement

I am making a new script which will take as input list of Ethereum private keys and produce the corresponding addresses with balances, and save the balance in the file if it's found along with private key and the address.

Now, I'm almost certain that my problem lies within the conditional, but cannot figure it out.

Script steps: 1. Take file of private keys as input (-i flag) 2. Convert them to public addresses/decode them 3. Trigger an API call to Etherscan for the information about the address 4. If the json()["result"] > 0 in API call, write it in output file (-o flag), else print out and sleep for 1 second

enter image description here

Can anyone give a heads up on where I am making mistake?

My code:

#!/usr/bin/python
import sys, os, argparse, requests, ethereum, binascii, time
from multiprocessing import Pool

def scanether(balance):
    try:
        # Convert private key to address and print the result
        eth_address = ethereum.utils.privtoaddr(INPUTFILE)
        eth_address_hex = binascii.hexlify(eth_address).decode("utf-8")
        eth_balance = requests.get("https://api.etherscan.io/api?module=account&action=balance&address=0x" + eth_address_hex + "&tag=latest&apikey=APIKEYHERE").json()["result"]

        # Check if the result is > 0
        if ('result' != 0) in r.eth_balance: 
            print("[*] Address with balance found: " + eth_address_hex + priv)
            # Write match to OUTPUTFILE
            fHandle = open(OUTPUTFILE,'a')
            fHandle.write(eth_address_hex + privkey + "\n")
            fHandle.close()
        else:
            print("balance: {} address: 0x{} privkey: {}".format(float(eth_balance)/100000000, eth_address_hex, priv))
            time.sleep(1)


    except Exception as e:
        return

if __name__ == '__main__':
    print("""
# Finding the Ethereum address with balance
        """)
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--inputfile', default='input.txt', help='input file')
    parser.add_argument('-o', '--outputfile', default='output.txt', help='output file')
    parser.add_argument('-t', '--threads', default=200, help='threads')
    args = parser.parse_args()

    INPUTFILE=args.inputfile
    OUTPUTFILE=args.outputfile
    MAXPROCESSES=int(args.threads)

    try:
        addresses = open(INPUTFILE, "r").readlines()
    except FileNotFoundError as e:
        print(e)
        exit(e.errno)

    print("Scan in progress...")
    pool = Pool(processes=MAXPROCESSES)
    pool.map(scanether, addresses)
    print("Scan finished.")

Conditional If Statement applied to dataframe

I am trying to iterate in a pythonic way (i.e. without a loop) through a dataframe in order to create a new columns based on whether the condition was met. In particular, given a dataframe of daily returns, I would like to create a new column that tells me whether either an upper limit or lower limit was crossed (limit is symmetric, but stock specific, so each row might have a different limit, called std in the df below) , something like this:

import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df1['date'])
df=df.set_index(['date','ticker'], drop=True)  

That should be transformed, such that I obtain a new column which contains the respective day's return, if the upper/lower threshold was crossed, if it wasn't crossed, it should just contain the last day's return (so returns2).

dict2 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df2 = pd.DataFrame(dict2)
df2['date']      = pd.to_datetime(df2['date'])
df2=df2.set_index(['date','ticker'], drop=False)   

I am trying to keep this flexible (so it works for more than just 2 columns with returns) and efficient (so that it works on very large dfs.

Can anyone suggest an approach?

mercredi 29 mai 2019

If statement variable assignment in batch file ignored

I am new to batch file coding and am trying to write a simple If-Else statement.

I have tried to use delayedexpansion as suggested in other questions but still don't seem to get the right value

@echo off
setlocal ENABLEDELAYEDEXPANSION

SET VAR=portrait
IF %VAR% == portrait do (
    SET /a height=1920;
    set /a width=1080;
) else do(
    set /a height=1080;
    set /a width=1920;
)

echo %height%

The code above gives the output as 1080, while I am expecting 1920 based on the logic I wrote. Can someone please help me understand?

If condition is getting skipped even if the condition is true

I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met

x=raw_input().split(" ")  
c=[]  
for a in x:  
    b=1  
    if a<0:  
        print "Please enter a number greater than or equal to 0"  
    else:      
        if(a==1 or a==0 ):  
            print "1"  
    for i in range(1,int(a)+1):  
            b=b*i  
    c.append(str(b))  

print ",".join(c)

the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.

Problem with nested ifelse function to subtract specific dates from a date vector

I have the following problem. I have two vectors on with characters (c.vec), one with dates(d.vec). I want to calculate a certain time interval if the char vector has a certain attribute. As the if-statement should check each row, I read that I need to use nested ifelse statements (as for certain months in the date vector, a specific date should be used to calculate the time interval). My ifelse statement should calculate as follows:

1) If the c.vec == 'Tree' and the month of d.vec is after October – then calculate 15.07.YearAfterd.vec - date of d.vec and overwrite another vector called d.diff (this vector already has numeric values stored in it) with the outcome

2) If the c.vec == 'Tree' and the month of d.vec is after May– then calculate 15.03.YearAfterd.vec - date of d.vec and overwrite d.diff with the outcome

3) If the c.vec == 'Tree' and the month of d.vec before May – then calculate 15.07.YearOfd.vec- date of d.vec and overwrite d.diff with the outcome

4) If c.vec =! 'Tree' then just use the value already stored in d.diff and do not overwrite anything

Here is what I tried (however, it just returns NAs and does not even overwrite the d.diff entries at all. I just prints the NAs in the console) - with an example:

c.vec <- c('tree','tree','tree','flower','flower')
d.diff <- c(150,80,97,52,74)
d.vec <- as.Date(c('2016-11-24','2017-06-14','2016-02-21','2017-05-07','2016-04-18'))

ifelse(c.vec=='tree',
       # Check if date is after October. The as.Date() part should return 15.07. of the year after d.vec
       ifelse(month(d.vec)>10,d.diff <- as.numeric(as.Date(capture.output(cat(year(d.vec)+1,'-07-15')),'%Y -%m-%d')-d.vec),
              # Check if date is after May
              ifelse(month(d.vec)>5,d.diff <- as.numeric(as.Date(capture.output(cat(year(d.vec)+1,'-02-15')),'%Y -%m-%d')-d.vec),
                     # Else, use 15.07. of the year of d.vec to calculate the time difference
                     d.diff <- as.Date(capture.output(cat(year(d.vec),'-07-15')),'%Y -%m-%d')-d.vec)),
       # if c.vec =! tree just use the existing values in d.diff
       d.diff <- d.diff)

How do I need to adjust it that I get the specific time differences in the d.diff vector? I also tried to use store the vectors in a data frame and then use df.name$... to use the entries of the vectors but it just returns NAs as well. Thanks for the help!

Create a binary column based on one condition across multiple columns [duplicate]

This question already has an answer here:

I have exported Survey Monkey data which, for each question, produces a separate column for each option and fills it with a character value if the respondent selected this response, otherwise it's NA (see df below).

I would like to create a new binary column based on the same condition across multiple columns.

diag <- structure(list(diag_stress_fracture = c(NA, "Stress 
fracture(s)", 
NA, NA, NA, NA), diag_disordered_eating = c(NA_character_, 
NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_), 
diag_asthma = c(NA, "Asthma", NA, NA, NA, NA), 
diag_low_bone_density = c(NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_, 
NA_character_), diag_acl_rupture = c(NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_
), diag_concussion = c(NA, "Concussion", NA, NA, NA, NA), 
diag_depression_or_anxiety = c(NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_
), diag_haemochromatosis = c(NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_
), diag_hypothyroidism = c(NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_
), diag_oligomenorrhea_or_amenorrhoea = c(NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_, 
NA_character_)), .Names = c("diag_stress_fracture", 
"diag_disordered_eating", 
"diag_asthma", "diag_low_bone_density", "diag_acl_rupture", 
"diag_concussion", 
"diag_depression_or_anxiety", "diag_haemochromatosis", 
"diag_hypothyroidism", 
"diag_oligomenorrhea_or_amenorrhoea"), row.names = c(NA, 6L), class 
= "data.frame")`

Essentially I want to know if a participant has had a diagnosis, regardless of what it is. I can get my desired outcome using the following code (where ... are the above columns of interest but I have truncated for this example):

diag <- diag %>%
mutate(diag.yn = ifelse(!is.na(diag_stress_fracture) |
!is.na(diag_disordered_eating) | 
!is.na(diag_asthma) | ... , 1, 0)

However this is obviously very clunky and time consuming given that I would like to do this for multiple questions. Is there a way of doing this using column positions e.g. these are 38:47 in my large data set?

IF statement using cell formatted value

In Google Sheets, how can you use the IF statement using the output of a cell's formatted value?

I've created a Google Sheet with a date value in B1. The cell is formatted using the date format. B1 is then copied across to the right so that it increments the days of the month.

https://i.imgur.com/KzhwHUw.png

https://i.imgur.com/d8S4Cco.png

In B2, based on the B1 date, I want to display the day value (ie Thu, Fri, Sat etc.). Similarly to the first step, I set the date format under Format > Number > More formats > More date and time formats, then from the select box, choose the day and I want to display the "Tue" date format.

https://imgur.com/4Owz7jl.png

Then in B8, I want to display an amount of 30 every Thursday, otherwise, show 0.

https://i.imgur.com/s5mTcct.png

This is where it doesn't work. Does it seem like the rendered cell's value can't be used in an IF statement? My desired output is that every the value in row 2 is a 'Thu' display 30.


As a side note, I jumped on Google support and asked this same question. Even though they are technical support, I thought I'd give them a try anyway, after all, I am paying for GSuite.

This is the formula they came back to me with: =if(B2=B1, "30", "0").

Of course, this formula will work in B8, because B2 is equal to B1 in the actual cell value, it doesn't take into account the formatted cell value. This formula will fail the output we need as it will always display 30 instead of only then row 2 is 'Thu'.

So essentially, is there a function in Google Sheets for a rendered cell value? Or another solution around this?

Note: I do NOT want to use any scripting to get this to work.

How to nest a conditional 3 quote strings inside another 3 quote strings in python?

I am trying to a paragraph of lines using 3 quote strings where some group of lines in the paragraph are to be included on a if condition. I am using {} brackets for those conditional lines and since each of them have to be on the next line, I have to use 3 quote strings for them. So its a nested 3 quote string with a condition

For example, I have

write_line_3nd4 = True
paragraph = f'''
this is line one
x = 12 #line two
{f'''
line 3,4 #this is line 3
x=34 #this is line 4''' if write_line_3nd4 else ''}
'''

It gives me an error as such:

File "<ipython-input-36-4bcb98c8ebe0>", line 6
line 3,4 #this is line 3
     ^
SyntaxError: invalid syntax

How do use conditional multi-line strings inside multi-line strings?

Replace values in one vector based on values greater than x in separate vector of dataframe

I have a dataframe where values above certain level in one vector should be changed in next vector.

I have tried if function, which gives back 'NA'.

if (mydata$duration >15) {
mydata$code==3
}

Here's some code of what the end function should look like labelled 'recode'

duration<-c(1,14,5,17,9,10,14,16,2,8,3,18)
code<-c(1,2,1,2,1,2,1,2,1,2,1,2)
mydata<-data_frame(code,duration)
recode<-c(1,2,1,3,1,2,1,3,1,2,1,3)
mydata<-data_frame(recode,duration)

If statement does not work when comparing to integers

I'am trying to make a python sort-of calculator that allows for any amount of digits to be entered and it checks if every second "word" is an operator, but when comparing the length of the sum and the index of the "word" it is currently checking to see if it should print the output, but it does not even though the 2 integers are the same.

operators = ["+", "-", "/", "*"]

def doSum(sum):
    split = sum.split()
    target = len(split)
    if split[1] in operators and "=" not in "".join(split):
        for WORD in split:
            if split.index(WORD) % 2 != 0:
                if WORD in operators:
                    if int(split.index(WORD)) == int(target):
                        print(eval("".join(split)))
                    else:
                        print(target)
                        print(len(split))
                        print("-=-=-=-=-=-=-=-=-=-=-=-")

doSum("1 + 2")
doSum("3 + 3")
doSum("8 - 4")
doSum("1 + 3 + 3 - 1")

The problem lines are lines 10 - 15. I expected the output to be: 3 6 4 6 But I got:

3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
3
3
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-
7
7 
-=-=-=-=-=-=-=-=-=-=-=-
7
7
-=-=-=-=-=-=-=-=-=-=-=-

from the "else block" I use for debugging

Is there a better other than writting so many if else to change button display condition in javascript?

After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?

if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
    ) {
      this.pullDisplay = true;
    } else {
      this.pullDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.cancelDisplay = true;
    } else {
      this.cancelDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.saveDisplay = true;
    } else {
      this.saveDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.reviseDisplay = true;
    } else {
      this.reviseDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.sendDisplay = true;
    } else {
      this.sendDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
    ) {
      this.approvalDisplay = true;
    } else {
      this.approvalDisplay = false;
    };

How to search list elements in a data frame?

I have a list dates with dates as string objects with all dates from 2003-01-01 to 2017-06-30:

['2003-01-01', '2003-01-02', '2003-01-03', '2003-01-04', '2003-01-05', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-11', '2003-01-12', '2003-01-13', '2003-01-14', '2003-01-15', '2003-01-16', '2003-01-17', '2003-01-18', '2003-01-19', '2003-01-20', '2003-01-21',...]

And I have a dataframe with date time objects:

0       2013-01-09 09:07:49
1       2013-01-09 09:16:25
2       2013-01-09 11:14:28
3       2013-01-09 11:25:51
4       2013-01-09 11:25:51
5       2013-01-09 11:33:35
6       2013-01-09 11:35:31
7       2013-01-09 18:11:03
8       2013-03-13 21:04:58
9       2013-03-13 21:05:57
10      2013-03-15 14:07:27
11      2013-03-26 21:53:35
12      2013-03-26 22:19:20
13      2013-04-09 14:21:48
14      2013-04-09 14:22:29
15      2013-04-09 14:22:45
16      2013-04-22 12:10:47
...

Then I want to check if the dates in the list dates exist in the dataframe. So I want to do something like this:

df = pd.read_csv("blabla.csv")
df['time'] = pd.to_datetime(df['time'])
for j in dates:
  if j in df['time']:
       return(yes)

How can I compare a string object with a datetime object in a dataframe?

Powershell If Statement Failure

I need another set of eyes because I'm certain this is simple but it's kicking my butt right now. And I realize this is the most basic of basics, so I'm almost embarrassed asking... But I need another set of eyes... I'm writing a script to install Windows roles/features on both Server 2008 and Server 2012 machines. I know that 2008 uses "Add-WindowsFeature" whereas 2012 uses "Install-WindowsFeature." So my goal is to look at the OS and if it's 2008 create a variable called $Install with a value of "Add-WindowsFeature" and if it's not 2008 give it the value of "Install-WindowsFeature." This is what I have now:

$OS = (get-wmiobject win32_operatingsystem).name

if($OS -like '2008') {$Install = 'Add-WindowsFeature'} 

    else {$Install = 'Install-WindowsFeature'}

Currently, when I call up the $OS variable I get a returned value of:

Microsoft Windows Server 2008 R2 Standard |C:\Windows|\Device\Harddisk0\Partition2

But when I call up the $Install variable I get a returned value of:

Install-WindowsFeature

I've also tried -contains instead of -like but I get the same result. I've also tried eliminating the spaces before the { brackets, but still no change. What am I doing wrong?

How to create a function with the input is if-statement of global variable and local variable in while loop?

I want to make a function for while loop in the example below with the changing in if-statement of global variables (fil_...) and local variable in while loop (rs_list[i]) but I can't get the result as expecting.

I have a result list like that: rs_list = [1, 2, 1, 3, 2, 4, 'a', 'b', 'a', 'c', 'd', 'b', 'a'] the rs_list will be filtered based on the conditions changing in steps:

Step01: code doing sth
fil_list_01 = [1, 2, 4, 'a', 'b', 'd']
# Use while loop to filter rs_list
i = 0
while i < len(rs_list):
    prd = rs_list[i]
    if prd not in fil_list_01:
        rs_list.pop(i)
    else:
        i = i + 1
Step02: code doing sth
fil_list_02 = [1, 2, 4]
# Use while loop to filter numbers in rs_list
i = 0
while i < len(rs_list):
    prd = rs_list[i]
    if prd not in fil_list_02:
        rs_list.pop(i)
    else:
        i = i + 1
Step03: code doing sth
fil_03 = 1.5
# Use while loop to filter numbers > fil_03 in rs_list
i = 0
while i < len(rs_list):
    prd = rs_list[i]
    if prd < fil_03:
        rs_list.pop(i)
    else:
        i = i + 1
rs_list --> [2, 4]

So I create a function for while loop like that:

def filter_while_loop(input_list, input_condition):
i = 0
output_list = input_list
while i < len(input_list):
    prd = input_list[i]
    if exec(input_condition):
        output_list.pop(i)
    else:
        i = i + 1
return output_list

Then using it in the code above like that:

Step01: code doing sth
fil_list_01 = [1, 2, 4, 'a', 'b', 'd']
# Use function to filter rs_list
rs_list = filter_while_loop(rs_list, "prd not in fil_list_01")
rs_list --> [1, 2, 1, 3, 2, 4, 'a', 'b', 'a', 'c', 'd', 'b', 'a']

But there are not any effect on the rs_list. How could I use a function for filtering while loop in this example with the changing in if-statement with global variable (eg: fil_list_01) and local variable in while loop (prd = input_list[i])?

Please help to optimize a lot of "if statements"

I want get rid of if statements. Maybe will be better to use a lot of classes. And use needed class that can handle needed action.

Or it will be fabric pattern. Or it ok to use 30+ similar if statements.

I've tryed to make a Dictionary with string and object class. But not worked. (or my skills not good enought)

        if (node[DATA_CONNECTION_ELEMENT] != null)
        {               
            return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
        }
        else if (node[FORM_PARAMETER_ELEMENT] != null)
        {
            return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
        }

        // + 30 more ifs


        else if (node[CLIPBOARD_ELEMENT] != null)
        {
            return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
        }
        else
        {
            return new ConstantDataBinding(form, node);
        }

Want to look something like

        foreach (var item in allThatShareSomeInterface)
        {
            if (item.CanHandle(node.Atributes[0]))
            {
                return item.neededObject();
            }
        }

How do I sequentially fill a big range of cells in Google Sheets?

I want to fill an entire column of Google Sheets with numbers from -4000 to 4000, but I can't find an easy way of doing it.

I'm aware of the auto-fill solution of google sheets that allows you to write two sequential numbers and then select them and use the drag-and-drop approach, but for big numbers, this is not a feasible approach.

Is there a way of automating it using some formula or some built-in option?

Nested if-conditions vs multiple separated if-conditions with return statement in each one

What is the most professional code-style in the below two functions ?
And what if the function become more complex & larger such as to have 20 checks ?
Note: i need to do some stuff after each check, so i can't concatenate all in one if-statement like:
if (vehicle.isBus) && (vehicle.numberOfWheels == 6) && (vehicle.motorVersion == 2019)

//first alternative
public bool validate(Vehicle vehicle)
{
    if(vehicle.isBus)
    {
        //do some stuff here related to vehicle.isBus
        if (vehicle.numberOfWheels == 6)
        {
            //do some stuff here related to vehicle.numberOfWheels
            if (vehicle.motorVersion == 2019)
            {
                //do some stuff here related to vehicle.motorVersion
                return true;
            }
        }
    }
    return false;
}

//second alternative
public bool validate(Vehicle vehicle)
{
    if (!vehicle.isBus)
    {
        return false;
    }
    //do some stuff here related to vehicle.isBus

    if (vehicle.numberOfWheels != 6)
    {
        return false;
    }
    //do some stuff here related to vehicle.numberOfWheels

    if (vehicle.motorVersion != 2019)
    {
        return false;
    }
    //do some stuff here related to vehicle.motorVersion

    return true;
}

If statement within look error 13 - type error

I have boolean or #N/A values in column DO. If a True boolean is within the DO column range, I wish for the corresponding cell in range r3FTop to be changed to the colour as per my code. My thinking is that DO2 cell corresponds to X5, and the D03 to X2.

When i run this code with Set rRng = Worksheets("mapOut").Range("DO2:DO2") and Set r3FTop = Worksheets("mapOut").Range("X5") the code works fine (cells turn to orange when the cell value at DO2 is True and don't when the cell value is False or #N/A). However upon adding the next cell in each range (DO3 and X2) I keep getting the type 13 error.

I've tried the bottom on the first row and it colours the cell at X5 perfectly. I run into problems when I try and add a second cell to the range.

For ease of use I have opted to batch the cell references I wish to colour in a group as they appear on screen.

Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range

' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")


Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
        r3FTop.Interior.Color = RGB(237, 125, 49)

    Else
        GoTo Continue

    End If

Continue:

Next rCell

End Sub

My actual column range is DO2:DO90 and I have corresponding cell values for r3FTop variable too. I wish for the code to go though and disregard and #N/A or False values and only change corresponding cell colors when a True boolean is found.

I've tried rewriting the above code so that the True boolean is dealt with first as so with dealing with blanks (using application.worksheet.isna(rRng).

Any pointers would be greatly appreciated.

mardi 28 mai 2019

return values from an elif statement

I am attempting to back test a stock market trading strategy. I would like to buy 100 shares every time cf_net > 0 and close the position when cf_net < 0. This cycle is every 5 min.

I have a pandas data frame called cf_slice which contains ('1. open', cf_now, cf_then, cf_net, long). The data set is 100 length. When cf_net > 0 I would like to add 100 shares to a new data frame called 'current_pos'. Also, I would like to calculate the ('1. open' x current_pos) and insert into a data frame called 'value'. Ideally I would like to count up 100 shares for every true and close the entire position when false. I would like to set this up on the short side but if you can help me with the long side, I can manage the short side.

Open = 282.91, 282.95, 282.87, 282.90, 283.02

cf_net = 1047, -1894, -2214, 3122, 3649

long = True, False, False, True, True

I have tried numpy arrays and iterating through pandas using a for loop. I am able to isolate the long/short data but what I am struggling with is adding to and closing the entire position.

cf_slice = (data.loc[:, ['1. open', 'cf_now', 'cf_then', 'cf_net', 'long']])

current_pos = 0
shares = 0
long_cost = 0
long_credit = 0
short_cost = 0
short_credit = 0
net_profit = 0

for cf in cf_slice.cf_net:
    # open long
    if cf > 0 and current_pos >= 0:
        current_pos += 1
        shares += 100
    # close long
    elif cf < 0 and current_pos > 0:
        current_pos = 0
        shares = 0
    # open short
    elif cf < 0 and current_pos <= 0:
        current_pos -= 1
        shares -= 100
    # close short
    elif cf > 0 and current_pos < 0:
        current_pos = 0
        shares = 0
    print(cf, current_pos, shares)

This code appears to count up and down correctly for the shares and current position. However, how do I incorporate calculating '1. open' x current position?

I need to know the value of the position as the position increases and ultimately closes.data

How to shift value with inside nested ifelse statement?

my code

re$p_RID <- ifelse((re$group_UID & re$Amount_type=='Draw'),
                           shift(re$id), 'NA')

my data frame look like this after I run the code:

id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        322
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111

I would like to use the id in first occurrence on amount_type of Non value for each p_RID column.(within the same group_UID, if there are many multiple occurrence of Non value, then treat each of them as the first occurrence) The result should look like this:

id  user_id  Amount_type group_UID p_RID
30    11        Non        1        NA
31    11        Draw       1        30
54    5         Non        2        NA
322   5         Draw       2        54
21    5         Draw       2        54 <- this is where I don't know how to edit
13    5         Non        2        NA
2445  5         Draw       2        13
111   44        Non        3        NA
287   44        Draw       3        111

Using R, if values in either variable A or B are 'NA', to then use values in variables C and D instead?

I am trying to calculate the mean of two variables and outputting it as a new variable. For example:

data$Average <- (data$Visit1 + data$Visit2) / 2

However, there are NA values for both 'Visit 1' and 'Visit 2' variables across the dataset.

How can I write some code such that I am able to identify if NA values exist in either Visit 1 or 2, then I would use the corresponding row's values but for 'Visit 3' and 'Visit 4' instead, to calculate the average?

Many thanks!

How would I write a function which uses multiple if statements, where each statement would modify the word one after the other?

I'm trying to write a function which would modify a tagged word depending on the tags present in the word, so basically a lemmatizer, but for words in Swedish.

For example if the word was tagged with A it would remove ending X from the word, and if the word also was tagged with B it would remove ending Y from the word etc. In total there are seven different endings that might be present in the word depending on the tag combinations and which I in that case want to remove.

What I've tried so far is to use several if statements after one another which would modify the word if it was tagged with one tag combination and then check if it was tagged with another tag combination and then modify it based on that and so on.

if tag1 == 'A':                                                   
    word = word.rstrip('x')
if tag2 == 'B' and tag3 == 'C' and tag4 == 'D':
    word = word.rstrip('y')
if tag3 == 'B' and tag4 == 'D':
    word = word.rstrip('z')

I'm having problems with understanding how I should phrase the if statements so that they would each check for a tag combination, modify the word if the statement is true and then pass the modified word along to the next statement. How would I do this?

Using !! in an if statement ( JavaScript Study; closures)

This was posted by another student and I would love to know what the double exclamations are doing in the if statement? I just can't get my head wrapped around this? Maybe I'm overthinking this too much, but can someone please explain what is happening here. Is this just badly written code? The code runs fine, but they have a job argument that's never called and when I use if (!name) The code starts undefined and then keeps on executing the 'Peasant' string.. my head is going to explode.

function interviewQuestion(job,question) {
    return function(name) {
        if (!!name) {
                console.log(name + question);
            } else {
                console.log('Peasant' + question);
            }
        }
    };


var interviewQuestionTyrant = interviewQuestion('Tyrant',', are you born of blood and fire?');
var interviewQuestionHand = interviewQuestion('Hand', ', can you outscheme the Lannisters?');
var interviewQuestionNightswatch = interviewQuestion('NightsWatch',', who will guard the Wall?');

interviewQuestionHand();
interviewQuestionNightswatch('Edd');
interviewQuestionTyrant('Sansa');
interviewQuestionHand('Tyrion');

Lambda function not executed in dictionary with "if-else" values

I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

def a():
    print('a')


def b():
    print('b')


def c():
    print('c')


def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()

if we set condition = False, the code will not print b, it will not do anything (it seems)..why? Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

Skip entity that exist in database

I have json data that I need to import in db. I need to check two field values in database before persisting entity. If they exist to skip them without throwing an error and if not to create just the one missing.

 $file = file_get_contents('file.json');
 $jsonData = json_decode($file, true);

    $check = $this->getMyRepository()->findOneBy([
        'first_name' => $firstName,
        'last_name' => $lastName
    ]);

        foreach ($jsonData as $data) {

            if ($check) {
                continue;
            } else {
                $new = new MyEntity();
                $new->setFirstName($data->getFirstName());
                $new->setLastName($data->getLastName());
                $this->em->persist($new);
            }
        }
    }
    $this->em->flush();
}

The import is working but when I trigger an api it always import all values and it shouldn't as I mentioned.

Can I use @else/@elseif within @unless in Laravel blade?

I just found out about using @unless instead of if(!...) so I changed some of my clauses.
But I just realized that I had an if-else-statement, so I only changed it from this:

@if (!empty($data['note']))
  <p></p>
@else
  <p>no information given</p>
@endif

to this:

@unless (empty($data['note']))
  <p></p>
@else
  <p>no information given</p>
@endunless

But it didn't change anything and seems working correctly.

Is it okay/normal to use @elseand @elseif within @unless-statement?

My code will not work and i dont understand why

Homework assignment for a log in system with a create account extension.

I have tried lots of different things but to no avail.

valid = True
while valid:
  try:
    x = input("Do you want to Login (A) or Create account (y)?")
      if x == y:
        file = open("database.txt", "r")
        username = input("Enter a username :")
        password = input("Now enter a password :")
        print("Your username is", username,".")
        file = open("database.txt","a")
        file.write (username)
        file.write (",")
        file.write (password)
        file.write("\n")
        file.close()
      else:
        username = input("Enter your username")

i expect it to carry out the function but have no idea why it is not.

My function based on user input and if/else statements gives the same output no matter the user input

I get the same output no matter what the user input is. The main python file I'm working from calls on the function from a secondary file.

I've tried changing the if else statement conditions but I keep having the same issue.


if __name__ == '__main__':
    import No_2   

    No_2.cont()

    print('File1: This would be a good place to continue data manipulation.')
    input("Press the enter key to close")

And here is No_2


def cont():
    import sys

    c = input('File2: Would you like to continue? ')
    if c == 'Y' or 'y':
        print('File2: Ok we\'ll carry on...')
        print(' ')
        return

    else: sys.exit()

I expect the script to close when C does not = Y or y... Where as I would like it to return to the main script if the input is Y or y.

How check, if button pressed twice?

I am able to press the Enter button in Python, using Pygame. Now, it prints "once" into the console everytime I press the button. How can i detect if the button is pressed more than once and print "more than once"?

  if event.key == pygame.K_RETURN:

      print("once")

Check the null or empty record condition

I wanted to know if I did this code well, to check if the coding of a record is null or empty, getTraduction (), if I did something wrong, just let me know where I went wrong. because I would like to have even null records printed

public void getTraduttoreIt_CLASS_HDR_NLS() throws Exception {
        List<ClassHdrNls> db2 = getListCLASS_HDR_NLS();
        List<DizioPt> sqlServer = getListDizioPt();
        BufferedWriter scrivi = new BufferedWriter(
                new FileWriter("C:/Users/francesco/Desktop/Table_ClassHdrNls_Sez3.txt"));
        for (int i = 0; i < db2.size(); i++) {
            for (int j = 0; j < sqlServer.size(); j++) {
                if (db2.get(i).getNlsClassName().equals(sqlServer.get(j).getKeyword())) {
                    System.out.println("-------------------FILE N°3---------------------------");
                    System.out.println("-------------------ITALIANO---------------------------");
                    System.out.println("CLASS_NAME: " + db2.get(i).getClassName());
                    scrivi.newLine();
                    scrivi.write("CLASS_NAME: ");
                    scrivi.write(db2.get(i).getClassName());
                    scrivi.newLine();
                    System.out.println("NLS_CLASS_NAME: " + db2.get(i).getNlsClassName());
                    scrivi.write("NLS_CLASS_NAME: ");
                    scrivi.write(db2.get(i).getNlsClassName());
                    scrivi.newLine();
                    System.out.println("NLS_PL_CLASS_NAME: " + db2.get(i).getNlsPlClassName());
                    scrivi.write("NLS_PL_CLASS_NAME: ");
                    scrivi.write(db2.get(i).getNlsPlClassName());
                    scrivi.newLine();
                    System.out.println("KEYWORD: " + sqlServer.get(j).getKeyword());
                    scrivi.write("KEYWORD: ");
                    scrivi.write(sqlServer.get(j).getKeyword());
                    scrivi.newLine();
                    System.out.println("LINGUA ITALIANO: " + db2.get(i).getLanguage() + " ***");
                    scrivi.write("LINGUA ITALIANO: ");
                    scrivi.write(db2.get(i).getLanguage() + " ***");
                    scrivi.newLine();

                    // Faccio un controllo se il valore è diverso da null o il record è vuoto
                    if (sqlServer.get(j).getTraduzione() == null || sqlServer.get(j).getTraduzione().isEmpty()) {
                        System.out.println("TRADUZIONE: ***********");
                        scrivi.write("TRADUZIONE: ");
                        scrivi.write("*******************");
                        scrivi.newLine();
                    } else {
                        System.out.println("TRADUZIONE: " + sqlServer.get(j).getTraduzione());
                        scrivi.write("TRADUZIONE: ");
                        scrivi.write(sqlServer.get(j).getTraduzione());
                        scrivi.newLine();
                    }

                    System.out.println("-------------------------------------------------------");
                    scrivi.flush();
                }
            }

        }
        scrivi.close();
    }

Output: Print only non-null and non-empty records.

I also want to print null records

How to show alertdialog for evey child in firebase has true in it

After executing an exercise, I wanted to show an alert dialog that says, "You have already executed this. Are you sure you want to do it again?"

So in my firebase, once the exercise has already been executed isProgramExerciseFinished will be set to true. But in my code, it seems that the dialog only shows once all of it is set to true.

public void onClick(View view) { currentWeek = programTrackers.get(0).getWeek(); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProgramTracker") .child(GlobalUser.getmUser().getiD()) .child(programTrackers.get(0).getProgramId()); databaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final int childCount = (int) dataSnapshot.getChildrenCount(); int count = 0; for (DataSnapshot snapshot : dataSnapshot.getChildren()) { ProgramTracker programTracker = snapshot.getValue(ProgramTracker.class); if (programTracker.getProgramExerciseWeek() == currentWeek) { programTrackChecker.add(programTracker);

                        }
                        count++;
                    }
                    if (count == childCount) {
                        boolean isFinished = false;
                        //last iteration
                        for (int i = 0; i < programTrackChecker.size(); i++) {
                            if (programTrackChecker.get(i).isProgramExerciseFinished()) {
                                isFinished = true;
                            } else
                                isFinished = false;
                        }
                        if (isFinished) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(DayExerciseActivity.this);
                            builder.setMessage("You have already completed all exercises. Are you sure you want to do it again?");
                            builder.setPositiveButton("Yes", (dialogInterface, i) -> {
                                startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                        .putExtra("programTrackers", programTrackers)
                                        .putExtra("exerciseNum", String.valueOf(0)));

                            });
                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            });
                            builder.show();

                        } else
                            startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                    .putExtra("programTrackers", programTrackers)
                                    .putExtra("exerciseNum", String.valueOf(0)));

                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    });
}

once it is true a dialog will show once it is false dialog will not be shown and automatically will be directed to doProgramActivity