jeudi 31 décembre 2015

Want to Assign Char Value using if condition - C Language

i am practicing to make a marks sheet where i want to assign subjects grade in a variable using if condition

here eper is subject percentage that i want to check and store it accordingly in a variable.

if(eper >=80){  
    geng = "A";
}

please do not confuse me with arrays n loops as i am in a learning phase & i am still at beginners level who has not studied Loops n arrays yet

Explain conditional html / javascript / css / other language code with PHP if/else

I understand that the below control flow works. My question is more conceptual: How does line 2 or line 4 run as just HTML in the midst of a PHP if/else without needing any echos or other PHP syntax? And if the condition is false, how does PHP just pick up later on at the else? I guess i'm just baffled at how the code makes sense and that it actually works.

1  <?php if (condition): ?>
2  //html code to run if condition is true
3  <?php else: ?>
4  //html code to run if condition is false
5  <?php endif ?>

Shortening the code

Is there any way to shorten this code? It works well, there just has to be a way to make it look better.

#d=69+12*log(2)*(f/440)
#d is midi, f is frequency
import math
f=raw_input("Type the frequency to be converted to midi: ")
d=69+(12*math.log(float(f)/440))/(math.log(2))
d=round(d)

The upper part is the converter, and the lower area is the area that needs to be shortened up...

if d==127:
    print("G")
elif d==126:
    print("F#")
elif d==125:
    print("F")
elif d==124:
    print("E")
elif d==123:
    print("D#")
elif d==122:
    print("D")
elif d==121:
    print("C#")
elif d==120:
    print("C")
elif d==119:
    print("B")
elif d==118:
    print("A#")
elif d==117:
    print("A")
elif d==116:
    print("G#")
elif d==115:
    print("G")
elif d==114:
    print("F#")
elif d==113:
    print("F")
elif d==112:
    print("E")
elif d==111:
    print("D#")
elif d==110:
    print("D")
elif d==109:
    print("C#")
elif d==108:
    print("C")
elif d==107:
    print("B")
elif d==106:
    print("A#")
elif d==105:
    print("A")
elif d==104:
    print("G#")
elif d==103:
    print("G")
elif d==102:
    print("F#")
elif d==101:
    print("F")
elif d==100:
    print("E")
elif d==99:
    print("D#")
elif d==98:
    print("D")
elif d==97:
    print("C#")
elif d==96:
    print("C")
elif d==95:
    print("B")
elif d==94:
    print("A#")
elif d==93:
    print("A")
elif d==92:
    print("G#")
elif d==91:
    print("G")
elif d==90:
    print("F#")
elif d==89:
    print("F")
elif d==88:
    print("E")
elif d==87:
    print("D#")
elif d==86:
    print("D")
elif d==85:
    print("C#")
elif d==84:
    print("C")
elif d==83:
    print("B")
elif d==82:
    print("A#")
elif d==81:
    print("A")
elif d==80:
    print("G#")
elif d==79:
    print("G")
elif d==78:
    print("F#")
elif d==77:
    print("F")
elif d==76:
    print("E")
elif d==75:
    print("D#")
elif d==74:
    print("D")
elif d==73:
    print("C#")
elif d==72:
    print("C")
elif d==71:
    print("B")
elif d==70:
    print("A#")
elif d==69:
    print("A")
elif d==68:
    print("G#")
elif d==67:
    print("G")
elif d==66:
    print("F#")
elif d==65:
    print("F")
elif d==64:
    print("E")
elif d==63:
    print("D#")
elif d==62:
    print("D")
elif d==61:
    print("C#")
elif d==60:
    print("C")
elif d==59:
    print("B")
elif d==58:
    print("A#")
elif d==57:
    print("A")
elif d==56:
    print("G#")
elif d==55:
    print("G")
elif d==54:
    print("F#")
elif d==53:
    print("F")
elif d==52:
    print("E")
elif d==51:
    print("D#")
elif d==50:
    print("D")
elif d==49:
    print("C#")
elif d==48:
    print("C")
elif d==47:
    print("B")
elif d==46:
    print("A#")
elif d==45:
    print("A")
elif d==44:
    print("G#")
elif d==43:
    print("G")
elif d==42:
    print("F#")
elif d==41:
    print("F")
elif d==40:
    print("E")
elif d==39:
    print("D#")
elif d==38:
    print("D")
elif d==37:
    print("C#")
elif d==36:
    print("C")
elif d==35:
    print("B")
elif d==34:
    print("A#")
elif d==33:
    print("A")
elif d==32:
    print("G#")
elif d==31:
    print("G")
elif d==30:
    print("F#")
elif d==29:
    print("F")
elif d==28:
    print("E")
elif d==27:
    print("D#")
elif d==26:
    print("D")
elif d==25:
    print("C#")
elif d==24:
    print("C")
elif d==23:
    print("B")
elif d==22:
    print("A#")
elif d==21:
    print("A")
elif d==20:
    print("G#")
elif d==19:
    print("G")
elif d==18:
    print("F#")
elif d==17:
    print("F")
elif d==16:
    print("E")
elif d==15:
    print("D#")
elif d==14:
    print("D")
elif d==13:
    print("C#")
elif d==12:
    print("C")
elif d==11:
    print("B")
elif d==10:
    print("A#")
elif d==9:
    print("A")
elif d==8:
    print("G#")
elif d==7:
    print("G")
elif d==6:
    print("F#")
elif d==5:
    print("F")
elif d==4:
    print("E")
elif d==3:
    print("D#")
elif d==2:
    print("D")
elif d==1:
    print("C#")
elif d==0:
    print("C")

If an 'if' statement is true, add it to the list of true ones, else ignore it

I'm trying to make a matching thing. If the 'if' statement like this

  $name = "how"; // <<<this is an input
