mercredi 30 septembre 2015

How do I modify variables in a function from the main script in C++

I've been at this for a few hours now. I am making a small game in C++ and I am trying to figure out how I can edit variables from inside of a function. I can place the variables in the main() and edit them them there no problem, but I can't figure out what I need to do to edit from a function. Below is the function.

void HeroSelect(string& hero)
{
    int gold = 20, health = 5, attack = 5, stats[2] = { health, attack };
    string weapon;
    cout << "Please choose your hero.\n";
    cin >> hero;
    if (hero == "Warrior" || hero == "warrior")
    {
        weapon = "Broad Sword";
        cout << "You are a Warrior wielding a " << weapon << endl;
        cout << "Good choice.\n"
            << "You start out with " << gold << " gold." << endl
            << "You have " << stats[0]<< " health and " << stats[1] << " attack.\n";
    }

Above is the function definition and I want to be able to edit the health when the player gets attacked or say gets a stronger weapon. Below is the main() of the script.

void main()
{
    double enter, room1, room2, room3, room4, BossRoom;
    int,   gold = 20; //This is used as part of check inventory and will be subtracted when necessary
    string hero, weapon;


    //Set decimal two places
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    Intro(enter);

    cout << "The first step in this adventure is to choose your hero. You can choose a warrior, a wizard, or an archer.\n";

    HeroSelect(hero);

So let's say he gets a new weapon and it gives +1 attack how do I reflect that in the function? Would I create a separate function for this?

As the player goes through the game, they can type in "stats" whenever, and when they do I want it to display their current health and attack and then essentially just loop back to the beginning of the room or fight they are in.

I know I can make the changes to the variables if I made all of my loops and all of my if-else statements in main(), but I wanted to try this and keep my main script clean. I did stats as an array, because I think it is good to print the array as a list. Any help would be great. Thanks!

How do I properly use prompts with if statements when creating a dialogue tree?

I am attempting to create a basic word game with a branching answer system. I am running into an issue right off the bat concerning prompts. When I write my 'if' statement to bring about another prompt, nothing happens. how can I fix this? The following is a sample of my work:

confirm("You wake up to your mother's voice, 'Wake up! I can't believe you slept in this late! You need to get dressed and hurry on down to Professor Oak's Lab! No time for breakfast! Get going!'");

var questionOne = prompt("1. Hurry out of bed, quickly get dressed, and run out the door! 2. Roll out of bed sleepily, manage to put on your clothes, and make a cup of coffee before leaving the house. 3. Grumble back at your mother and go back to sleep." , "Enter 1, 2, or 3.");

if (questionOne === 1)
{
  prompt("You arrive at Professor Oak's lab in a rush, but haven't quite missed the event! It's time to get your first Pokemon! When you meet the Professor he says with a wink, 'Ah yes, it's you! I remember your mother quite well. Wonder woman... Alright, follow me!' You follow Oak into his lab to find 3 Pokeballs on his desk. 'Choose one,' he says with a hand gesture. [1. Left Pokeball. 2. Middle Pokeball. 3. Right Pokeball.]");
}

Bug in a fixed If - Else statement

this is my first post in this site.

As the title says, I encountered a bug in an If - else if - else block of codes. What the problem is that, I am pretty confident that I have covered all 9 possible outcomes that there should be.

It is quite hard to explain more, so if you guys could take a look at my .cpp file and run it ( hopefully it runs because I used c++ on a mac), you may find an easier understanding of my problem.

source code cpp file

If you browse through my action();, in the else statement, I purposely displayed that you encountered a bug so just in case there were bugs, I'd be informed.

What I am trying to do is like this:

userinput | randomAImove | outcome

A             1           statement
A             2           statement
A             3           statement
D             1           statement
D             2           statement
D             3           statement
W             1           statement
W             2           statement
W             3           statement
else        1||2||3       statement

There are corresponding statements to each conditions met. 'A', 'W', 'D' are user input. I used a toupper command to force the compiler to just check on 'A' 'W' 'D'. However, the main problem I find is that, even if the toupper works(which I confirmed), the program displays the correct statement often but still somehow manages to bug even if the user(I tried it) input from A, W, D (not-case sensitive cuz of toupper).

Please just try it and after a few tries you may encounter it also. I wrote "you encountered a bug" if you ever do encounter it.

Please help me because I can't really see any other way to find the mistake. Maybe its in my plain sight but I can't seem to notice which one is it.

Thank you!

At the end of the Quiz display number of correct answer and incorrect answer + percentage of correct answer?

import java.util.Scanner;

/*The Circle Rock Paper scissors game implement to display to the standard output.
@author Mun
@class CIS168
@date 9/28/2015*/
public class Quiz{

   public static void main(String[] args)

   {

int choices;
 int song;
 int song2;
 int song3;
 int song4;
 int song5;  

// scanner to input singer name Scanner scan = new Scanner(System.in); // Display a song to input singer name System.out.println("Who sing this the song 'Locked Away':");

      System.out.println("Choose 1 for R. City & Adam Levine's. \nChoose 2 for Justin Bieber.  \nChoose 3 for Selena Gomez. \nChoose 4 for Katy Perry.");
      song = scan.nextInt();




if (song!=1){

System.out.println("Your answer is incorrect  R. City & Adam Levine's is the right answer .");


   }

{

   while(song==1){

        System.out.println( "Congrate you answer is correct");

song++;
  } 
     System.out.println();     
  }  

// Display a song to input singer name System.out.println("Who sing this the song 'Beauty and the beast':");

      System.out.println("Choose 1 for R. City & Adam Levine's. \nChoose 2 for Justin Bieber.  \nChoose 3 for Selena Gomez. \nChoose 4 for Katy Perry.");
    song2 = scan.nextInt();



if (song2!=2){

System.out.println("Your answer is incorrect  Justin Bieber is the right answer.");


   }

{

   while(song2==2){

        System.out.println( "Congrate you answer is correct ");

song2++;
  } 
     System.out.println();     
  }  

System.out.println("Who sing this the song 'Heal the world':");


      System.out.println("Choose 1 for R. City & Adam Levine's. \nChoose 2 for Micheal Jackson.  \nChoose 3 for Selena Gomez. \nChoose 4 for Katy Perry.");
    song4 = scan.nextInt();



if (song4!=2){

System.out.println("Your answer is incorrect  Micheal Jackson is the right answer.");


   }

{

   while(song4==2){

        System.out.println( "Congrate you answer is correct");

song4++;
  } 
     System.out.println();     
  }  

System.out.println("Who sing this the song 'Roar':");


      System.out.println("Choose 1 for R. City & Adam Levine's. \nChoose 2 for Justin Bieber.  \nChoose 3 for Selena Gomez. \nChoose 4 for Katy Perry.");
 song3 = scan.nextInt();



if (song3!=4){

System.out.println("Your answer is incorrect  Katy Perry is the right answer.");


   }

{

   while(song3==4){

        System.out.println( "Congrate you answer is correct");

song3++;
  } 
     System.out.println();     
  }  

System.out.println("Who sing this the song 'The Heart Wants What It Wants ':");


      System.out.println("Choose 1 for R. City & Adam Levine's. \nChoose 2 for Justin Bieber.  \nChoose 3 for Selena Gomez. \nChoose 4 for Katy Perry.");
  song5 = scan.nextInt();



if (song5!=3){

System.out.println("Your answer is incorrect  Salena Gomez is the right answer.");


   }

{

   while(song5==3){

        System.out.println( "Congrate you answer is correct");

song5++;
  } 
     System.out.println();     
  } 
  switch (song){
  case 1: song1=1;
   result=1;

System.out.println(song);


          } //calculate correct answer here

        }//how I will calculate how many wrong and right answer I got and percentage //of total correct answer.
        }

My final else sentence isn't working in program(Java) [duplicate]

This question already has an answer here:

So I've been trying to do this school exercise, the code compiles and all, but it won't print the final else sentence if the characters won't pair (aka aren't same brackets such as "( and )" or "[ and ]".

Any advice?

public  class PairOrNot {
    public static void main(String[] args) {
        char first;
        char last;
        System.out.println("Hello blahblah");
        System.out.println("1st input");
        first = In.readChar();
        System.out.println("2nd input");
        last = In.readChar();
        if (first == '(')
            if (last == ')')
                System.out.println(
                        "Blahblah " + first + " and " + last + " blahblah.");
        if (first == '[')
            if (last == ']')
                System.out.println(
                        "Blahblah " + first + " and " + last + " blahblah.");
        if (alku == '{')
            if (loppu == '}')
                System.out.println(
                        "Blahblah " + first + " and " + last + " blahblah.");
        if (first == '<')
            if (last == '>')
                System.out.println(
                        "Blahblah " + first + " and " + last + " blahblah.");
            else {
                System.out.println("Characters " + first + " and " + last
                        + " aren't a pair.");
            }
    }
}

if preg_match and elseif wont work

$embedcode=""
if($embedcode==""){
$file="some-url-here";
if ( preg_match("/vbox/i",$file) ) { 
preg_match_all('#vbox-(.*?)-end#smi',$file,$gell);
$gelll= $gell[1][0];
echo 'embed code from vbox';
} elseif ( preg_match("/youtube/i",$file) ) { 

echo "embed code from youtube";

}elseif ( preg_match("/facebook/i",$file) ) { 
echo "embed code from facebook";
}else {
echo "my player";
}

Gives:

Parse error: syntax error, unexpected T_ELSEIF in from the first elseif

this is a small php code to get a embed url

but dont work for me

I have a PHP table that calculates Fahrenheit into Celsius, I need to use Span Class to change color of the Celsius results based on certain criteria

How can I go about doing this? I know I have to use an if statement, but I have tried placing it everywhere and my code just gets messed up.

The criteria is if the value in C is less than or equal to 0, the result should be blue. If it is greater than or equal to 100 C, it's displayed in red. All other temperatures in C should be green.

This is my table code,

<tr>
        <td align="center"><strong>Fahrenheit</strong></td>
        <td align="center"><strong>Celsius</strong></td>
    </tr>

   <?php

   for ($tempFahrenheit = 0; $tempFahrenheit <= 250; $tempFahrenheit++){
   $tempCelsius = (5/9)*($tempFahrenheit-32);
   echo "<tr><td>$tempFahrenheit&degF.</td>";
   echo "<td>$tempCelsius&degC.</td></tr>";   

  }

  ?>

Swift - If statement not working as it should

I'm trying to animate an UIButton once two textsfields have had text entered. The button animates even if there is no text entered. I thought maybe it was an issue with there being placeholder text, but that has no effect. I have tried != "" as well as != nil

Here's my code

    override func viewDidLoad() {
    super.viewDidLoad()

    self.title = ""

    textFieldConfig()
    loginButtonConfig("LOG IN")
}

func loginButtonConfig(title:String) {
    let frameWidth = self.view.frame.width
    let frameHeight = self.view.frame.height

    var button = UIButton()
    button.frame = CGRect(x: 0, y: 300, width: 0, height: 50)
    button.bounds = CGRect(x: 0, y: 0, width: 0, height: 50)
    button.backgroundColor = UIColor(red: 24.0/255.0, green: 198.0/255.0, blue: 152.0/255.0, alpha: 1.0)
    button.setTitle(title, forState: .Normal)
    button.titleLabel?.textAlignment = NSTextAlignment.Center
    self.view.addSubview(button)

    //WHY ISN'T THE IF STATEMENT WORKING AS IT SHOULD???
    if self.userTextField.text != nil && self.passwordTextField.text != nil {
       UIView.animateWithDuration(1.0, animations: { () -> Void in
        button.frame = CGRect(x: 0, y: 300, width: frameWidth, height: 50)
        button.bounds = CGRect(x: 0, y: 0, width: frameWidth, height: 50)
       })
    }
}

Any help would be appreciated. Thanks :)

I am not sure where to put my if statements? need help getting things straight

I am not sure where to put my if statements because I get an error when in the constructor and I'm not sure where else to put them.

import java.awt.Color;

/**
* Create a class called GrowingDot. This will draw a circle on the screen
* in a specified color. Every time it is drawn it will increase 
* in size until it reaches a maximum size and then it will be reset
* to its minimum size and start growing again.
* 
* The class will need 4 class variables. Declare 3 ints (the x, y location
* of the circle and the size of the circle). 
* The class will also need a Color variable to store the circle's color.
* 
* Create a Constructor that takes two ints and a Color object as 
* parameters. These represent the x, y coordinates of the circle 
* (in that order) and its color. Use the parameters to set the 
* appropriate class variables.
* 
* If the x parameter is less than 0, set the class's variable to 0.
* Otherwise, use the value of the parameter. The same should be done
* with the y parameter.
* 
* If the Color object is null, set the class's variable to red.
* Otherwise, use the value of the parameter.
* 
* For the size of the circle, it should start off at 5.
* 
* Create a getX method that returns an int and takes no parameters. This
* should return the x coordinate of the circle.
* 
* Create a getY method that returns an int and takes no parameters. This
* should return the y coordinate of the circle.
* 
* Create a getColor method that returns a Color and takes no parameters.
* This should return the color of the circle.
* 
* Create a setPosition method that takes two int parameters (the x, y 
* coordinates) and returns nothing. If the x parameter is greater than 
* or equal to 0, update the class's variable to the parameter's value. 
* Otherwise, do nothing. Do the same with the y parameter.
* 
* Create a display method that takes a Graphics object as its parameter and
* returns nothing. Using the Graphics object draw a filled oval using 
* the class's size variable for its dimensions and the Color variable 
* for the color. Use the class's x, y variables as
* the coordinates for the circle.
* 
* After the circle has been drawn, increase the size variable by 1. If the
* new size is greater than 10, change it to 5.  
* 
* Make sure you format it and include the needed documentation.
*/

public class GrowingDot {

    int x;
    int y;
    int location;
    Color c;

    public GrowingDot(int x1, int y1, Color color) {
        x = x1;
        y = y1;
        c = color;

        if (x1 < 0) {
            return x = 0;
                return x1;
        }

        if (y1 < 0) {
            return y = 0;
                return y1;
        }

        if (color = null) {
            return c = red;
                return color;
        }
        }    
    }
}

If a $var1 equals a string then set $var2 equal to another string

Basically if $var1 = 'Refi' then I want $var2 = 'Refinance'. If $var = 'Purch' or 'Purchase' then I need $var2 = 'Purchase'.

$var2 = '';

if (!(strcasecmp($var1, 'Refi') === false)) {
$var2 = 'Refinance';
}

if (!(strcasecmp($var1, 'Purch') === false) || !(strcasecmp($var1, 'Purchase') === false)) {
$var2 = 'Purchase';
}

The output I am getting is just defaulting to 'Purchase'. I also need the strings to be case insensitive. I don't know what is going on with it, the logic seems correct in my help.

passing value of two buttons to alter info with nested if in javascript

I have two buttons (in OP2.0) with a standard form, but want the option for one of the two buttons to alter the data being sent. Both buttons are still sending original data (identical to Opt1)...and want to overwrite it when Opt2 is clicked.

<center><table><tr><td>
<p>

<img src="http://ift.tt/1YORnH0" alt="try now with text" width="358" height="110" style="cursor:pointer;" onclick="proceed();" value="Opt1"/>
</p>
</td><td width="40px"></td><td>
<p>
<img src="http://ift.tt/1JCTsdD" alt="30 off with text" width="346" height="110" style="cursor:pointer;" onclick="proceed();" value="Opt2"/>
</p>
</td></tr></table></center>

and javascript....

<script type="text/javascript">

   function proceed(){
      var chk=0;        
        jQuery('.test1').each(function(){
          if(jQuery(this).is(':checked'))
          {
            chk++;
          }
        });

        if(chk==1){

    function setForm(Value){
         if (value == 'Opt1'){
                document.getElementById('price').value = '19.95'
                document.getElementById('productId').value = '492'
                document.getElementById('tagId').value = '3754'
                document.getElementById('inf_custom_conversion').value = 'almanacupsell'
                orderProcessUpsale()

         }
          if (value == 'Opt2'){
                document.getElementById('price').value = '168.00'
                document.getElementById('productId').value = '494'
                document.getElementById('tagId').value = '3756'
                document.getElementById('inf_custom_conversion').value = 'almanacupsell'
                orderProcessUpsale()

         }

    }

          orderProcessUpsale();
          jQuery(".blackout").css("display", "block");
          $('.blackout').css('cursor', 'wait');
          unhook();
        }
        else
        {
          alert('Checkbox must be checked!');
          jQuery("html, body").animate({ scrollTop: jQuery(document).height() }, 1000);
        }

      }
</script>

<script>

    jQuery("#test1").on("change", function() {
        if (jQuery(this).is(':checked')) {
            jQuery('#test2').prop("checked", true);

        } else {
            jQuery('#test2').prop("checked", false);
        }
    });

</script>
<script>

    jQuery("#test2").on("change", function() {
        if (jQuery(this).is(':checked')) {
            jQuery('#test1').prop("checked", true);

        } else {
            jQuery('#test1').prop("checked", false);
        }
    });

</script>


<script>
EnableSubmit = function(val)
{
    var sbmt = document.getElementById("agree");

    if (val.checked == true)
    {
        sbmt.disabled = false;
    }
    else
    {
        sbmt.disabled = true;
    }
}      
</script>




<script type="text/javascript">

  jQuery(".btn2").on("click", function(){
    jQuery('.btn2').css('cursor', 'wait');

  });

</script>

jQuery issues with the 'this' modifier and if/else statement

Ok, so I'm trying to make it so that an image can be modified or moved in the browser by clicking on buttons on the side of the page, but the script in my if/else statement isn't working like I'd like it to. Here's what I have so far in jQuery:

var menu = $('ul li').click(function() {
console.log($(this).index());
});

if ($('menu') = 0) {
$('this').css('width', '80%')
}

else if ($('menu') = 1) {
$('this').css('height', '80%')  
}

else if ($('menu') = 2) {
$('this').css('height', '80%')
}

else if ($('menu') = 3) {
$('this').css('top', '30')
}

else if ($('menu') = 4) {
$('this').css('left', '50')
}
else {

}

Java : Nesting an if/else statement inside a while loop

this is my first question in StackOverflow, so I hope that you will forgive me for the many possible error I'm going to make in setting this post.... My problem is the following : this code should generate a random number, display it to the user(in order to help me guess it whitout making too many attempts... this should be only an exercize), ask the user to guess a number between 0 and 50, check if the input is an integer or not and, If the user guesses the right number, print "Yes, the number is.." . BUT, if the user digits a letter or whatever which is not a number, the if/else loop goes crazy and the program starts printing "Choose a number between 0 and 50: Please insert a number between 0 and 50, not a letter" whitout stopping... Can anywone help me please?

package methods;

import java.util.Scanner;

public class Methods {

    static int randomNumber;
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {

        System.out.println(getRandomNum());

        int guessResult = 1;
        int randomGuess = 0;

        while (guessResult != -1) {
            System.out.print("Choose a number between 0 and 50: ");

            if (userInput.hasNextInt()) {
                randomGuess = userInput.nextInt();
                guessResult = checkGuess(randomGuess);
            } else {

                System.out.println("Please insert  a number, not  a letter");
            }

        }

        System.out.println("Yes, the number is " + randomGuess);
    }

    public static int getRandomNum() {

        randomNumber = (int) (Math.random() * 51);
        return randomNumber;

    }

    public static int checkGuess(int guess) {

        if (guess == randomNumber) {

            return -1;
        } else {

            return guess;

        }
    }
}

"If" statement dependent on time range

Say we have a data set similar to:

DF = pd.DataFrame({'Time':[1,2,3,4,5,6,7,8,9,10],'Value': [1,3,5,5,6,8,9,5,6,7]})

giving:

   Time  Value
0     1      1
1     2      3
2     3      5
3     4      5
4     5      6
5     6      8
6     7      9
7     8      4
8     9      6
9    10      7

What I want to do is set all values that are > 5 to equal 0 in "Values" but only when "Time" is > 5. End product would be:

   Time  Value
0     1      1
1     2      3
2     3      5
3     4      5
4     5      6
5     6      0
6     7      0
7     8      4
8     9      0
9    10      0

I have been using a code:

 DF.Value = [0 if x > 5 else x for x in DF.Value] 

Which obviously changes all values to 0 if they are > 5. I have tried adding things to this code such as:

  DF.Value = [0 if x > 5 in DF.value and x < 4 in DF.Time else x for x in DF.Value]

But I can't seem to get the right combination of words/code to yield what I want. Any suggestions? Thank you.

If-else statements, always running

I am working on making a coffee ordering system. It takes inputs from users and calculates the price of their coffee. One of the inputs asked for is "syrupshots". This code always makes syrupshots = 3 even if the user properly chose a number according to the size of their coffee.

//if size == tall   syrup shots <=3
if(size == 1 && syrupshots < 1 || syrupshots > 3)
{
    syrupshots = 3;
}
//else if size == medium     syrup shots <=5
else if(size == 2 && syrupshots < 1 || syrupshots > 5)
{
    syrupshots = 3;
}
//else if size == Venti        syrup shots <=7
else if(size == 3 && syrupshots < 1 || syrupshots > 7)
{
    syrupshots = 3;
}
System.out.println(syrupshots);

I am not sure why syrupshots is always = 3 no matter what.

Python if elif else problems [duplicate]

This question already has an answer here:

New to python. Not sure what I'm doing wrong here. For some reason the if elif else statements are not working, and it just defaults to the first if statement no matter what the input. Kinda stuck here. According to everything I have read my syntax is correct. any help would be appreciated. Heres the code:

#main function
def main():
    name=input("Please input your name:")
    acct_id=input("Please input your account id:")
    trans_code=input("Please input your transaction code \
(w=withdrawal, d=deposit):")
    prev_bal=float(input("Please input your previous balance:"))
    trans_amt=float(input("Please input your transaction amount:"))

    if trans_code == "W" or "w":
        withdrawal(name,acct_id,trans_code,prev_bal,trans_amt)
    elif trans_code == "D" or "d":
        deposit(name,acct_id,trans_code,prev_bal,new_bal)
    else:
        print("This transaction is invalid")

#withdrawal function        
def withdrawal(name,acct_id,trans_code,prev_bal,trans_amt):
    if trans_amt > prev_bal:
        print("Not enough funds")
    else:
        new_bal=prev_bal-trans_amt
        print_bal(name,acct_id,new_bal)
#deposit function
def deposit(name,acct_id,trans_code,prev_bal,new_bal):
    new_bal=prev_bal+trans_amt
    print_bal(name,acct_id,new_bal)

#print function
def print_bal(name,acct_id,new_bal):
    print("Hello:",name)
    print("Your account ID is:",acct_id)
    print("Your new balance is:$",format(new_bal,",.2f"))
main()

Thanks in advance for any input!

Python. unclear behavior of IF-statement

I tried to solve the problem described in this question.

Briefly, I have 3 threads and one singleton class Data. All threads read and write values in Data. All writes concluded in threading.Lock():

locker.acquire()
# some writes
locker.release()

And I saw that if statement never ends sometimes.

if len(app_data.ip_table[app_data.cfg.MY_IP]['tasks']):  # Если есть задания для выполнения
        print u"Есть что выполнять"
        if (app_data.cfg.MULTITHREADING or app_data.complete_task.is_set()):  # Если текущее задание выполнено или включена мультипоточность
            job = Worker(locker, app_data, SRV.taskResultSendToSlaves, app_data.ip_table[app_data.cfg.MY_IP]['tasks'].pop())  # ipTable[MY_IP][0].pop()
            job.setDaemon(True)
            print 0
            job.start()  # Запуск в классе Worker на исполнение одного задания
        else:
            print u"Не выполнено"
        print u"Итерация 3"
    ##### THIS CODE ARE NEVER EXECUTE SOMETHIMES ######
        print 7.0
    print 7.1
    print 7.2
    locker.release()  # app_data.locker.release()
    print "unlock 6"
    ###################################################

All threads works fine, but in some random moment this code going to fall down. And highlighted code does not get executed, so locker.release() is never executed, so threads are in deadlock.

But why this IF statement falls down in some unclear times? Any ideas?

If inside a while loop, can't break out of the while loop

I recently started studying Java and came across a problem while testing out something. This might be a very easy question, but I can't seem to solve it. This is my code:

    int firstj = 1;

    if (firstj == 1) {
        String choice = "Type a number between 1 and 4";
        System.out.println(choice);
        while (true) {

            if (firstj == 1) {
                Scanner third = new Scanner(System.in);
                String thirdch = third.nextLine();

                while (true) {

                    if (thirdch.equals("1")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    } else if (thirdch.equals("2")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    } else if (thirdch.equals("3")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    }

                    else if (thirdch.equals("4")) {
                        // I need this to break the loop and move on to the
                        // "Done." string
                        break;
                    }

                    else {
                        System.out.println("Type a number between 1 and 4");
                        thirdch = third.nextLine();
                    }
                }

            }
        }
    }
    String done = "Done";
    System.out.println(done);

I want to make it so that when you type 1, 2 or 3, you get the string telling you to type a number again and accept user input, while when you type 4 the loop breaks and goes to the String done. I would be grateful if you could help me solve this problem with an easy code, since I don't know any of the more advanced things.

Challenging Formula in excel to calculate successive remainder

I am trying to find a formula which will work out an allowance amount based on the time it has taken for a task to be completed.

Here is an example, in cell:

A1: I have an allowance value of 150 (which does not change)

B1: I have the time it has taken for the task to be performed

C1: I want a formula to return a value based on the criteria below

Criteria 1: 6hrs or less return 20% of the allowance =IF(AND(B1>=0.01,B1<=5.99),A1*0.2,"")

Criteria 2: Between 6hrs and 12hrs, return 50% of the allowance =IF(AND(B1>=6,B1<=11.99),A1*0.5,"")

Criteria 3: Between 12hrs and 24hrs, return 100% of the allowance =IF(AND(B1>=12,B1<=23.99),A1*1,"")

Criteria 4: First 24hrs, 100% of the allowance and for each successive 12hrs add 50% of the allowance (on top of the 100% for the first 24hrs)

If possible I would like one formula to cover all those criterias into C1 cell. As you can see, I have a formula for the first three criterias but not the last one.

It would be great if someone can help. Many thanks in advance :)

