mardi 28 mars 2017

Why does an assignment works as a condition?

I know that an assignment can be used as a condition in () after if statement. Like

int i;
if(i = 1) printf("Hey guys !");

. But It is unlike usual conditions like a < b , so I can`t understand its mechanism. Why can it works as a condition?

while loop doesn't stop, with if statement as nested loop

see my code below:

x = -1
num = -9

print("For exit press 0")

while (x != 0):
    num = input("Enter a number  :")
    print("You entered: ", num)
    x = num
    if x == 0:
        break


print("Good bye!")

The code doesn't stop even if 0 is fed as value. what could be the possible reason?. Thanks!

Not getting same results using switch statement and if else

I have the following code that looks like this:

if ((peek() >= '0' && peek() <= '9') || peek() == '.'){
        return number();
    }else if (peek() == '('){
        cout<<"(\n";
        get(); // '('
        double result = expression();
        cout<<")\n";
        get(); // ')'
        return result;
    }
    else if (peek() == '-'){
        get();
    }
    return 0;

If I enter something that looks like (2*5) + 7 the output will look like:

(
*
+
)
17

which is the format I want. I want to try to achieve the same results using a switch statement but I can't get it to work with parenthesis. Here is my switch statement:

switch (peek()){
        case '0':
            return number();
            //break;
        case '1':
            return number();
            //break;
        case '2':
            return number();
            //break;
        case '3':
            return number();
            //break;
        case '4':
            return number();
            //break;
        case '5':
            return number();
            //break;
        case '6':
            return number();
            //break;
        case '7':
            return number();
            //break;
        case '8':
            return number();
            //break;
        case '9':
            return number();
            //break;
        case '.':
            return number();
            //break;
        case '-':
            get();
            //break;
        case'(':
            cout<<"(\n";
            get();
            double result = expression();
            get();
        default:
            return 0;
            //break;
    }

with my Switch statement I get an error stating: cross initialization of 'double result'. I can get the error removed if I eliminate the case'('How can I make my switch statement work with the parenthesis so I get the same output? It seems like that's where the problem is.

IndexOutOfBoundsException Index 0 Size 0

I am writing a program that pretty much is taking a string of numbers and operators, splitting them up, then doing the calculations on it. I have four separate IF statements for each operator inside a For loop. The code compiles, but gives me an IndexOutOfBoundsException Index:0 Size:0 at lines 70 and 28. Does anyone have any suggestions as to why this is happening? Thanks.

import java.util.*;
import java.io.*;

public class Lab8
{
public static void main( String[] args)
{
    if ( args.length<1) { System.out.println("FATAL ERROR: Missing expression on command line\nexample: java Lab8 3+13/5-16*3\n"); System.exit(0); }

    String expr= args[0];  // i.e. somethinig like "4+5-12/3.5-5.4*3.14"; 
    System.out.println( "expr: " + expr );
    ArrayList<String> operatorList = new ArrayList<String>();
    ArrayList<String> operandList = new ArrayList<String>();

    StringTokenizer st = new StringTokenizer( expr,"+-*/", true );
    while (st.hasMoreTokens())
    {
        String token = st.nextToken();
        if ("+-/*".contains(token))
            operatorList.add(token);
        else
            operandList.add(token);
        }
    System.out.println("Operators:" + operatorList);
    System.out.println("Operands:" + operandList);

    double result = evaluate( operatorList, operandList );
    System.out.println("The expression: " + expr + " evalutes to " + result + "\n");
} // END MAIN





static double evaluate( ArrayList<String> operatorList, ArrayList<String> operandList)
{
    String operator;
    double result;

    ArrayList<Double> andList = new ArrayList<Double>();

    for( String op : operandList )
    {
        andList.add( Double.parseDouble(op) );
    }

    for(int i=0;i<operatorList.size();++i)
    {
        if(operatorList.get(i).equals("*"))
        {
        operator = operatorList.get(i);
        }
            result = andList.get(i) * andList.get(i+1); 
            andList.set(i,result); 
        //operandList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);


        if(operatorList.get(i).equals("/"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) / andList.get(i+1); 
            andList.set(i,result); 
            andList.remove(i+1);
            operatorList.remove(i);



        if(operatorList.get(i).equals("+"))
        {
            operator = operatorList.get(i);
        }   
            result = andList.get(i) + andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i); 



        if(operatorList.get(i).equals("-"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) - andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

    }

    return andList.get(0);  
}

} //

Cannot send email in localhost

why i can't send email in localhost but when i try in hosting it can send email this my code **

define('ROOT', 'localhost/OMG1/');
$kode = md5(uniqid(rand()));
$to = $_GET['f11'];
        $headers = "From: rizka.nugroho@omg-indonesia.com\r\n";
        $headers .= "Reply-to: $to\r\n";
        $pesan    = "Klik link berikut untuk verifikasi dan mengaktifkan akun : ";
        $pesan    .= ROOT."active.php?email=".$_GET['f11']."&kode=$kode&username=".$_GET['f5'];var_dump($pesan);
$a = @mail($to, "Aktivasi Akun Anda", $pesan, $headers);var_dump($a); 
if($a)
        {
            echo "Email send";
        }
        else
        {
            echo "failed to send mail";
        }

** please help solved my problem

R 3.3.3 "Error in if (corl > corr) { : argument is of length zero"

Sequential similarity of similar scale

    library(quantmod)

    #input symbol, start and end dates:

    my_symbol<-readline("What symbol would you like analyzed?")
    start_date <- readline("When do you want the series to start?")
    end_date <- readline("When do you want the series to end?")

    #Scaled series begins here        
    start_date2 <- readline("When do you want the scaled series to start?")
    end_date2 <- readline("When do you want the scaled series to end?")
    s_min<-readline("What is the minimum scaling factor you would like the use?")
    s_max<-readline("what is the maximum scaling factor you would like to use?") 

    data1 <- as.data.frame(getSymbols(my_symbol, from = start_date, to = end_date, env = NULL)) 
    data2<- getSymbols(my_symbol, from = start_date2, to = end_date2, env = NULL)
    data3<- as.ts(data2[,4])

    section<-length(data3)/3
    #divide subset into 3 sections

    subdata1<-data3[1:section]
    subdata2<-data3[section:(section*2)]
    subdata3<-data3[(section*2):(section*3)]

    #Dataframe function goes here!
    data_frames<- function(subdata, df){      
                section2<-length(subdata)
                testdata1<-data1[,4]
                testdata2<-testdata1[1:section2]
                co<-readline("what is the minimum correlation accepteable for the current part?")
                corr<-as.numeric(co)
                steps<-readline("what is the minimum step desired per iteration?")
                steps_numeric<-as.numeric(steps)
                #Iterate through testdata
                len2<-length(subdata)
                x<-as.numeric(s_min)
                while (x < as.numeric(s_max)){
                  resize<-approx(seq_along(subdata), subdata, n = len2*x)$y
                  len<-length(resize)
                  for (i in seq(1, length(testdata1), by = steps_numeric)){
                    testdata2<-testdata1[(1+i):(len+i)]
                    corl<-cor(testdata2, resize)
                    corl<-na.omit(corl)
                    if(corl > corr) {
                      maxes<-c(corl, (len/len2), i)
                      write.table(maxes,"a.txt", append = TRUE, quote = FALSE, row.names = FALSE, col.names = FALSE)

                    }
                  }
                  x<-(x+0.01)
                }
                df<- read.table("a.txt")
                file.remove("a.txt")
                df<-as.matrix(df)
                df<-matrix(df, ncol = 3, byrow = TRUE)
                df<-as.data.frame(df)

              }

    df<-data_frames(subdata1,df)
    df<-df[ order(-df[,1], df[,1]), ]
    df2<-data_frames(subdata2, df2)
    df2<-df2[ order(-df2[,1], df2[,1]), ]
    df3<-data_frames(subdata3, df3)
    df3<-df3[ order(-df3[,1], df3[,1]), ]
    colnames(df)<-c("Cor", "Scale", "Step")
    colnames(df2)<-c("Cor", "Scale", "Step")
    colnames(df3)<-c("Cor", "Scale", "Step")

I get an error when running the if statement that says $Error in if (corl[i] > corr) { : missing value where TRUE/FALSE needed

How can this be resolved?

Thanks in advance

Why does my python script stop at if-else conditions?

I had written a python script with if-elseif conditions which when satisfied, would perform some task. I am taking an input from the user (1st input), and if that matches the if condition, it would execute the piece of code within that conditional block. That conditional block again contains if-else conditions and would ask the user for input again (2nd input). When i look at the code, it seems fine but when i try to execute it, the script runs successfully one time, and next time it just stops after receiving the user's input (1st input).

Below is my code:

choice1 = int(input("Enter Number 1"))

if choice1==1:
    choice2 = int(input("Enter Number 2"))
    if choice2==1:
         print "You have entered 1 - 1"
    elif choice2==2:
         print "You have entered 1 - 2"
    else:
         pass

elif choice1==2:
    choice2 = int(input("Enter Number 2"))
    if choice2==1:
         print "You have entered 2 - 1"
    elif choice2==2:
         print "You have entered 2 - 2"
    else:
         pass

elif choice1==3:
    choice2 = int(input("Enter Number 2"))
    if choice2==1:
         print "You have entered 3 - 1"
    elif choice2==2:
         print "You have entered 3 - 2"
    else:
         pass

elif choice1==4:
    choice2 = int(input("Enter Number 2"))
    if choice2==1:
         print "You have entered 4 - 1"
    elif choice2==2:
         print "You have entered 4 - 2"
    else:
         pass

else:
     pass

So when i run the script, sometimes it asks me for 'Number 1 ' followed by 'Number 2' and the script runs successfully, and sometimes the script gets stuck after asking me for 'Number 1'. I have to manually disrupt the execution and run the script again. Does anyone know what i am doing wrong? I am using 'Anaconda Prompt' for running the script.

Thanks in advance