if(preg_match(  "/(How|my|brain|works)/i",$name)){
                        $result1= "this is one of the results";
}else{
          $result1= " ";

I'm planing to store the results that if there's an actual match, it would display the first message, it might sometimes be pictures. The problem is how I can make it so that when I later do the match and if it's not true it wouldn't have a blank page. How can I skip over it. If for example I'm doing a list and there's about 5 that match with the input, it would display the 5 input instead of showing 10 list. The list would probably look like this

<ul>
  <li><?php echo $result1 ?></li>
  <li><?php echo $resutl2 ?></li>
  <li><?php echo $match10    // and so on ?></li>
</ul>

How can I make it so that it skips over for example match 9 because it's equal to space or display it because it's not equal to space. The problem is that it would list out all 3 and if match9 is equal to space, it would display space and I want it to skip over those.

Jekyll categories causing problems with "if / then" statements

I have a jekyll post with YAML Front Matter like so:

---
layout: post
title:  "Insulation"
categories: build-manual
variable: build-manual // this is just for troubleshooting purposes
---

You would think on the post's page I could write a simple liquid if / then statement using the current post's category. Something like this:

{% if page.categories == 'build-manual' %}
Hey I am in build-manual category
{% else %}
No I am not in build-manual category
{% endif %}

For some reason, this does not work. I receive the output: "No I am not in build-manual category"

To make it more confusing, if I change "page.categories" to "page.variable" it works. I receive the output: "Hey I am in build-manual category"

Any ideas on why it's not recognizing the categories?

PHP day and time if/elseif not working

I put together a php to display a certain page based on whether or not we're open. test1.html is when we are open and test2.html is when we are closed. I saved the php as index.php.

When it executes, it only opens the else, which is the test2.html.

Can someone take a look at my code and see what's wrong with it? Thanks!

<?php
 $day = date('N') ;
 $time = date('H:i') ;

 if (($day <= '4') && ($time >= '7:00') && ($time <= '19:30')) 
 {
    echo readfile ("test1.html");
 }
 elseif (($day == '5') && ($time >= '7:00') && ($time <= '18:30')) 
 {
    echo readfile ("test1.html");
 }
 elseif (($day == '6') && ($time >= '7:00') && ($time <= '17:30')) 
 {
    echo readfile ("test1.html");
 }
 else
 {
    echo readfile ("test2.html");
 }
 ?>

if ifelse or what else?

I have a problem I couldn't find an answer to. Let's say I have the following:

x <- seq(1,1000,0.1)
y <- seq(1,1000,0.1)
a <- rnorm(100,50,5)
df <- data.frame(a)

and I want to loop over every line in my data frame and evaluate if it meets two conditions.

df$a[i] > x/2 & df$a[i] <= log(x) 
df$a[i] < log2(x)

For each condition I want to indicate the result in a new column on my data frame. I know that if statements can't go over vectors and ifelse takes one condition. My original problem is how to assign data in a graph based on fitted curve.

skips "if" statement in certain inputs

So i have done a program that encrypts input in the way Julius Ceasar did (adding to all letters a constant number).

The program seems to work fine until it reaches the z + 6 barrier, at which point it start to dismiss the if statement that will make the alphabet circular.

I just can't understand why it will stop working when it reaches that point.

This is my code:

#include <iostream>
using namespace std;

char encoded(char c, int k) {
    k %= 26; //too big numbers!
    c += k; //encrypt
    if (c > 'z')
        c = c-'z'+ 'a' -1; //circular alphabet
    c = c - 'a' +'A'; //uppercase
    return c;
}

int main () {
    int k;
    while (cin >> k) {
        char c;
        while (cin >> c and c != '.') {
            if ('a' <= c and c <= 'z') 
                cout << encoded(c,k);
            else if (c == '_') 
                cout << ' ';
            else 
                cout << c;
        }
        cout << endl;
    }
}

If someone can give me a clue on what is going on I would greatly appreciate it.

I'm Having trouble adding values to a ArrayList with methods

So basically my problem is in this program which i will explain better after i put it in

    package learning;
//This class has an important method that i have been working on called Dice6 don't delete

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class GameBoard {

    public static void main(String[] args) {

        System.out.println("Welcome To The Gameboard");
        System.out.println("What is your name player 1?");

        Scanner Scan = new Scanner(System.in);

        String ScanResult1 = Scan.nextLine();

        System.out.println("Well... " + ScanResult1 + " This is the Board");

        System.out.println("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~|");// Don't Question its
                                                        // placement its weird,
                                                        // but it works
        System.out.println("               |");
        System.out.println("               |~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");

        System.out.println("Lets start with a Dice Roll");

        System.out.println(ScanResult1 + " Got a Roll of " + Dice6(10));

        Scan.close();

    }

    static int Dice6(int y) {
        ArrayList<Integer> Dice = new ArrayList<Integer>();
        Dice.add(1);
        Dice.add(2);
        Dice.add(3);
        Dice.add(4);
        Dice.add(5);
        Dice.add(6);


        int DiceAmount = Dice.size();
        while (DiceAmount != 6) {
            DiceAmount= DiceAmount - 1;
            Dice.add(Dice.size() + 1);
        }
        Collections.shuffle(Dice);
        Collections.shuffle(Dice);
        Integer DiceResult = Dice.get(3);
        return DiceResult;
    }

}

Ok so the problem I'm having is from System.out.println(ScanResult1 + " Got a Roll of " + Dice6(10)); to the bottom of the program basically I'm trying to add Array values in the ArrayList by using the parameter 10.... what suppose to happen is there is suppose to be 10 values in the ArrayList depending on what i put in the parameter....I've tried a lot of things and done a lot of fixing, i ever did a for(blank x : Dice) to show all values and 10 didn't come up only the original 6....if any body has any idea how to solve this please tell me

strange return on python

I am writing an application on PyCharm in Python 2.6.6 and a strange return appears in this section:

if VAR1 != row2:
                    print "Hostname: %s" %VARNAME
                    print "Status 1: %s" %VAR1
                    print "Status 2: %s" %row2
                    print "%s != %s" % (VAR1, row2)

Return:

Hostname: SERV01
Status 1: 3
Status 2: 3
3 != (3L,)

Does somebody know what's happening here?

Multiple IFs with one else

I have a validation procedure in which I have to check conditions one by one and then throw error messages accordingly. To achieve this, I am using multiple if statements, and if all the conditions are false, I should execute a task.

Here's my code:

if(s1.equals("") || s2.equals("") || s3.equals("") || s4.equals("") || s5.equals("") || s6.equals(""))      
    Toast.makeText(getApplicationContext(),"Enter all Details first", Toast.LENGTH_SHORT).show();       
if(!s5.matches("[A-Za-z0-9]+"))     
    e5.setError("Username cannot contain special characters");      
if(s5.length()<6)
    e5.setError("Username must be a minimum of 6 characters.");
if(!(s3.contains("@")&& s3.contains(".")))
    e3.setError("Enter a valid Email Id");      
if(!s6.equals(s7))
    e7.setError("Passwords dont match");
if(s2.length()!=10)     
    e2.setError("Please enter a valid 10 digit number");        
else
{
    Validate v2=new Validate();
    v2.store_values(s1,s2,s3,s4,s5,s6,s8);
    v2.execute();
}   

The problem is that the else statement is associates only with the last if statement, and the previous 5 if statements work independently. Please note that I cannot use else-ifs, since all the fields should be validated. How should I solve this problem?

C# IF Statments Not Working in While Loop

 while (Loop == true)
            {
                Thread.Sleep(1000);
                tt = tt + 1;
                string myString = tt.ToString();
                MessageBox.Show(myString);
                if (Keyboard.IsKeyDown(Key.T))
                {
                    MessageBox.Show("Down");
                    if (Mouse.LeftButton == MouseButtonState.Pressed)
                    {
                         MessageBox.Show("Clicked");
                    }
                 }
            }

When i run the Program it Pops up, "1", But not the Other ones when i click The Buttons or mouse.... an does not re loop to Continue the count down....

Thanks-

mercredi 30 décembre 2015

Rock, Paper, Scissors game, Codecademy Javascript

I built this as part of completing the Codecademy Javascript lesson. I wanted to perfect it, make it readable and functional, and as efficient as possible. As far as I can tell it can't be any more efficient than this. But maybe I can't tell. What do you think? I know there are little things, maybe the victory variable should have a console.log in it. Probably one or two more. But hopefully this is a good example for people who need help with writing their Rock, Paper, Scissors challenge.

Cheers,

Rich

//Loop ensures only valid user input is rock, paper, scissors
var i, infiniteloop;
for (i=0; i<1; infiniteloop++) //infiniteloop allows loop to continue if user is infinitely retarded
{
    var userChoice = prompt("You're playing rock, paper, scissors against the computer. Type your choice in lower case letters.")
    if (userChoice === "rock") {i=1;} //escapes loop
        else if (userChoice === "paper") {i=1;} //escapes loop
        else if (userChoice === "scissors") {i=1;} //escapes loop
        else {alert("Try again, stupid.");} //alerts, loops back to start
}

console.log("You chose " + userChoice + "!"); //announces userChoice

//generate a random computer choice, assign a string to replace it
var computerChoice = Math.random(); //random function. generates a number between 0 and 1
if (computerChoice <= .33) { computerChoice = "rock"; }
    else if (computerChoice <= .66) { computerChoice = "paper"; }
    else { computerChoice = "scissors"; }

console.log("Computer chose " + computerChoice + "!"); //announces computerChoice

var victory = "You win! A master strategist is you." //preset victory announcement
if (userChoice === computerChoice) { console.log("Tie game!"); }
    else if (userChoice === "rock" && computerChoice === "scissors") { victory }
    else if (userChoice === "paper" && computerChoice === "rock") { victory }
    else if (userChoice === "scissors" && computerChoice === "paper") { victory }
    else {console.log("You have suffered a devastating loss.");}

Python: Filtering out sublist from list based on contents of entire sublist?

So here is what I have:

lst = [["111","101","000"]["1001","1100","1111"]["00","11","00"]]

And I want to filter out the sublists that contain only strings of "0"*len(string) and "1"*len(string). The result should look like this:

[["111","101","000"]["1001","1100","1111"]]

This seems like it should be fairly easy but I can't seem to figure it out! Help would be greatly appreciated!

else if statement - contains word remove or add class jquery

The last else if contains "Arriving" the string is actually "Arriving date" but I only want to find the first word and then do the logic for adding and removing classes. But I feel I'm not using the .length() correctly for this last one. can you guys help me understand how to test this correctly. the first two conditions work fine.

 jQuery("#custcolmen_size, #custcolmen-width").change(function () {

                               if($('.stock-message > span:contains("Out of stock")').length){ 
                                    $(".add2cart-div > input").addClass('disabled').removeClass('cart');
                                    $(".stock-message > span").addClass('alert alert-danger');
                                } 

                                else if($('.stock-message > span:contains("")').length) {
                                    $(".add2cart-div > input").removeClass('disabled').addClass('cart');
                                    $(".stock-message > span").removeClass('alert alert-danger');
                                 }

                                 else if($('.stock-message > span:contains("Arriving")').length) {
                                    $(".stock-message > span").addClass('alert alert-danger');
                                 }
                            });

Batch File For Creating .txt with computer names and Teamviewer Numbers

I have been trying to figure out how to get a list of computers and their team viewer IDs. At this point I have a file with computer names. The Batch file I started trying to write looks at that list of names creates a bridge to my machine then reports back the hostname and Teamviewer CLientID. The problem is that we have different versions of teamviewer installed and the location is not the same. When I run my batch file as it is it will give me teamviewer 7 CLientIDs but thats it. As this is my first batch file any help is greatly appreciated!

::Creates .txt file with hostname and Teamviewer ClientID on network location.

call net use x: \server\location (Password) /user:(UserName)

call hostname >> x:\TeamviewerID.txt

for /f "tokens=3" %%a in ('reg query HKLM\Software\Wow6432Node\TeamViewer\Version7 /v ClientID') do (set /a num = %%a) if %ERRORLEVEL% EQU 0 GOTO Print ELSE GOTO EIGHT

:EIGHT for /f "tokens=3" %%a in ('reg query "HKLM\Software\Wow6432Node\TeamViewer\Version8 /v ClientID"') do (set /a num = %%a) if %ERRORLEVEL% EQU 0 GOTO Print ELSE GOTO NINE

:NINE for /f "tokens=3" %%a in ('reg query HKLM\Software\Wow6432Node\TeamViewer /v ClientID') do (set /a num = %%a) if %ERRORLEVEL% EQU 0 GOTO Print

:Print echo Teamviewer ID is %num%>> x:\TeamviewerID.txt

call net use x: /delete

I want to include an If statement in my SQL script

I have this insert statement I wrote, but I want to test for null before I insert data into the database> Below is the code

use master
DECLARE @PriviledgeID uniqueidentifier
DECLARE @UserName uniqueidentifier 

SELECT @PriviledgeID=roleId 
FROM aspnet_Roles 
WHERE RoleName = 'Operator'

SELECT @UserName=USERID
FROM aspnet_Users
WHERE username = ments@point.com'


INSERT INTO aspnet_UsersInRoles
 VALUES(@UserName, @PriviledgeID )

My aim is to make sure I don't insert values of null into the database, how can I do this? Thanks.

storing something if the statement is ture

This is a simple code I can't figure out

if(preg_match(  "/where/","where's my backpack") == true){
      echo "this is a match";
                        // this is the part i cant figure out
                    // how can I store it as == $match1
                    // I tried $match1 == "this is a match"; but it didn't work   

                }else{
                //$match1= " "; << this what I tried and didn't work
       //when I say echo match1 later, it displays this is a match even when its wrong
        }

how can I store it as a variable or something for later. for example, if those two matches are true, store it as $match1 so that I can later say 'echo $match1' so that it displays "this is a match". if not just display a space.

the overall code is in php BTW

inserting the php sendmail fuction into a confirm button within a pop up box

I am trying to use the sendmail function in php threw a pop up box. i have gotten as far as making the sendmail function and the pop up to work separately. but i haven't been able to figure out how to connect the sendmail in the right way. below is the last working git version i have. any help would be wonderful.

{

    <th align="center">Instrument Serial Number:</th>
                        <td align="left"><input type="text" class="cInstTravText" name="SerialNumber" id="idSerialNumber"/></td>
                        <button onclick="drop_check()">comfirm</button>

                        <p id="drop_check"></p>
                    <script>
                        function sendEmail() 
                            {
                            $to = 'jonsrod1992@gmail.com'; 
                            $subject = 'Test email using PHP';
                            $message = "test";
                            //$message = 'hellow world.\n\n this is a test for fuctionality\n\n this is the first try\n place instrument serial Number here--> '<$modelNumber>'<-- there.'; 
                            $headers = 'From: jonr@twobtech.com' . "\r\n" . 'Reply-To: jonr@twobtech.com' . phpversion();
                            mail($to, $subject, $message, $headers, '-fwebmaster@example.com'); 
                        }
                        function drop_check() {
                            var x;
                            if (confirm("transfer and send email!") == true) {
                            x = "transfered and email sent!";
                            } else {
                            x = "You pressed Cancel!";
                            }
                            document.getElementById("drop_check").innerHTML = x;
                        }
                    </script>
                    </tr>

if-and statement isn't working c#

This is my first post here and I'm fairly new to C# so I apologize for the noob question. I'm doing if checks and when certain criteria are met either messages are displayed or a function is run. All of the if checks are working except the if ((textBox1.Text != "") && (textBox2.Text != ""))

The process just doesn't run. No errors. But if both statements are true it does nothing. I do have this check running at the end of the others, but there are no contradictions that would cause it to stop early that I can find. None of my other checks are being triggered.

Thanks in advance for any help.

C# - basic if statement inquiry - can't find the answer

this has probably been answered but i don't know how to frame the question, therefore can't find a past answer.

so what i wanna do is something like this: (more variables for the same if check)

if ((aa && bb && cc) == 1)
    {
       win = 1;
    }

what's the correct syntax for this?

thanks a bunch

Java: try-catch vs if-else for initialization: performance

I've heard it's a sin to use try-catch for anything that might be expected to happen in normal program flow, and that one should use if-else instead.

But, what about the case where we want to use it for initialization (an event that happens once and once only). You may want this when you initialization depends on the first incoming data, as in the following example:

class RunningVectorSum{

    double[] running_sum;

    public double[] add(double vec[]){

        try{
            for (int i=0; i<running_sum.length; i++)
                running_sum[i]+=vec[i];
        }
        catch(NullPointerException ex){
            running_sum = new double[vec.length];
            for (int i=0; i<running_sum.length; i++)
                running_sum[i] = vec[i];
        }
        return running_sum;
    }
}

In this case, should it be faster in the long run to use the try-catch vs using:

    public double[] add(double vec[]){
        if (running_sum==null)
            running_sum = new double[vec.length];
        for (int i=0; i<running_sum.length; i++)
            running_sum[i]+=vec[i];
        return running_sum;
    }

instead?

edit: Things I'm aware of:

  • Yes in this particular example, there's a possible problem if vec has a varying length
  • Yes I know this is a terrible sin.

Things I'm not aware of:

  • Why is it such a terrible sin?
  • Is it faster to always pass through a try (except once, which amortizes to nothing) than it is to always pass through an if(condition)

if else statement chatbot

I try to make a simple chat bot. So far the bot answer is user type in defined question. But how can I make it that the chatbot gives out a "sorry I don't understand" if user ask something that is not defined?

function ai(message){
            if (username.length<3){
                username = message;
                send_message("Nice to meet you " + username + ", how are you today?");
                responsiveVoice.speak("Nice to meet you " + username + ", how are you today?");
            }

            if (message.toLowerCase().indexOf("how are you")>=0){
                send_message("Thanks, Iam good!");
                responsiveVoice.speak("Thanks, Iam good!");
            }

r if statement returns number rather of level than the level text

I have a table like the following image and I'm trying to use a simple if statement to return the country name only in cases where food is "Oranges". The 3rd column is the desired outcome, the 4th column is what I get in R.

enter image description here

In excel the formula would be:

=IF(A2="Oranges",B2,"n/a")

I have used the following r code to generate the "oranges_country" variable:

table$oranges_country <- ifelse (Food == "Oranges", Country , "n/a")

[As per the image above] The code returns the number of the level (e.g. 6) in the levels list for 'Country' rather than 'Country' itself (e.g. "Spain"). I understand where this coming from (the position in the extract as below), but it's a pain particularly when using several nested if statements.

levels(Country)
[1] "California"  "Ecuador"     "France"      "New Zealand" "Peru"        "Spain"       "UK"  

There must be a simple way to change this???

HTML comment if without javascript

I know that I can display/hide content whether the browser is IE or not or even the version of IE. I was wondering if I can use other expressions too such as

<!--[if 1 == 0]-->
This should be hidden
<!--[endif]-->

The reason behind this is that I'm sending auto generated E-Mails and for me it would be easier to insert such comments in the template E-Mail instead of creating multiple templates.

Count how many times a conditional is true inside for loop with javascript

I'm banging my head against the wall with this, and I know it can't be that difficult. I have a for loop that runs over a range of cell values in a Google Apps script I'm trying to write, and each time it loops, it checks to see if a certain condition is true. If it's true, for the time being, it's logging the results to Logger.log().

I need the total number of results that show up in Logger.log() (in this case, it would be 10) and the best way I was able to think of doing that would be to count up by 1 each time that conditional is true in the for loop. It should be very simple to get a numerical value of how many results, but I'm inexperienced and have been searching for hours for anything that I think might be able to help me and I just can't figure it out. Here's the code I'm using.

var currentsheet = SpreadsheetApp.getActiveSheet();
var values = currentsheet.getRange("A28:E").getValues();

for (i=0; i<values.length; i++) {
if (values[i][3] === "Section 179 Depreciation") {
  var date = values[i][0];
  var amount = values[i][1];
  var desc = values[i][2];
  var expType = values[i][3];
  var notes = values[i][4];

 }
}

If someone could fill me in on what I'm missing, I would appreciate it very much!

mardi 29 décembre 2015

Objective C Logical OR operator not evaluating in block

I am trying to check which array element's values are equal to each other or to the NSNumber 10. The array has count 15. The problem is that when I test the value against NSNumber 10 in an if statement, the code does not seem to evaluate.

In the array below, for example, the code should return that the value in index 0 is present in indices {0, 9, 10} since NSNumber 1 is present in index 0 and 10 and NSNumber 10 is present at index 9.

1-2-3-4-5-6-7-8-9-10-1-2-3-4-5

However, it only evaluates whether the NSNumber value in index 0 is equal to NSNumber 1 and not to NSNumber 10. The output is not as expected {0, 9, 10} but only {0, 10}.

    for (NSNumber *number in mutableArray) {
            self.matchingIndex = [mutableArray indexesOfObjectsPassingTest:^BOOL(NSNumber *obj, NSUInteger idx, BOOL *stop) 

{

            BOOL returnValue;
            NSNumber *ten = [NSNumber numberWithInt:10];
            if ([number isEqualToNumber:obj] || [number isEqualToNumber:ten])
            {
                returnValue = TRUE;
            }

            return returnValue;  
        }];
        }

for loop inside a case statement

I am trying to execute a stop/start script on client machine from remote jump server. I want to run a for loop where it takes Jboss instance names and stop/start the instances one by one on client machine. The script is not able to get the instance names from the variable instance which is defined before the case statement.

#!/bin/bash
sudo su - username <<EOF
instance="instance1 instance2"
case $1 in
stop)
        case $2 in
        all)
                #STOP ALL JBOSS INSTANCES
                for i in $instance
                do
                echo "checking if $i instance on the server are running or not"
                f_isjboss $i | head -2
                if [[ $(ps -aef --width 2000 | grep 'run.sh' | grep "\-c $i " | grep java | grep -v grep | wc -l) -gt 0 ]]
                then
                echo "$i instance is running and script will kill the process"
                f_stopjboss $i
                echo "tailing the server.log file to make sure shutdown is complete"
                grep -m 1 "Shutdown complete" <(tail -f /opt/sw/jboss/jboss/jboss-eap-5.2/jboss-as/server/$i/log/server.log | tee /dev/tty);
                sleep 2s
                echo "$i Shutdown Command executed successfully and script will continue to next instance"
                else
                echo "$i instance is not running and script will continue to next instance"
                fi
                done
                ;;
        esac
        ;;

Razor ASP.NET: Show data from 'if' inside 'foreach'. 'break;' doesn't work

I'm having the following situation (in razor using ASP.NET):

@if(@groups.Users != null)
{
    @foreach(var user in @groups.Users)
    {
        @if(@user.UserId == VALUE)
        {
            CASE 01
            break;
        }
    }
    CASE 02

}
else
{
SHOW CASE 02
}

So all I want is CASE 01 if the Value is in the collection of @user.UserId. And else display CASE02.

But, because if there are no users in the group, then it should display CASE02 too. Pretty simple I thought.

Now this does not work (after it shows CASE 01, it also shows the CASE02(because of the else). Else the code works fine.

I tried putting another 'break;' after the CASE 02 in the if statement, but then it cuts off my code?

I think I'm just missing something here ...

I hope I explained it right? Thank you

Find div inside div

I want to find child3 is exists in parent2 or not. If child3 exists it will show alert "exists" otherwise "element doesnt exists". But it seems if/else statement not working. I use alert before if/else to test function working or not. Following is my code

<!DOCTYPE html>
<html>
<body>

<div class="parent1">
<div class="child1">Child1</div>
<div class="child2">Child2</div>
<div class="child3">Child3</div>
</div>

<div class="parent2">
<div class="child1">Child1</div>
<div class="child1">Child2</div>
</div>

<button onclick="find()">search</button>



<script>
function find()
    {
alert('testing function working');

if($collection.children().is(".child3")){ alert('exists');}

else{alert('Element doesnt exists');}
    }
</script>

</body>
</html>

Best way to refactor If-statement

I have the following code:

                            if (adSetting.Core_standard_application_role)
                            {
                                rc = new IntegrationRoleCompany();
                                rc.RoleCompany = firmSettings.FirmNo.ToString();
                                rc.RoleName = "Core standard application role";
                                rcList.Add(rc);
                            }
                            if (adSetting.Expense_Invoice_Application_Access)
                            {
                                rc = new IntegrationRoleCompany();
                                rc.RoleCompany = firmSettings.FirmNo.ToString();
                                rc.RoleName = "Expense Invoice Application Access";
                                rcList.Add(rc);
                            }

The problem is that I have 20 if-checks where I check addSetting.Property. Now to the question:

What is the best and most effective way to refactor this if-statements?

Mess with if php

Hi so I am trying to make a function which actually detects the time and depends on date(H); shows what courses and some other info happen right now.

$holidays = false;
//$hour = date('H');
 $hour = "11"; //Changed it to test the code

function classes()
{
    if ($holdays == false) //Are we on holidays? No
    {
        if($hour > "9" && $hour < "21") //University working hours? yes
        {   
            if ($hour = "10") //Hour 10? classes below
            { 
                echo "<tr>";
                    echo '<th class="course-title"><a href="course.html">...</a></th>';
                    echo '<th class="course-category"><a href="">...</a></th>';
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                echo "</tr>";
                //Another Class
                echo "<tr>";
                    echo '<th class="course-title"><a href="course.html">...</a></th>';
                    echo '<th class="course-category"><a href="">...</a></th>';
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                echo "</tr>";
               //Another Class
                echo "<tr>";
                    echo '<th class="course-title"><a href="course.html">...</a></th>';
                    echo '<th class="course-category"><a href="">...</a></th>';
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                    echo "<th>...</th>";
                echo "</tr>";
            }
            else{ //Hour not 10?
                echo "No classes right now.";
            }
        }
        else{ //Not working hours?
            echo "University closed at this time.</br>";

        }
    }
    else{ //Vacation?
            echo "University closed for vacation!";
    } 

}

So I setted $hour value to 11 so it will pass the first two ifs successfully and I expect that it will echo that there are no classes right now, but it returns that university is closed at this time. I may also mess up the } on the code.

PS: I know i am using to many echos I am not that experienced yet to go with strings

Python If(and) statement syntax error

I'm trying to make a simple console game in Python 2.7, where the user gets a dilemma and makes a decision by typing the number correlating to the option he wants to choose. This question is the main menu.

#imports
import os
import time

#classes
class question:
  def __init__(self, valid, alt):
    self.valid = valid
    self.alt = alt

#functions
def is_number(s):
  try:
    int(s)
    return True
  except ValueError:
    return False

def asker(question):
  #make it read out the question
  print(question.alt)
  #make it find the possible answers
  print(question.valid)
  #make it get the answer from the user and return it
  valid = False
  while(valid == False):
    q = question.alt
    v = question.valid
    s = raw_input("Enter a number in the range 1 to %s\n> " % v
    if (is_number(s) and s in q):           
        return s
        break
    elif (is_number(s) == False):
        print("Only numbers allowed.")
    else:
        print("That is not a valid number.")

menu =  question(["1: Start new game", "2: Load new game", "3: Settings"], 3)
asker(menu)

print("Congratulations on submitting a valid answer!")


raw_input("> ")

I'm getting a "SyntaxError: Invalid syntax" from the if (is_number(s) and s in q) statemet when trying to run the program. It was working fine before i added the question.

This is my first real program.

How to use if in applescript

Hi i am making a game application in applescript. But when i was done it said this "Expected end of line but found ":".". The code i used was

`display alert "By taping ok you accept the following rules: Do not hack, do not cheat, edit komponents or download our site to your desktop! If you do not follow these rules you could get banned"

if {button returned:"OK"}
tell application "/Applications/Safari.app"
open location http://ift.tt/1YQ6vku 
end tell`

Can anyone help?

stopping a nested javascript function running more than once

I'm trying to get a javascript function to run only once. I've seen this question has been asked before, e.g. Function in javascript that can be called only once, but I can't get the solutions in here to work. I'm not sure if it's because I've got nested functions, or whether there's something I'm missing. Essentially, I'm trying to run a function which, when a webpage is scrolled, it: - runs a little animation on a canvas in the header - reduces the size of the header - leaves it at that

But when there is any subsequent scrolling, the animation keeps re-running. Here's a summarised version of the non-working code:

$(document).on("scroll",function(){

    var arrange_title = function(){

        //some code 
    };

    if($(document).scrollTop()>0){ 
        arrange_title();
        arrange_title = function(){};
        setTimeout(function(){
            $("header").removeClass("large").addClass("small");
        },1000);
    }
});

I've also tried declaring a global variable, setting it to "false" in a "window.onload" function, then set it to true in an if function that runs the animation (the if function running only if the variable is false), but that doesn't stop it either. Thoughts?

Reading keystrokes from a keyboard and using if statement in Java [duplicate]

This question already has an answer here:

I am learning how to program in Java. I wrote the following code but, I can't get the if statements to work when the variable inputName is compared to a string and the statement is true. Does anyone have any tips on how to fix this?

import java.util.Scanner;
public class HelloWorld {

  public static void main(String[] args) {
    String x = ("Hello type in your first name.");
    System.out.println(x);
    Scanner keyboard = new Scanner(System.in);
    String inputName = keyboard.next();


    if (inputName == "erick") {
      System.out.println("Hi");
    }
    String v = "victor";
    if (inputName == v) {
      System.out.println("Hi");
    }
    String c = "christy";
    if (inputName == c) {
      System.out.println("Hi");
    }

    keyboard.close();
  }
}

VBA Conditional IF statement using WEEKDAY

I am trying to write a conditional IF statement based on the day of the week. column A has the date. Column AK has a weekend value, column AL has a weekday value. Need the correct value (depending on day of week) to flow into column AT. the code I came up with isn't working. All that's showing up in AT is the AK value. I'm pretty new to VBA, I'm definitely missing something. Thanks in advance for any help.

Sub Weekday()

For i = 2 To Cells(Rows.Count, "A").End(xlUp).Row

If Range("A" & i) = "=Weekday" Then 'This line of code doesn't work

Range("AT" & i).Value = Range("AL" & i).Value 'This line of code works

Else
Range("AT" & i).Value = Range("AK" & i).Value 'This line of code works

End If

Next

End Sub

R - Error in if (nrow(M) == 2) { : argument is of length zero

In following code:

    det<-function(M)
    {
        if (nrow(M) == 2)
        {
            return(M[1,1]*M[2,2]-M[1,2]*M[2,1])
        }
        else
        {
          d<-0
          for (i in 1:ncol(M))
          {
            d<-d+(-1)^(i+1)*M[1][i]*det(M[-1,i])
          }
          return(d)
       }
    }

to execute function I determined x<-matrix(c(1:9),nrow=3) when execute the function det(x) I get error: Error in if (nrow(M) == 2) { : argument is of length zero

Getting size and comparing attribute value from ArrayList in other class

I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you

    public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();

public ResultList() {
     ArrayList<Athlete> temp = new AthleteList().getArrayList();
}

void addResult() {
    int competetionNumber;
    System.out.print("What is the athletes competetionnumber?");
    competetionNumber = scanner.nextInt();
    scanner.nextInt();
    for (int i = 0; i < athletes.size(); i++) {

    }
}
}

Other class with the Athlete ArrayList:

    public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {

}
     public ArrayList<Athlete> getArrayList() {
     return athletes;
}

imacro if else statement javascript imacro

I am stucked here to get the if, else if, statements to work and ask for someone to help. I am using Javascript (scripting interface to iMacro) to accomplish the following executed from the javascript scripting interface. I have a .js file and a .iim file (recorded iMacro file). As you can see, I have big problems to get the if statement correct in the Javascript. Please help!

The end-to-end flow:

1) Check a website for a the word "maintenance".

a) If the word "maintenance" appears, iMacro will return a negative value (<0) and the macro shall start a .bat file

b) If the word doesnt appear, iMacro returns a positive value and the imacro shall continue

