vendredi 31 août 2018

My code is always printing the else statement in C [duplicate]

This question already has an answer here:

Hello guys i just started learning C and decided to make a simple guess game, but im having some trouble. My code is always printing out the else condition why?Photo of my code

Python function multiple IF statements?

I have question regarding for loops and functions, so there list of values which as three input variables which are values for example 0-5 or direction (West, North etc), I am not sure if I using If statement correctly. Have I done something wrong with for loop command or the function?

Example of array input variables but there isn't any set limit in data set:

['Start', 'Bottom right', 1]['South', 1, 1], ['North', 3, 4], ['West', 4, 0], ['West', 2, 0], ['South', 3, 4]

If I run the function, it will always give me else function and won't follow any of commands.

enter image description here

def follow_path(a):
    legend()    #draw legend

    for draw in a:
        direction(a[0])
        location(a[1])
        choosetoken(a[2])


def location(corner):
    if corner == 'Top left':
        goto(0,600)
    if corner == 'Top right':
        goto(600,600)
    if corner == 'Bottom left':
        home()
    if corner == 'Bottom right':
        goto(600,0)
    if corner == 'Center':
        goto(300,300)
    if corner == 1:
        forward(100)
    if corner == 2:
        forward(200)
    if corner == 3:
        forward(300)
    if corner == 4:
        forward(400)
    if corner == 5:
        forward(500)
    else:
        print ("Check input '1' is correct or not")

def direction(direction):
    if direction == 'West':
        setheading(180)
    if direction == 'East':
        setheading(0)
    if direction == 'North':
        setheading(90)
    if direction == 'West':
        setheading(270)
    if direction == 'Start':
        home()   
    else:
        print ("Check input '0' is correct or not")

def choosetoken(a): #Draw shapes
    if a == 0:
        youtube()
    elif a == 1:
        chrome()
    elif a == 2:
        googledrive()
    elif a == 3:
        gmail()
    elif a == 4:
        photo()
    else:
        print ("Token Value out of range, check if input '2' is correct or not")

Python IF Else and For loop workflow

I am trying to write a function that returns the number of prime numbers that exist up to and including a given number.

Initially this was my code:

def count_primes(num):

prime = [2]

x = 3

if num < 2:
    return 0

while x <= num:
    for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
        else:
            prime.append(x)
            x += 2

return len(prime)

How ever I realise this code will run forever because of the following line of code:

for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
        else:
            prime.append(x)
            x += 2

Can anyone help to explain to me why will this end up with an infinite loop compared to the following code?

for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
else:
    prime.append(x)
    x += 2

Excel Date difference without weekend days

Last time I posted a quite vague story about a date difference challenge which I haven't solved yet. I will try to elaborate since I have tried everything in my power and the problem still isn't fixed.

I currently have three columns.

  • Column 1 (F)
    • the date a car starts its repairs (format DayOfWeek-DD-MM-YYYY)
  • Column 2 (G)
    • the number of days in which the car is repaired (service level agreement [SLA]; the standard is 10 days)
  • Column 3 (H)
    • the output, which is the date the car should be finished. So the number of days after the startdate*

*Th thing which makes this case difficult is that only weekdays are included.

So, for example:

If a car starts repairs on Monday 1st of August, the finish date is Tuesday the 14th of August.

I tried to solve this with the following formula:

=IF(WEEKDAY(F218)=2;(F218+11);
  IF(WEEKDAY(F218)=3;F218+12;
  IF(WEEKDAY(F218)=4;F218+13;
  IF(WEEKDAY(F218)=5;F218+14;
  IF(WEEKDAY(F218)=6;F218+15)))))

In other words:
If startdate = Monday then startdate + 11,
if startdate = Tuesday then startdate + 12, etc.

This works, but I have 300+ rows and dragging this function down doesn't change the cell references.

I know about the NETWORKDAYS and WEEKDAY functions, but I encounter problems with any Monday where only 1 weekend passes and other days where 2 weekends pass.

If product count reached, trigger alert. If product count already reached, don't trigger alert Woocommerce

I'm not sure if this is possible, or how to achieve this. I thought maybe a nested IF statement?

I am checking the product count in Woocommerce to check for a maximum of 4 items from a given category. I would like the IF statement to have logic as follows:

  • If the count becomes equal to 4, Trigger the javascript alert. (i.e. from 3 to 4)
  • If the count is already 4, do not trigger the javascript sweet alert if the user attempts to add another item to the cart. (This is where the js alert fires incorrectly)
  • If the count becomes 4 or more, then drops below 4 and then becomes equal to 4 again, Trigger the javascript alert.