Ab

It error "Subquery returns more than 1 row"

SELECT stdId,
       stdCodeId,
       tnName,
       stdFname,
       stdLname,
       stdClsId,
       stdScId,
       stdYearId,
       stdTermId,
       srId,
       srStatus,
       srUnitId,
       IF(srStatus='2',
            (SELECT chgWithdraw
             FROM nbs_financial.fin_chargeFee
             WHERE nbs_register.rg_student.stdScId = nbs_financial.fin_chargefee.chgScId),IF(srStatus='1',
                                                                                               (SELECT chgWithdraw
                                                                                                FROM nbs_financial.fin_chargeFee
                                                                                                WHERE nbs_register.rg_student.stdScId = nbs_financial.fin_chargefee.chgScId), IF(srStatus='0', IF(stdClsId='3',
                                                                                                                                                                                                    (SELECT chgNotWithdraw
                                                                                                                                                                                                     FROM nbs_financial.fin_chargeFee
                                                                                                                                                                                                     WHERE nbs_register.rg_student.stdScId = nbs_financial.fin_chargefee.chgScId
                                                                                                                                                                                                       AND chgStatus = '1'),
                                                                                                                                                                                                    (SELECT chgNotWithdraw
                                                                                                                                                                                                     FROM nbs_financial.fin_chargeFee
                                                                                                                                                                                                     WHERE nbs_register.rg_student.stdScId = nbs_financial.fin_chargefee.chgScId
                                                                                                                                                                                                       AND chgStatus = '0')),NULL))) AS amount