2) The imacro (.iim) continues and do an imagevalidation to compare image.

a) If no match on images, I macro returns a negative value (<0) and shall wait x seconds and restart the .iim file again (imacro1.iim)

b) If match on image , I macro returns a positive value (>0) and shall start another .iim-file (imacro2.iim)

My js-file:

' play macro
i = iim1.iimPlay("macro1.iim")

if i > 0 then
Set WshShell = WScript.CreateObject("WScript.Shell")
Command = "C:\start\start.bat"
WshShell.Run Command

else if
i = iim1.iimPlay ("CODE:IMAGESEARCH POS=1 IMAGE=20151228_1550.png     CONFIDENCE=95" > 0)

WScript.Sleep 10000

i = iim1.iimPlay("macro1.iim")

else 

i = iim1.iimPlay("macro2.iim")

end if

My .iim-file (macro1.iim)

URL GOTO=http://www.XXXXXX.com

WAIT SECONDS=5

TAG POS=1 TYPE=* ATTR=TXT:*maintenance* CONTENT=EVENT:FAIL_IF_FOUND

IMAGESEARCH POS=1 IMAGE=20151228_1550.png CONFIDENCE=95

How can i shorten this python code

i want to shorten this codes, all loop is acceptable. for, if(inside if), while, foreach, or another one.