Currently whats happening is that the alert is triggering successfully for when 3 items becomes 4 items in the cart. But then it triggers the javascript alert again when the user attempts to add another and added_to_cart event fires.

                    success: function (response) {
                    $.each( JSON.parse(response), function( category, count ) {
                        if( count == 4 ){ //IF STATEMENT HERE                         
swal({
  type: 'success',
  title: "You've Added The 4 Minimum "+category+" Items!",
  allowOutsideClick: false,
  showCancelButton: false,
  showConfirmButton: false,
timer: 3000,
})        
                        }

Perl if statement and hash

My script prints multiple copies of the $value in the hash because there is likely a problem with the way my if statement is written. It is printing the entire hash for each occurrence where there is a regex match.

How do I restructure my if statement such that for each match only the corresponding value is printed and not the entire array?

Example Input

1 .....  A
2 .....  A
3 .....  WT00
4 .....  WT00

Example Output

3
4
3
4

Desired Output

3
4

Script

 #!/usr/bin/perl
 use strict;
 use autodie;
 use File::Basename;

 my $input_path = $ARGV[0];
 my %hash;
 my $key;
 my $value;

 open(my $input_fh, "<", $filename) or die $!;
 while (my $data = < $input_fh > ) {
     chomp $data;
     my@ columns = split '\s+', $data;
     my($firstletter) = ($columns[2] =~ m/^(\w)/);
     my($coordinates) = sprintf("%9.5f%16.5f%16.5f\n", $columns[5], $columns[6], $columns[7]);
     $key = $columns[10];
     $value = $columns[1];
     $hash {$key} = $value;
     if ($key =~ m/WT00/){
         print "$hash{$key}\n";
     }
}

Have multiple condition and rules, which is better switch or if-else in javascript [duplicate]

This question already has an answer here:

I need to know which is better switch or if-else, but in my case, it will be sensitive because I will add condition rules for APIs, so I need to know the best way to switch between APIs condition without damage memory,

Note: the page will load with the condition, I will not switch between them in SPA, no It will load by condition but I need to know which better to make sure other conditions contain APIs off If user don't choose it

there are many roles and this role knows as props, so user will update it manually and refresh the page, I need to make sure other condition will be off, and which is better as a performance

switch (true) {
    case (role == 'rolenumberOne'):
      this.$http
        .get(`https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors`)
        .then(response => (this.getData = response.data))
        .catch(error => console.log(error.response))
      break;

    case (role == 'rolenumberTwo'):
      this.$http
        .get(`https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors`)
        .then(response => (this.getData = response.data))
        .catch(error => console.log(error.response))
      break;

    case (role == 'rolenumberThree'):
      this.$http
        .get(`https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors`)
        .then(response => (this.getData = response.data))
        .catch(error => console.log(error.response))
      break;

    case (role == 'rolenumberFour'):
      this.$http
        .get(`https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors`)
        .then(response => (this.getData = response.data))
        .catch(error => console.log(error.response))
      break;

    default:
      break;
}

multiple if condition php

I am new to PHP and I am making this page and I want to display the Records from database IF there is any value in the records. I am using If condition but, it's not working. Here's my code:

 $active_proof=FALSE;
 while ($row_proof = mysqli_fetch_assoc($res_proof)){

if ($row_proof['proof_cat'] == "Proof of Address"  && $row_proof['proof_cat'] == "Proof of Identity"  ){

           echo '<tr>

                <td>'.$row_proof['proof_cat'].'</td>
                <td>'.$row_proof['proof_doc'].'</td>

            </tr>';
            $active_proof = TRUE;
        }else{
        $active_proof  = FALSE;
    }

    }

Help me guys!

A problem with multiple conditions in R that does not work

I am having problem with multiple conditions in R. My data is like this:

Region in UK Year Third column (year.city) Liverpool 2008
Manchester 2010 Liverpool 2016 Chester 2015 Birmingham 2016 Blackpool 2012 Birmingham 2005 Chester 2009 Liverpool 2005 Hull 2011 Leeds 2013 Liverpool 2014 Bradford 2008 London 2010 Coventry 2009 Cardiff 2016 Liverpool 2007

What I want to create is a third column in a way that it has for groups in it: Liverpool before 2010, Liverpool after 2010, Other cities before 2010, other cities after 2010. I tried couple of codes like mutate but could not solve it. May you please help me to do it? Thanks

Order of evaluation of if statement in Python

So I thought I found a typo in code I was working on. I thought 'not' would operate on string "eta" and make it False and False is not in the List,so nothing should print - however in both the below case "Eta not found" is printed. I guess this has something to do with order of evaluation that both statements are equal.

if not "eta" in ["alpha", "beta", "gamma"]:
   print ("Eta not found")

if "eta" not in ["alpha", "beta", "gamma"]:
   print ("Eta not found")

Adding fields to an object with if-statement in js

Im trying to aggrigate huge array of objects to single object, but my if statements replace each other:

const obj = [];
res.map((el) => {
    if (el.resource.name === "FORM01" && el.name === "cost.ttl") {
        obj[el.resource.name] = { [el.name]:  el };
    }
    if ( el.resource.name === "FORM01" && el.name === "cost.use") {
        obj[el.resource.name] = { [el.name]:  el };
    }
});

in result i wat add in obj[el.resource.name] = {} two fields "cost.ttl" and "cost.use".

IF variable is set then show variable not working

I have written some PHP code, which shows an author alias if the variable is set, if not it shows the author.

I've written the following code, but it's not working.

The site is running PHP 5.3.10

    <?php if (!empty($author_alias)) { 
        echo $author_alias 
    }

    else {
        echo $this->item->author;
    } ?>

Python - If json.object is empty, repeat the function until new value?

So I have been trying to find out a more beautiful way to actually do some fault and errors in a script I am working on.

Basically I have a json_resp = resp.json() who either gives me values or [] meaning either there is something or not.

Now the question I am having trouble with is that I don't know which way is the best to repeat a function if it is empty, shall I repeat the whole function or what else would be most "best reason" to solve it in a good way?

What I have done is that I changed the objects from the json resp to a len. If its 0 then repeat else do other stuff:

#json_resp['objects'] either has empty [] or not always.

json_resp = resp.json()

        if len(json_resp['objects']) == 0:
            print('Sleeping in 2 sec')
            time.sleep(2)
            run_method() #Shall I call the function to start over?

        else:
            print(len(json_resp['objects']))
            continue do rest of the code

As you can see right now I am compare with len of the json_resp but what makes me unsure is that if it is a good way to actually call the function again? Wouldn't it have a limit or maybe delay the whole process... Im not sure but what is your thoughts of making this function "better, smarter, faster"?

My thought was maybe to either put a try except or while loop that? Let me know what you guys think

More efficient way search for multiple objects in array

I am currently using a for loop and multiple if statements to count the number of records that match a string.

for (var i = 0; i < DailyLogs.length; i++) {
  if (DailyLogs[i].created_at >= this.state.startMonth && DailyLogs[i].created_at <= this.state.finishMonth) {
    if (DailyLogs[i].created_by_id === "37aa0778-c148-4c04-b239-18885d46a8b0" ) { md1++; }
    if (DailyLogs[i].created_by_id === "869a7967-ffb3-4a20-b402-ad6d514472de" ) { md2++; }
    if (DailyLogs[i].created_by_id === "92c0f155-ce82-4b50-821f-439428c517a3" ) { md3++; }
    if (DailyLogs[i].created_by_id === "aa9eb0f2-35af-469a-8893-fc777b444bed" ) { md4++; }
    if (DailyLogs[i].created_by_id === "967d63ea-492c-4475-8b08-911be2d0bf22" ) { md5++; }
    if (DailyLogs[i].created_by_id === "47ec8d60-1fa2-4bf5-abc8-34df6bd53079" ) { md6++; }
    if (DailyLogs[i].created_by_id === "92c0f155-ce82-4b50-821f-439428c517a3" ) { md7++; }
  }
}

Is there a better way to do this, apart from having multiple if statements, or perhaps shorting this somehow.

Alternative for too many switch case for cyclomatic complexity reduction?

I have a function for checking the type of a $value is valid or not. My current code is a simple switch case with too many cases exceeding the cyclomatic complexity to 17. I need to add more cases as well as reduce the complexity.

 /**
 * Check type of attribute value
 * @param $type
 * @param $value
 * @return bool
 */
public function typeCheck($type, $value)
{
    $this->value = $value;
    switch ($type) {
        case 'string':
            return is_string($value) || is_integer($value) || is_bool($value);
        case 'StringNotNull':
            return is_string($value);
        case 'LongStringNotNull':
            return is_string($value);
        case 'SuperLongStringNotNull':
            return is_string($value);
        case 'FortyStringNotNull':
            return is_string($value) && (strlen($value) < 41);
        case 'integer':
            return is_numeric($value);
        case 'positiveInteger':
            return is_numeric($value) && ($value > 0);
        case 'boolean':
            return is_bool($value) || ($value == 'true' || $value = 'false');
        case 'float':
            return is_numeric($value);
        case 'decimal':
            return is_numeric($value);
        case 'PositiveDimension':
            return is_numeric($value) && ($value > 0);
        case 'Dimension':
            return is_numeric($value) && (strlen($value) < 13);
        case 'Barcode':
            $validator = $this->getBarcodeValidator();
            $validator->setBarcode($value);
            return is_string($value) && (strlen($value) < 17 && $validator->isValid());
        case 'dateTime':
            return true;
        case 'normalizedString':
            $this->value = strip_tags($value);
            return is_string($value);
        default:
            return is_string($value);
    }
}

Any better way around?

Timing user input keys

this is my first attempt at making a program. I want to time how long it takes for the user to type what is displayed on the screen, however, it is only timing once every two tries.

For example X might be displayed they type X and it doesn't time. When e.g. Y appears next and they type Y it will time it, and it just goes round in circles like that.

This is what i have so far sorry if it's bad.

answer.addKeyListener(new KeyAdapter() {
        long entryStart;
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER)
            {
                countTime++;
                if (countTime % 2 != 0) {
                    entryStart = System.currentTimeMillis();
                }
                if (countTime % 2 == 0)
                {
                    long entryEnd = System.currentTimeMillis();
                    long differenceEntry = (entryEnd - entryStart);
                    timeField.setText(String.valueOf(differenceEntry / 1000.0));
                }
                if (answer.getText().isEmpty()){
                    JOptionPane.showMessageDialog(answer, "Error!");        
                }
                if (answer.getText().equals(matchingField.getText())){
                    points++;
                    pointsField.setText(String.valueOf(points));
                }
                else {
                    incorrectpoints++;
                    incorrectField.setText(String.valueOf(incorrectpoints));
                    points--;
                    pointsField.setText(String.valueOf(points));
                }
                matchingField.setText("");
                answerField.setText("");
                StringGenerator sg = new StringGenerator(); 
                matchingField.setText(sg.randomString());
            }
        }

Also if you could provide any details on how I could improve my code that would also be appreciated. Thank you.

i have tried hard to answer this code, about if-statement

'' Var name = ""
Var age = 15
Var money = 100

If ( age < 17 )
Console.log ( 'drink tea')
Else
Console.log ( 'drink wine')

Tea price about $5
And wine price about $150

If ( money < 5 ) // if we drink tea
Console.log( 'your money  not enough')
Else 
Console.log(' your money enough , your money left + (money - 5 ) // price of tea

If (money < 150) // if we drink wine
Console.log('your money not enough')
Else 
Console.log('your money enough , your money left + (money 
- 150) // price of wine

// can someone fix this statement or is there any affective method to make it short???? //

jeudi 30 août 2018

Java 8 if else alternative

Want to use Java 8 feature for my following code,

   boolean  var1 = true;
        boolean var2 = true;
        boolean var3 = var1 && var2;
        String result = var3 ? "variable3" : var2 ? "varible2" : "variable1";
        System.out.println(result);

multiple if statement with javascript in html input

I want to execute specific javascript if $_post['value'] larger than 100 and another javascript if $_post['value'] smaller than 100

<script language="JavaScript">
    if (document.getElementById("user_amount") > 100) {
        function euroConverter() {
            document.amount.value =
            document.user_amount.value - (document.user_amount.value * 0.08)
        }
    }

    if (document.getElementById("user_amount") < 100) {
        function euroConverter() {
            document.amount.value =
            document.user_amount.value - (document.user_amount.value * 0.1)
        }
    }
</script>

and html

<div class="form-group input-group">
    <input type="number" id="user_amount" class="form-control" name="user_amount" onChange="euroConverter()">
    <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span>
</div>
<div class="form-group input-group">
    <input type="number" class="form-control" name="amount" onChange="dollarConverter()">
    <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span>
</div>

Thanks

Odd IF behavior

UPDATE:

using:

listTransactions.getStatus().equals("PENDING")

seems to work. But why doesn't it work the other way? I admit I'm newish to Java coming from C# but this is as elementary as it gets. Does Java not use "==" with Strings?


Hello,

In the below snippet:

Log.d("test",listTransactions.getType()+" "+listTransactions.getStatus());
    if(listTransactions.getType()==2 && listTransactions.getStatus()=="PENDING")

    {
        Log.d("test2","WORKING");
    }

the Log.d output is

D/test: 2 PENDING

but for some reason the code inside IF does not evaluate.

getType() returns int and getStatus() returns String.

I've spent the last half hour trying to re-write it with the same result. What could be causing this?

Many thanks for your time.

Bash Scipt with function / for loop

I'm writing a bash script for inventory information, and i'm attempting to collect data on two seperate version of Red Hat. They have two different types of output for the ifconfig, so i'm simply trying to add an 'if' statement to the already working function. I keep getting an error that says syntax error: unexpected end of file . I assume i'm not closing something somewhere, but I can't seem to see it, though i've probably been looking at it too long. any assistance would be great.

Here is the script

#!/bin/sh
OS_VERSION=`cat /etc/redhat-release  |awk '{print $0}'`
pat=".*Santiago.*"

num=1
        if [[ "$OS_VERSION" =~ $pat ]]; then

                for i in `/sbin/ifconfig -a |grep -i -B 3 "UP" |grep -i "HWaddr"|awk '{print $1}'`
                        do
                                {
                                MacAddress=`/sbin/ifconfig $i |grep -i -B 3 "UP" |grep -i "HWaddr"| awk '{print $NF}'`
                                Ip_Address=`/sbin/ifconfig $i|grep -i "inet addr"|awk '{print $2}'|awk -F: '{print $2}'`
                                echo -n "ethName$num=$i | ethMac$num=\"$MacAddress\" | ethIp$num=\"$Ip_Address\" | "
                                num=$(expr $num+1|bc)
                                }
                         else 
                            echo "Not Santiago, use other script"
done;
echo "";
exit

How to compare a variable in a FOR command with one outside of the FOR command?

I'm working on a program that's based on a device used in the early 20th century. While testing on parts of the program, a part of the code doesn't work like I thought it would. Here is some code that is similar to it:

@echo off
setlocal enabledelayedexpansion
cls
set /p ar=Type a number:
:loop
for /l %%a in (1,1,100) do (
    set var1=%%a
    if !var1! equ %ar%(
        echo It worked
        goto pause1
    ) else (
        echo It didn't work
    )
)
:pause1
pause

What I'm trying to do here is comparing the "%%a" variable with a variable set outside of the FOR command, but every time I tested the program, it would suddenly exit from the command prompt. I have tried changing the order of the commands, and changing the symbols, but the output is the same. I've checked many references and I haven't found any that tackles this certain scenario. Can you tell me what I'm doing wrong here and what to do to fix it? Thank you.

Why does else-statement have no effect?

I have this code:

    def askyesno_pr():
        msg1 = tk.messagebox.askyesno(
            title='Are you ready to begin?',
            message='To begin payroll you will need these reports\n '
                    'for one pay period:\n\n'
                    '     -Stylist Analysis\n'
                    '     -Tips By Employee Report\n'
                    '     -Employee Hours for Week 1\n'
                    '     -Employee Hours for Week 2\n'
                    '     -Client Retention\n'
                    '     -Employee Service Efficiency\n\n'
                    'Are you ready to begin?')
        if msg1:
            askfilesaveloc()
        else:
            0

The last 2 lines is where I am showing an issue in PyCharm. It says "Statement has no effect" but when I remove the 0 the code does not operate correctly - so clearly the 0 does have an effect. Is there something else I should have in the place of a 0 so that it does not throw this code? Or is it just a false-positive in PyCharm?

Why I get this error: Uncaught TypeError: Cannot read property 'serviceId' of undefined

I can display value of serviceId to console but when I try to compare it in if(), I got this error. Can you tell me why does this happend and how to solve it, please?

        var servicesCompare1 = [];
        var servicesCompare2 = [];
        $.getJSON("http://localhost:55972/api/status", function (data) {
            self.services(data.services);
            self.lastCheck = data.lastCheck;
            servicesCompare1 = (data.services);
        });

        function DashboardRefresh() {
            self.servicesRefresh = ko.observable([]);
            $.getJSON("http://localhost:55972/api/status", function (data) {
                servicesCompare2 = (data.services);
                self.servicesRefresh(data.services);                
            });
          if (servicesCompare2.length > servicesCompare1.length) {
              for (i = 0; i < (servicesCompare2.length-1); i++) {                   
                  console.log(servicesCompare2[i].serviceId);
                  if (servicesCompare1[i].serviceId !== servicesCompare2[i].serviceId) {
                      self.services.push(servicesCompare2[i]);

                  }
              }
          } 
        }
        setInterval(DashboardRefresh, 5000);

Console output: 47 48 49 ... other Ids

Uncaught TypeError: Cannot read property 'serviceId' of undefined at DashboardRefresh (NetworkStatus.html:66)

Excel: IF statement with 3 possible outcomes (2 times text, 1 empty cell)

Situation:

Cell A1 is a number (age of a person)

Cell B1 generates one of 2 texts.

I can't get to the solution of this: If A1 is larger then 14 and smaler or equal to 17 it should give text A. If A1 is larger then then 17 it should give text B. But if A1 is empty B1 should stay empty too.

I messed my head already with this puzzle.

Close Form if Field is Blank

I have a form that if a field is blank, it tells the user that it can't be blank, and gives the user the option to fill in the blank field (Yes) or close the form (No). Problem is that when the user picks No (or close the form), it gives me a run-time error 2585. After researching, I have it checking if the field is blank on the field after using On Got Focus. (After Update on the field didn't work because there's no update if it's blank.) Here's my code:

If IsNull(Me.txtSSN) Then

  strMsg = "Social Security Number Must Not Be Left Blank!" & vbCrLf
  strMsg = strMsg & "Do you want to add new veteran's record?" & vbCrLf

  If MsgBox(strMsg, vbQuestion + vbYesNo, "Go to Record?") = vbYes Then

    Me.Undo
    Me.Refresh
    Me.txtSSN.SetFocus
    Exit Sub

  Else
    Me.Undo
    Me.Refresh
    Me.txtSSN.SetFocus

    Me.Undo
    'DoCmd.OpenForm "fmuMainMenu"
    DoCmd.Close acForm, "frmVetNewMainForm"

  End If

Else 'Rest of Code...

In Matlab's very old versions, what did "\" stand for in a conditional statement?

For my thesis work I was suggested to use a related code made in year 2000 on Matlab; when transcribing it I found the next syntax for some if loops:

if \ min(x)>= 0
   statement;
end

However it is not valid anymore for recent software's versions. I did some search on Google but using "\" is pretty ambiguous and found nothing out of conditionals. Do you know what does it stand for?

VBA Conditional Statement with Target.Cells.CountLarge Not Working

Desired Behaviour:

I want to change the value of a cell if and only if a cell current value of another cell matches some constant string value (only alpha characters) I have chosen.

Code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    With ActiveWindow

        Dim sht As Worksheet
        Set sht = ThisWorkbook.Sheets("Sheet1")

        Dim selection As Long
        selection = Target.Cells.CountLarge
        Dim someString As String
        someString= "something"



        If selection = 1 Then
            If (Target.Column = 4 And Target.Value = someString And IsEmpty(Target) =False) Then
                thisrow = Target.Row
                sht.Cells(thisrow, 5).Value = "N/A"
            End If
        End If


    End With
End Sub

Question: Is there a better way to handle this? The first if statement is necessary to ensure one cell is selected and to avoid error message type mismatch.

PowerShell hashtable storage for categorical data

I have data that is in the structure of: Subject > Category > Subcategories

e.g.

Planet of the Apes

-Scifi

--Movie

--TV series

-Popular

--Remake

--Cult Classic

----------------

BBC News

-Topical

--Daily News

-Geographical

--UK

--England

(the data isn't actually as bad this!)

I'm trying to work out the best way to convert this into something I can work with to filter and sort. Since the data currently is plain text, I've got an if statement that works out if it's a Subject, Category, or Subcategory but what would be the most sensible way to build a hashtable out of data like this?

$processedData = @{}
$versionattribs | ForEach-Object{
if($_ -match "^\s*$" -or $_ -match "Inherits.*")
    {
    # Is a blank line
    }
elseif($_ -notmatch "`t")
        {
        # Is a Subject
        Write-Host "Subject: $_ "
        $Subject = $_
        }
elseif($_ -match "`t" -and $_ -notmatch "`t`t")
        {
        # Is a category
        Write-host "Category: $_"
        $category = $_
        }
elseif($_ -match "`t`t")
        {
        # Is a sub-category label
        Write-Host "Label: $_ "
        $label = $_
        }
else
        {
        #Unexpected attribute
        Write-host "Error - unexpected line indentation : $_"
        }
}

ELSE was unexpected at this time

I frequently work on the Windows command line within ConEmu and occasionally, after working in a given window for some time, get the following unexpected error:

ELSE was unexpected at this time.

Currently, it occurred after pasting about 150 lines of rm commands (may be unrelated).

Once I get that error, I cannot use the ELSE statement in that window; I must start a new shell process, at which point my scripts work as expected. For example, once that error occurs in a window, I observe the following:

C:\> IF DEFINED AN_ENV_VAR (ECHO YES) ELSE ECHO NO
ELSE was unexpected at this time.
C:\> IF NOT DEFINED AN_ENV_VAR (ECHO YES) ELSE ECHO NO
ELSE was unexpected at this time.
C:\> IF DEFINED AN_ENV_VAR (ECHO YES)
C:\> IF NOT DEFINED AN_ENV_VAR (ECHO YES)
YES

A new shell gives expected results:

C:\> IF DEFINED AN_ENV_VAR (ECHO YES) ELSE ECHO NO
NO
C:\> IF NOT DEFINED AN_ENV_VAR (ECHO YES) ELSE ECHO NO
YES
C:\> IF DEFINED AN_ENV_VAR (ECHO YES)
C:\> IF NOT DEFINED AN_ENV_VAR (ECHO YES)
YES

Is there any way to fix the current shell?

Python: automating the generation of a variable number of if statements

I have two numpy arrays similar to these, which represent coordinates:

import numpy as np
x=np.array([1,3,2,4,6,5,4,1])
y=np.array([4,4,3,2,2,1,3,5])

I also have n squares:

s1 -> x=0 to 3, y=0 to 3
s2 -> x=3 to 6, y=3 to 6
s3 -> ...
s4 -> ...

and I want to count the number of points falling within each square. This comes down to evaluating n inequalities.

My approach is verbose and (probably) inefficient:

count1=0
count2=0
count3=0
count4=0
for j in range(0, len(x)):
    #Square 1
    if x[j]<=3 and y[j]<=3:
        count1+=1
    #Square 2
    if x[j]<=3 and y[j]>3 and y[j]<=6:
        count2+=1
    #Square 3
    if x[j]>3 and x[j]<=6 and y[j]<=3:
        count3+=1
    #Square 4
    if x[j]>3 and x[j]<=6 and y[j]>3 and y[j]<=6:
        count4+=1

Given my two arrays, this returns:

In[1]: count1, count2, count3, count4
Out[1]: (1, 3, 4, 0)

My real problems consists of a variable number of squares (it could be 6, it could be 36, etc.).

Is there a way I can automate both the generation of the count variables, as well as the number and boundaries of the if statements?

use of if else statement in python getting runtime error

n=range(101)
if n%2==0:
     print("weird")
if range(2,6):
     print("not weird")
if range(6,21):
     print("weird")
if n>20:
     print("not weird")
else :
     print("weird")

Given an integer, , perform the following conditional actions:

If is odd, print Weird If is even and in the inclusive range of 2 to 5, print Not Weird If is even and in the inclusive range of 6 to 20 , print Weird If is even and greater than 20, print Not Weird

SaltStack - How to conditionally enforce states?

This is a self-answered question.
Please provide edits, additional points of view and input if needed.

What is the best practice for conditionally enforcing states (depending on other command outputs)?

Here's my case:

# vim: set syntax=yaml:

# Ensures that outbound connections are allowed for httpd
httpd:selinux:
    cmd.run:
        - name: /usr/sbin/setsebool -P httpd_can_network_connect 1

Now, I only want to run this if SELinux is enabled (enforced).

Is "if(!myobject)" the same as "if(myobject == null)"?

Today I've come across an interesting bit of C# code:

if(!myobject) { /*Do Stuff*/ }

It does seem to behave the same as:

if(myobject == null) { /*Do Stuff*/ }

... but is it really the same thing? I haven't found any documentation about this anywhere yet.

Is there a reason to not use the shorter version or prefer one over the other?

if(y&(y=2) so how to deal with this if condition

#include<stdio.h>
int main()
{int y=1;
 if(y&(y=2))
 printf("true %d\n",y);
 else
 printf("false %d\n",y);

return 0;
}

how does the ouput come as true 2? according to me inside the if condition this will happen "if(1&(2))" but the output comes as true 2 .

Create mysql sum column when multiple other columns are true

I want to create a column in mysql workbench where there is a sum of the duration of a behaviour when multiple columns (e.g condition, trial, subject, behaviour type...) are the same.

I am relatively new to working in sql and have so far mostly just used it for extracting data. Is this something that is possible? If so how do I go about it?

Thanks :)

Execute function if user logged in - Wordpress

First time I post here ! Hope my question will be relevant.

I defined a function to exclude a category in a calendar which works well when I execute it like this:

function tribe_exclude_events_category_month_list( $query ) {

if ( isset( $query->query_vars['eventDisplay'] ) && ! is_singular( 'tribe_events' ) ) {

    if ( $query->query_vars['eventDisplay'] == 'list' && ! is_tax( Tribe__Events__Main::TAXONOMY ) || $query->query_vars['eventDisplay'] == 'month' && $query->query_vars['post_type'] == Tribe__Events__Main::POSTTYPE && ! is_tax( Tribe__Events__Main::TAXONOMY ) && empty( $query->query_vars['suppress_filters'] ) ) {

        $query->set( 'tax_query', array(

            array(
                'taxonomy' => Tribe__Events__Main::TAXONOMY,
                'field'    => 'slug',
                'terms'    => array( 'reunions'),
                'operator' => 'NOT IN'
            )
        ) );
    }

}

return $query;} add_action( 'pre_get_posts', 'tribe_exclude_events_category_month_list' );

But what I want is to execute it if only if user is logged in. So I did this :

function tribe_exclude_events_category_month_list( $query ) {

if ( isset( $query->query_vars['eventDisplay'] ) && ! is_singular( 'tribe_events' ) ) {

    if ( $query->query_vars['eventDisplay'] == 'list' && ! is_tax( Tribe__Events__Main::TAXONOMY ) || $query->query_vars['eventDisplay'] == 'month' && $query->query_vars['post_type'] == Tribe__Events__Main::POSTTYPE && ! is_tax( Tribe__Events__Main::TAXONOMY ) && empty( $query->query_vars['suppress_filters'] ) ) {

        $query->set( 'tax_query', array(

            array(
                'taxonomy' => Tribe__Events__Main::TAXONOMY,
                'field'    => 'slug',
                'terms'    => array( 'reunions'),
                'operator' => 'NOT IN'
            )
        ) );
    }

}

return $query; } 

function exclude_category_when_logged_in() {
if ( is_user_logged_in() ) {
  add_action( 'pre_get_posts', 'tribe_exclude_events_category_month_list' );
}} add_action( 'init', 'exclude_category_when_logged_in' );

But this doesn't seem to work.

Could you help please ? Thanks a lot Lucas

How to use my if/else statement in a for loop with arrays?

I have code that compares userinput from EditText to the correct translation(String[] answers). Now i wrote a if/else statement but I'm trying to put that in a for loop. Otherwise I need to write over 30 statements. just with a few numbers different.

Now I have came up with the following 'basis':

for(int i = 0; i < answers.length; i++){

        if (Uinput[].equals(answers[])) {
            edit1.setBackgroundColor(Color.parseColor("#00FF00"));
        } else {
            edit1.setBackgroundColor(Color.parseColor("#FF0000"));
        }
    }

What do I need to put between the brackets([]) as it wont allow it empty, and further any recommendations or changes? Thanks in advance.

Code sample of what I'm currently using:

private String[] answers = {"daylight", "task"};

private EditText edit1;

this.edit1 = findViewById(R.id.edit1);

String Uinput[] = {edit1.getText().toString()};

//        Comparison 1
        if (Uinput[0].equals(answers[0])) {
            edit1.setBackgroundColor(Color.parseColor("#00FF00"));
        }
        else {
            edit1.setBackgroundColor(Color.parseColor("#FF0000"));
        }

parsing an argument into Jenkins freestyle job?

how do i pass an argument into jenkins job and the code is in python which ask for an argument in if condition

i tried using " os.environ.get" for global variable. But for the input which asks by IF statement is seems to be not working with the environ.get methon

How to break out of a while loop and if statement?

I need to break out both the while loop and if statement when the the value inside the if statement is great than 0, in turn the code should then break from the while loop.

How can I achieve this?

My code is as follows:

it('x Accordion description should appear after 5 seconds upon being clicked', function(done) {
      //this.timeout(15000);
      //setTimeout(done, 6000);
      var i = 0;
      while (i < 15000) {
          browser.click('#accordion');
          //var timeoutText = browser.getText('#timeout').length;
          var timeoutText = browser.getText('#timeout').length;
          console.log(timeoutText);

            if (timeoutText > 0) {
                  browser.pause(5000);
                  console.log("Pass");
                  break;
                  i++;
            }
      }

Thanks for your help.

mercredi 29 août 2018

variable scope under while+for loop and if statement

The purpose of this code is trying to output the route where the second element of one tuple is the same as the first element of another tuple.

When the i += 1 has the same indentation as for loop, "JFK" is the origin, path = segments. I got ['JFK', 'DEN', 'SFO', 'LAS', 'LAX', 'ORD', 'ATL'] which is the correct answer.

When i += 1 has the same indentation as if statement, I only got ['JFK', 'DEN', 'SFO', 'LAS']. Does anyone know why???

segments = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"),   
("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]

def get_route(path, origin):

    my_list = []

    i = 0

    list_len = len(path)

    path_copy = path.copy()

    while i <= list_len:

        for k in path_copy:

            if origin == k[0] and origin not in my_list:

                my_list.append(k[0])

                origin = k[1]

                path_copy.remove(k)

         i += 1

    return my_list

why setting input.value equal to empty string doesn't remove recently pressed key?

In below code if I press 'a' after some keys it should remove everything from input including but 'a' is not going away in below code.

const input = document.querySelector("input");

function type(e) {
  if (e.key === "a") {
    console.log("helo");
    input.value = "";
  }
}
window.addEventListener("keydown", type);

JS/jQuery array looping thumbnails using next and previous image arrows for navigation

I'm fairly new to arrays and I was interested in using it to control a series of thumbnail positions whenever a next or previous arrow is pressed. Additionally these thumbs should loop whenever an image completes a cycle across the array. I used a series of if/else statements and splice to add and remove thumbs that needed to be recycled.

I was successful at getting the Next button to accomplish the task I was working to achieve, but I cannot seem to get the Previous button to behave the same way and reverse the thumbnail flow in the opposite direction. I've tried many different things, but have had no success.

// find elements
var $galleryThumbs = $('#galleryThumbs');
var $galleryThumbsWrapper = $('#galleryThumbsWrapper');
var $next = $('#nextBtn');
var $prev = $('#prevBtn');

var $thumb01 = $('.thumb#t01');
var $thumb02 = $('.thumb#t02');
var $thumb03 = $('.thumb#t03');
var $thumb04 = $('.thumb#t04');
var $thumb05 = $('.thumb#t05');
var $thumb06 = $('.thumb#t06');
var $thumb07 = $('.thumb#t07');

// handle click and add class
var pic = new Array();
  pic = [$thumb05, $thumb06, $thumb07, $thumb01, $thumb02, $thumb03, $thumb04];

var x = $($galleryThumbsWrapper);

var thumbOrder = 0;

function checkNextOrder(thumbOrder){
x.css('float','left');
if(thumbOrder == 0) {
    console.log("thumbOrder == 0");
    pic.splice(0, 1, $thumb04);
    x.append($thumb04);
    return thumbOrder;

}else if(thumbOrder == 1) {
    console.log("thumbOrder == 1");
    pic.splice(0, 1, $thumb05);
    x.append($thumb05);
    return thumbOrder;

}else if(thumbOrder == 2) {
    console.log("thumbOrder == 2");
    pic.splice(0, 1, $thumb06);
    x.append($thumb06);
    return thumbOrder;

}else if(thumbOrder == 3) {
    console.log("thumbOrder == 3");
    pic.splice(0, 1, $thumb07);
    x.append($thumb07);
    return thumbOrder;

}else if(thumbOrder == 4) {
    console.log("thumbOrder == 4");
    pic.splice(0, 1, $thumb01);
    x.append($thumb01);
    return thumbOrder;

}else if(thumbOrder == 5) {
    console.log("thumbOrder == 5");
    pic.splice(0, 1, $thumb02);
    x.append($thumb02);
    return thumbOrder;

}else if(thumbOrder == 6) {
    console.log("thumbOrder == 6");
    pic.splice(0, 1, $thumb03);
    x.append($thumb03);
    return thumbOrder;
}
}



function checkPrevOrder(thumbOrder){
x.css('float','right');
console.log('previous');
if(thumbOrder == 6) {
    console.log("thumbOrder == 6");
    pic.splice(6, 1, $thumb04);
    x.append($thumb04);
    return thumbOrder;
}else if(thumbOrder == 5) {
    console.log("thumbOrder == 5");
    pic.splice(6, 1, $thumb03);
    x.append($thumb03);
    return thumbOrder;
}else if(thumbOrder == 4) {
    pic.splice(6, 1, $thumb02);
    x.append($thumb02);
    return thumbOrder;
}else if(thumbOrder == 3) {
    console.log("thumbOrder == 3");
    pic.splice(6, 1, $thumb01);
    x.append($thumb01);
    return thumbOrder;
}else if(thumbOrder == 2) {
    console.log("thumbOrder == 2");
    pic.splice(6, 1, $thumb07);
    x.append($thumb07);
    return thumbOrder;
}else if(thumbOrder == 1) {
    console.log("thumbOrder == 1");
    pic.splice(6, 1, $thumb06);
    x.append($thumb06);
    return thumbOrder;
}else if(thumbOrder == 0) {
    console.log("thumbOrder == 0");
    pic.splice(6, 1, $thumb05);
    x.append($thumb05);
    return thumbOrder;
}
}

$($next).on('click', function() {
console.log('next');
console.log("Thumborder is currently at:" + thumbOrder);
if(thumbOrder < 6){
    thumbOrder++;
    checkNextOrder(thumbOrder);
}else{
    thumbOrder = 0;
    checkNextOrder(thumbOrder);
}
})



$($prev).on('click', function() {
console.log('prev');
if(thumbOrder > 0){
    thumbOrder--;
    checkPrevOrder(thumbOrder);
}else{
    thumbOrder = 6;
    checkPrevOrder(thumbOrder);
}
})

I have laid out my issue in a JS Fiddle for review. If anyone has a more simple/elegant way of solving this, your feedback would be greatly appreciated.

Change header based on parent product category in Woocommerce

I am running an e-commerce store where I have two custom headers for different sides of the store. I am wondering if is possible that for:

  • the parent product category A to display header A
  • the parent product category B to display header B

I just don't know where to put it in my theme.

Here is my actual code example:

if(is_category('category-a-slug')){
    get_header('a');
}elseif(is_category('category-b-slug')){
    get_header('b');
}

Any help is appreciated.

when is an 'if' statement code incorrect even after giving an output?

am completely new to programming and I am learning through edX now and I came across this code but I do not really know why the code is termed incorrect even though it gives an output. would have asked on the edx platform but the course finished two years ago, just learning from what is archived. Thanks .

The result is 'i win' and 'tie' it has an output so why is it still incorrect?

comp = 'rock'
user = 'rock'

if comp == 'rock':
    print 'I win *_*!'
if user == 'paper':
    print 'You win.'
else:
    print 'Tie.'

Send order to delivery service based on order status in Woocommerce 3

My orders are automatically sent to the external delivery service. But when the status of the order changes, it is again sent to the external delivery service. How to fix it?

add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
    // Only for 'processing' and 'hold-on' order statuses change
    if ( $new_status == 'processing' || $new_status == 'hold-on' ) {
        // Checking if this has already been done avoiding reload
        if (get_post_meta($order_id, 'delivery_order_id', true)) {
            return; // Exit if already processed
        }
    }

    $order_data = $order->get_data();

    // Send data
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?new_order");
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    curl_close($ch);

    $decoded = (array) json_decode($result);

    // Output
    if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['order_id']) && !empty($decoded['order_id']) ){
        update_post_meta( $order_id, 'delivery_order_id', esc_attr( $decoded['order_id'] ) );
    }
}

Nested 'for' and 'if-else' statement jinja2 template

I am trying to write a nested loop in jinja2, but the last line is not printing as I expect:



Thanks in advance

Check if text exists in textfile c#

im trying to figure out if the text url that I get from current url exists in 'linkx.txt', if it does then show message, if it doesn't then write to text file. however, when i run this code program writes to text file twice before recognizing the text exists.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
            {
                string url = "";
                if (keyData == Keys.F1) { Application.Exit(); return true;   }
                else if (keyData == Keys.F2) { url = webBrowser1.Url.AbsoluteUri; }

                    using (StreamReader sr = File.OpenText("linkx.txt"))
                    {
                        string texxt = url;
                        string[] lines = File.ReadAllLines("linkx.txt");
                        bool matched = false;
                        for (int x = 0; x < lines.Length - 1; x++)
                        {
                            if (texxt == lines[x])
                            {
                                sr.Close();
                                MessageBox.Show("there is a match");
                                matched = true;
                            }
                        }
                        if (!matched)
                        {
                            sr.Close();
                            using (StreamWriter wriite = File.AppendText("linkx.txt"))
                            {
                                wriite.WriteLine(url);
                                MessageBox.Show("url copied!");
                                return true;    // indicate that you handled this keystroke
                            }
                        }
                    }
                // Call the base class
                return base.ProcessCmdKey(ref msg, keyData);
            }

if else structure in java printing out strange code

Hi there I have become stuck with an exercise on if-else statements in java the problem is when I run the code it prints; Enter a card: 9 S end 9ofS

please see below for my code example:

 String suit;
 String rank;
 String userOne; 
 Scanner sc = new Scanner( System.in );
 System.out.print("Enter a card: ");
 rank= sc.next(); 
 suit= sc.next();
 userOne= sc.next();
 if (userOne.equals("9")){ System.out.println("Nine");
 } else if (userOne.equals("S")){ System.out.println("Spades");       
 } System.out.print(rank+ "of" +suit);

had to squeeze the code in at the bottom I know its not in the right format but for just getting an answer to this question I had to lay it out like that.

Why is the code printing out- Enter a card: 9 S end 9ofS instead of Enter a card: 9 S Nine of Spades ?     

if -else loop Error Java netbeans

I have a project that requires Java-Mysql connectivity. Here I require the use of if-else blocks within the try and catch statements.

But it shows errors wherever I use the if-else loop. The error shown is :

Cannot find Symbol

(the checkbox & radio box no.s are correct)

PART 1 PART 2

Can we use await and same functions for promises?

So i have request coming in based that i am building this.request array so i can make calls to urls and request.body pushed into it , In below code if i am trying to use RequestResponseHandler.processRequest for both promises but its always going into spec when i call same function processRequest for other promise , How can i make sure if processRequest is called for spec ignore that if condition and go to PTM

request

{ lineOfBusiness: ["spec","PTM"] , body: data }

handler.ts

    export class RequestResponseHandler {
        public static processRequest(data: any, url: string): Promise < any > {
            const reqObject: IRequestURL = {}
            as IRequestURL;
            const lob = data.header.lineOfBusiness;
            if (lob === "spec") {
                const specUrl = urlConfig + url;
                reqObject.url = specUrl;
                reqObject.body = data;
            }
            if (lob === "PTM") {
                const ptmUrl = urlConfig + url;
                reqObject.url = ptmUrl;
                reqObject.body = data;
            }
        }
    }

controllet.ts

 const bRetSpec: boolean = await this.specBalanceRequest(request);
        const bRetPtm: boolean = await this.ptmBalanceRequest(request);

    private async specBalanceRequest(@Body() request: ExpressRequest): Promise < boolean > {
        const specUrl = "/payments";
        const reqObject = await RequestResponseHandler.processRequest(request.body, specialtyUrl);
        this._request.push(reqObject);
        return Promise.resolve(true);
    }

    private async ptmBalanceRequest(@Body() request: any): Promise < boolean > {
        const careURL = "/Order";
        const reqObject = await RequestResponseHandler.processRequest(request.body, caremarkURL);
        this._request.push(reqObject);
        return Promise.resolve(true);
    }

Checking for, installing, and loading packages in for loop in R [duplicate]

This question already has an answer here:

this is my first post on SO, so forgive me if the formatting is wanting.
I'm trying to write a utility script that checks whether required packages are installed and installs the packages if not installed. I am trying to use a for loop to do this. For example,

requiredpackages <- c("FinancialMath", "FinCal", "ggplot2")

for (pkg in requiredpackages) {
  if (pkg %in% rownames(installed.packages()) == FALSE)
  {install.packages(pkg)}
  if (pkg %in% rownames(.packages()) == FALSE)
  {library(pkg)}
}

When I run this script, however, I get the following error message: "Error in library(pkg) : there is no package called ‘pkg’"

What am I doing wrong?

Thank you for your time.

If Else not being recognized

I have a form in which the user inputs a number, and I want my macro to check whether the number exists in a specific list in order to do some stuff. Here's how I did it:

Private Sub CommandButton3_Click()
 Dim number As Integer, i As Integer
 For i = 10 To 10020
     If TextBox1.Value = Sheet1.Cells(i, 2).Value Then
         number = TextBox1.Value
     End If
 Next i
     MsgBox "A dica número " & TextBox1.Value & " não consta na lista.", vbOKOnly, "Dica não encontrada!"
     Exit Sub

 'Do the rest of the code here
End Sub

The thing is: no matter what number I input, the message box always comes up. number = TextBox1.Value is never read. I've tried manually checking if the values were the same for a specific input with message boxes, and even though they were the same, If/Else was never accessed.

Any help would be appreciated.

How I can check if parameter it contains variable or string

How I can check if parameter it contains variable or string for example :

    String text = "hello";

    //I want like this
    Demo(text);
    //But if he wrote like this give him error
    Demo("hello");

    public void Demo(String text) {

    }

program control not coming out of else if condition in Java

int pi_digits1=0;
int pi_digits2=0;

System.out.println("Would you like from starting to fixed no. or for a 
range:\n1.Fixed no\n2.Range");
byte choice = input.nextByte();

if(choice ==1){
System.out.println("Enter the no. of digits after decimal within 1 million 
of pi to see and play");
pi_digits2=input.nextInt();
}
else if(choice ==2){
 System.out.println("Enter the smaller +ve no of range");
 pi_digits1=input.nextInt();
 System.out.println("Enter the larger +ve no of range");
 pi_digits2=input.nextInt();
 System.out.println("Check");
}
else{
 System.out.println("Wrong choice.Program terminated");
}

When the choice is 1,loop works fine. But for the choice 2,after taking inputs for pi_digits2 ,it is still asking for inputs.

Check is also being printed,but program is strucked in input loop and hence further code is not being executed.

Program executed in Bluej environment

Python Email PDF from file Directory

I need to email a pdf and a generic cover letter from a file directory to a an email address that matches the 5 digit code. the code can be found in the first 5 of the pdf name and then the corresonding dataframe that contains the 5 digit code and email address. Is there an easy way to accomplish this? Thanks

 # loop through the email list 
for i in email_list.itertuples():
    PDF_name = i.AGCODE + '_2017 Net_Initial.pdf'
    cover_letter_name = 'CoverLetter.pdf' 
    print(PDF_name)
 #attach an excel file and PDF file: 
with open(dir_path + PDF_name, 'rb') as f, open(dir_path + cover_letter_name, 'rb') as g:
 # Read the binary file contents
     PDF_content = f.read()  
     cl_content = g.read()
     PDF_att = FileAttachment(name=PDF_name, content=PDF_content) 
     cl_att = FileAttachment(name=cover_letter_name, content=cl_content) 

 # if you want a copy in the 'Sent' folder
m = Message(
      account=a 
     ,folder=a.sent
     ,subject=('Award Letter for ' + i.FACILITY_NAME + ' -- Agency Code: ' + i.AGCODE)
     ,body = body_of_email 
     ,to_recipients=[Mailbox(email_address=i.FAC_EMAIL_ADDR)])

#attach files
m.attach(cl_att)
m.attach(PDF_att)
# send email each time          
m.send_and_save()
#======================== 

Swift - If text matches any string in array exactly [duplicate]

This question already has an answer here:

I am trying to see if my UITextField.text matches any of the strings in my array exactly. As I am using letters I need to know if the text matches exactly and not just contains elements from the array.

In the if statement I am not sure what to put after 'cameraBodies' to search over the whole array?

Thank you for any help

let cameraBodies = ["A","B","C","D","E","F","G","H","I","J","K",
                    "L","M","N","O","P","Q","R","S","T","U","V",
                    "W","X","Y","Z","Other"]

if cameraBodyTextField.text != cameraBodies (Here is the problem) {     
            print("Does not match")
        } else {    
            print("Does match")
        }
}

HAML .each function with a list and duplicates

I am trying to figure out how can i distribute particular elements of a list, based on an if statement.

This is the list:

@x = ["american", "assistive", "audio", "blind", "braille", "closed-captioning", "closed-captioning", "deaf", "low", "phone", "question-circle", "question-circle", "sign", "tty", "universal", "wheelchair"]

This is my haml code:

        %ul.list-inline
        - @x.each do |i|
          - if i[0].length < i[1].length
            %li            
              %i{:class=>"fas fa-#{i[0]} fa-2x"}
              %span.f6 #{i[0]}                      
          - else
            %li             
              %i{:class=>"far fa-#{i[1]} fa-2x"}
              %span.f6 #{i[1]} 

What i am trying to do, is to determine the length of each string in the list and compare it to the length of the next string in the list.

Once the second string is determined as being a duplicate, it should go under the else statement.

The problem i am facing, is that by going with i[0], instead of the first string in the list, i am getting the first letter of the each string in the list.

I don't know if my way of using length is the best way to solve this issue, so if anyone else has a better solution i am open for it, as long as it gets the job done.

I am thinking that maybe if i could filter the elements in the list based on which elements are unique and which are duplicates, i could then distribute them accordingly.

But how i do that?

Thank you.

Constraits to execute uml tools

I have designed UML diagrams in different tools such as plantUML. I am looking for a way to add condition to execute a part of the code. Is it possible ? For example, I will present only the first part if the input value is 1 and the second part if the value is 2, etc... Any idea please?

Function with IF ELSE doesn't work

I have a simple function:

new_function <- function(x)
 {
letters <- c("A","B","C")
new_letters<- c("D","E","F")

 if (x %in% letters) {"Correct"}
 else if (x %in% new_letters) {"Also Correct"}
 else   {x} 
 }

I make a dataframe with letters:

df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")

I want to apply the function on the dataframe:

  df$result <- new_function(df$Letters)

And it doesent work (the function only writes "Correct")

i get this warning:

Warning message: In if (x %in% letters) { : the condition has length 1 and only the first element will be used

Parse error: syntax error, unexpected 'if' (T_IF) on if statement [duplicate]

This question already has an answer here:

I am trying to update my database and im getting "Parse error: syntax error, unexpected 'if' (T_IF)" on my second if statement and i cant seem to find the error. Please do help me. Thank you.

Here's my code:

 <?php
include('../connect.php');

if (isset($_POST['update'])) {
    $name = $_POST['stockname'];
    $code = $_POST['stockcode'];
    $des= $_POST['stockdes'];

    $sql = mysqli_query($conn, "UPDATE SIInfo SET StockName = '$name', ProductCode='$code', StockDescription = '$des' ")

    **if ($sql)** {
        echo "<script>alert ('Record Updated!')</script>;";
        include ('../SI/selectSI.php');

    }else{
        echo "<script>alert ('Error! Failed to update.')</script>;";
        include ('../SI/selectSI.php');
    }


}     

?>

Use conditions in javascript [duplicate]

Can i use multiple if and then after an else like this ?

if(sky == 'blue') { ... }
if(sky == 'red')  { ... }
else { alert('Sky is not blue or red'); }

When do I need else if ?

Thanks.

Java If else Statement on String value, with Scanner input

I’m writing a program in the Java language, and I’m using if else statement. In this program i need to input word(s), i.e., alphabet character that has been assigned to be the values of the String data type. So that the program will print the sequential if statement, but is seems that program is not recognizing the input, because it keep printing only else statement. I need to know how to assign String values in Java language, import java.util.Scanner; on an if else Statement algorithm.

import java.util.Scanner;

public class Compare
{
    public static void main (String []args)
    {

        Scanner input = new Scanner(System.in);
        String name = “Henry”;
        System.out.println(“Enter a NAME”);
        name = input.nextLine();

        If ( name = “Henry”)
            System.out.println(“Welcome Henry”);
        else 
            System.out.println(“Invalid Input”);
    }
}

When i run it in CMD:

C:\CODE>java Compare
Enter a NAME:
Henry
Invalid Input

It doesn’t accept the String value “Henry” thats why the else statement keeps displaying “Invalid Input”.

Return value of cell if adjacent cell contains specific text?

I have 2 columns in Sheet 1 (named Projects), "Projects" in column A and "Status" in column B. The number of rows is dynamic.

In Sheet 2, I want to extract the projects that meet a certain string criteria and populate a table. For example, if the Status is "Operating", take the project name in column A for that row and put it in a table.

I tried =IF(Projects!B1:B="Operating",Projects!A1:A,"") but it returns the names of the projects in the same row position as in Sheet 1. So if there is a 2 row gap in Sheet 1 between two operating projects, it keeps the 2 row gap in Sheet 2.

How do I get rid of the gaps?

shoud I use 2 if's ou 1 AND operator?

My question is, what's the best way to verify two conditions?

In this case the conditions are not very long but what's the best pratice? Should I create 2 if's or should I use the AND (&&) operator?

Example:

if ( A > X AND  A > Y)
    code here...
ENDIF

Ou:

if ( A > X )
    if ( A > Y)
         code here...
    ENDIF
ENDIF

Java: How to return the correct value from an int[] array?

I'm new to Java (and programming in general), so apologies if some of this doesn't make sense and/or if the code is really bad:

I am trying get a unique four digit code from a user input (that is what the Keyboard.readInput line does), and I have put in a couple of conditional statements to ensure that the code that is entered can only be 4 digits and that each digit must be different to the other three.

The if statements work as intended in the sense that they output the error message and prompt them to re-enter (i.e. the method getPlayerGuess() gets called). For example, if the user enters 123 (i.e. userGuess.length() != 4), it will prompt them to enter again. If they then enter 1234, the method will complete.

However, the problem I have is that when I call this method in another class that I have, the code that is being pulled through is the first code entered (i.e. 123) and not the four digit one I want (i.e. 1234) - which is resulting in an arrayOutOfBoundsException.

Any ideas on how I can ensure that the code that is being returned is the four digit one that passes the conditionals, and not the first one entered?

public int[] getPlayerGuess() {

System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();

  if (userGuess.length() != 4) {
      System.out.print("Your code must be 4 digits - ");
      getPlayerGuess();
    }

    int[] userCode = createArrayFromGuess(userGuess);

    for (int i = 0; i < userCode.length-1; i++){
        for (int j = i+1; j < userCode.length; j++){
            if (userCode[i] == userCode[j]) {
                System.out.print("Code must have four unique digits - ");
                getPlayerGuess();
            }
        }
    }
    return userCode;
}

Performance difference between if(x) {return;} DoSth(); and if(!x) {DoSth();}

Just had to decompile my old code and i'm used to write it this way:

if(!x)
{
  DoSth();
}

but the decompiler always wrote it this way if there is no code after the snippet:

if(x)
{
  return;
}

DoSth();

Is there any performance advantage in calling return like in the lower code snippet or is it just a personal preference thing?

Code is taking half of my input

I am in a programming class to learn C++. We had to work on a if and else statement problem. Below is my code, and I am trying to figure out why it is halving it.

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

   int age;
   double price;
   char category;
   double finalPrice;

   cin >> price;
   cin >> age;
   cin >> category;

if (age <= 0) {
   cout << "Wrong input";
   }
if (age > 0 && age <= 5) {
   if (category != 'A' || 'a') {
      finalPrice = price - (( price * 100)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }

else if(category == 'A' || 'a') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
}

if (age > 5 && age <= 12) {
   if (category != 'B' || 'b') {
      finalPrice = price - (( price * 50)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'B' || 'b') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }   
   }

if (age > 12 && age <= 26) {
   if (category != 'C' || 'c') {
      finalPrice = price - (( price * 60)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'C' || 'c') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }      
}

if (age > 26 && age <= 60) {
   if (category != 'D' || 'd') {
      finalPrice = price - (( price * 70)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'D' || 'd') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
}

if (age > 60) {
   if (category != 'E' || 'e') {
      finalPrice = price - (( price * 80)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
   }
else if(category == 'E' || 'e') {
      finalPrice = price - (( price * 0)/100);
      cout << fixed;
      cout << setprecision(2) << finalPrice;
      }      
}

return 0;
}

So above is my code for a assignment for school.

When I enter the values 14.56 25 C I get an output of 5.8.2

However my expected output should just be 14.56

Am I just overseeing something? I don't get how it is even getting half.

Thanks!

mardi 28 août 2018

Don't display the specific empty column of row from database

I have a working code that can insert and update information from the database and echoing it to page. but I like to hide the specific empty column while displaying all the information from the row. check this screenshot my goal is to hide the "image" column when its null/empty; so the crock image wont display. here is my code below:

 <?php
    $result = mysqli_query($mysqli, "SELECT * FROM blogs ORDER BY id DESC");
    while ($row = mysqli_fetch_array($result)) 

    if (!empty($row['image'] != "")) 

    {
      echo "<div class='row'>
        <div class='col-lg-12 box'>
           <div class='content-heading'>
             <p>
                <text>".$row['title']."</text>
             </p>
           </div>

             <p>    
                <text1 class='pull-right' >".$row['image_text']."</text1><br/>
             <img class='img-size' id='hp'src='admin/upload_images/".$row['image']."'/>

             <text>".$row['definition']."</text> 
            </p>
          </div>
       </div>";     

   }
?>

but this code if (!empty($row['image'] != "")) is hiding all the row from my database. can anyone have the right code from my problem?

How to define new behavior for the if and else statements in C++

This is my first question on SO, so my apologies if it is poorly composed.

The project I am working on involves a class, let it be myClass, which is similar to a set, and I need to allow the programmer to compare objects of this type in a meaningful way.

What I would like to be able to do is something like this:

myClass a, b;
...
if (a == b)
{
    //execute code where a and b are implicitly used as
    // each of a and b's elements, respectively
}

and have my custom if statement execute the conditional code for each pair of elements from a and b, based on the condition performed on the pair of elements.

Here is a more concrete example:

myClass a = {1, 2}, b = {2, 3};

if (a == b)
    std::cout << a << " equals " << b << std::endl;
else
    std::cout << a << " does not equal " << b << std::endl;

Where the result would be (not necessarily in this order):

1 does not equal 2
2 equals 2
1 does not equal 3
2 does not equal 3

Currently, I have comparison operators overloaded to return a "comparison type" which simply stores the two operands and the comparison function for lazy evaluation. Is there a way to accomplish this custom if/else behavior so that it occurs whenever an if statement receives a parameter of type "comparison type?" Or is it necessary to just define a regular function which accepts an object of this type and a reference to a binary operator function as the conditional code?

I saw this question, but simply defining a conversion to bool will not work in this case. C++ 'overloading' the if() statement

Calling a function within an elif statement [duplicate]

This question already has an answer here:

I know it's not the best way to write code, but I would like to fix what I have- not necessarily change the entire thing. I know there are parts where the code will stop since I haven't created anything else for it. At this point what I would like to fix is that once I call the initial_username function, and I enter N as the input for the confirm variable, it still prints what is under the if statement rather than calling the function within the elif statement.

def wrong_data():
    print("I'm sorry, I didn't get that.")
    fix_name()

def fix_name():
    print("Let's try that again.")
    fn_error= input('Please re-enter your first name: ')
    ln_error= input('Please re-enter your last name: ')
    second_confirm= input('Is your full name ' + str(fn_error) + ' ' + str(ln_error) + '? Please enter Y or N: ')
    if second_confirm== 'Y' or 'y':
        print('Thank you, ' + str(fn_error) + ' ' + str(ln_error) + '.')

def initial_username():
user_fn= input('Please enter your first name: ')
user_ln= input('Please enter your last name: ')
confirm= input('Is your full name ' + str(user_fn) + ' ' + str(user_ln) + '? Please enter Y or N: ')
if confirm == 'Y'or 'y':
    print('Thank you, ' + str(user_fn) + ' ' + str(user_ln) + '.')
elif confirm == 'N' or 'n':
    fix_name()
else:
    wrong_data()

initial_username()

Julia: check if is a vector of numbers

I'd like to check if my vector / array is made of numbers.

I've tried:

if isa(x, Array{Number}) println("yes") end

But it doesn't seem to work...

Else vs new IF - Readability and Performance

I'm working in C# using Visual Studio and have been going over my code trying to improve its readability. I came across this site, that lists 15 best practices. #7 - Avoid Deep Nesting, it talks about If statements and says instead of using Else, make another If statement.

This got me wondering about the difference in the instructions between the two. Would using additional If statements cost more performance than just using Else?

Example:

if(condition)
{
    actions;
}
else
{
    actions;
}

OR

if(condition)
{
    actions;
}

if(condtion)
{
    actions
}

Any advice would be appreciated

If condition is being met when it should not be

I am running an if-statement to check if a file upload input is not empty. I am checking the fileNameVal with the following code if (fileNameVal != null) {. It seems to be always running true when it should not if a file input does not have anything within it.

The fileShow.text() code line is always displaying.

If you need to see this live, visit here.

Does anyone see what I am doing wrong?

var fileShow = $('#fileUploadMessage');
fileShow.hide();
var fileNameVal = '';

$('#uploadedFileTest').change(function () {
    fileNameVal = $('#uploadedFileTest').val();
    console.log(fileNameVal);
});


$("form#submit").submit(function (e) {
    $.LoadingOverlay("show");
     if (fileNameVal != null) {
        fileShow.text('Please wait while your file uploads.');
        fileShow.show();
    }
});

CSS

#fileUploadMessage {
    position: fixed;
    bottom: 20vh;
    left: 50%;
    -webkit-transform: translateX(-50%);transform: translateX(-50%);
    color: #000;
    font-size: 3rem;
    font-family: 'Muli', sans-serif;
    letter-spacing: .2rem;
    text-align: center;
    display: block;
    z-index: 9999999999999999999999999999999999999;
}

HTML

<form action="" method="POST" id="submit">
    <input id="first_name" type="text">
    <input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple>
    <p id="fileStatus">Upload File</p>
    <button type="submit">SEND</button>
</form>
<p id="fileUploadMessage"></p>

Why changing the "if" condition give different answers when I use === instead of !==?

The function checks if array elements are same, if they are same it should return true.

When I use the function below, it gives the correct result.

var arr = [1, 2, 3, 4];

function isUniform(arr) {
  var store = arr[0];

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] !== store) {
      return false;
    }
  }
  return true;
}
console.log(isUniform(arr));

But when I use the function like this i.e; changing the if condition, it returns false

var arr = [1, 2, 3, 4];

function isUniform(arr) {
  var store = arr[0];

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === store) {
      return true;
    }
  }
  return false;

}

console.log(isUniform(arr));

SQL stuck on and else syntax error

I'm running into an ELSE syntax error and would really appreciate a 2nd set of eyes to show me what is wrong! I'm using SSMS v17.3. The message I am receiving is:

Msg 156, Level 15, State 1, Line 98

Incorrect syntax near the keyword 'ELSE'.

Line 98 is the last ELSE before the go. About 6 lines above the end of the entire statement. Thank you in advanced!

DECLARE @GroupID uniqueidentifier
DECLARE @fCompID int
DECLARE @fPropID int
DECLARE @fCompGUID uniqueidentifier

Set @GroupID = 'E63DC5E7-C8C8-4EA3-B1BF-75712DD83EF4'
SET @fCompID = '0'
SET @fPropID = '0'

WHILE @fCompID <= '999'
    BEGIN
    IF @fCompID = (SELECT fID FROM tSCCompany WHERE fID = @fCompID)
        SET @fCompGUID = (SELECT fCompanyID FROM tSCCompany WHERE fID = @fCompID)
        WHILE @fPropID <='999'
            BEGIN
            IF @fPropID = (SELECT fID FROM tSCProperty WHERE fID = @fPropID AND fCompanyID = @fCompGUID)
                BEGIN
                INSERT INTO zPropTest(fGroupID, fPropertyID)
                    Select @GroupID, (select fPropertyID from tSCProperty where fID = @fPropID AND fCompanyID = @fCompGUID)
                SET @fPropID = @fPropID + 1
                END
            ELSE
                BEGIN
                SET @fPropID = @fPropID + 1
                END
            END
    ELSE
        BEGIN
        SET @fCompID = @fCompID + 1
        SET @fPropID = '0'
        END
    END
GO

ESXi shell scripting getting rid of a message

I'm working on a small VMware ESXi project (personal project, not for any company). Im trying to build a html file that contains a table with some information from ESXi OS, like time/date, OS version, patch number, etc. However there are some commands that give no output and then my table has an empty box (cell). What i am trying to do..and terribly failing at ...is that i am trying to put a simple if-else-fi statement in the shell script that would check if the output is empty or not. Here is the command i use the check if there is an output to the command or not:

if [ $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}') != " "  ]; then echo "Not Empty!"; else echo "Empty!"; fi

The problem with this is, that while it gives the correct result, it also prints out the following:

sh:  : unknown operand
Empty!

Yes, the result is supposed to be "Empty!", but i cant get rid of the "sh: : unknown operand" message. It seems it does not like that the != operand is not close to ")".

If however i put the "!=" operand close to the ")", like this:

if [ $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}')!=" "  ]; then echo "Not Empty!"; else echo "Empty!"; fi

..it no longer gives the "sh: : unknown operand" message but it gives the wrong result "Not Empty!". If however i insert a command in the if-else-fi statement that gives an output, for example:

if [ $(esxcli system time get) != " "  ]; then echo "Not Empty!"; else echo "Empty!"; fi

..it give no "sh: : unknown operand" messages and gives the correct result as "Not Empty!"

I have tried in the following ways but it gave the same "sh: : unknown operand" message:

if [[ $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}') != " "  ]]; then echo "Not Empty!"; else echo "Empty!"; fi

if [ -n $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}') ]; then echo "Not Empty!"; else echo "Empty!"; fi

if [ -z $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}') ]; then echo "Not Empty!"; else echo "Empty!"; fi

if "$(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}')" == " " ; then echo "Not Empty!"; else echo "Empty!"; fi

if $(esxcli hardware ipmi bmc get |grep -i gate |awk '{print $2}')==" "; then echo "Not Empty!"; else echo "Empty!"; fi

How can i get rid of that message...What else can i do?

php if else statement not echoing else

I'm trying to echo Norwegian language if there is a xmllang="no" if not echo "noname". Like

000000000121698001,text 000000000121699001,noname

But this is only returning all productids that have a xmllang="no" and not printing productid with no xmllang="no"

XML

<catalog>
<product productid="000000000121698001">
    <displayname xmllang="da">text</displayname>
    <displayname xmllang="fi">text</displayname>
    <displayname xmllang="no">text</displayname>
    <displayname xmllang="sv">text</displayname>    
</product>

<product productid="000000000121699001">
    <displayname xmllang="da">test</displayname>
    <displayname xmllang="x-default">test</displayname>
    <displayname xmllang="sv">test</displayname>
</product>

PHP

foreach ($xml->product as $product) {


foreach ($product->displayname as $name) { 
switch((string) $name['xmllang']) {
case 'no':


  echo $product->attributes()->productid. ",";

  if (isset($name)){
    echo $name. ",", PHP_EOL;
    } else {
    echo 'noname ,';
    }
  echo "<br>\n";
    }
}

}

Updating data in a cell with data from another cell when a specific outcome is reached

I am trying to make it so that when one cell (B1) reaches a value of 0, A1 which is text entered by user, is now replaced with the data in C1 which is also data entered by the user. Meaning that formulas cannot be placed in either A1 or C1 as they are data inputted by user (B1 already has formula calculating its value.)

Instinctly I want to use =IF(B1=0,A1=C1,"") but obviously that doesn't work as A1 = C1 is checking if they equal each other, not replacing A1 with C1.

There's probably going to be a simple solution to this but I cannot figure out a way to make it work.

Java: Finding out if all numeric fields of an object are 0

I have a java-8 class:

  class MyClass{
    double field1;
    double field2;
    int field3;
    ...
    float fieldN;

    boolean isEmpty() {
        // I want to implement this such that if all my numeric fields are 0's then return true else false
    }

}

What would be the most elegant way of implementing isEmpty() instead of adding many different if(fieldX == 0 ) conditions in there ?

change class in javascript by d3 select and filter

I have a function like below.

First, I change all class to "badge badge-secondary". Then, check text in span. If it is "right" and clicked, then change to "badge badge-primary". Else, it is "wrong" and clicked, changing to "class", "badge badge-danger".

Can I make my code more concise and righter?

function updateOrderType(ansType) {
    lastAnsType = ansType;
    var ansBadge = d3.select("#anstype").selectAll("span.badge");
    ansBadge.attr("class", "badge badge-secondary");
    ansBadge.filter(function() {
        if (d3.select(this).text() == ansType) {
            return d3.select(this).text() == "right";
        }
    }).attr("class", "badge badge-primary");
    ansBadge.filter(function() { 
        if (d3.select(this).text() == ansType) {
            return d3.select(this).text() == "wrong";
        }
    }).attr("class", "badge badge-danger");
}

R if statement with condition >1 length error

I'm trying to run an if statement, where I want to run something IF any of 23 values is below a certain value.

   test.df<-as.data.frame(c(1:50))
   if (test.df[,c(27:50)] <30){ print("hi")}

I get the error that the condition has length > 1 and only the first element will be used. Which is true... Does anyone know how I can test this if statement for 23 values, whithout having to type them one by one?

Thanks!

Java Script/jQuery – Simple if-statement not working with pre-defined variable

Sorry, I'm kind of new to this.

Is there a specific reason, why the if-statement in this snippet is not working? If yes, could somebody point me in the right direction?

var app = (function(){
   selector = {
       app: ".js-app",
       app__home: ".js-app__home"
   }

   foo();

   foo = function () {
     console.log(selector.app__home);
     if ($(selector.app).hasClass(selector.app__home)) {
        console.log("is home page")
     }
   }       
})();

$(document).on("ready", function() {
   app();
});

The first console.log()-output (the one outside the if-statement) works correctly though. Thanks!

golang if initialization statement scoped to inner if block. Why?

I've found a bug in my code

func receive() (err error) {
    if v, err := produce(); err == nil {
        fmt.Println("value: ", v)
    }
    return
}

Error is never returning from this function, but I was absolutely sure it should.

After some testing I understood that err is redeclared in the if statement. More than that - all variables are always redeclared in short variable assignment inside if statement, despite they were declared before.

This is working code

func receive() (err error) {
    v, err := produce()
    if err == nil {
        fmt.Println("value: ", v)
    }
    return
}

Here is an example: https://play.golang.org/p/1AWBsPbLiI1

Seems like if statement

//some code
if <init_statement>; <expression> {}
//more code

is equivalent to

//some code
{
    <init_statement>
    if expression {}
}
//more code

So, my questions:

1) why existing variables are not used

2) why such scoping is not mentioned in documentation/language spec

3) why compiler doesn't say that no one returns a value

Python - is there a more elegant way of writing these if statements

I have a plot on which I want to plot either diagram A, or diagram B, or both.

Currently my structure is:

if bool_A:
 plot A
 if bool_B:
  plot B
elif bool_B:
 plot B
 if bool_A:
  plot A

Is there a more concise / more elegant way?

lundi 27 août 2018

SSRS - Using Expressions with "If" statements and multiple parameter values

So I'm trying to set up some dynamic text for a report in SSRS with 4 user parameter fields and I keep running into the same error. I'm still pretty new to SSRS and Visual Basic, so it's a bit hard to understand the error message.

System.Web.Services.Protocols.SoapException: The Value expression for the textrun 
‘Textbox2.Paragraphs[2].TextRuns[1]’ contains an error: [BC33104] 'If' operator
requires either two or three operands.

The 4 parameter fields are beginYear, beginMonth, endYear, & endMonth. The following is the code I have in the expression:

If (bYear = eYear) And (bMonth = 1) And (eMonth = 3)
"3rd Quarter January - March " & eYear

ElseIf  (bYear = eYear) And (bMonth = 4) And (eMonth = 6)
"4th Quarter April - June " & eYear

ElseIf  (bYear = eYear) And (bMonth = 7) And (eMonth = 9)
"1st Quarter July - September " & eYear

ElseIf  (bYear = eYear) And (bMonth = 10) And (eMonth = 12)
"2nd Quarter October - December " & eYear

ElseIf  (bYear = eYear) And (bMonth = 1) And (eMonth = 12)
"Calendar Year " & eYear

ElseIf  (bYear = eYear) And (bMonth = eMonth)
eYear & " " & eMonth 

ElseIf  (((Convert.toInt32(bYear)) = (Convert.toInt32(eYear)) - 1) And (((Convert.toInt32(eYear)) = (Convert.toInt32(bYear)) + 1) And (bMonth = 7) And (eMonth = 6)
"Fiscal Year " & bYear & "-" & eYear

Else
             bMonth & " " & bYear & "-" & eMonth & " " & eYear
End If

So if I selected the following parameters from the report as follows (in the month parameters, I assigned numerical values to months):

-Begin Year=2018
-Begin Month=April
-End Year=2018
-End Month=June

I should see the following expression in the text box of the report => "4th Quarter April - June 2018"

Selecting one of multiple values that satisfy a condition

So I have this data frame of a condition column and a value column. Suppose I want to change one of the values for which the condition is satisfied, but not all of the values for which the condition is satisfied. The idea here is that I would like to change the values one by one (or select one randomly).

df <- data.frame(condition = c(TRUE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE),
                 value = 8:1)

I would like to store this in a new column. Suppose I randomly select row 2: The condition is TRUE and the original value is 7. I change it to 0 (or some other value). The desired output in this case is:

> df
condition value
1      TRUE     8
2      TRUE     7
3      TRUE     6
4      TRUE     5
5     FALSE     4
6     FALSE     3
7     FALSE     2
8     FALSE     1

I suppose I could do this with an if statement, a third column of group-row-numbers and the sample function, but is there a nicer way? In particular, I need to make sure I do not generate a new column in case the condition is not satisfied for any of the values. Otherwise I am wasting a lot of computing time later on in the analysis. I usually do things inside the tidyverse if I can, but I do not mind if there is a nice solution without using the package (or using a different package). Thanks!

If chained - how to delete?

I'm doing an application where I have the following scenario:

I have several rules (business classes)

where they all return the client code. They are separate classes that will look for the code trial and error, if find the client code returns it and so on.

How can I use a rule without using a bunch of IFs or threaded IFs in the class that calls the others that contains the specific business rules?

For the specific classes, I used the design pattern strategy.

EX: Main Class

  public abstract class Geral
{
    public abstract string retornaCodigo(Arquivo cliente)
    {
        var codigo = "";   // logica  

        return codigo;
    }

}

//Classe derivada 1


public class derivada1 : Geral
{
    public override string retornaCodigo(Arquivo cliente)
    {

        var codigo = "";  // logica  

        return codigo;
    }

}

//Classe derivada 2



public class derivada2 : Geral
{
    public override string retornaCodigo(Arquivo cliente)
    {

        var codigo = "";    // logica 2 

        return codigo;
    }

}

//Classe derivada 3



public class derivada3 : Geral
{
    public override string retornaCodigo(Arquivo cliente)
     {

         var codigo = "";  // logica 3 

       return codigo ;
     }

}


//Classe de Negocio 



public class Negocio
{

    public string Codigo()
    {
        var arquivo = new Arquivo();
        var derivada1 = new derivada1().retornaCodigo(arquivo);

        var derivada2 = new derivada2().retornaCodigo(arquivo);
        var derivada3 = new derivada3().retornaCodigo(arquivo);


        if (derivada1.Equals(null))
        {
            return derivada1;
        }
        if (derivada2.Equals(null))
        {
            return derivada2;
        }

        if (derivada3.Equals(null))
        {
            return derivada3;
        }
        return "";
    }
}

what I wanted and that I did not have to use Ifs in the Business class for validation whether or not I found the code where it can fall under any condition gave example of 3 classes plus I have more than 15 conditions and can increase, case would be many Ifs.

Code Rewite for tuple and if else statements by using LINQ

In my C# application i am using linq. I need a help what is the syntax for if-elseif- using linq in single line. Here is the code:

        var Date1 = RangeData.ToList();

        foreach (var tr in Date1)
        {
           int id =0;

            if (tr >0)
            {
               id =1;
            }
            else if (tr >3)
            {
               id =2;
            }
            if (id > 0)
            {
                //
            }
        }

shell script missing semicolon in if statement and no syntax error?

Someone pointed out a missing semicolon in a simple shell script and I'm curious why it's not throwing a syntax error.

Full script:

interval () {
    INTERVAL="$*"
    WHEN_TO_RUN=0
    while read LINE; do
        if (( $(epoch 0S) >= $WHEN_TO_RUN )) then
            echo $LINE
            WHEN_TO_RUN="$(epoch $INTERVAL)"
        fi
    done
}

line in question:

if (( $(epoch 0S) >= $WHEN_TO_RUN )) then

I'm also confused as to why the parens make that line work, when I'd normally expect:

if [ $(epoch 0S) -ge $WHEN_TO_RUN ]; then

on OSX if relevant

How to write python code independent of code's position?

I am new in python and using Spyder for scripting. I have some python codes for nested if-else (multiple statements). But the problem is same code may give different outputs if someone shifted the codes. Following is an example of that kind of situation.

num1 = -1
num2 = -2

if(num1 > 0):
    if(num2 < 0):
        print("num1 +ve")
        print("num2 -ve")
elif(num2 < 0):
    print("num1 -ve")
    print("num1 -ve")
else:
    print("num1 -ve")
    print("num2 +ve")

# num1 -ve
# num1 -ve


if(num1 > 0):
    if(num2 < 0):
        print("num1 +ve")
        print("num2 -ve")
    elif(num2 < 0):
        print("num1 -ve")
        print("num1 -ve")
else:
    print("num1 -ve")
    print("num2 +ve")

# num1 -ve
# num2 +ve

Can I use any parenthesis or something like that so that code shift do not effect the output?

filtering data in array

I have an array, of type myClass, got (status, description_1, description_2, .. till 6, duration_1 ... till 6, fromDay_1 to 6, toDay_1 to 6 fromTime_1 to 6 toTime_1 to 6) these data all in String format: data Example:

    "status" : "present",
    "description1": "2P MTR M-F 7:30-16:00",
    "description2": "2P MTR M-F 18:30-20:30",
    "description3": "2P MTR SAT 7:30-20:30",
    "description4": "2P SUN 7:30-18:30",
    "duration1": "120",
    "duration2": "120",
    "duration3": "120",
    "duration4": "120",
    "endtime1": "16:00:00",
    "endtime2": "20:30:00",
    "endtime3": "20:30:00",
    "endtime4": "18:30:00",
    "fromday1": "1",
    "fromday2": "1",
    "fromday3": "6",
    "fromday4": "0",
    "starttime1": "07:30:00",
    "starttime2": "18:30:00",
    "starttime3": "07:30:00",
    "starttime4": "07:30:00",
    "today1": "5",
    "today2": "5",
    "today3": "6",
    "today4": "0"

I have a 3000 data set. I need to output a different result for each set for example :

if (current time between fromTime_1 and toTime_1) and (current week day between fromDay_1 and toDay_1) output: description_1 else if (current time between fromTime_2 and toTime_2) and (current week day between fromDay_2 and toDay_2) output: description_2. and so on for all the 6 conditions.

The other part is I also wanted to display different img on the screen for below conditions:

if (current time between fromTime_1 and toTime_1) and (current week day between fromDay_1 and toDay_1) and status = Unoccupied "but i need to check if the status is = present" and duration_1 = 15 "but duration might be 60 or 120 or 240 and that is output a different img in regarding to the time and the status" output: imgGreen

else if ... same for all 6 conditions. What is the best way to filter my data, I have not much experience in this type of data filtering so please help. Thanks in advance.