FROM nbs_register.rg_student
LEFT JOIN nbs_financial.fin_statusreimburse ON nbs_register.rg_student.stdId = nbs_financial.fin_statusreimburse.srStdId
LEFT JOIN nbs_controltemplate.titlename ON nbs_register.rg_student.stdTnId = nbs_controltemplate.titlename.tnId
WHERE stdYearId = '3'
  AND stdTermId = '1'
  AND stdScId = '21'
  AND stdRoomId = '34'   

I don't know where is problem.

a simple python code that astonishingly ignores if condition & statement [duplicate]

This question already has an answer here:

I have a really simple code here. But the problem is really bothering me. In line no 7, there is a if-condition; astonishingly this if condition is never addressed! I ran the program and checked multiple times using python version 2.7. It behaves as if the if-condition and its statements (along with break) is inside the comment and is simply ignored.

from random import randint
random_number = randint(1, 10)
guesses_left = 3
while (guesses_left>=1):
    print (random_number)
    guess = raw_input('Guess ?')      
    if guess == random_number: #this statement is never checked?
        print ('You win!')
        break
    guesses_left -= 1 
else:
    print ('You lose.')

Zoom to layer extent in Openlayers 3

I have a drop down list of application numbers and when the user clicks on one of these, I would like my application to display that feature on the map from my application layer and then zoom to its extent.

The feature is displaying correctly but I cannot seem to be able to zoom to the extent of the layer, I receive an error:

Uncaught TypeError: Cannot read property '0' of undefined

The relevant code is below which is within an if statement, there appears to be some sort of issue with the last 2 lines - is it because I am unable to call methods to the map layer as it was created at the same time? Do I need to delay the zoom to extent somehow?

if (name === "planning") {
      var planapp = new ol.layer.Tile({
      source: new ol.source.TileWMS({url: '../../geoserver/wms',
      serverType: 'geoserver',
      params:{
        'LAYERS':"planning:planapps_testlayer", 'TILED':true, 'cql_filter':"applicatio='" + datum.APPLICATION_NUMBER + "'"
      }
      }),
      name: 'planapp',
      label: 'Planning Applications',
      visible: true
      });
    map.addLayer(planapp);
    var selectedAppExtent = planapp.getExtent();
    map.getView().fit(selectedAppExtent, map.getSize());
  }

Thanks for any help you can give!

Determine the max values in one column based in another column

I would like to determine the max the values in column value1 based the values in column value2:

df <- 'inf value1 value2
       xx1   20    30
       xx2   15    40
       xx3   25    20'
df <- read.table(text=df, header=T)

My expected output would be like that:

out <- 'inf value1 value2
       xx1   20    30
       xx2   15    40
       xx3   20    20'
out <- read.table(text=out, header=T)

In the third row in the column value2 now I have 20 instead 25, because this is the value at value2column at the same row. I have a large dataset, I would appreciate any ideas to deal with that. Thank you!

why does it print twice? if -else

I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.

This is the code so far:

import java.util.Scanner;

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

        Scanner input = new Scanner(System. in );
        // receive amount
        System.out.println("Enter an amount in double, for example 11.56: ");

        double amount = input.nextDouble();

        int remainingAmount = (int)(amount * 100);

        // find the number of one dollars
        int numberOfDollars = remainingAmount / 100;
        remainingAmount = remainingAmount % 100;

        // find the number of quarters in the remaing amount
        int numberOfQuarters = remainingAmount / 25;
        remainingAmount = remainingAmount % 25;

        //find the number of dimes in the remaing amount
        int numberOfDimes = remainingAmount / 10;
        remainingAmount = remainingAmount % 10;

        //find the number of nickels in the remaing amount 
        int numberOfNickles = remainingAmount / 5;
        remainingAmount = remainingAmount % 5;

        //find the number of pennies in the remaining amount
        int numberOfPennies = remainingAmount;

        //Display results
        System.out.println("Your amount" + amount + "consists of");

        if (numberOfDollars > 1) {
            System.out.println(" " + numberOfDollars + "dollars");
        } else if (numberOfDollars == 1); {
            System.out.println(" " + numberOfDollars + "dollar");
        }