I can not do it, please help me. codes is below:

def FindChannel():
rc_program_up = "Ch+"
rc_ok = "ok"
rc_exit = "exit"
value0 = checkPicture(15)

if (value0 == 100):
    send_rckey(rc_exit)
else:
    send_rckey(rc_program_up)
    value0 = checkPicture(15)

if (value0 == 100):
    send_rckey(rc_exit)
else:
    send_rckey(rc_program_up)
    value0 = checkPicture(15)

if (value0 == 100):
    send_rckey(rc_exit)
else:
    send_rckey(rc_program_up)
    value0 = checkPicture(15)

if (value0 == 100):
    send_rckey(rc_exit)
else:
    send_rckey(rc_program_up)
    value0 = checkPicture(15)

if (value0 == 100):
    send_rckey(rc_exit)
else:
    send_rckey(rc_program_up)
    value0 = checkPicture(15)

Batch code if date created is less than 24 hours

I have already written here for this problem, we solved it but now I have to add this "if the file was created in the last 24 hours copy it else don't". I have found several examples online but I just cant seem to be able to figure the Commant syntax out. I would really apreciate some help with this ... here is the website i found :

http://ift.tt/1OiJ0yW

and here is my code:

ECHO OFF
set ReadFolder1="C:\Users\ugrum\Desktop\new"    
set Destination="C:\Users\ugrum\Desktop\Zacasnamapa"
set sevenZipDir="C:\Program Files\7-Zip\7zG.exe"
set currentDate=%date%

IF NOT EXIST %Destination% MKDIR %Destination%

FOR /R %ReadFolder1% %%G IN (*_NOT*) DO (
    ECHO %%G 
    FOR %%f IN %%G DO SET filedatetime=%%~tf
    IF %currentDate% - %filedatetime:~0, 10% <= 24      
    XCOPY "%%G" %Destination% /C
)

%sevenZipDir% a -tzip neustrezne.zip %Destination%
RMDIR /Q /S %Destination%

PAUSE

I know the if is wrong but i have no idea how to get it right.

Excel 2007 Nested IF Statement

I need help your help. I have 3 columns as shown in the sample image.

I would like a formula for a nested IF statement in order to calculate the amount in local currency [Column C] by different rates for each currency Click For Sample

If statement not triggered even when equal to true

I have attempted to write a program which tells your BMI(Body mass index) and if you're over/under weighted or not when you enter your weight and height.