The output is: run:

Enter an amount in double, for example 11.56: 
12,33
Your amount12.33consists of
 12dollars
 12dollar
 1quarters
 1quarter
 0dimes
 0dime
 1nickles
 1nickle
 3pennies
 3penny

Why is everything printed double? 3 == not 1 so why does it still say 3 penny? Noob question maybe, but thats because i am one :) Thanks for help!

PLS-00103: Encountered the symbol "IF" when expecting one of the following in oracle function

I am writing the below function in which i am getting error as PLS-00103: Encountered the symbol "IF" when expecting one of the following: ( - + case mod new null <an identifier>. I know this error is coming at the line where i am trying to append if condition with THRESHOLD_MIN_ALERT string . I want to append the string Minimum Threshold with the if condition and value. So for example for Minimum threshold it should come like this if V_THRESHOLD_MIN_ALERT = Y then

THRESHOLD_MIN_ALERT(Alert Configured) 100

If the V_THRESHOLD_MIN_ALERT = N then

THRESHOLD_MIN_ALERT 100

If i remove the if condition then my function runs fine.I dont know the syntax of how to append the if codition.Here is my function:

FUNCTION BUILD_ALERT_EMAIL_BODY
    (
      IN_ALERT_LOGS_TIMESTAMP IN TIMESTAMP
    ) RETURN VARCHAR2 AS
    BODY VARCHAR2(4000) := '';
    V_KPI_DEF_ID NUMBER := '';
    V_KPI_TYPE_ID NUMBER := '';
    V_KPI_THRESHOLD_MIN_VALE NUMBER := '';
    V_KPI_THRESHOLD_MAX_VALE NUMBER := '';
    V_THRESHOLD_MIN_ALERT NUMBER;        

    BEGIN

    Select KPI_DEF_ID INTO V_KPI_DEF_ID FROM KPI_LOGS WHERE KPI_LOG_ID = IN_KPI_LOG_ID;
    Select KT.KPI_TYPE_ID INTO V_KPI_TYPE_ID FROM KPI_DEFINITION KD JOIN KPI_TYPE KT ON KD.KPI_TYPE = KT.KPI_TYPE_ID WHERE KD.KPI_DEF_ID = V_KPI_DEF_ID;
    Select THRESHOLD_MAX_VAL INTO V_KPI_THRESHOLD_MAX_VALE FROM KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;
    Select THRESHOLD_MIN_VAL INTO V_KPI_THRESHOLD_MIN_VALE FROM KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;
    Select THRESHOLD_MIN_ALERT INTO V_THRESHOLD_MIN_ALERT FROM KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;
    Select THRESHOLD_Max_ALERT INTO V_THRESHOLD_MAX_ALERT FROM KPI_DEFINITION WHERE KPI_DEF_ID = V_KPI_DEF_ID;

        BODY := 'ALERT TIMESTAMP : ' || to_char(IN_ALERT_LOGS_TIMESTAMP,'DD.MM.YYYY HH24:MI') || Chr(13) || Chr(10);

        IF ((V_KPI_TYPE_ID = 18) OR (V_KPI_TYPE_ID = 19))  THEN  
        BODY := BODY || 'Minimum Threshold' || if (V_THRESHOLD_MIN_ALERT = Y) then '(Alert Configured)' END IF; || V_KPI_THRESHOLD_MIN_VALE || Chr(13);            
        END IF;

       RETURN BODY;
    END BUILD_ALERT_EMAIL_BODY;

what return 'windows.location.pathname'? It isn't a string?

I tested something with the function window.locatin.pathname.

This is my js script:

   var location = window.location.pathname;

   console.log(location); // -> /de/immobilien-auf-mallorca

    if(location == "/de/immobilien-auf-mallorca"){
      console.log('true'); //doesn't work! It is not true???
    }else{
      console.log('false'); //Output in my console    
    }

I think that my var 'location' is a string and contains this string '/de/immobilien-auf-mallorca'.

But if I include an if statement (if location = /de/immobilien-auf-mallorca) I don't come into the first part of my if statement. (Take a look above)

I don't know why maybe my variable isn't a string?!

Maybe someone knows more about this.

Thanks for help!

mardi 29 septembre 2015

if/else coding style consequences

I am a novice programmer and was in lecture one evening, we were studying the "if,else" coding section from my professor and I was curious about an aspect of it. What I was curious about was if we have a bunch of nested if,else's in our program, is it just bad coding style to end an if,else with an "else,if" line of code instead of if "x", else "y"? For example,

if "x"
else if "y"
else if "z"
end

compared to

if "x"
else if "y"
else "z"
end

It would still run the program without an error, but are there consequences later on other than having bad programming style?

How do I go through the String to make sure it only contains numbers in certain places

I am writing something that will take a user's input for a phone number and tell the user if their input was valid or not based on five parameters:

1) input is 13 characters in length

2) char at index 0 is '('

3) char at index 4 is ')'

4) char at index 8 is '-'

5) All other characters must be one of the digits: ’0’ through ’9’ inclusive.

So far I have everything down except the 5th parameter. My code for that goes as followed

   if (number.contains("[0-9]+"))
    {
        ints = true;

        if (number.contains("[a-zA-Z]*\\d+."))
        {
            ints = false;
        }
    }
    else 
    {
        ints = false;
    }

(Side note: number is my string that is the user's input, and ints is a boolean declared earlier in the code).

Avoid 26 if/elseif/else statements when checking for a letter in user input

I was just wondering if there was a simple way to check for the value of a letter from user input. For example,

Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();
String letter;
int length = message.length();
for(int i = 0; i < length; i++){
    letter = message.substring(i,i+1);
    if(letter.equalsIgnoreCase("a")){
        System.out.println("letter a");
        //of course the real program won't just print out "letter a" but this is to show that all actions are different) 
    }else if(letter.equalsIgnoreCase("b"){
        System.out.println("letter b");
    }etc... for all of the possible values of "letter" 
} 

Is there any way to write the above statement without having to make 26+ if/else statements? (I know there's switch-case but you'd still have to write 26+ of them). Any help is greatly appreciated!

Sorry for any formatting errors as I am on my phone currently.

ConnectFour Program Issues in Java

I'm creating a Connect Four program from scratch for good practice and I am having trouble with my checkAlignment() method, or what would be the win condition. It works in some rows but not all, and it doesn't work for any other direction (vertically, diagonally forwards, diagonally backwards).

public char checkAlignment(int row, int column) {
char color = board[row][column];
char[][] current = getBoard();

// Horizontal Left-to-Right Check - - - - - - - - - -
if (column + 4 <= columns) {
    for (int i = 1; i < 4; i++) {
        if (current[row][column + i] != color) {
            return NONE;
        }
    }
    return color;
}

// Horizontal Right-To-Left Check - - - - - - - -
if (column - 4 > -1) {
    for (int i = 1; i < 4; i++) {
        if (current[row][column - i] != color) {
            return NONE;
        }
    }
    return color;
}

//  Vertical Top-To-Bottom Check - - - - - - -
if (row + 4 <= rows) {
    for (int i = 1; i < 4; i++) {
        if (current[row + i][column] != color) {
            return NONE;
        }
    }
    return color;
}

// Vertical Bottom-To-Top Check - - - - - - - -
if (row - 4 > -1) {
    for (int i = 1; i < 4; i++) {
        if (current[row - i][column] != color) {
            return NONE;
        }
    }
    return color;
}

// Main Diagonal Backwards Check - - - - - - - - - -
if (column - 4 > -1 && row - 4 > -1) {
    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < 4; j++) {
            if (current[row - i][column - j] != color) {
                return NONE;
            }
        }
    }
    return color;
}

// Main Diagonal Forwards Check - - - - - - - - - -
if (column + 4 <= columns && row + 4 <= rows) {
    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < 4; j++) {
            if (current[row + i][column + j] != color) {
                return NONE;
            }
        }
    }
    return color;
}

// Secondary Diagonal Backwards Check - - - - - - - - -
if (column - 4 > -1 && row + 4 <= rows) {
    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < 4; j++) {
            if (current[row + i][column - j] != color) {
                return NONE;
            }
        }
    }
    return color;
}
// Secondary Diagonal Forwards Check - - - - - - - - - -
if (column + 4 <= columns && row - 4 > -1) {
    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < 4; j++) {
            if (current[row - i][column + j] != color) {
                return NONE;
            }
        }
    }
    return color;
}
return NONE;

}

Can anyone help me out?

Nested IF field in Word VBA

first timer here.

I have an issue that is causing me lots of grief. I'm trying to create a word addin that adds complex IF Statement Creation, from a list of possible mergefields.

Complex is

{ IF { = OR ( { COMPARE { MERGEFIELD Field_1 } <= "Value" }, { COMPARE { MERGEFIELD Field_2 } >= "Value" } ) } = 1 "True Instructions" "False Instructions" }

Im trying to do this all in VBA, but im having issues with my Complex if, as I cant get the "}" to end in the right locations.

If I use the terminator "Selection.EndKey Unit:=wdLine" in any other location besides the end, it creates a mess and putts all the } at that line.

Here is my Code:

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:="IF "


Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:=" = " & JointOperator1 & " ( "

'FIRST ARG
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:="COMPARE "


Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False, Text:="MERGEFIELD " & FirstArg1

    Selection.TypeText Text:=" "
    Selection.TypeText Text:=ComparisonType1
    Selection.TypeText Text:=" "
    Selection.TypeText Text:=Chr(34) & SecondArg1 & Chr(34)


Selection.TypeText Text:=", "


'SECOND ARG
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
    Selection.TypeText Text:="COMPARE "


Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False, Text:="MERGEFIELD " & FirstArg2

    Selection.TypeText Text:=" "
    Selection.TypeText Text:=ComparisonType2
    Selection.TypeText Text:=" "
    Selection.TypeText Text:=Chr(34) & SecondArg2 & Chr(34)


Selection.TypeText Text:=" ) "

Selection.TypeText Text:=" = 1 "

Selection.TypeText Text:=vbCrLf & " " & Chr(34)


Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=strTempIfTrue


Selection.TypeText Text:=Chr(34) & " " & vbCrLf
Selection.TypeText Text:=" " & Chr(34)

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    PreserveFormatting:=False
Selection.TypeText Text:=strTempIfFalse


Selection.TypeText Text:=Chr(34)
Selection.EndKey Unit:=wdLine
Selection.TypeParagraph

And this is what I get when generating the "Complex if"

{IF { = AND ( {COMPARE{MERGEFIELD FHB} = "T", { COMPARE {MERGEFIELD BLAH} = "F") = 1 "If True text" "If False Text"}}}}