Everything went perfectly until the if-else statement, no matter what the "BMI" is it always displays "You are under weighted."

Ex:

Would you like to use Standard/U.S
Standard
Whats your weight?
200
What's your height?
50
Your BMI is 800
You are underweighted!

Here is the area I believe is causing the error:

if(which==0)
        { 
            int old = 1;
         for(double faf = 0;faf<=BMI2;faf=faf+0.5) 
         {
             double fof = 0;
             fof++;
             if(fof<37 && old!=0)   
             {
              System.out.println("You are underweighted!");
              old = 0;
             }
             else if(fof<50 && old!=0)
             {
              System.out.println("You are Normal Weighted!");
              old = 0;
             }
             else if(fof<60 && old!=0)
             {
              System.out.println("You are Overweighted!");  
              old = 0;
             }
             else if(fof>=60)
             {
              System.out.println("Obesity!");
              old = 0;
             }
         }
        }
         else if(which==2)
         {
             int old = 1;
             for(double faf = 0;faf<=BMI;faf=faf+0.5) 
             {
                 double fof = 0;
                 fof++;

                 if(fof<37 && old!=0)   
                 {
                  System.out.println("You are underweighted!");
                  old = 0;
                 }
                 else if(fof<50 && old!=0)
                 {
                  System.out.println("You are Normal Weighted!");   
                  old = 0;
                 }
                 else if(fof<60 && old!=0)
                 {
                  System.out.println("You are Overweighted!");
                  old = 0;
                 }
                 else if(fof>=60)
                 {
                  System.out.println("Obesity!");
                  old = 0;
                 }
         }

         } 

and here is the full code in case that wasn't the area causing the problem:

import java.util.Scanner; 
import java.text.*;
public class BMI {

    public static void main(String[] args) {
        Scanner lol = new Scanner(System.in);
        int which = 1;
        System.out.println("Would you like to use Standard/U.S scale?");
        String choice = lol.next();
        System.out.println("Whats your weight?");
        double weight = lol.nextDouble();
        System.out.println("What's your height?");
        double height = lol.nextDouble(); 
        double BMI2 = weight/ (height* height)*10000;
        double BMI = (weight* 703)/ (height* height);
        if(choice.equals("U.S"))
        { 
        NumberFormat internet = NumberFormat.getInstance();
        internet.setMaximumFractionDigits(1);
        System.out.printf("Your BMI is " + internet.format(BMI) + "\n");
        which = 2;
        }
        else if(choice.equals("Standard"))
        {
        NumberFormat internet = NumberFormat.getInstance();
        internet.setMaximumFractionDigits(1);
        System.out.printf("Your BMI is " + internet.format(BMI2) + "\n");
        which = 0;
        }
        else 
        {
            System.out.println("Not an option.");
        }
        if(which==0)
        { 
            int old = 1;
         for(double faf = 0;faf<=BMI2;faf=faf+0.5) 
         {
             double fof = 0;
             fof++;
             if(fof<37 && old!=0)   
             {
              System.out.println("You are underweighted!");
              old = 0;
             }
             else if(fof<50 && old!=0)
             {
              System.out.println("You are Normal Weighted!");
              old = 0;
             }
             else if(fof<60 && old!=0)
             {
              System.out.println("You are Overweighted!");  
              old = 0;
             }
             else if(fof>=60)
             {
              System.out.println("Obesity!");
              old = 0;
             }
         }
        }
         else if(which==2)
         {
             int old = 1;
             for(double faf = 0;faf<=BMI;faf=faf+0.5) 
             {
                 double fof = 0;
                 fof++;

                 if(fof<37 && old!=0)   
                 {
                  System.out.println("You are underweighted!");
                  old = 0;
                 }
                 else if(fof<50 && old!=0)
                 {
                  System.out.println("You are Normal Weighted!");   
                  old = 0;
                 }
                 else if(fof<60 && old!=0)
                 {
                  System.out.println("You are Overweighted!");
                  old = 0;
                 }
                 else if(fof>=60)
                 {
                  System.out.println("Obesity!");
                  old = 0;
                 }
         }

         } 
        lol.close(); 
    }

}

Pardon me if I make any mistakes, English isn't my first language.

Thank you for taking your time to look over my question, I truly appreciate it. -John

php if inside or outside the function

I often get in this situation where I have an if statement and I can't deside where to put it. As a wrapper around the function or inside the function?

Is one of the two solutions here better than the other? If so, why?

Solution 1

function one($something) {
    if( $something === 'yes') {
        two();
    }
}

function two() {
    echo 'ok';
}

one('yes');

Solution 2

function one($something) {
    two($something);
}

function two($something) {
    if( $something === 'yes') {
        echo 'ok';
    }
}

one('yes');

Getting unexpected behavior of if condition

template <class T>
class Queue {
  private:

    array<T,10> elems;
    int frt=-1,bck=-1;    
};

When i run the following code of snippet

template<class T>
void Queue<T>::Enque(T const& item){
    cout<<"Size of array:"<<elems.size()<<"\n";
    if(bck<elems.size())
    {

        if(bck==-1)frt=0;
        ++bck;
    elems.at(bck)=item;
    cout<<"Element Inserted\n";
    }

    else
        cout<<"Queue is overflow\n";

}

I get this output

enter image description here

Here it is showing that the size is 10 and the value of bck is -1 but it is going to the else statement.

But if I replace the if condition with if(bck<10) the code is working fine.

enter image description here

Can anyone help me in identifying this behavior.

If statement in batch and app not recognized anymore

I try to access some Excel data stored on a server and copy these files to another server ; the destination path should be different with the name of the file. Here is my code :

setlocal enabledelayedexpansion
net use Z: \\10.0.0.1\Statistiques
set path=Z:\
set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
echo %date%
for /f "delims=" %%a in ('dir *.xlsx /b /a-d "%path%" ') do (
    set "name=%%~na"
    set folder=Empty
    if "!name!"=="!name:Client1=!" (
        set folder=Client1
    )
    if "!name!"=="!name:Client2=!" (
        set folder=Client2
    )
    copy "%path%%%a" "\\10.0.0.2\Documents\Statistiques\!folder!\%year%%month%%day%_!name!%%~xa"
)
net use Z: /delete

My issue is that the last 'net' is not recognized as an internal or external command, operable program or batch file.

On the first net use, the drive is correctly mount ; the files are correctly copied, but when I want remove the drive I have this error.

May be an error in my if () statement ?

If string statement: What am I missing? [duplicate]

This question already has an answer here:

I've created a simple code which looks like this:

name = str(input ("What is your name?"))

gender = str(input ("What is your gender?"))

if gender == 'male' or 'Male':

    print ("Hello Mr %s" % (name))

elif gender == 'female' or 'Female':

    print ("Hello Mrs %s" % (name))

else:

    print ('Invalid gender. Please try again.')

However, no matter what gender I type (even random words like test), it always prints out the if statement, which means it satisfy the gender == male portion. Like if I key in female, the if statements still prints out. What am I missing here?

lundi 28 décembre 2015

#PYTHON - Else statements with Loop? [duplicate]

This question already has an answer here:

I am a C guy. These days i am learning python for my latest project requirement. Now my question is : What is the significance of Else statements with Loops[While, For..]. Do we really need them ??

Else statement returning to original script

I'm working on a login script using Python and SQLite and I just came across a weird error.

This is the code I got:

while c.fetchone() is not None:
    if oper in ["3350",""]:
        print(term.move(28,1))
        time.sleep(3)
        os.system("python /SABB/app1.py")

    elif oper == "1010":
        os.system("python /SABB/app2.py")

if oper == "/":
    sys.exit()

else:
    main('self')

It validates the username and password, and depending on the "oper" that was typed in, open either one of the available applications, which is working correctly.

But the else statement seems to have created a problem. When the user exits the applications, they are sent back to the login script. The same behavior as if the code was:

else:
    os.system("python /SABB/app1.py")
    main('self')

Any ideas?

Recursive method keeps running after the return statement

The code i have is for a method that will take an input string and will try to sort them into the correct order that an unknown preset code is in. When the method calls the current guess method it is finding out how many of the characters in the string are in the correct position.

Then the three conditionals will then determine what happens next. The element pegs[1] in the array is how many of the characters are in the correct position. So if the the correct positions is equal to the total characters then the correct order for the code has been found, and the method should end. If the new pegs is higher then it should call the method again and start from the next position. If the correct positions then the characters was in the correct place, so it should reset the code and call the method again moving to the next position in the array.

I have another method that is called before it that will find all of the characters that are in the code, and so it is using that as the basis for what to try. For example if the code is RYGB then the starting input for the method would be RBGY. It gets the code to into the correct order, RYGB and will print it but then it continues calling the method and will eventually crash due to the method calling an index out of the array size.

I can't seem to figure out why its happening, i thought it would end the method when the return statement is used, after it prints it out the code. However it will continue to call the sort code method. Any help on this problem is greatly appreciated!

public void sortCode(int position) {
    int currentBlackPegs = pegs[1];
    String inputCode = new String(unorderedCode);
    for(int i = 0; i < currentGuess.length(); i++) {
        unorderedCode[position] = unsortedColours[i];
        String orderedCode = new String(unorderedCode);
        System.out.println("The ordered codethat will be tried" + orderedCode);

        pegs = newGame.currentGuess(currentCode, orderedCode, codeLength);

        if(pegs[1] == codeLength) {
            System.out.println("The code has been found and is " + orderedCode);
            return;
        } 
        if(currentBlackPegs > pegs[1]) {
            unorderedCode = inputCode.toCharArray();
            pegs[1] = currentBlackPegs;
            sortCode(position+1);
        } 
        if(pegs[1] > currentBlackPegs) {
            sortCode(position+1);
        }
    }
}

c# if bool not working

I have an interesting issue here. I'm trying to make a simple rubber band selection in C# and I have everything working except for a weird bug if I don't make a selection.

Expected result: MouseDown/MouseUp without moving mouse and no selection should be made after moving the mouse.

Actual result: MouseDown/MouseUp without moving mouse, then when I mouse the mouse, the selection is drawn as I move my mouse. If I click, the selection disappears. Then if I click again and mouse the mouse, the new selection is continuously redrawn.

I added a label to my form to check the state of the bool. When I do this, everything works as expected. However, once I comment out the label1.Text line, it's no longer working as expected. I've tried adding multiple bools to resolve said issue but no avail.

So why is the bool not being recognized unless I set the label text? P.S. I'm a newbie to C# so I welcome any criticism. I pulled this code from http://ift.tt/1OpUEns

Here is my current code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RubberBand
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Bitmap m_Orig = null;
        private int X0, X1, Y0, Y1;
        private bool sArea, isDown, hasMoved = false;
        private Bitmap sImg = null;
        private Graphics sGraph = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            m_Orig = new Bitmap(pictureBox1.Image);
            this.KeyPreview = true;
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 27)
            {
                if (!sArea) return;
                sArea = false;
                isDown = false;
                hasMoved = false;

                sImg = null;
                sGraph = null;
                pictureBox1.Image = m_Orig;
                pictureBox1.Refresh();
            }
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            sArea = true;
            isDown = true;
            //label1.Text = isDown.ToString();
            X0 = e.X;
            Y0 = e.Y;

            sImg = new Bitmap(m_Orig);
            sGraph = Graphics.FromImage(sImg);
            pictureBox1.Image = sImg;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!sArea) return;
            hasMoved = true;
            //label1.Text = isDown.ToString();

            if (isDown)
            {
                X1 = e.X;
                Y1 = e.Y;

                sGraph.DrawImage(m_Orig, 0, 0);

                using (Pen select_pen = new Pen(Color.Red))
                {
                    select_pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                    Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
                    sGraph.DrawRectangle(select_pen, rect);
                }

                pictureBox1.Refresh();
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (!sArea) return;
            if (!hasMoved) return;

            sArea = false;
            hasMoved = false;
            isDown = false;
            //label1.Text = isDown.ToString();
            sImg = null;
            sGraph = null;
            pictureBox1.Image = m_Orig;
            pictureBox1.Refresh();

            Rectangle rect = MakeRectangle(X0, Y0, X1, Y1);
            if ((rect.Width > 0) && (rect.Height > 0))
            {
                MessageBox.Show(rect.ToString());
            }
        }

        private Rectangle MakeRectangle(int x0, int y0, int x1, int y1)
        {
            return new Rectangle(
                Math.Min(x0, x1),
                Math.Min(y0, y1),
                Math.Abs(x0 - x1),
                Math.Abs(y0 - y1));
        }
    }
}

Efficient way to find whether a coordinate is a vertex/border coordinate?

Imagine a Cartesian plane and every Cell object represents a point in the plane (the plane will be the maze). When building my maze, I want to figure out whether a Cell object is a vertex (the four corner points) or just a border point (any cell that is on the edge of the maze, vertex points are also border points).

I need to know so that I can add neighboring cells as neighbors of the particular cell (I am creating a graph structure with nodes). Different borders have different requirements for what cells are neighbors (a top-right vertex for example cannot have a neighbor that is y + 1 or x + 1 as it is outside of the maze, whereas a bottom-left vertex cannot have y - 1 or x - 1).

How I tried to implement this was through a slew of if statements which I feel isn't a really good practice. So I wanted to ask whether there is a better way to know what type of coordinate a point is?

Here is how I did it:

private String typeOfBorderCell(Cell cell){
    if (!isBorderCell(cell)){
        throw new IllegalArgumentException("cell is not a border cell");
    }
    double x = cell.getCoordinate().getX();
    double y = cell.getCoordinate().getY();

    // Vertices
    if (x == 0 && y == 0){
        return "bottom-left";
    }

    else if (x == 0 && y == height - 1){
        return "top-left";
    }

    else if (x == width - 1 && y == 0){
        return "bottom-right";
    }

    else if (x == width - 1 && y == height - 1){
        return "top-right";
    }

    // Non-Vertices
    else if (x == 0 && (y > 0 && y < height - 1)){
        return "left";
    }

    // and so on for the other three non-vertex borders
}

The height/width are the size of the maze, but I had to subtract 1 as the maze coordinates start at origin (0,0) thus a 5x5 maze goes up to a max of 4 for its y and 4 for its x.

Doing this, I would get a total of 8 conditional statements (and the method that uses this method would require a switch statement with 8 cases as well). Is there a more efficient way to do this without a bunch of conditional statements?

if condition not affecting display of div

I have searched on StackOverflow but no questions matched my specific dilemma. I have a div with a class foo that is set via css to display: inline-block.

I would like foo to be visible when the variable temp is a number or a string, but not display when it is not a number or a string.

var temp;
        if (temp != undefined || temp != null) {
            temp = temp / 1000;
            temp = temp + 'K';
            $('.foo').css("display", "inline-block");
        }
        else {
            $('.foo').css("display", "none");
        }

When I run this code the "foo" does not display at all.

when I change the code to

var temp;
        if (temp != undefined || temp != null) {
            temp = temp / 1000;
            temp = temp + 'K';
            $('.foo').css("display", "inline-block");
        }
        if  (temp == undefined || temp == NaN) {
            $('.foo').css("display", "none");
        }

foo is still all set to display:"none"

I ran console.log on each if, and when temp is a value it does go through the first if and when it is NaN or null it does go through the second if. But why does ONLY the display: "none" take affect?

Thank you in advance. - VS

how can I check for more than I input for if...else android

This is my code. I want to compare within morning,afternoon and evening. can I do like this? private String interpretFT(int morninghour, int afternoonhour, int eveninghour) { if (morninghour > afternoonhour ) { return "Time to exercise : Morning"; } else if (afternoonhour > eveninghour) { return "Time to exercise : Afternoon"; } else if (eveninghour > morninghour) { return "Time to exercise : Evening"; } else { return "Please have the freetime to have some exercise"; } }

Mutiple "if" conditions

So I got this code that gets a caption for how many comments there are in each post of my blog

$pego_comment_caption = " Comments";

if (get_comments_number($post->ID) == 1) {
    $pego_comment_caption = " Comment";
}

Since I'm more of a grammar nazi than I understand PHP, "0 Comments" is actually gramatically incorrect since 0 is less than 1 and.. well, you know

I'd like to change the if conditions making it display the word "Comment" instead of "Comments" when there are 0 OR 1 comment. It's probably simple but I couldn't do it. Does anybody know how to?

Setting velX on collision to bounds with random speed

I know this is a stupid question, but I cannot get my head around this and I have spent a good hour searching online for results to no avail.

I am making a game where enemies move side to side on X-axis at random speeds between 1-5. I have set them up to change direction upon hitting the walls, which worked fine on fixe integers, but does not seem to work on random number.

Upon hitting the rightmost wall, WIDHT-32, they bounce back and maintain their set speed. However, when moving x < 0, they don´t bounce back and leave the screen.

What is the problem?

I have used the following code;

public int speed = (randomno.nextInt(4)+1);
public Enemy(int x, int y) {
    super(x, y);
}

public void update(){
    x+=speed;
    if(x > MainClass.WIDTH-32){
        // This works
        speed = -speed; 
    }
    if(x < 0){
        // Neither of these do....
        // Tried A
        speed = -(-speed);
        // Tried B
        speed = speed;
    }

}

How can I build if sentence with compare to varius values?

How can i write this if condition in better way?

if ((data_in(8 downto 1)=x"70") or (data_in(8 downto 1)=x"69") or 
    (data_in(8 downto 1)=x"72") or (data_in(8 downto 1)=x"7A") or
    (data_in(8 downto 1)=x"6B") or (data_in(8 downto 1)=x"73") or
    (data_in(8 downto 1)=x"74") or (data_in(8 downto 1)=x"6C") or
    (data_in(8 downto 1)=x"75") or (data_in(8 downto 1)=x"7D")) then
      data_make_code <= data_in (8 downto 1); -- enter key to buffer
      wrong_data <='0';
      cnt_bit :=0;
      -- if valid key then
      current_state <= break_code_receive; 
elsif
 ...
end if;

Multiple If conditions in Excel

I clearly have a syntax issue and would like to know where am I magically missing the point. Got tired of trying to find the answer so I decided to ask.

Code just wants to check if X is not any of three specific variables, and if not then P = 3, other P will equal 1 or 2 based on a combo box result.

I tried using Or statements with this and no luck.

 If X <> 15 Then
     P = "3"
 Else
     If X <> 18 Then
         P = "3"
     End If
         Else
             If X <> 20 Then
                 P = "3"
             End If
 ElseIf ComboBox <> "Other Condition" Then
     P = 1
     Else: P = 2
 End If

How to check if one out of four strings have been entered?

I am looking for a statement that checks if the input is either: yes, y, no, n. It should also ignore whether or not there are big or small letters. I have been searching here for a while but couldn't find an answer I understood. Is there a way to add more then just "yes" to the if statement?

    String result;
    do {
    System.out.print("Bigger the better");
    result = scanner.nextLine();
        if (!("yes".equals(result))) {
            System.out.println("Invalid answer, try again");
        }
    } while(!result.matches("[A-ZÅÄÖa-zåäö]+"));

Check .HasValue and .Value for bool

I've need to do some refactoring and I came across to this:

if(LoanTerms.RateIncreasable.HasValue && LoanTerms.RateIncreasable.Value) { ... }

and LoanTerms.RateIncreasable is type of bool?

So I'm wondering do I need .HasValue check on this? Will null be treated like false in if statement?

the if statement do not work in javascript

I want to have a try with the clearInterval() method in some conditions. But it seems do not work anyway.

window.onload = function(){
    var list = document.getElementById("list");

    list.style.position = "relative";

    list.style.left = 0;

    var move = function(){
        list.style.left = parseInt(list.style.left) + 200 + "px";  
        demo[0].innerHTML = parseInt(list.style.left);
    } 

    var myVar = setInterval(move,1000);

    if (parseInt(list.style.left) == 600) {
        clearInterval(myVar); 
    }
}  

I don't konw why there is nothing happened when the value of left property is "600". Thank you very much for help.

Implementing Strategy pattern instead of several if statements

I have this method with lot of if statements, in which I'm filtering SharePoint list based on employee position.The result is query string which is passed as parameter to another method QuerySPList.

 public List<Phone> GetListOfPhones(Employee emp)
 {
    List<Phone> records = new List<Phone>();
    string query = string.Empty;

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Regular")
    {
       query = "";// some querystring                              
    }


    if (emp.Positions.Count == 1 && emp.Positions[0] == "OfficeDirector")
    {   
       query = "";// some querystring    
    }

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
    {
        query = "";// some querystring 
    }              

    if (emp.Positions.Count == 2 && emp.Positions.Contains("Regular") && emp.Positions.Contains("OfficeDirector"))
    {

      query = "";// some querystring 

     }

   var rawItems = QuerySPList(query);

   foreach (SPListItem item in rawItems)
   {
        //business logic 
   }
   return records;
}}