But it should be this:

{IF { = AND ( {COMPARE{MERGEFIELD FHB} = "T" } , { COMPARE {MERGEFIELD BLAH} = "F" } ) } = 1 "If True text" "If False Text"}

If someone could shed some light on this matter, where am I going wrong. Or If there is a way of forcing the location of the Ending }, that would be great Im very new to VBA (I'm a C++ Programmer)

Thank you very much in advance.

How to shorten the same part in jQuery function?

If I have a if/else statement:

if(a) {         
  $('#aa').removeClass('Offselect').addClass('Onselect').css('background-image','url(../images/menu.gif)');
} 
else if(b) { 
  $('#bb').removeClass('Offselect').addClass('Onselect').css('background-image','url(../images/menu.gif)');
} 
else if(c) { 
  $('#cc').removeClass('Offselect').addClass('Onselect').css('background-image','url(../images/menu.gif)');
} 
else if(d) { 
 //same part
}

You can see the code have the same part:

removeClass('Offselect').addClass('Onselect').css('background-image','url(../images/menu.gif)');

Is it possible or any suggestion to shorten the same code?

I am trying to use substr to extract the part of the array element value with a if-else statement

I am really new to PHP and am having some trouble on how to output this.

$employee_numbers = array( "Sam Jerry"=>"1849", "David Flint"=>"2274", "Lena Vincent"=>"2532", Robert Vanny"=>"3471" );

I am trying to output it so that the substr shows the Name and number.

So it looks something like this

Sam Jerry's employee number is: 1849 --> MANAGEMENT

Thanks in advanced

If/else if/else error - unexpected identifier

I'm trying to execute an if/elseif/else statement, but I am getting an unexpected identifier error on the second else if. The rest of the statement works fine. I'm very new to coding, so I apologize if this is a simple mistake.

if (jQuery("#question").val() === "" && (rowCount == 1)) {
    analysis_empty=1;
} else if (rowCount > 1) {
    jQuery('.analysis_empty_title').css({"line-height":"normal"});
    jQuery('.analysis_empty_title').text("Results Displayed by Date Groups");
    jQuery('#here').html(jQuery('#dategrouptable').clone().attr('id', 'tableb_copy'));
    jQuery('#tableb_copy').css({"font-style":"italic"});
    var ptr = jQuery("#tableb_copy").find("tr");    
    ptr.find("td:last").remove();
} else if ((rowCount > 1) and (jQuery("#question").val() != "" )){
    jQuery('#analquestion_empty').css({"display":"none"});//ERROR HERE
} else {
    analysis_empty=0;
    jQuery('#analquestion_empty').css({"display":"none"});
}

Any thoughts?

my program doesn't run completely

For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.

import java.util.Scanner; public class GradeCalculation {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner grade = new Scanner (System.in);

    // A new scanner must be created. The scanner is essential to this program performing properly. 

    double A = 90-100; 
    double B = 80-89; 
    double C = 70-79; 
    double D = 60-69; 
    double F = 0-59;
    String LetterGrade; 
    String yes; 
    String no;
    double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
    double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
    double knownWeight;
    double PercentageWeights;

    // As always, the variables must be declared at the beginning of the program. 


    System.out.print(
            "Grading Scale:\n"+
            "A = 90-100 \n"+
            "B = 80-89 \n"+ 
            "C = 70-79 \n"+ 
            "D = 60-69 \n"+
            "F = 00-59 \n");

    System.out.println("What letter grade do you want to achieve in this course?");
    LetterGrade = grade.next();

    // The user will type the letter grade that it wants in this part. 

    System.out.println("\nEnter Percentage Weights: \t");

    String input = grade.nextLine();

    // The string above is needed when the user enters the exam grades and averages. 

    System.out.print("\n\nExam 1: \t"); 
    Exam1 = grade.nextShort();
    System.out.print("\nExam 2: \t"); 
    Exam2 = grade.nextShort();
    System.out.print("\nFinal Exam: \t");
    finalExam = grade.nextShort();
    System.out.print("\nLabs: \t");
    Labs = grade.nextShort();
    System.out.print("\nProjects: \t");
    Projects = grade.nextShort();
    System.out.print("\nAttendance: \t");
    Attendance = grade.nextShort();
    System.out.print("\nQuizzes: \t");
    Quizzes = grade.nextShort();

    PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);

    // The equation above will provide the sum of the percentage weights. Since the variables in the equation were 
    // originally declared as doubles, I had to put "int" before the actual equation. 


    if (PercentageWeights > 100 || PercentageWeights < 100) { 
        System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
        System.exit(0);
    }
    else { 
        System.out.println("\nEnter your scores out of a 100: \t");
    }

    // The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100, 
    // the program will continue to run. If the sum is greater than or less than 100, the program will terminate. 

    System.out.print("\nDo you know your Exam 1 score?");
    if (input.equalsIgnoreCase("yes")) {
        System.out.print("\nScore received on Exam 1: "); 
        Exam1Grade = grade.nextDouble();
    }
    else{ 
        Exam1Grade = 0;
    }

    System.out.print("\nDo you know your Exam 2 score?");
    if (input.equalsIgnoreCase("yes")) { 
        System.out.print("\nScore received on Exam 2: ");
        Exam2Grade = grade.nextDouble();
    }
    else{ 
        Exam2Grade = 0;
    }
    System.out.print("\nDo you know your final exam score?");
    if (input.equalsIgnoreCase("yes")){ 
        System.out.print("\nScore received on final exam: ");
        finalExamGrade = grade.nextDouble();
    }
    else{
        finalExamGrade = 0;
    }
    System.out.print("\nDo you know your lab average?");
    if (input.equalsIgnoreCase("yes")){ 
        System.out.print("\nAverage lab grade: "); 
        LabAverage = grade.nextDouble();
    }
    else{
        LabAverage = 0;
    }
    System.out.print("\nDo you know your project average?");
    if (input.equalsIgnoreCase("yes")){
        System.out.print("\nAverage project grade: "); 
        ProjectsAverage = grade.nextDouble();
    }
    else{
        ProjectsAverage = 0;
    }
    System.out.print("\nDo you know your quiz average?");
    if (input.equalsIgnoreCase("yes")) {
    System.out.print("\nAverage quiz grade: ");
        QuizzesAverage = grade.nextDouble();
    }
    else{ 
        QuizzesAverage = 0;  
    } 
    System.out.print("\nDo you know your attendance average?");
    if (input.equalsIgnoreCase("yes")){ 
    System.out.print("\nAverage Attendance Grade: ");
        AttendanceAverage = grade.nextDouble();
    }
    else{
        AttendanceAverage = 0;      
    }

    // The user has finished answering the questions. Now the program will automatically calculate the data based on 
    // what the user typed into the program. 

    double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade; 

    // The doubles above need to be declared in order for the equations below to work properly. 

    WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));

    CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));

    knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);

    if (grade.equals(A)){ 
        finalOverallGrade = 90;
    }
    else if (grade.equals(B)){ 
        finalOverallGrade = 80;
    }
    else if (grade.equals(C)){ 
        finalOverallGrade = 70;
    }
    else if (grade.equals(D)){ 
        finalOverallGrade = 60;
    }
    else 
        finalOverallGrade = F; 

    avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));

    // The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade. 
    // If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.

    if (finalOverallGrade >= 90){ 
        System.out.print("Congratulations! You got an A in the class! Hooray!");
    }
    else if (finalOverallGrade >=80 && finalOverallGrade < 90){ 
        System.out.print("Good job. You got a B in the class!");
    }
    else if (finalOverallGrade >=70 && finalOverallGrade < 80){ 
        System.out.print("You got a C in the class.");
    }
    else if (finalOverallGrade >=60 && finalOverallGrade < 70){
        System.out.print("You got a D in the class.");
    }
    else 
        System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
    }

}

If Else: String Equality (Java)

Lab Description : Compare two strings to see if each of the two strings contains the same letters in the same order.

This is what I have so far far:

import static java.lang.System.*;

public class StringEquality
{
    private String wordOne, wordTwo;

    public StringEquality()
    {
    }

    public StringEquality(String one, String two)
    {
        setWords (wordOne, wordTwo);
    }

    public void setWords(String one, String two)
    {
        wordOne = one;
        wordTwo = two;
    }

    public boolean checkEquality()
    {
        if (wordOne == wordTwo)
        return true;
        else
        return false;
    }

    public String toString()
    {
        String output = "";
        if (checkEquality())
        output += wordOne + " does not have the same letters as " + wordTwo;
        else
        output += wordOne + " does have the same letters as " + wordTwo;
        return output;
    }

}

My runner looks like this:

import static java.lang.System.*;
public class StringEqualityRunner
{
    public static void main(String args[])
    {
        StringEquality test = new StringEquality();

        test.setWords(hello, goodbye);
        out.println(test);


    }
}

Everything is compiling except for the runner. It keeps saying that hello and goodbye aren't variables.

How can I fix this so that the program does not read hello and goodbye as variables, but as Strings?

Comparing integers and creating the smallest integer possible from the digits of the given integers

I need to write the following method: accepts two integer parameters and returns an integer. If either integer is not a 4 digit number than the method should return the smaller integer. Otherwise, the method should return a four digit integer made up of the smallest digit in the thousands place, hundreds place, tens place and ones place.

For example biggestLoser(6712,1234) returns 1212 For example biggestLoser(19,8918) returns 19

Here's how I've started to write it:

public static int biggestLoser(int a, int b){
    if(a<9999 || b<9999){
        if(a<b)
            return a;
        else if(b<a)
            return b;
    }
    int at=a/1000;
    int ah=a%1000/100;
    int an=a%100/10;
    int ae=a%10;
    int bt=b/1000;
    int bh=b%1000/100;
    int bn=b%100/10;
    int be=a%10;
    if(at<bt && ah<bh && an<bn && ae<be)
        return at*1000+ah*100+an*10+ae;
    else if(at<bt && ah<bh && an<bn && be<ae)
        return at*1000+ah*100+an*10+be;
    else if(at<bt&& ah<bh && bn<an && ae<be)
    else return at*1000+ah*100+bn*10+ae;

However, it looks like I'm going to have to write way too many if statements, is there a shorter way to write the code?

Else component of if/else not executing (C++)

I have a relatively large program and not all of it is relating to my question, but this particular bit is stumping me. Below is my int main:

int main ()
{
    int caseNumber ;
    string clientName, clientEmail, subject, path, fileName, firstTime ;
    //creates string for path of files created and where the Python project is stored (with the .exe)
        path = _pgmptr ;
        fileName = "EmailGenerator.exe" ;
        fileName.length() ;
        path.erase(path.length() - fileName.length()) ;

    //checks first time use for customizing
        cout << "Welcome to the Ticket Email Generator.\n\n" 
            << "If this is your first time using this program,\nplease enter Y to customize some personal details.\n" 
            << "If not, enter any other character.\n" ;
        cin >> firstTime ;
        cin.ignore() ;
        if (firstTime == "Y" || firstTime == "y")
        {
            //save sender email (defaults to morgan_wallace@cable.comcast.com - creator)
            setSender (path) ;

            //Verifies signature file is as desired (to be saved for the future)
            char ready = 'n' ;
            while (!(ready == 'y' || ready == 'Y')) 
            {
                std::cout << "\nPlease modify the signature.txt file located in " + path << endl
                        << "Enter Y when done.\n" ;
                cin >> ready ;
                cin.ignore() ;
            }
        }

    //Email "To" field:
        setTo (path) ;

    //Email "Subject" field:
        setSubject (path) ;

    //Email "Body" field:
        std::cout << "\nPlease provide the following information for the body of the email:" << endl ;
        //create standard time-based greeting at top of message
            setToName (path) ;
        //select message type & compose body of message
            ofstream scriptfout (path + "script.txt") ;
            std::cout << "\nPlease select from case type menu:" << endl << endl ;
            caseTypeMenu(scriptfout) ;
            scriptfout.close() ;
        //compose full body and add signature
            setBody (path) ;

    std::cout << "Would you like to review your email before sending? Y/N  " ;
    char reviewChar ;
    cin >> reviewChar ;
    cin.ignore() ;
    if (reviewChar == 'y' || reviewChar == 'Y')
    {
        review (path) ;
    }
    else if (reviewChar == 'N' || reviewChar == 'n')
    {
        //run email sender (python program)
                string pythonPathString = path + "EmailProj/EmailProj/EmailProj.py" ;
                string pythonString = "C:/Python27/python.exe " + pythonPathString + " " + path ;
                system(pythonString.c_str()) ;
        //Exit program
                string anything ;
                std::cout << "Enter anything to exit\n" ;
                cin >> anything ;
                cin.ignore() ;
    }
    else
    {
        cout << "Invalid entry review: " + reviewChar << endl ;
        //Exit program
                string anything ;
                std::cout << "Enter anything to exit\n" ;
                cin >> anything ;
                cin.ignore() ;
    }

    return 0 ;
}

My specific issue my last if/else (everything else executes as expected):

        std::cout << "Would you like to review your email before sending? Y/N  " ;
        char reviewChar ;
        cin >> reviewChar ;
        cin.ignore() ;
        if (reviewChar == 'y' || reviewChar == 'Y')
        {
            review (path) ;
        }
        else if (reviewChar == 'N' || reviewChar == 'n')
        {
            //run email sender (python program)
                    string pythonPathString = path + "EmailProj/EmailProj/EmailProj.py" ;
                    string pythonString = "C:/Python27/python.exe " + pythonPathString + " " + path ;
                    system(pythonString.c_str()) ;
            //Exit program
                    string anything ;
                    std::cout << "Enter anything to exit\n" ;
                    cin >> anything ;
                    cin.ignore() ;
        }
        else
        {
            cout << "Invalid entry review: " + reviewChar << endl ;
            //Exit program
                    string anything ;
                    std::cout << "Enter anything to exit\n" ;
                    cin >> anything ;
                    cin.ignore() ;
        }

If you input an 'h', or some character not Y, y, N, or n, it does not print the error script with the inappropriate answer. It prints a line of my code (something that is printed to screen with cout in an earlier portion of the code) and then "Enter anything to exit" and waits for input. If you input 'g', it just skips the error message altogether and prints the "Enter anything to exit line" and waits for input.

The point of this last if/else is to allow the user to view their message, and then decide whether to send it, edit portions of it, or just disregard it completely. For purposes of error checking, I would like to handle inputs that are not Y, y, N, and n, even though theoretically there should be no other inputs.

Function for thresholds of two variables

I am trying to write a function with two variables. m has four categories: equal to 19 or less,20,21, and 22. al has three categories: less than 30,30 to 400, and over 400.

Input:
m=c(19,20,21,22)
al=c(30,400)

Output:
out1 <- c(0.95, 0.94. 0.93, 0.92)
out21 <- 1.091+3.02*(al-30)
out22 <- 1.093+3.03*(al-30)
out23<-  1.099+3.08*(al-30)
out24 <- 1

out3 <- c(0.87, 0.89, 0.91, 0.93)

I am trying to write a function with if else that looks like

out <- function(m,al)
{ 
if(m<=19 & al<30){
  out=0.95     
} else {
  if(m=20 & al<30){
    out=0.94    
  } else {
    if(m=21 & al<30){
      out=0.93    
...

I like to get an easy looking function that gives me output more easily. Further explanation on the conditions:

If m <=19 & al <30, out=0.95
If m =20 & al <30, out=0.94

...

If m <=19 & al in between 30 and 400, out=1.091+3.02*(al-30)
If m =20 & al in between 30 and 400, out=1.093+3.03*(al-30)
...

If m <=19 & al >400, out=0.87
If m =20 & al >400, out=0.89

C++ while loop, using if else statements to count in an array

I'm having trouble with a basic c++ program assignment, and would greatly appreciate any help. The assignment is as follows:

Write a program that accepts input from the keyboard (with the input terminated by pressing the Enter key) and counts the number of letters (A-Z and a-z), numerical digits (0-9), and other characters. Input the string using cin and use the following looping structure to examine each character in the string with an "if" statement and multiple "else if" statements.

My program thus far is:

#include <iostream>
using namespace std;

int main()
{
char s[50];
int i;
int numLet, numChars, otherChars = 0;

cout << "Enter a continuous string of       characters" << endl;
cout  << "(example: aBc1234!@#$%)" <<      endl;
cout  << "Enter your string: ";
cin  >> s;

i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))
  {numLet++;
  }
else if (s[i] >= 48 && s[i] <= 57)
{numChars++;
    }
else if ((s[i] >= 33 && s[i] <= 4) || (s[i] >= 58  && s[i] <=64) ||  (s[i] >= 9 && s[i] <= 96) || (s[i]   >= 123 && s[i] <= 255))
  {otherChars++;
  }
  i++;
}

cout  << numLet << " letters" << endl;
cout << numChars << " numerical characters" << endl;
cout << otherChars << " other characters" << endl;

return 0;
}

The letter count gives a value a little too low, and the number count gives a large negative number. Other chars seems to function fine.

Better way to check a list for specific elements - python

I'm using try/except blocks as a substitute for if/elif that has a bunch of ands. I am looking into a list and replacing some elements if it has x and x and x, etc. In my project, I have to check for upwards of 6 things which drew me to using the try/except with .index which will throw an error if the element isn't present.

An analogy looks like this:

colors = ['red', 'blue', 'yellow', 'orange']

try:
    red_index = colors.index('red')
    blue_index = colors.index('blue')
    colors[red_index] = 'pink'
    colors[blue_index] = 'light blue'
except ValueError:
    pass
try:
    yellow_index = colors.index('yellow')
    purple_index = colors.index('purple')
    colors[yellow_index] = 'amarillo'
    colors[purple_index] = 'lavender'
except ValueError:
    pass

So if the color array doesn't contain purple as well as yellow, I don't want the array to change.

I am a bit wary of this approach because it seems like abuse of try/except. But it is much shorter than the alternative because I would have to grab the elements' index anyway, so I would like to know if there are blatant problems with this or if this is crazy enough that other developers would hate me for it.

Elif unexpected indentation when trying to print out single line with total count

I have created a very simple function that counts the number of occurrences in a list, however, I cannot get one single line to print out the total number of occurrences because the elif part of my if statement creates an unexpected indentation in my code. I'm using the elif part to check whether the code entered is part of the list or not.

So for example, instead of getting:

2 entries(s) for uk found

I get:

1 entries(s) for uk found
2 entries(s) for uk found

Can anyone please help me out with a suggestion on how to correct this? Thanks a lot !

PS: This is just my third week coding, please take it easy on me guys.

def myList(list):
    countOccurrence = 0    
    for code in list:
        if code == countryCode:
            countOccurrence += 1              
            print str(countOccurrence) + ' entrie(s) for ' + str(countryCode) + ' found'            
        elif countryCode not in list:
            print 'Invalid Country Code'
            break      

list = ['ec','us','uk','ur','br','ur', 'ur', 'uk']

countryCode = raw_input('Please provide country code > ')
myList(list)

Why is there a "deadbranch" in my code?

below my code was working fine until my last if-else. It appears I've done something wrong with my boolean variables canGraduate and onProbation. Perhaps I'm reassigning them incorrectly in the prior if-else statements. The deadbranch occurs at the else half of my last if-else. Thank you for your time.

package lab5;
import java.util.Scanner;
public class Lab5 {

public static void main(String[] args) {

    //creates scanner object
    Scanner scanner = new Scanner(System.in);

    //PART II
    //creating variables
    double gpa;
    int totalCreditsTaken;
    int mathScienceCredits;
    int liberalArtsCredits;
    int electiveCredits;
    boolean canGraduate = true;
    boolean onProbation = false;

    //prompts user for imput
    System.out.println("What is your GPA?");
        gpa = scanner.nextDouble();
    System.out.println("What's the total amount of credits you've taken?");
        totalCreditsTaken = scanner.nextInt();
    System.out.println("How many math and science credits have you taken?");
        mathScienceCredits = scanner.nextInt();
    System.out.println("How many liberal arts credits have you taken?");
        liberalArtsCredits = scanner.nextInt();
    System.out.println("How many elective credits have you taken?");
        electiveCredits = scanner.nextInt();

    //creates first "if" statment to determine if GPA is high enough to be on track or on probation 
    if (gpa < 2.0){
        System.out.println("You're on academic probation.");
        onProbation = true;
    }

    //PART III
    //creates a conditional to see if there's enough credits to graduate 
    if (totalCreditsTaken < 40 ){
        System.out.println("You need more credit(s) to graduate.");
        canGraduate = false;
    }
    else{
        System.out.println("Examining credit breakdown...");
        canGraduate = true;
    }

    //PART VI
    //Nested if-else if-else to determine if the student qualifies for BA or BS
    if ((mathScienceCredits >= 9) && (electiveCredits >= 10)){
        System.out.println("You qualify for a BS degree.");
        canGraduate = true;
    }
    else if ((liberalArtsCredits >= 9) && (electiveCredits >= 10)){
        System.out.println("You qualify for a BA degree.");
        canGraduate = true;
    }
    else{
        System.out.println("You currently don't meet the degree requirments.");
        canGraduate = false;
    }

    //PART V
    //Uses an if statement to either congradulate the student or tell the student to take more classes
    if ((onProbation = true) || (canGraduate = false)){
        System.out.println("You don't qualify to graduate.");
    }
    else{
        System.out.println("Congradualations you qualify to graduate.");
    }

}
}

Trying to refine several if statements down

I'm trying to find a more elegant way to reduce my if statements down, what I have right now is a little messy and I reckon could be done better, any suggestions?

        if(ship.position.y >= transform.position.y + yBound)
        {
            hitBounds = true;
        }
        if(ship.position.y <= transform.position.y - yBound)
        {
            hitBounds = true;
        }
        if(ship.position.x >= transform.position.x + xBound)
        {
            hitBounds = true;
        }
        if(ship.position.x <= transform.position.x - xBound)
        {
            hitBounds = true;
        }

Thanks for your time!

C++ (Can't get this project to compile) [on hold]

So I'm doing this project in class where we have to calculate a customer's monthly bill which fluctuates depending on how many minutes they used and which package they are subscribed to. As of right now, we are supposed to complete it with if/else statements until we learn about switch statements. I've done the majority of the program, but I just can't seem to get the code to compile. Any help is appreciated.

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
  // Variables
    char package;
    const double packageA = 39.99, packageB = 59.99, packageC = 69.99;
    int minutesUsed;
    double overageA, overageB;

    // Displays and asks what package the user is subscribed to
    cout << "The following packages are listed: " << endl;
    cout << endl;
    cout << "Package A: 359.99/month - 450 Minutes - $0.45 per additional      minute" << endl;
    cout << "Package B: $59.99/month - 900 minutes - $0.40 per additional minute" << endl;
    cout << "Package C: $69.99/month - Unlimited Minutes" << endl;
    cout << endl;
    cout << "What package are you subscribed to?" << endl;
    cin >> package;
    cout << "How many minutes were used?" << endl;
    cin >> minutesUsed;
    {
    if (package = 'A')
      {
        if (minutesUsed > 450)
          overageA = packageA + ((minutesUsed - 450)*.45);
        cout << "Your total charge is $" << overageA << endl;

        else
          minutesUsed <= 450;
          cout << "Your total charge is $" << packageA << endl;
      }
    if (package = 'B')
      { 
        if (minutesUsed > 900)
          overageB = packageB + ((minutesUsed - 900)*.40);
       cout << "Your total charge is $" << overageB << endl;

       else
         minutesUsed <= 900;
         cout << "Your total charge is $" << packageB << endl;
      }
    if (package = 'C')
      {
        if minutesUsed >= 1
        cout << "Your total charge is $" << packageC << endl;
      }

          return 0;
    }
}

SystemVerilog 'if' statement inside always_comb 'not purely combinational logic' error

I'm confused! And a bit frustrated. I've spent quite a lot of time working on some SystemVerilog in Modelsim. I got it to a certain stage where I could test it on my hardware however compiling in Quartus was unsuccessful. I did understand this may happen but in this case my errors don't seem to make sense.

The code below is inside an always_comb block. When I compile I get the following error:

Error (10166): SystemVerilog RTL Coding error at fifo_interface.sv(80): always_comb construct does not infer purely combinational logic.

I really don't understand this. This is the code, it's just a mux.

always_comb
    if(fifo_select == 0)
    begin
        fifo0_data_in = data_in;
        fifo0_in_clk = in_clk;
        fifo0_in_dn = in_dn;
        in_rdy = fifo0_in_rdy;

        fifo1_in_clk = 0;   //Prevent 'in_clk' entering fifo1
    end

    else
    begin
        if(fifo_select == 1)
        begin
            fifo1_data_in = data_in;
            fifo1_in_dn = in_dn;
            fifo1_in_clk = in_clk;
            in_rdy = fifo1_in_rdy;

            fifo0_in_clk = 0;   //Prevent 'in_clk' entering fifo0
        end 
    end
end

When I change the block to type 'always' Modelsim will act strangely. It will break in the code or will crash altogether with the exit code 211. Changing the type back to 'always_comb' does not fix the issue and so I have to restart modelsim to successfully simulate the HDL.

I'm interested to know what the source of the error is?

Thanks for any help.

shell scripting to check a value in a file

Hi i have to run a automated script for a in-house command of us . the command will list subnets and also give info of each subnet through various options here i had listed the subnets and then greped the names, then checked the info of each subnet and now for each subnet i need to check if dhcp is set to none and we dont have anything mentioned as none it is just "dhcp:" now i need to see if the value is none in the output as like dhcp: not as dhcp:x.x.x.x or dhcp:test.server.com. how can we do that :

#!/bin/bash
cat subnet list | cut -f 2 -d '|' |egrep -v "NAME|^-" |awk '{print $1}' |while read NAME  
 do
if  cat subnet info --name $NAME | grep 'DHCP:' |  awk '{ print $2 }' <  /dev/null
then
echo dhcp is set to none
else
echo "dhcp is set to a value"
fi
done
fi
 done

Here the if statement is wrong because when there is value cat subnet info --name $NAME | grep 'DHCP:' | awk '{ print $2 }' it shows the value but if loop still shows none

Listjs filter with radio buttons not working

I'm trying to use listjs filter possibilites, but instead of listing buttons one by one and writing separate functions I need them to be created with Wordpress loop and everything works except item.values().batch is always the same value and somewhy it doesn't go through the

if (item.values().batch == value ) {
      return true;
console.log("True");
    } else {
      return false;
console.log("False");
    }

as I never get "True" or "False" printed in console, but the value of (this) changes perfectly.

JS Fiddle

(Gets a error in JS Fiddle that doesn't appear in the original code ran on Wordpress)

Using str_replace with array gives unexpected results

I have an array of numbers, something like 1,2,3,4,5,6,7, etc. These are IDs stored in a database.

I have a group of labels that I am trying to apply to these numbers for use later on, but my output isn't showing what I expect. For instance, I have this:

$ids[0] = 7, $ids[1] = 4

which, I use this to apply the labels:

$ids = str_replace('7', '1Mbps Internet', $ids);
$ids = str_replace('4', '2Mbps Internet', $ids);
$ids = str_replace('1', '3Mbps Internet', $ids);
$ids = str_replace('8', 'Commercial Internet', $ids);
$ids = str_replace('12', 'Tower Friends', $ids);
$ids = str_replace('6', 'Cable TV', $ids);
$ids = str_replace('11', 'Cable TV Basic', $ids);
$ids = str_replace('5', 'VOIP', $ids);
$ids = str_replace('10', 'Web Services', $ids);

However, my output is looking like this:

3Mbps InternetMbps Internet, 2Mbps Internet

When it should come out like this:

1Mbps Internet, 2Mbps Internet

Which, that code is as follows:

$Package1 = $ids[0]; 
$Package2 = $ids[1];
$Package3 = $ids[2];
$Package4 = $ids[3];

if (!$Package1) {$P_word = "$Package:"; $Packages = "None Subscribed";}
else if ($Package1 && !$Package2) {$P_Word = "Package:"; $Packages = "$Package1";}
else if ($Package1 && $Package2 && !$Package3) {$P_Word = "Packages:"; $Packages = "$Package1, $Package2";}
else if ($Package1 && $Package2 && $Package3 && !$Package4) {$P_Word = "Packages:"; $Packages = "$Package1, $Package2, $Package3"; }
else {$P_Word = "Packages:"; $Packages = "$Package1, $Package2, $Package3, $Package4"; }

I am really unfamiliar with PHP, but it seems like it should be working. Is there something I am missing here?

Thank you.

Error in mutiple if statements

I am writing the following code in R but it gives me an error

S=function(x,a){
if(x<=a) {return (g)}
    else 
        if (a < x <= b) {return(h)}

> Error: unexpected '<=' in:
> "
>    else if (a < x <="
>                   else (return(i))
>    }

How do I correct it?

Quick sorting method for c++

I remember there being a quick way of sorting variables using if statements (not bubble sorting) but I can't remember how to execute it exactly

its was something along the lines of

if (a > b)& b : a;

but that isn't right.

If anyone knows what I'm talking about could you please refresh my memory?

MSProject/Excel VBA Loop through 'Flag' columns, how?

Hopefully an easy one. In Excel VBA, I'd like to be able to loop through the custom flag columns in a MSProject file I have open.

In pseudo

For i = 1 to 20
If task.flagi then ....

Ho do I write the 'flagi' in code?

Thanks,

Jon C

(CPP) Does an IF-Statement checks every OR operator?

At the moment I´m testing around with particles and have one important question.

if (condition a || condition b || condition c)

or

if(condition a)
        if(condition b)
             if(condition c){

}

What is faster?

Arduino+processing and string information in an "if" statment

I am using an arduino to read out information from a scale into Processing. Now I want certain things to happen depending on the weight registered. The weight is read out in a String. I have found out that ">=" does not work for strings. I have tried "if (val >= str ("20.00")){" but that doesnt work either. I have also tried to convert it into a float using "float scale = Float.parseFloat(val);" But that doesnt work either. Does anyone have an idea. That would be great!

PImage pictureday;
import processing.serial.*;
import cc.arduino.*;
import org.firmata.*;

Serial myPort;  
String val;     
color textcolor = color(0, 50, 50, 240);
color textcolor2 = color(255, 0, 0); 

void setup()
{
  fullScreen();
  background (189, 215, 239);
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) 
  {  // If data is available,
    val = myPort.readStringUntil('\n'); 
  } 

  if (scale >= 20.00)
  { 
    image(pictureday, 0, 0);  
    textSize(50);
    fill(textcolor);
    text(val, 900, 360);
    text("KG ", 1030, 360);  
    println (val);
  }
}

getting error after copying&pasting results from VBA recorder into editor

I'm hoping someone can explain to me why I'm having difficulty. I put in a monster of an 'if' statement and used the VBA recorder to get it into VBA-speak. However, after copying and pasting the results into the code, I get the following message when it reaches that specific line:

"Run-time error '1004': Application-defined or objected-defined error"

Has anyone ever encountered this issue before?

I really hope to get some solutions without having to post the 'if' statement here. It's a doozy.

Thanks.

java, catching last letter of string

I got a question that I was not able to answer... Any help would be appreciated.

Question --> "Show a name and a region where the last letter of the name equals the last letter of the region."

I have tried to answer it but can't get it right.

static void oneLine(String name, String region,
               int area, long pop, long gdp)
{
  if (name.substring(name.length() - 1)  == name.substring(region.length()-1))
    {
      System.out.println(name+"  "+region);
    }
 }

How can I implement this?

Wrong computation in ifelse on factors

I have a dataframe called g1. It has 3 columns that are factors: max_num, max_res and g1$bdest. I have a number N = 8. I would like to create a new column with name g1$WMA. For each row: in case g1$max_num > N/2 I would like g1$WMA to get the value g1$max_res otherwise - g1$bdest. I used the following command, however I get a wrong computation:

g1$WMA = ifelse ( (( as.numeric(as.character(g1$max_num) ) )> (N/2)), g1$max_res, g1$bdest) 

How can I correct it?

if the first value equal to one then echo

In a bash script I read a file aa001 and return the first value. When the first value is equal to 1, return a message like ok, on the terminal

#!/bin/bash  
varReprise=`head -n 1 aa001`
echo $varReprise
un=1
if [`$varReprise` = `$un`]
 then
   echo " OK "
else 
   echo "not Ok"
fi

But I have the following error when I run the script:

./test: ligne 5: 1 : command not found 
./test: ligne 5: [: « ] » command not found 

Razor outputting my if statement as HTML

So I have a razor which I'm using to check the months and years that a learning module is running for:

        @{  
                string liClass = "prl-4 prs-3";

                if(cssCount == 4){
                    liClass = "alpha prl-4 prs-3";
                }

                <li class="@liClass">
                <i class="icon-test"></i> 

                if(cYears.Count() > 1) {
                      if (cMonthDisplays.Count() > 1) {

                      @cMonthDisplays[0]<text>&nbsp;</text>@cYears[0] <text>/</text> @cMonthDisplays[1]<text>&nbsp;</text>@cYears[1]
                      } else {
                        @cMonthDisplay<text>&nbsp;</text>@cYears[0] <text>/</text> @cMonthDisplay<text>&nbsp;</text>@cYears[1]
                      }
                }
                else {
                      @cMonthDisplay<text>&nbsp;</text>@cYearDisplay
                }

                </li>
                cssCount++;
            }

The first part of my razor works correctly and the class of the li is replaced when the if statement finds that the count does match 4.

However after the initial 'if' statement worked the second if statement outputs to my page as HTML.

This is then displayed on my page:

      if(cYears.Count() > 1) {
            if (cMonthDisplays.Count() > 1) {
               March 2016 / September  2017 
             } 
             else { March, September 2016 / March, September  2017 } 
      } 
      else { March, September 2016, 2017 }

I'm a bit stuck as to why my if statements are displaying only for the second if statement. I'm probably missing something really obvious - but any help would be greatly appreciated!

lundi 28 septembre 2015

Check if object attributes are non-empty python

I can check if python list or dictionary are empty or not like this

lis1, dict1 = [], {}
# similar thing can be done for dict1
if lis1:
    # Do stuff
else:
    print "List is empty"

But if I try to do this with my class object, i.e checking if my object attributes are non-empty by typing if my_object: this always evaluate to True

>>> class my_class(object):
...   def __init__(self):
...     self.lis1 = []
...     self.dict1 = {}
... 
>>> obj1 = my_class()
>>> obj1
<__main__.my_class object at 0x10c793250>
>>> if obj1:
...   print "yes"
... 
yes

I can write a function specifically to check if my object attributes are non-empty and then call if obj1.is_attributes_empty():, but I am more interested in knowing how if evaluates the standard data-types like list and dict to True or False depending on the items they contain or are empty.

If I want to achieve this functionality with my class object what methods I need to override or make changes to

Escape if statement in C

#pragma warning(disable: 4996)
#include<stdio.h>
int main(){    
    double array1[8] = {0};    
    double data;    
    double lg_data=0;    
    int i = 0, j = 0;    
    int count = 1;    
    int lg_count = 1;    

    printf("7개의 양의 실수를 입력하세요.(마지막 원소는 자동으로 -1이 됩니다.)\n");
    for (i = 0; i < 8; i++){
        if (i == 7){
            array1[i] = -1;
        }
        else{
            scanf("%lf", &array1[i]);
        }
    }//end of loop
    for (i = 0; i < 8; i++){
        count = 1;
        for (j = 0; j < i; j++){
            if (array1[i] == array1[j]){
                count++;
                if (count >= lg_count){
                    lg_count = count;
                    data = array1[i];
                    if (data >= lg_data){
                        lg_data = data;
                    }
                }
            }
            else{
                if (array1[i] >= lg_data){
                    lg_data = array1[i];
                    lg_count = count;
                }
            }
        }//end of for(j)
    }//end of for(i)
    printf("%lf %d\n", lg_data, lg_count);
    return;

If there are values that agree with if (array1[i] == array1[j]) statement, I want to stop for loop even though still have values that agree with else statement. I already tried to put break statement inside if statement ... but it didn't work. How could I solve this problem?

Using a BOOL to replace verbose code

I have a hideous line of code that's a gigantic PITA to type repeatedly and to read. I tried to replace it with a nice, neat BOOL property and corresponding method in my class, but it's "flakey" (and it doesn't crash). I'd like to replace this hideous monstrosity with something neater. Here's what I've done so far.

This is works...

    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"stretchMultiplier"]integerValue] * self.currentStretch.sideMultiplier.integerValue < self.stretchSideMultiplierCount) {
        // blah blah blah
    }

...but it looks hideous, so I tried to get rid of it by creating a BOOL property in the implementation:

@property (nonatomic, assign) BOOL lastRoundOfCurrentStretch;

...and a method down below...

- (BOOL) lastRoundOfCurrentStretch {
    if (self.currentStretch.sideMultiplier.intValue * [[[NSUserDefaults standardUserDefaults]valueForKey:@"defaultStretchRepetition"]intValue] == self.stretchSideMultiplierCount) {
        NSLog(@"** LAST ROUND **");
        return YES;
    } else {
        return NO;
    }
}

When I'm done, I'd like to be able to use this BOOL as an alternative to typing out the hideous line of code at the top of my query.

Begin Edit This should be NO, not YES, as I originally typed.

    if (self.lastRoundOfCurrentStretch == NO) {
        // blah blah blah
    }

End Edit

After I made the change, the class isn't working the way it "used to", but it's not crashing. I'm certain this boils down to startlingly stupid user error on my part, but I'm coming up short finding an answer here. This is as close as I got to an answer that's applicable to what I'm trying to do.

Using a BOOL property

Boolean behaving strange, logic issue

I'm having an issue with boolean expected behavior. I can make the desired result but I'm not sure why the strange behavior occurs. This:

def palindrome?(string)
  rev = string.reverse
  if rev == string
    true
  else
    false
  end
end

produces a wrong result:

palindrome?("abc") == false: true
palindrome?("abcba") == true: true
palindrome?("z") == true: true

while this:

def palindrome?(string)
  rev = string.reverse
  if rev == string
    true
  end
end

produces the correct result:

palindrome?("abc") == false: false
palindrome?("abcba") == true: true
palindrome?("z") == true: true

The following might be similar:

def nearby_az(string)
  counter = 0
  string = string.split("")
  if string.count == 1
    false
  elsif (string.index("z") - string.index("a")) <= 3
    true
  else
    false
  end
end

nearby_az("a") == false: true
nearby_az("z") == false: true

SPARC Assembly Condition Statement

I have this bit of code

swap:

        cmp     %min_r, %y_r    !comparing the minimum

        bg      last            !If result is greater than 0, skip

        nop

        mov     %y_r, %min_r    !branch execution

last:

        add     %x_r, 1, %x_r   !x++

        cmp     %x_r, -1        !comparing x

        bg      loop            !go back to loop

        nop                     !delay slot

        mov     1, %g1

        ta      0

Which technically should move the minimum value if needed, and then jump to last to do the increment and quit the program if needed.. However, if I don't put the labels in and get rid of swap label and it's contents, and also get rid of label last, the increment works perfect and either jumps back to loop or exits. However, once I add the swap in it gives me an error of a "recursive infinite loop"

Here is what gdb says

0x106d4 <loop+92>:      cmp  %l1, %l2  <--- Here I am comparing my current minimum with the y value

(gdb) ni

0x000106d8 in loop ()

1: x/i $pc

0x106d8 <loop+96>:      bg  0x106e4 <last>  

0x106dc <loop+100>:     nop 

(gdb) ni

0x000106dc in loop ()

1: x/i $pc

0x106dc <loop+100>:     nop <---- followed right after by this nop, but instead of jumping to either last or executing the swap, the program exists

(gdb) ni



Program exited with code 0354.

(gdb) 

The program is not being run.

(gdb) 

I followed the example from the book and from the notes I took, and for some reason it's not working, I can't seem to spot the bug...Any suggestions?

How to check if an array has enough empty/null "consecutive" positions to place values together randomly in Java?

I'm creating a commercial airline flight program and I'm still learning how to get around with Java. So, I was wondering if there was any way to check if an array has enough consecutive positions to place values together in those positions in the array? For example, I have an array of strings called seats, each position in this array corresponds to an available seat on the flight. Initially these seats are all empty.

String[] seats = new String[8];

In the long-run, this program is going to be inserting values into this array and I want my program to be able to check if there are any empty seats(positions) in the flight(array) to assign a passenger to a seat. I sketched this to check.

for(int i=0; i< seats.length-1;i++) {
if(seats[i] != null) {
     do something;
   } else {
       system.out.println("No seats available");
       (how do I not assign seats or accept more values to my array?)
   }
}

but advised on using an objective approach, I got to this

private static int MAX_SEATS = 8;
private String[] seats = new String[MAX_SEATS];

public boolean addPassenger(String passengerName) {
    for (int i = 0; i < seats.length; i++) {
        if (seats[i] == null) {
            seats[i] = passengerName;
            return true;
        }
    }
    return false;
}

If the program finds an empty seat after checking, It should then check again if there are empty consecutive seats. (For example, if we wanted to make 3 passengers seat together, the program should check if there are empty 3 seats and then seat them there). If the program finds 3 consecutive positions in the array, it should randomly assign the passengers to whichever 3 position. otherwise it should randomly try another seat, repeating until successful. Right now, my array of seat can take up to 8 values, so the possible 3 positions could be (1,2,3 or 2,3,4 or 3,4,5 or 4,5,6 or 5,6,7). If the program does not find a consecutive position to seat these 3 people, it should randomly place them in different positions.(pick random seat numbers till it can find an empty seat) This code is just adding passengers to the seats array .

//accepting more values to the seats array
public boolean addPassengers(String... passengerNames) {
    boolean everyoneAdded = true;
    for (String passengerName : passengerNames) {
        everyoneAdded = everyoneAdded && addPassenger(passengerName);
    }
    return everyoneAdded;
}

How is it possible to check for consecutive positions in an array in order to add groups of passengers randomly? Any correction/contribution would be helpful.