I've read that with implementing strategy pattern we can avoid messy code with lot of if's , however , I'm new to developing , and design patterns , so I need little help with this one,so if someone can guide me what should I do and give me advice , feel free to answer my question.I have idea , but I think that I'm going in the wrong direction. Idea is to create interface IRoleHandler and than implement it to 3 classes , for example RoleAdmin ,RoleRegular,RoleOfficeDirector.Something like this :

public interface IRoleHandler<T>
{
    string handleRole(T obj);
}
public class RoleAdmin:IRoleHandler<Employee>
{

    public string handleRole(Employee emp)
    {
        if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
        {
            //return some string query
        }

    }
}

Then idea is to create dictionary,something like this :

Dictionary<string, IRoleHandler<Employee>> strategyHandlers = new Dictionary<string, IRoleHandler<Employee>>();
        strategyHandlers.Add("Admin", new RoleAdmin());
        strategyHandlers.Add("Regular", new RoleRegularUser());

?? null-coalescing operator vs if == null

When instantiating null objects with ?? null-coalescing operator is there any performance difference, additional cycles, etc. vs simple if == null statement? Any effect from assigning object to itself?

RedColorBrush = RedColorBrush ?? new SolidColorBrush(renderTarget, Color.Red);

vs

if (RedColorBrush == null)
{
    RedColorBrush = new SolidColorBrush(renderTarget, Color.Red);
}

Regex ÅÄÖ in if-statement

I have an if statement that checks so that someone has entered an input correct and not only whitespace or blank. I also want it to allow for the swedish letters å, ä and ö and not only the letters a - z. I cannot find how to get it right. I appreciate your help!

String name;
do {
    System.out.print("name: ");
    name = scanner.nextLine();
    if (!name.matches("[A-Za-z]+")) {
        System.out.println("Wrong input, try again!");
    }
} while

Can someone please explain to me what is happening in these conditions?

I have been trying to create a keylogger using data structures, and I saw this piece of code on a website.

I don't understand if the "character" is ASCII value or what? Plus why are we incrementing value of character by 32 in the last condition.

for (character = 8;character <= 222;character++)
{
    if (GetAsyncKeyState(character) == -32767)
    {
        FILE *file;
        file = fopen(FileName, "a+");
        if (file != NULL)
        {
            if ((character >= 39) && (character <= 64))
            {
                fputc(character, file);
                fclose(file);
                break;
            }
            else if ((character>64) && (character<91))
            {
                character += 32;
                fputc(character, file);
                fclose(file);
                break;
            }
            /* ... */
         }
     }
}

Odoo 8 validate field on Save button

I wanna check some IF-ELSE conditions for a certain field when I press the save button. I've overwritten the create and write funtions, but with the use of the write function I get stuck because of the fact that I can't use val['field_name'] when this field isn't changed.

if statement with for loop

I am writing a function to calculate a value of p.

The formula is p=r*q + pa. The pa value is column vector which i have got from the ode45 function. I have to change the value of q w.r.t time i.e from 0 to 1 sec q=500, from 1 to 2 sec q=0.

I have written this program:

function [p] = fom(t,pa)
r=0.007;
tin=1;
t=0:0.01:2;

if t <=tin
    q = 600;
else t <= 2
    q = 0;
end

[t,pa]=ode45('FOM1',[t],[0])

for i=[palv]
    p=(r*q)+(i);
end

end

The problem is I am getting correct values after 1 sec in my output but before 1 sec where q is 0 values are not changing. Is this if statement correct?

if condition for amount in USD $ in rails

My requirement is to show button only if my @order.display_total < $200 so when I have included given code:

- if method.method_type == 'cashondelivery' && @order.display_total < $200
     .form-buttons{"data-hook" => "buttons"}
        = form.hidden_field :cod_pay, :value => true
        = submit_tag "Order Now", :class => 'order-now btn btn-danger'

it gives me error :

NoMethodError - undefined method `<' for #<Spree::Money:0x007ff3d9366490>:

where as @order fetch this:

#<Spree::Order id: 5964, number: "R981938713", item_total: #<BigDecimal:7ff3d2514f78,'0.3843E3',18(18)>, total: #<BigDecimal:7ff3cea3bd20,'0.3843E3',18(18)>, state: "address", adjustment_total: #<BigDecimal:7ff3d25149b0,'0.0',9(18)>, user_id: 1, completed_at: nil, bill_address_id: 24481, ship_address_id: 24482, payment_total: #<BigDecimal:7ff3d25142f8,'0.0',9(18)>, shipping_method_id: nil, shipment_state: nil, payment_state: nil, email: "admin@skinnymint.com", special_instructions: nil, created_at: "2015-12-27 03:45:02", updated_at: "2015-12-28 12:30:34", currency: "USD", last_ip_address: "127.0.0.1", created_by_id: 1, shipment_total: #<BigDecimal:7ff3d251eb68,'0.0',9(18)>, additional_tax_total: #<BigDecimal:7ff3d251ea00,'0.0',9(18)>, promo_total: #<BigDecimal:7ff3d251e7d0,'0.0',9(18)>, channel: "spree", included_tax_total: #<BigDecimal:7ff3d251e5c8,'0.0',9(18)>, item_count: 7, approver_id: nil, approved_at: nil, confirmation_delivered: false, considered_risky: false, guest_token: "aGoCAkyLXJs1oOUp9dS96w", locale: nil, state_lock_version: 0, cod_pay: false>

and @order.display_total = $398.40

Please guide me how to put if condition for this as I am new in spree rails. Thanks in advance.

Why does it always only show the first alert?

I want do make a register view and for that I want to make to fields for a password. the first to choose a password and the second to confirm it. And I also want to check if the Emailadress is a Emailadress I want to be able to log in. The App will only be for my friends. The Problem is, that no matter what I put in the textfields it always show the first alert.

Can someone help me what I've done wrong?

@IBAction func register(sender: AnyObject) {

    if RegisterPassword1 != RegisterPassword2 {
        let alert = UIAlertView()
        alert.title = "Fehler"
        alert.message = "Passwörter stimmen nicht überein!"
        alert.addButtonWithTitle("Ok")
        alert.show()
    } else if ListOfAllEmail.contains(RegisterEmailadress.text!) {
        self.performSegueWithIdentifier("UserIdentified", sender: self)
    } else {
        let alert = UIAlertView()
        alert.title = "Fehler"
        alert.message = "Emailadresse steht nicht im Rodel!"
        alert.addButtonWithTitle("Ok")
        alert.show()
    }
}

variable returning empty in if statement python

title = article.title
title = re.sub(r' - Wikipedia, the free encyclopedia','',title)
title_lower = title.lower()
title_lower = title_lower.replace(' ','-')
print title
print title_lower
title_query = ("INSERT INTO  myguests "
               "(firstname) "
               "VALUES (%s)")

cursor.execute("SELECT id FROM myguests "
                 "WHERE firstname='"+title+"'")

row = cursor.fetchall()
if row !=[]:
    print "List is not empty"
if not row:
    print "List is empty"
    title_query = title
print title

For some reason in my if statement my title variable keeps coming back empty when it is called if not row:

I am trying to insert variable if the variable dose not exist in column.

Multiple if are not working in python

I have this code:

Split = Message.Body.split()
    split = Split

    if 'a' or 'b' or 'b' in split:
        time.sleep(2)
        print '1'
    elif 'c' or 'd' in split:
        time.sleep(2)
        print '2'
    elif 'e' or 'f' in split:
        time.sleep(2)
        print '3'           
    else:
        time.sleep(2)
        print '4'

I have used split to separate the words from my message and I want if a certain message is received to print a certain word, but now it only prints 1 regardless of the input.

syntax error "SyntaxError: Unexpected keyword 'else'" for JS

Hello I'm learning JavaScript currently at Codecademy and I am up to the paper scissors rock game, though I am getting an error

SyntaxError: Unexpected keyword 'else' 

here is my code, thnx! :)

var compare = function(choice1, choice2)
{
    if(choice1 === choice2)
    {
        return ("The result is a tie");
    }
    else if(choice1 === "rock")
    {
        if(choice2 === "scissors")
        return ("rock wins");
    }
    else
    {
        return ("paper wins");
    }
    else if(choice1 === "paper")
    {
        if(choice2 === "rock")
        return ("paper wins");
    }
    else
    {
        return ("scissors wins");
    }
}

IF command to check if input is string

#include "iostream"
using namespace std;


int main(){
    int quantity;
    cout<<"What Quantity did u receive : \n";
    cin >> quantity;
    if (quantity != int){
        cout << "please use numerical values only!\n";
    }
}

please i want to verify the correct IF command for the 'if statement' int the above code, thank you

dimanche 27 décembre 2015

Code suggestion needed on this revision

I'm posting question to this site because simply my teacher, whom I can ask about this, is not available for days or so and I don't have anyone aroudn to get help from.

Question : Finish the coding that would result in this numbers

2 3 5 (typed number on command prompt) 2 + 5 + 8 + 11 + 14 == 40

or

22 -2 7 (typed number on command prompt) 22 + 20 + 18 + 16 +14 + 12 + 10 == 112

#include <stdio.h>
int main(void)
    {
    int a, d, n;
    int i, s;
    scanf("_____", __, __, __);
    ___;
    for (i = 1; _____; i = i + 1) {
        _________________;
        printf("____ ", _________);
        _________________
        _________________
        _________________
        _________________
    }
    printf("%d\n", s);
    return 0;
}

Below is my answer

---------------My answer --------------

#include <stdio.h>
int main(void)
    {
    int a, d, n;
    int i, s;
    scanf("%d%d%d", &a, &d, &n);
    s = 0;
    for (i = 1; i <= n; i = i + 1) {
       if (i != n)
           printf("%d + ", a + (i - 1)*d);
       if (i == n)
           printf("%d", a + (i - 1)*d);
       s = (a + a + (i - 1)*d)*i / 2;
    }
    printf(" == %d\n", s);
    return 0;
}

When I submitted my answer to the teacher, he said that the error was "source code format not identical to each other." I couldn't ask further because he was busy and he had to leave for something important. I was wondering what was problem with my answer. Maybe because last print statement includes "== %d\n" instead of "%d\n"? and my statements inside "for" statement total up to 5 which are supposed to be six, as suggested on the question? My codes illustrated right numbers and results but I guess he wants some different coding...

Help please...

How can I write output result depending on two state of input

i am using if command to decide output from two input A,B as the table

 A   B   write_output
 0   0   1 1
>0   0   0 1
 0  >0   1 0
>0  >0   0 0

For example, if A>0 and B=0 then i will write the output value as 0 and 1. I am using if command to implement it. But it was not my expected table. Could you help me to fix it

This is my code

std::ofstream myfile;
myfile.open ("report.txt", std::ios::app);  
if(A==0 & B==0)
   myfile <<  1 << "\t" <<1<<'\n';
else if (A>0)
   myfile << 1 << "\t" <<0<<'\n';
else if (B>0)
   myfile << 1 << "\t" <<0<<'\n';
else
   myfile << 0 << "\t" <<0<<'\n';
myfile.close();

Check whitespaces and isempty

I am looking for a if statement to check if the input String is empty or is only made up of whitespace and if not continue with the next input. Below is my code so far which gives an error when I input a whitespace.

    name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
    if(name != null && !name.isEmpty() && name.contains(" ")) {
        System.out.println("One");
    } else {
        System.out.println("Two");
    }

Trying to create little program in python, having some issues. (New to coding)

I'm creating a code that will allow for my mouse pointer to go in circles, only when I'm holding down shift on my keyboard.

pyautogui.dragTo(100, 100, duration=0.25)
pyautogui.dragTo(200, 100, duration=0.25)
pyautogui.dragTo(200, 200, duration=0.25)
pyautogui.dragTo(100, 200, duration=0.25)

only when I'm holding shift down.

Would it be best to create a variable in which the value is 1 only when shift is held, then set my loop to only run when the value is 1? Or not even create a variable in general?

Not sure how to translate that into a if/loop statement.

How can I evaluate the bitwise operator in this condition?

I just practice some basic Java practice problems and this below shows up.

if((b2 = false) | (21 % 5)>2) return true;

So b2 is assigned with false and 1 > 2 is certainly false, but how do we evaluate "|" ? should it return true?

If Else statement in Wocommerce template page

I'm trying to write an if else statement for a Woocommerce template page that does this:

if category is not a subcategory then:

do_action( 'woocommerce_before_subcategory_title', $category );

else show this:

<h3>
    <?php
        echo $category->name;

        if ( $category->count > 0 )
            echo apply_filters( 'woocommerce_subcategory_count_html', ' <mark class="count">(' . $category->count . ')</mark>', $category );
    ?>
</h3>

So far I have a very primitive function that is no where near what the end product will be.

Your help is greatly appreciated!

Conditional logic with switch cases

Is something like this possible or should I just use 500 lines of if and else logic instead of switch?

<?php
switch ( $something ) {

case 'one' :

    if( /* case 'two' is also the case */ ) {

        $color = 'red';
        break;
    }
    else {

        $color-1 = 'black';
        break;
    }

case 'two' :

    if( /* case 'one' is also the case */ ) {

        $color = 'red';
        break;
    }
    else {

        $color-2 = 'white';
        break;
    }
}
?>

Do I lose a lot in performance if I use a lot of if statements instead of switch?

java if condition never executes with or operation

why does this piece of code always enters the if condition no matter what the input is?

 Scanner input = new Scanner(System.in);
    int x = input.nextInt();
    if (x != 4|| x!= 3)
        System.out.println("testing");

The problem is definately with the NOT combined with OR because if instead of != i write == it works (obviously different logic than what i want but still works).

Simple session example not working

I writed this little session script and i saw that's not working.

<?php
  session_start();
  $username = $_SESSION["username"];
?>

  <html><head>
  <title>Simple Session Example</title>
  </head>
  <body>

<?

  if(isset($_SESSION['username'])) {
  $username = $_POST["username"];
  echo "<h3>Hello $username</h3>";
  }

  else {
  echo "<h3>OUT!</h3>"; 
  echo "<form action='index.php' method='POST'>";
  echo "<input type='text' name='username'>";
  echo "<input type='submit' name='submit' value='Submit'></form>";
  }

  ?>

I can't figure out which part is wrong. looks all good for m but definatelly something is wrong.

imacros javascript conditional eval statement

Trying to insert a conditional "if Else" statement using the imacros EVAL using the same format from a few examples I came across. However it seems I'm still missing a thing or two.

 TAG POS=1 TYPE=SPAN ATTR=CLASS:log-1 EXTRACT=TXT
 SET !VAR7 {{!EXTRACT}}
 TAG POS=2 TYPE=SPAN ATTR=CLASS:log-1 EXTRACT=TXT
 SET !VAR6 {{!EXTRACT}} 
 SET !NEWVAR EVAL("var s=\"{{!VAR6}}}\"; if(s==\"#EANF#\") {s=\"!VAR6\";} else {s=\"!VAR7\";}")
 PROMPT !NEWVAR

If function with 8 conditions

I got the following tables. The first on the left is what i got after i manually write the data within excel. The second on the right is the reference table. Basically what i want is a multiple if functions that makes me able to recognize the aim of my training program. For instance i did 3 sets and 10 repetitions with an intensity of 66% and a rest of 150 sec. Based on that i want a quick function that gives me if this program was designed for power, strength, endurance or hypertrophy. If you have trouble reading the table on the right this can make you better understand how to read it. In order to training "Power Single" you should do from 2 to 6 sets with less or equal to 6 reps, intensity over 85% and rest from 120 to 300 seconds.

Thank you for your help

P.S. I believe the if function to be a good solution, anyway if you got something else feel free to tell me.

Why (positive_integer < negative_integer) is getting evaluated to be true in C?

$ gcc --version  
gcc (Debian 4.9.2-10) 4.9.2

In the following code snippet why is the expression 100 < strlen(str) - 4 getting evaluated as true?

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

int main(void)
{
    char str[50];

    scanf("%s", str);
    printf("%d\n", strlen(str) - 4);

    if(100 < (strlen(str) - 4))
        printf("NOT POSSIBLE!\n");

    return 0;
}

Terminal:

$ gcc so.c -o so  
$ ./so  
foo
-1
NOT POSSIBLE!  

From experimenting a bit I found out :

  1. the if expression evaluates to true for any positive_int, negative_int pair such that positive_int < negative_num (which is absurd) where negative_int is in the form of strlen function call (see 2.)
  2. if we replace the strlen with a hard coded negative integer then if evaluates to false as expected. Looks like there's something wrong with strlen.

if variable == ' some value' is not working properly

[1]:-the code i entered in python 3.5 (new file-not idle) [2]:-this is what i get when i run module and type 2. When i click run module and type 2, it prints what i have kept for else : .... etc. check it out in [2]. Please help me out with my problem.But when i exchanged if input == 2 with if input != 2 , and type 2 , it shows what i have written for if info != 2. how's that possible? [1]http://ift.tt/1OmHo33 [2]http://ift.tt/1PqxYsw

I can't solvebasic code form in php

I am new in Php world. This is my first question ever in any form. Please tell me what errors in my page. When i submit form no result came out. Please give me any solution.

I try to follow this video. https://www.youtube.com/watch?v=15Ucddc2ksM

enter code here

<!Doctype html>
<html>
<head>
    <title> My page </title>``
</head>
<body>

    <p style="font-weight:bold">hello1 world</p>
    <?php

    // Restaruant open at 8
    // Restaruant from 8-11
    // Lunch from 11-4
    // closes at 4
    $launch_menu = "Nashta <br /> 
    halwa <br /> gosher <br /> ";

    $breakfast_menu = "Launch <br />
    sugar <br /> meat <br /> ";

    if(isset($_post['time'])) {
        $time = $_post['time'];

        if($time < 8 or $time >= 16 ) {
            echo "sorry, we are closed <br />" ;
        }
        else{
            echo "Hi, what would you like order <br /> ";
            if($time < 11){
                echo $breakfast_menu;
            }
            else if ($time < 16)
            {
                echo $launch_menu;
            }
        }
    }

    ?>
    <form action='index.php' method='post'>
    What time is it? <input type='text' name='time' /> <br />
    <input type='submit' value='Submit'>
    </form>
</body>
</html>

samedi 26 décembre 2015

Return with a for loop

The code i am using is below. As far as i am aware the logic of the code is fine but when the return is after the print for the char B then the i within the for loop wont increment. If i remove the return statement then the for loop will increment as i wanted it too, however i need the method to end if the B/W is printed so i need the return to be present. Any help is greatly appreciated i've been trying to work out whats wrong for hours now.

if(currentCodeString.contains("" + currentGuessChar)) {
        for (int i = 0; i < codeLength; i++) {
            System.out.println("" + i);
            //System.out.println(currentGuess[i] + " - " + currentCode[i]);
            if(checkPins(currentGuess[i], currentCode[i])) {
                System.out.print("B");
                return;
            }
        }
        System.out.print("W");
        return;
    }

How to check if element is greater than another by certain %

I need to put a check in a C program to check if value[1] > value[2] by a certain % (in this case 15%) . But am struggling to come up with the simplest method?

Thanks,

'if statement' not firing on mobile?

This works fine on everything except for mobile. Is there a reason for this? How do I get around it?

$(document).ready(function()
  var my_var = 10;
  if(! my_var =="") {
    //do my code
  }
});

if statement to indicate whether a market has gone up or down

I have a dataset from library(ISLR) and I would like to make my own up and down, but my if statement always fail, any help would be appreciated:

library(ISLR)
attach(Smarket)

for (i in 1:nrow(Smarket)){
Smarket$myown = ()
if (Smarket[i, "Today"]>0) { Smarket$myown = "Up"
} else { Smarket$myown = "Down"
}}

Please note that if I use the statement ifelse then the issue is solved, but I want your help to MODIFY the above code, so I may learn

 Smarket$myown = ifelse(Smarket[, "Today"]> 0, "Up", "Down")  

How can I insert a if function in an array

I have an array

$data_array =

array
    (
        "limit" => $limit,
        "page_number" => $page,
        "books" => $books
    );

I want that if $books is set then the array should be

array
    (
        "limit" => $limit,
        "page_number" => $page,
        "books" => $books
    );

and if the variable $books is not set the array should be

array
(
    "limit" => $limit,
    "page_number" => $page
);

please can anybody help me.