lundi 31 août 2015

Why is this "in" statement not evaluating to True?

I have this code here

input1 = input("Toppings: ")
split = input1.split("|")
length = len(split)

for i in range(0, length-1):
  if "cheese" in str(split[i]):
    del split[i]

s = "|"
print(s.join(split))

and it's meant to take a string, split it by "|" into an array, then search the array for the string "cheese", and if it finds it; take it out of the array, and then print out the parsed array.

When inputting this:

Toppings: ham|lettuce|cheddar cheese|sliced cucumber|tomato
ham|lettuce|sliced cucumber|tomato

The output is correct - it removes the element that has "cheese" in it from the array. However, when inputting this:

Toppings: egg|lettuce|cheese spread|mac'n'cheese
egg|lettuce|mac'n'cheese

It doesn't remove it from the array. When I looked up the in operator it said it didn't match whole word only so I thought it would work. What would be the correct code to put into the if statement so it would detect "cheese" in "mac'n'cheese"?

If statement smartclient changing properties

in smart client I would like to see if its possible to have a condition for a property

if(field.Name===employeeid||employeeName||customerID||customerName||vendorID ||vendorName)

{ selectEditorType: "comboBox"; }

thats all i have

Do we still need to use `[...]` in Bash?

If don't care about compatibility or portable issue, do we still need to use test construction [...] in Bash?

Many tutorials/books tell that [[...]] is more better and more flexible than [...] e.g. [[...]] is support glob/regex, But today I still see many people prefer to use [...] as standard form.

What is a reason behind this? What [...] can do but [[...]] can not do?

Javascript Else If Style Changing Issue

JS:

var div = document.getElementById('testdiv');
var button = document.getElementById('testbutton');

function showNotification(){
    if(div.style.display = "none") {
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
}

The code above simply shows and hides a div, Well thats what its meant to do but for some reason it wont hide using display: none when its set to display block. I also tried an else if statement but nothing will work.

P.S: I know I can just do 2 functions, hide/showNotification and just make it change the onclick from hide to show respectively but its not a great way to do it.

Buffer Reader code to read input file

I have a text file named "message.txt" which is read using Buffer Reader. Each line of the text file contains both "word" and "meaning" as given in this example:

"PS:Primary school"

where PS - word, Primary school - meaning

When the file is being read, each line is tokenized to "word" and "meaning" from ":". If the "meaning" is equal to the given input string called "f_msg3", "f_msg3" is displayed on the text view called "txtView". Otherwise, it displays "f_msg" on the text view.

But the "if condition" is not working properly in this code. For example if "f_msg3" is equal to "Primary school", the output on the text view must be "Primary school". But it gives the output as "f_msg" but not "f_msg3". ("f_msg3" does not contain any unnecessary strings.)

Can someone explain where I have gone wrong?

try {
    BufferedReader file = new BufferedReader(new InputStreamReader(getAssets().open("message.txt")));
    String line = "";

    while ((line = file.readLine()) != null) {
    try {
    /*separate the line into two strings at the ":" */
    StringTokenizer tokens = new StringTokenizer(line, ":"); 
    String word = tokens.nextToken();
    String meaning = tokens.nextToken();

    /*compare the given input with the meaning of the read line */
    if(meaning.equalsIgnoreCase(f_msg3)) {
    txtView.setText(f_msg3);
    } else {
    txtView.setText(f_msg);
    }
    } catch (Exception e)  {
    txtView.setText("Cannot break");
    }
    }

}   catch (IOException e) {
    txtView.setText("File not found");
}

How to correctly refactorize this big and with very similar code if/else statements?

I'm trying to refactorize this code that would be much more bigger and I'm wondering wich is the better way to do it.

string obje = String.Empty;
long userId = 0;
long objNewId = 0;
long objOldId = 0;
string action = String.Empty;

if (oldObject.GetType() == typeof(FooDto))
{
    obje = ConstantParams.WCFLOG_APPLICATION_Foo;
    FooDto newFoo = (FooDto)response.Data;
    FooDto oldFoo = (FooDto)oldObject;

    userId = newFoo.UserApplicationId;
    objNewId = newFoo.Id;
    objOldId = oldFoo.Id;
}
else if (oldObject.GetType() == typeof(BarDto))
{
    obje = ConstantParams.WCFLOG_APPLICATION_Bar;
    BarDto newBar = (BarDto)response.Data;
    BarDto oldBar = (BarDto)oldObject;

    userId = newBar.UserApplicationId;
    objNewId = newBar.Id;
    objOldId = oldBar.Id;
}

action = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;

string message = Helper.GenerateMessage(action, obje, userId, objNewId);

The thing is that it may be possible to write something like this but don't know if something like that is possible:

obje = ConstantParams.WCFLOG_APPLICATION_[[XXX]];
[[XXX]]Dto newItem = ([[XXX]]Dto)response.Data;
[[XXX]]Dto oldItem = ([[XXX]]Dto)oldObject;

userId = newItem .UserApplicationId;
objNewId = newItem .Id;
objOldId = oldItem .Id;

Execute jquery in if statement

I got a login system, and what I want to do is to hide a div and show another div when the user types the incorrect login details. However it doesn't seem to work.

if(...) { // here I check if the user enters the correct information

... //much code inside

} else { // if incorrect info, do this
    echo "<script>$('#jqueryhide2').hide();
        $('#jqueryhide').show();</script>";
}

Tried to google a bit but can't find anything that could solve my problem.

Last 30 days and % of weighted average Sales- Trailing date Range

I'm trying to build a calculated True/False field. I'm struggling with creating a trailing date range to make the formula just evaluate the last 30 days.

I want to create a formula that displays:

IF in the last 30 days SUM([rev]) > 500 AND SUM([QTY]) > 10 AND the current listing price for a unit of the material is less than 70% of the last 30 day [AvgWeightedPrice] THEN "True" ELSE "False" END

I am using a standard [Date] field (mm/dd/yyyy)

Any help would be much appreciated. Thanks

Check first condition in IF and test in the next statement too in Python

I'd like to understand something in Python - IF condition. Using this example code:

num = 1

if (num == 1):
    print ("op 1")
elif (num < 2):
    print ("op 2")
elif (num <= 1):
    print ("op 3")
elif (num != 1):
    print ("op 4")
else:
    print ("Fail")

print ("End")

I'll get the first condition and then go to the end.

How can I do it to check, for example, the first and if True go check the next condition too? And check all of them?

Trying to use CONTINUE not worked; I used a bunch of IFs instead of IF->Elif, but is this the right way to do?

bash scripting not opening text editor

following code executed in a terminal opens a text editor and displays loop.txt:

if [ -f loopy.txt ]; then
rm loopy.txt
touch loopy.txt
for i in $( seq 1 10)
do
echo $i line added >> loopy.txt
done
xdg-open loopy.txt

if I run it as a script, text editor does not open. Can anyone tell me why not?

Tks, Robert

If-Else statements

Hey guys I am making a java application to book installation. I am trying to set up an If else statement to make the InstallType column print out either "Standard" or "Custom" The way it needs to do this is: if the numOutlets variable is greater than 4 OR is numZones is greater than 2 then is should print out Custom. If the number of either numOutlets is lower or equal to 4 or the number in numZones is equal to or less than 2 it should print out "Standard".

I am trying to make it do this on the enterButton:

 public void enterButtonClicked(){
    Installation installation = new Installation();
    installation.setCustomerName(nameInput.getText());
    installation.setHouseNumber(Double.parseDouble(houseInput.getText()));
    installation.setStreetName(streetInput.getText());
    installation.setTown(townInput.getText());
    installation.setNumOutlets(Integer.parseInt(outletInput.getText()));
    installation.setNumZones(Integer.parseInt(zoneInput.getText()));
    installationTable.getItems().add(installation);

    double numOutlets = Double.parseDouble(outletInput.getText());
    double numZones = Double.parseDouble(zoneInput.getText());

    if (numOutlets>=2 || numZones>=5)
        installationType = "Custom";
    else
        installationType = "Standard";

    installType.setText(InstallationType + "");


    nameInput.clear();
    houseInput.clear();
    streetInput.clear();
    townInput.clear();
    outletInput.clear();
    zoneInput.clear();


}

This is my TableView

public void start(Stage primaryStage) throws Exception {

    window = primaryStage;
    window.setTitle("CQ Air-Conditioning");

    //installationID
    TableColumn<Installation, Integer> installationID = new TableColumn<>("Installation ID");
    installationID.setMinWidth(100);
    installationID.setCellValueFactory(new PropertyValueFactory<>("installationNumber"));

    //CustomerName
    TableColumn<Installation, String> nameColumn = new TableColumn<>("Name");
    nameColumn.setMinWidth(200);
    nameColumn.setCellValueFactory(new PropertyValueFactory<>("customerName"));


    //House Number
    TableColumn<Installation, Double> houseNo = new TableColumn<>("House Number");
    houseNo.setMinWidth(100);
    houseNo.setCellValueFactory(new PropertyValueFactory<>("houseNumber"));


    //Street Name
    TableColumn<Installation, String> street = new TableColumn<>("Street Name");
    street.setMinWidth(200);
    street.setCellValueFactory(new PropertyValueFactory<>("streetName"));


    //Town Name
    TableColumn<Installation, String> Town = new TableColumn<>("Town Name");
    Town.setMinWidth(200);
    Town.setCellValueFactory(new PropertyValueFactory<>("town"));

    //number outlets
    TableColumn<Installation, Double> numberOutlets = new TableColumn<>("Outlets");
    numberOutlets.setMinWidth(50);
    numberOutlets.setCellValueFactory(new PropertyValueFactory<>("numOutlets"));

    //number Zones
    TableColumn<Installation, Double> numberZones = new TableColumn<>("Zones");
    numberZones.setMinWidth(50);
    numberZones.setCellValueFactory(new PropertyValueFactory<>("numZones"));

    //Installation Type
    TableColumn<Installation, String> installType = new TableColumn<>("Type of Installation");
    installType.setMinWidth(200);
    installType.setCellValueFactory(new PropertyValueFactory<>("installationType"));

    //total cost
    TableColumn<Installation, Double> cost = new TableColumn<>("Total Cost");
    cost.setMinWidth(150);
    cost.setCellValueFactory(new PropertyValueFactory<>("totalCost"));



    //nameInput
    nameInput = new TextField();
    nameInput.setPromptText("Enter Name");
    nameInput.setMinWidth(100);

    //houseInput
    houseInput = new TextField();
    houseInput.setPromptText("enter house number");

    //streetInput
    streetInput = new TextField();
    streetInput.setPromptText("enter street Name");

    //town input
    townInput = new TextField();
    townInput.setPromptText("enter town");

    //outlets input
    outletInput = new TextField();
    outletInput.setPromptText("enter number of outlets");

    //zones input
    zoneInput = new TextField();
    zoneInput.setPromptText("enter number of zones");

    //buttons
    Button enterButton = new Button ("Enter");
    enterButton.setOnAction(e -> enterButtonClicked());
    enterButton.setMinWidth(200);
    Button clearButton = new Button ("Clear");
    clearButton.setOnAction(e -> clearButtonClicked());
    clearButton.setMinWidth(50);
    Button deleteButton = new Button ("Delete");
    deleteButton.setOnAction(e -> deleteButtonClicked());
    deleteButton.setMinWidth(50);
    Button exitButton = new Button ("Exit");
    exitButton.setOnAction(e -> exitButtonClicked());
    exitButton.setMinWidth(50);


    HBox hbox = new HBox();
    hbox.setPadding(new Insets(25, 10, 50, 10));
    hbox.setSpacing(10);
    hbox.getChildren().addAll(nameInput, houseInput, streetInput, townInput, outletInput, zoneInput);

    HBox buttons = new HBox();
    buttons.setPadding(new Insets(10,10,10,10));
    buttons.setSpacing(15);
    buttons.setAlignment(Pos.CENTER);
    buttons.getChildren().addAll(clearButton, enterButton, deleteButton, exitButton);


    installationTable = new TableView<>();
    installationTable.setItems(getInstallation());
    installationTable.getColumns().addAll(installationID, nameColumn, houseNo, street, Town, numberOutlets, numberZones, installType, cost);


    VBox vbox = new VBox();
    vbox.getChildren().addAll(hbox,installationTable, buttons);

    Scene scene = new Scene(vbox);
    window.setScene(scene);
    window.show();
}

I am using a "Main" class and a class called "Installation" with my variables and getters and setters.

This is my variables in the "Installation" Class

private String customerName;
private String streetName;
private String town;
private String installationType;

private double postCode;
private double houseNumber;
private int numZones;
private int numOutlets;
private double totalCost;
private double standardCost = 7200;
private double customCost;

private int installationNumber = 0;

Thank you to anybody that helps me, i have been trying at this for ages and cant quite seem to get it. Thanks so much! sorry if i am not posting correctly, still trying to learn.

App crashes on if statement [duplicate]

This question already has an answer here:

I want to create a randomizer app but every time i click on the button the app crashes here is the code for the MainActivity.java

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;

    import java.util.Random;

    public class MainActivity extends AppCompatActivity {

        TextView random_number_text_view;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

        random_number = (TextView) findViewById(R.id.random_number_text_view);

    }

    public void onButtonClick(View view) {

        Random random = new Random();

        int randomNumber = random.nextInt(5 - 1) +1;


        if (randomNumber == 1){

         random_number_text_view.setText(randomNumber);
     }

        else {

         random_number_text_view.setText(randomNumber);
        }

    }
}

And here for the activity_main.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
        xmlns:tools="http://ift.tt/LrGmb4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|top"
        android:orientation="vertical"
        android:padding="20dp"
        tools:context=".MainActivity">

    <TextView
        android:id="@+id/random_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/random_number"
        android:textSize="30sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onButtonClick"
        android:text="Click me" />

</LinearLayout>

Python: How to figure out the output of these if & else statements?

The code is written below. I'm having trouble understanding what would be the output of these codes if certain numbers were being input.

m = int(input("Enter a number: "))
for n in range(m):
    for k in range(m):
        if (n > k):
            print (" G ", end='')
        elif (n < k):
            print (" L ", end='')
        else:
            print(" E ", end='')
    print(" ")

For example, what would be the output if:

the value input for max is 5 the value input for max is 1 the value input for max is 0

for loop gets to the end of the string

I'm practicing Java at CodingBat.com, and I have a problem.

zipZap("azbcpzpp") returns "azbcpzpp". Expected to return "azbcpzp"

Thanks

// http://ift.tt/1yb3m7N
// Look for patterns like "zip" and "zap" in the string -- length-3,
// starting with 'z' and ending with 'p'. Return a string where for 
// all such words, the middle letter is gone, so "zipXzap" yields "zpXzp". 

public String zipZap(String str) {
  if (str.length() < 2)
    return str;

  String result = str.substring(0, 1);

  for (int i=1; i < (str.length()-1) ; i++) {
    if ((str.charAt(i-i) != 'z') || (str.charAt(i+1) != 'p')) 
      result += str.charAt(i);
  }

  result += str.substring(str.length()-1);  

  return result;
}

dimanche 30 août 2015

How do i encase Infobox Parameters inside a #if

I am trying to create a template based off the Infobox Template i exported from Wikipedia following the instructions here

I first got the Infobox working with the following code

{{Infobox
|above = Nanoha Takamachi
|image= [[Fie:nanoha.jpg|200px]]
|caption = Young Nanoha (left) and Adult Nanoha (right)
|data1 = http://ift.tt/1Fb3pP1

|header2 = Character Profile
|label3 = Other Names
|data3 = Ace of Aces<br/>The White Devil
}}

and that worked perfectly. given that this infobox will more or less be reused for other characters i figured i'd create it as a template so if i changed header2 it will apply to all uses of the template and for fields like label3 i can just provide the value of data3 (ie othername = Ace of Aces<br/>The White Devil)

Looking into the #if functionality i tried to turn data1 into an optional field to only appear if the parameter wikia is defined

{{Infobox
|above = {{{name}}}
|image= [[Fie:{{{image}}}|200px]]
|caption = {{{description}}}
|-
{{#if: {{{wikia|}}}|
{{!}}data1 = {{{wikia}}} }}

|header2 = Character Profile
|label3 = Other Names
|data3 = Ace of Aces<br/>The White Devil
}}

with {{!}} being just a | in a new template (Template:!) as i read that to use | inside #if i need to call another template

However while the the first 3 values appear the 4th doesn't appear, even when i replaced the ! Template with a |. when i change it to

|data1 = {{{wikia|}}}|{{{wikia}}} }}

it does appear when wikia is specified and disappears when it isn't. while it looks how i want it my goal was to also make label3 and data3 optional so they only appear if a single paramater is passed rather than doing something like this

|label3 = {{{othernames|}}}|Other Names }}
|data3 = {{{othernames|}}}|{{{othernames}}} }}

So how can I encase one or more infobox parameters inside the single #if

if else condition in angularjs to compare string and int value

I want to check if both the font and the fontSize is undefined which was sent from the client side.When the user do not select the font or font size, it pass the value undefined. These conditions work well when only one of them (font or font size) is undefined, but when both of them are undefined, I recieve an error,

TypeError: Cannot read property 'font' of undefined
    at Scope.StylesCtrl.$scope.addStyles (http://ift.tt/1ie3M6q)
    at fn (eval at <anonymous> (http://ift.tt/1IxDqBe), <anonymous>:4:317)
    at ngEventDirectives.(anonymous function).compile.element.on.callback (http://ift.tt/1ie3M6u)
    at Scope.$get.Scope.$eval (http://ift.tt/1IxDqBj)
    at Scope.$get.Scope.$apply (http://ift.tt/1ie3Jr5)
    at HTMLInputElement.<anonymous> (http://ift.tt/1IxDsZO)
    at HTMLInputElement.jQuery.event.dispatch (http://ift.tt/1ie3MmK)
    at HTMLInputElement.jQuery.event.add.elemData.handle (http://ift.tt/1IxDqBm) undefined

Below is my if else conditions in the server side,

if(font == undefined && fontSize == undefined){ //doesn't work
        console.log("font");
        updateFile(main, [
            {rule: ".made-easy-themeColor", target: "color", replacer: color}
        ], function (err) {
            console.log((err));
        });
    }

    else if(font == undefined){ //work well
        updateFile(main, [
            {rule: ".made-easy-themeColor", target: "color", replacer: color},
            {rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
        ], function (err) {
            console.log((err));
        });
    }
    else if(fontSize == undefined){ //work well
        updateFile(main, [
            {rule: ".made-easy-themeColor", target: "color", replacer: color},
            {rule: ".made-easy-themeFont", target: "font-family", replacer: font}
        ], function (err) {
            console.log((err));
        });
    }

    else{ //work well
        updateFile(main, [
            {rule: ".made-easy-themeColor", target: "color", replacer: color},
            {rule: ".made-easy-themeFont", target: "font-family", replacer: font},
            {rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
        ], function (err) {
            console.log((err));
        });

    }

This is the html code in front end

 <h3 ng-style="{'font-family': styles.textSize.font, 'font-size': styles.textSize.size + 'px'}">Text Is</h3>

This is the controller to send data to the server

$scope.addStyles = function(styles) {
            $scope.fontdata = {
                appId: "55c0ace94aa248735d75b140",
                header: styles.uploadme,
                color: styles.myColor,
                font: styles.textSize.font,
                fontSize: styles.textSize.size
            };
                stylesService.editStyles($scope.fontdata)
                    .success(function (res) {
                        console.log("success");
                    })
        };

Is there any problem with my if else statements? or is it because I am comparing string value(font) and an int value(fontSize)?

errors in while loop in pl/sql stored procedure when using with mysql

CREATE PROCEDURE grades() 

BEGIN 
DECLARE avrg,p,c,m,no int(3);
declare grd varchar(20);
set no=1 ;

while no < 11 do  
select phy,chem,math into p,c,m from stud where id=no; 
set avrg=(p+c+m)/3;

if (avrg%10)<4.00 then set grd="fail";
else if  (avrg % 100) < 0.50 then set grd="pass";
else if (avrg % 100) < 0.56 then set grd="sec";
else if (avrg % 100) < 0.60 then set grd="Hsec";
else if (avrg % 100) < 0.66 then set grd="First";
else if (avrg%100) > 0.66 then set grd="Distinction";
end if ;

update stud set avg='avrg',grade='grd' 
where id=no;
set no=no+1;

end while ;
end$$

this code is giving error

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'while ; end' at line 1.

Please help.

Foreach column loop and IF EXISTS Issue

How do I send the columns for only the row selected thru another query without their values? This is what i have but i am not sure if $key is the correct value to use for this.

    echo "
    <div class='formTitle' style='position: relative; text-align: center; margin-top: 20px'>Medals</div>
    <table class='profileTable' id='medalTable' style='border-top-width: 0px'>
    ";
$mID = $_GET['mID'];
$awardObj = new Award($mysqli);
$awardObj = new Basic($mysqli, "clanawards", "name");
$result = $mysqli->query("SELECT * FROM ".$dbprefix."clanawards_members WHERE maa_member_id = '$mID'");
    while($row = $result->fetch_assoc()) {
        //RETRIEVE ALL COLUMN NAMES then run a foreach to run each one through the next query
            foreach($row = $key) {
            $result = $mysqli->query("SELECT * FROM ".$dbprefix."clanawards WHERE name = '$key'");
                while($row = $result->fetch_assoc()) {
                    $awardName = $row['name'];
                    $description = $row['description'];
                    echo "
                        <tr><td class='main' align='center'>Viewing all medals now<br><br>$awardName </td></tr> 
                    ";
            }
        }
    }
echo "</table>";

Just missing the value i need for the columns. Been racking my brain of this and need a fresh pair of eyes.

i want to send the columns for only the row selected thru another query.

Why Scanner.next of "C" is not equal to String "C" [duplicate]

This question already has an answer here:

My code is:

import java.util.Scanner;

public class EvaluateTemperature {

public static void main(String[] args)
{
    Scanner temperatureScanner = new Scanner(System.in);
    Scanner unitScanner = new Scanner(System.in);
    Double  converted = 0.0;

    System.out.println("What's the temperature now?");
    int temperature = temperatureScanner.nextInt();

    System.out.println("Is it Celsius or Fahrenheit?");
    String unit = unitScanner.next();

    System.out.println(unit == "C");

    if (unit == "C")
    {
        converted = temperature * 1.8 + 32;
    }

    if (unit == "F")
    {
        converted = (temperature - 32) / 1.8;
    }

    System.out.println(converted);

    temperatureScanner.close();
    unitScanner.close();
    }
}

The input and output in the console is:

What's the temperature now?
40
Is it Celsius or Fahrenheit?
C
false
0.0

It seems that the block code of if has not been executed because the value unit is not equal to “C” or “F”.

With the code System.out.println(unit == "C”); of which the output is “false”, it can be proved that even thought I input “C” to the value unit, the value unit is not equal to “C”.

WHY?

Thanks.

How can I check if one value is A or B and another value is A or B?

I'm trying to do something to the effect of:

if (firstChoice == A || B && secondChoice == A || B){
    //passes check.
}

Logically, I want this to pass if the first and second choice are either A or B. Is this syntax valid? Is there a better way to do it?

Using JavaScript & Regex how to check if my current url matches a certain pattern?

The pattern of the url would have to match this: http://ift.tt/1ErBgYW

if(current url matches the pattern) then execute code end if

<script type="text/javascript">

    var currentURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

</script>

Xcode Display Image if there is no image on Imageview

I need help to make somthink like this

IBOutlet UIImageView *imageview;
IBOutlet UIImageView *imageview2;

If(imageview have no image){
 SET this image @"x";
}else if(imageview2 have no image){
 Set this Image @"x";
}

And save and load the code With NSuserdefaults

PLS HELP!

THANKS!

if elseif else statement

What is the substantial differences between these if-else, if-elseif-else statements:

if (condition 1) {
    die();
}
elseif (condition 2) {
    die();
}
else {
    code;
}

,

if (condition 1) {
    die();
}
elseif (condition 2) {
    die();
}
elseif (!condition 1 && !condition 2) {
    code;
}
else {
    die();
}

and

if (!condition 1 && !condition 2) {
    code;
}
else {
    die();
}

where condition 1 and condition 2 are, for example, empty($var)?

If-statement with NSMutableString hasprefix phone number (Beginner)

Hey I don't succeed to make a functional if-statement with my NSString

j is ABMultiValueGetCount(phones).

I've three cases : j=0, j=1, j=2...

I would like that when j = 0 or 1 or 2, that doesn't take number with prefix 02...

if j has number with prefix 06, save this number.

if j has number with other prefix save it, except if number with prefix 06 is already saved.

I tried to make this code, but it doesn't work, I don't know where is my error :

if (j == 0) {
                        if ([phoneNumber hasPrefix:@"02"]){}
                        else if([phoneNumber hasPrefix:@"06"]){
                            person.number = phoneNumber;    }
                        else
                        {
                        if ([phoneNumber length] == 0)
                            {
                                person.number = phoneNumber;
                            }
                }
            }
            if (j == 1) {
                if ([phoneNumber hasPrefix:@"02"]){}
                else if([phoneNumber hasPrefix:@"06"]){
                    person.number = phoneNumber;    }
                else {if ([phoneNumber length] == 0)
                {
                    person.number = phoneNumber;
                }}
            }
            if (j == 2) {
                if ([phoneNumber hasPrefix:@"02"]){}
                else if([phoneNumber hasPrefix:@"06"]){
                    person.number = phoneNumber;    }
                else {if ([phoneNumber length] == 0)
                {
                    person.number = phoneNumber;
                }}
            }

Objective C NSNumbers in if statements

Hi I am retrieving an NSNumber value from an array (a rating e.g. 4.3) and am then need to test this value to then assign star rating images.

However when I write the if statement, I am getting errors "Expected Expression"

Here is the code:

if (rating >=1 && <2) {
        return [UIImage imageNamed:@"1starimage"];
    }else if (rating  >=2 && <3){
        return [UIImage imageNamed:@"2starimage"];
    }

Thanks for any explanation on how I can do this without causing errors.

Using If and Switch statements together in a program

I am a student and I am trying to make a very simple program that displays the quadrant of an angle that is entered in by the user.

However I want it to display that the angle is on the X axis or Y axis if the user enters the angle as 0,90,180 or 270.

I did put these 4 conditions in an if statement but the code is not terminating there and I am also getting the quadrant number corresponding to that angle. How do I terminate the code for those 4 angles after the if statement?

#include <iostream.h>
void main()

{
int angle;

cout<<"Enter an angle: ";
cin>>angle;

if (angle==90) cout<<"The angle lies on the positive Y axis";
else if (angle==0) cout<<"The angle lies on the positive X axis";
else if (angle==180) cout<<"The angle lies on the negative X axis";
else if (angle==270) cout<<"The angle lies on the negative Y axis";


angle=(angle/90)+1;

switch(angle)
{
case 1: cout<<"First Quadrant"; break;
case 2: cout<<"Second Quadrant"; break;
case 3: cout<<"Third Quadrant"; break;
case 4: cout<<"Fourth Quadrant"; break;
default: cout<<"That is not a valid angle.";

}
}

If inside foreach not working as expected in Laravel

My if is not displaying as expected in Laravel.

This is in the model:

    public function getTags()
{
    $tags = [];
    foreach (Config::get('products.tags') as $tag) {
        if ($this->$tag)
            $tags[] = $this->getLabel($tag);
    }
    if ($this->extra_tag)
        $tags[] = $this->extra_tag;

    return $tags;
}

And this in the view:

    @foreach($product->getTags() as $tag)
        @if($this->$tag='bespoke shape')
            <div class="tag-purple">
        @else
            <div class="tag-grey">
        @endif
        {{$tag}}</div>
    @endforeach

I would expect to see the tag 'bespoke shape' to have purple background and other tags to have grey background. Unfortunately, they all have purple background. The names of the tags, however, are displayed correctly.

Do you have any ideas of what I can do to make it work?

PHP IF not working after Encrypt and Decrypt a String

I want to encypt all my session php data and when I want to use these information , decrypt them for this I am using these functions :

define("ENCRYPTION_KEY", "!@#$%^Soheil&*");

/**
 * Returns an encrypted & utf8-encoded
 */
function encrypt($pure_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
    return $encrypted_string;
}

/**
 * Returns decrypted original string
 */
function decrypt($encrypted_string, $encryption_key) {
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
    return $decrypted_string;
}

and when I want to set my data I use this code:

$_SESSION["admin_username"] = encrypt($username, ENCRYPTION_KEY);
$_SESSION["seller_id"] = encrypt($user_array['id'], ENCRYPTION_KEY);
$_SESSION['seller_name'] = $user_array['name'];
$_SESSION['login_ok'] = encrypt('ok', ENCRYPTION_KEY);

now when i want to show Decrypted date it works good , but when I want to use it in an IF statement it does not work :

$seller_user_id =  decrypt( $_SESSION["seller_id"] , ENCRYPTION_KEY); 
$seller_user_name =  $_SESSION["seller_name"] ;  
$login_ok = decrypt( $_SESSION["login_ok"] , ENCRYPTION_KEY); 

echo "login_ok is : " .$login_ok  ;

if ( $login_ok  == 'ok'  )
{

}
else
{
    echo "Login Fail";
    echo "<br> " .$login_ok ;

}

and this out put is :

login_ok is : ok Login Fail ok

as you see $login_ok == 'ok' is true but the code says it is fals ! I dont Know whats the problem ! It is simple but ...

samedi 29 août 2015

PHP SQL IF statement problems

Ok so I'm trying to pull some data from my SQL database and use it in an IF statement.

I have a database called DB_Default and I have a table called Users

Inside Users I have all the normal columns such as id, username, password but I also have a column called isadmin.

I want to be able to do a mysql query through PHP selecting all users with the username $_SESSION[username] and isadmin = 1.

What I aim on doing is including a few navigation links for escalated privileged users only. So as the page that the code is going to be put into is for logged in users only I thought right, lets use the already defined username session i,e if my sessions username was set to Admin.

the statement should be

$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");

I have set $admin = "1"; so that it should only be able to return results if the user logged in has isadmin set to 1.

Instead I'm either having the navigation links show to any user regardless of their isadmin status or not at all.

To be honest the code is very messy as it's 5:40am and I haven't been coding for a while so quite rusty so I'm more than aware of how easy this should be of a fix.

I'm 99% sure it has to do with the fact I just set $admin = "1"; but for the life of me can't figure out where I've gone wrong. Going to give it a rest for today and come back tomorrow. Hopefully by then someone will have posted a resolution and obviously I'll vote up the best answer otherwise I'll give the code a lookover and see if I can't fix it myself!

Thanks!

bash and if with multiple logical operands

I am trying to check if 2 variables are empty or not defined at the same time in bash. If that is the case, no user password will be changed.

#!/bin/bash
read -s  -p "Enter root password: " rootpass1
echo
read -s  -p "Enter root password again: " rootpass2
echo

if  [[-z "$rootpass1"] && [-z "$rootpass2"]]
then
    echo "Password will not be changed"
else
    echo "user:$rootpass1" | chpasswd
fi

But I am getting the following error:

script.sh: line 7: [: missing `]'

Any clue?

Lua Math.random and if statement

the purpose of the code is to produce a random number and based na the number produced to do a certain thing.

local x = math.random(1,2)
if x = 1 then
  print("x = 1")
  else
    print("x > 1")
  end

However when I run the code I get the following error "'the'" expected near '='" and I still dont seem to get why it is not working, so could somebody please lend me a hand? :)

Best way to use if / else [on hold]

Whats the best way to use an if/else query, when I cant check different conditions in one query?

Example 1

public void method1()
{
    if(condition1 == true)
    {
        if(condition2 == true)
        {
            if(condition3 == true)
            {
                //do something
            }
        }
    }
}

Example 2

public void method2()
{
    if(condition1 == fale)
    {
        return;
    }
    if(condition2 == false)
    {
        return;
    }
    if(condition3 == false)
    {
        return;
    }

    //do something
}

I think Example 2 is much clearer, but is Example 1 the better way?


Creating a bar graph in C++ that turns numbers from an array into 'spaces' and '*'s'

I was just wondering if I am on the right track to creating a program that creates a bar graph out of spaces and asterisks and stops when it hits the number 0 (the highest number would be 100 also). So if this was entered: 1 2 3 4 3 2 1 10 0, an outcome like this would appear:

       *
       *
       *
       *
       *
       *
   *   *
  ***  *
 ***** *
********

As of right now it works but I need it to appear vertically as shown in the outcome. Any tips or suggestions are appreciated. thanks

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    const int MAX = 100;
    int values[MAX];
    int input_number;
    int total_number = 0;
    int largest_number = 0;

    for (int i = 0; i < MAX; i++)
    {
        cin >> input_number;
        if (input_number != 0)
        {
                total_number++;
                values[i] = input_number;
        }

    else if (input_number == 0)
    {
        for(int t = 0;t<total_number;t++)
        {
            if(values[t]>largest_number)
            largest_number = values[t];
        }

    for (int j = 0; j <largest_number; ++j)
    {
        for (int i = 0; i <total_number; ++i)
        cout << (j+values[i] >= largest_number ? '*' : ' ');
    }
    break;
    }
    }

    return 0;
}

if statement and Imageview

I need to display and image according a value. but with my code only is displayed the last line.

The value is 2 to put an example, so the image to be displayed must be "srm2", but my code display the image corresponding with the value 6.

why???

 totsrmI=((int) Math.round(totsrmI));
    if (totsrmI==2) {
        colorpint.setImageResource(R.drawable.srm2);
    }
    if (totsrmI==3) {
        colorpint.setImageResource(R.drawable.srm3);
    }
    if (totsrmI==4) {
        colorpint.setImageResource(R.drawable.srm4);
    }
    if (totsrmI==5) {
        colorpint.setImageResource(R.drawable.srm4);
    }
    if (totsrmI==6) {
        colorpint.setImageResource(R.drawable.srm6);
    }

If statement condition is not satisfied, do not return error?

I have a variable $cc, this variable stores checkbox selections in this fashion:

251000-1,252000-2,252012-1 ... etc (Depending on how many choices)

I have successfully figured out how to store the data in multiple tables using a strpos if condition :

if (strpos($b,'251000') !== false) {
        $sql3="INSERT INTO engworkshops (studentid, ckb)
            VALUES ('$studentid', '$cc')";
            echo 'true';
        }


        if (strpos($b,'252000') !== false) {
        $sql4="INSERT INTO engdrwnga (studentid, ckb)
            VALUES ('$studentid', '$cc')";
            echo 'true';
        }


        if (strpos($b,'252012') !== false) {
        $sql5="INSERT INTO engdrwngb (studentid, ckb)
            VALUES ('$studentid', '$cc')";
            echo 'true';
        }
     if (!mysqli_query($dbcon,$sql3)) 
       {
          die('Error: ' . mysqli_error($dbcon));
       }
       if (!mysqli_query($dbcon,$sql4)) 
       {
          die('Error: ' . mysqli_error($dbcon));
       }
         if (!mysqli_query($dbcon,$sql5)) 
       {
          die('Error: ' . mysqli_error($dbcon));
       }

The problem lies here : The logic of this code only works if all three if conditions are satisfied meaning that if my "variable $cc" contains 251000 and 252000 and 252012 , it stores the data in each table with no problems what so ever.

I tried nested if statements elseif statements both didnt work

My guess is that the way I'm defining my insert statements and checking for errors in them if they are not executed is causing the problem , How can I fix this ?

Java Scanner If Statement [duplicate]

This question already has an answer here:

I don't know why this isn't working. Thanks very much.

public String name;

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter your name....");
    String input = scanner.next();

    if (input == "judy") {
        System.out.println("Hello judy, its so nice to have you here");
    }

When I enter judy, it doesn't print "Hello....". Why?

AHK if/else of output from Custom Message Box Function

I've been trying to create a script that displays message boxes conditioned on the output from another customized message box with more than 3 options.

The custom functions are taken form this thread http://ift.tt/1UdiTy9

I've tried both the CMsgbox and the MsgBoxV2 functions, running into the same problem. The Message "IT WORKED!" testing with if(condition) will always appear regardless of whether pressing any of the Sym|&Go|&C options, and the message "worked" will never appear regardless of actually pressing C, In other words no specificity or sensitivity regarding variable testing.

!o::
var := MsgBoxV2("Question11","Hi, what's up??","Sym|Go|C","24")
Msgbox 4,, You Pressed %var%

if (%var% = C) 
{  
    Msgbox 4,, IT WORKED!
}

IfEqual, %var%,C
{  
  Msgbox 4,, worked
}
return

!e:: 
var := CMsgbox( "s", "d", "*&Sym|&Go|&C","",1 )
Msgbox 4,, You Pressed %var%
if (%var% = C) 
{  
    Msgbox 4,, IT WORKED!
}

IfEqual, %var%,C
{  
  Msgbox 4,, worked
}
return

I don't know if this is because I've misunderstood the if/Else testing in ahk, or if the output from these custom functions cannot be tested, or both. One solution would be to figure out what type of variable %var% is, but I've not been able to find a way to figure that out either.

Thanks for reading and hope you guys can help.

here are the custom message functions for testing.

MsgBoxV2(Title="",Text="",Buttons="",IconPath="",Timeout="",Font="",Schriftart="Arial",Colors="||",WindowStyles="",GuiNr = "")
{
Static Stat2,Stat1
Col1:="0xFFFFFF" ,Col2:="0x000000",Col3:="0x000000", Color1:="", Color2:="", Color3:=""
Loop, Parse, Colors,`|
Color%A_Index% := (A_Loopfield = "") ? Col%A_Index% : A_Loopfield
Loop 3
Color%A_Index% := (Color%A_Index% = "") ? Col%A_Index% : Color%A_Index%
if instr(WindowStyles,"+altsubmit")
{
AltSub := "1" 
Stringreplace,WindowStyles,WindowStyles,`+altsubmit
}
Gui, Color, %Color1%,%Color1%
Gui, Font, s9
Gui, Font, %Font%, %Schriftart%
X := 20 ,Y := 20
ifexist, %IconPath%
{
Gui, Add, Picture, x20 y20 w32 h32, %IconPath%
X := 70 ,Y := 30
} else
if IconPath is integer
{
Gui, Add, Picture, x20 y20 icon%IconPath% w32 h32, %A_WinDir%\system32\shell32.dll
X := 70 ,Y := 30
}
Gui, Add, Text, x%X% y%Y% c%Color2% vStat2, %Text%
GuicontrolGet, Stat2, Pos
X2 = 10
Y2 := (Stat2Y + Stat2H < 52) ? 82 : Stat2Y + Stat2H + 30
HMax = 0
Gui, Add, Text, vStat1 +border -background
Loop, Parse, Buttons,|,`|
{
Gui, Add, Button, x%X2% w100 Y%Y2% gExButton , %A_Loopfield%
ButT%A_Index% := A_Loopfield
Guicontrolget, Button%A_Index%,Pos
if (HMax < Button%A_Index%H)
HMax := Button%A_Index%H
ABut := A_Index
X2 += 110
}
Loop %ABut%
Guicontrol, Move, Button%A_Index%,h%HMax%
Gui, %WindowStyles%
Gui, Show, Autosize Center,%Title%
Guicontrol, Move, Stat1, % "X-1 Y" Y2 - 10 " W" 1400 " h" 41 + HMax
Guicontrol, -Background +hidden, Stat1
Guicontrol, show, Stat1
Gui, +LastFound
WinGet, G_id
if Timeout !=
if Timeout is integer
settimer, Timeout, %Timeout%
Winwait, ahk_id %G_id%
retval = 0
while winexist("ahk_id " G_id)
sleep 100
if !AltSub
return ButT%retval%
else
return retval
Timeout:
if Timeout =
return
GuiClose:
Gui, destroy
return
ExButton:
MouseGetPos,,,, Control
Stringreplace,retval,Control,Button
Gui, destroy
return
}


;-------------------------------------------------------------------------------
; Custom Msgbox
; Filename: cmsgbox.ahk
; Author  : Danny Ben Shitrit (aka Icarus)
;-------------------------------------------------------------------------------
; Copy this script or include it in your script (without the tester on top).
;
; Usage:
;   Answer := CMsgBox( title, text, buttons, icon="", owner=0 )
;   Where:
;     title   = The title of the message box.
;     text    = The text to display.
;     buttons = Pipe-separated list of buttons. Putting an asterisk in front of 
;               a button will make it the default.
;     icon    = If blank, we will use an info icon.
;               If a number, we will take this icon from Shell32.dll
;               If a letter ("I", "E" or "Q") we will use some predefined icons
;               from Shell32.dll (Info, Error or Question).
;     owner   = If 0, this will be a standalone dialog. If you want this dialog
;               to be owned by another GUI, place its number here.
;
;-------------------------------------------------------------------------------

CMsgBox( title, text, buttons, icon="", owner=0 ) {
  Global _CMsg_Result

  GuiID := 9      ; If you change, also change the subroutines below

  StringSplit Button, buttons, |

  If( owner <> 0 ) {
    Gui %owner%:+Disabled
    Gui %GuiID%:+Owner%owner%
  }

  Gui %GuiID%:+Toolwindow +AlwaysOnTop

  MyIcon := ( icon = "I" ) or ( icon = "" ) ? 222 : icon = "Q" ? 24 : icon = "E" ? 110 : icon

  Gui %GuiID%:Add, Picture, Icon%MyIcon% , Shell32.dll
  Gui %GuiID%:Add, Text, x+12 yp w180 r8 section , %text%

  Loop %Button0% 
    Gui %GuiID%:Add, Button, % ( A_Index=1 ? "x+12 ys " : "xp y+3 " ) . ( InStr( Button%A_Index%, "*" ) ? "Default " : " " ) . "w100 gCMsgButton", % RegExReplace( Button%A_Index%, "\*" )

  Gui %GuiID%:Show,,%title%

  Loop 
    If( _CMsg_Result )
      Break

  If( owner <> 0 )
    Gui %owner%:-Disabled

  Gui %GuiID%:Destroy
  Result := _CMsg_Result
  _CMsg_Result := ""
  Return Result
}

9GuiEscape:
9GuiClose:
  _CMsg_Result := "Close"
Return

CMsgButton:
  StringReplace _CMsg_Result, A_GuiControl, &,, All
Return

Why can't we define variable just afte if statement Like follows

public class Foo{

public static void main(String []args){

int a=10;

if(a==10)

int x=20;

}
}

While compiling above code, an error is thrown at compile.

But, in the below code it is fine. Why?

public class Foo{

public static void main(String []args){

int a=10;

if(a==10){

int x=20;
}
}
}

I don't get it. What exactly is happening in these? As I understand, we can write one statement after an if statement without curly braces (compound statement block).

jQuery If/Else statement, to check if element has class produces both results?

I am using the enquire.js library to add JavaScript media queries into a site I am developing.

The issue happens when I initially load the website.

  1. I resize into the 860px breakpoint, and toggle the nav. All works fine and as expected.
  2. Then I resize past 860px.
  3. And once again I resize back into the 860px enquire.js media query. The toggle nav outputs both console messages.

Any ideas?

   enquire.register("screen and (max-width:860px)", {

        match : function()
        {   
            nav_wrapper.removeClass('show').addClass('hide');

            nav_toggle.click(function()
            {
                if((nav_wrapper).hasClass('hide'))
                {
                    console.log('It\'s hidden bud');
                    nav_wrapper.removeClass('hide').addClass('show');
                }
                else
                {
                    console.log('It\'s opedn up mate');
                    nav_wrapper.removeClass('show').addClass('hide');
                }

            });

        },

        unmatch : function()
        {
            nav_wrapper.removeClass('hide').addClass('show');
        },

    });

Loop an If Statement for each row in Sql table

I am trying to make an If statement in PHP loop for each row in an Sql table. I think I'm almost there but there is a syntax error that I cant quite figure out. Heres what i've got so far:

$mysqli = new mysqli("localhost", "root", "usbw", "favourites");

                // check connection
                if ($mysqli->connect_errno) {
                    die("Connect failed: ".$mysqli->connect_error);
                }

                $query = "SELECT * FROM defaultTiles";
                $result = $mysqli->query($query);

                while($row = $result->fetch_array()){

                echo "<?php if ($tile_name === '$row[name]'){
                    $tile_colour = '$row[colour]';
                    $img_url = '$row[img_url]';
                    $link_url = '$row[link_url]';
                } ?>";
                }

Using VBA to assign a criterion for average.ifs()

I use the following formula in excel

=AVERAGEIFS(B4:B440;A4:A440;"<"&A441;A4:A440;">"&EDATE(A441;-6))

to get the average of a range of values, based on the values in an adjacent column. However I need to apply this formula for more than a thousand dates (column A contains dates). I have a macro, which asks the user to specify sheet name and date (using dialog boxes). So I would like to add some code, that takes the date specified by the user and replaces cell A441 from the above formula with it. Then copy the average, so that I can paste it where desired. Here is what I tried coding so far, with no success:

Sub Find()

Dim FindString As Date
Dim Sumact As Range
Dim Analyst As Double
Dim shname As String
        Do Until WorksheetExists(shname)
                      shname = InputBox("Enter sheet name")
                      If Not WorksheetExists(shname) Then MsgBox shname & " doesn't exist!", vbExclamation
                Loop
                Sheets(shname).Select
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets(shname).Range("A:A")
        Set Sumact = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Sumact Is Nothing Then
            Application.Goto Sumact, True
        Else
            MsgBox "Nothing found"
        End If
    End With
End If   
 Set Analyst = Application.AverageIf(Range(("B:B"), ("A:A")), "<Sumact")
Selection.Copy 
End Sub

Bash "if" conditions unclear to me

I have a problem with bash conditions especially in "if" constructions. There is my example of if condition:

while [[ $BUT_O1 -eq false && $BUT_O2 -eq false && $BUT_O3 -eq false ]]
do
...
done

I need that cycle to stop when one of the variables comes true.

P.S. I read bash scripting how to but its still unclear for me. I even dont' understand why 0=true , when in the most languages 1=true.

Link two tables based on conditions in matlab

I am using matlab to prepare my dataset in order to run it in certain data mining models and I am facing an issue with linking the data between two of my tables.

So, I have two tables, A and B, which contain sequential recordings of certain values in a certain timestamps and I want to create a third table, C, in which I will add columns of both A and B in the same rows according to some conditions.

Tables A and B don't have the same amount of rows (A has more measurements) but they both have two columns:

  • 1st column: time of the recording (hh:mm:ss) and
  • 2nd column: recorded value in that time

Columns of A and B are going to be added in table C when all the following conditions stand:

a. The time difference between A and B is more than 3 sec but less than 5 sec

b. The recorded value of A is the 40% - 50% of the recorded value of B.

Any help would be greatly appreciated. Thank you in advance for your time.

How to limit value assignment in foreach?

Here is my array and foreach:

$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}

I need to just assign only the first three keys and I want this output:

red
green
blue

I can do that like this:

$i=1;
foreach ($colors as $value) {
    if ($i=4){break;}
    echo "$value <br>";
    $i++;
}

But I think using a if() statement in a loop (in reality my array has more than 100 elements) is not optimized, so there is any better approach for doing that ?

handling large number of state transition

I have a class which has a property State.It's type is ObjectState enumeration.

ObjectState has near 30 different values that an object can only be in one of these state.

I managed to check validity of state transition between different state with 'if' statements:

if (currentState == ObjectState.SomeState && 
      nextState == ObjectState.AnotherState &&
      someOtherCondition)
{
   ....
} // many of these if statements since there are near 80 different transitions

As number of states grows the code is somehow hard to understand and managing valid transition is getting harder. What should I do?

If object is in a specific state, next state will be determined by just nextState variable and if this transition is valid then object state will change to nextState.

if else function returns not what I asked for

I have the following function

aa<-function(x){
    if (x==c(3,4,5))
        return (1)
    if (x==c(6,7,8))
        return(2)
    else
        return(0)
}

I then try the following:

> `aa(3)`
[1] 1
> `aa(4`)
[1] 0
> `aa(5)`
[1] 0
> `aa(6)`
[1] 2
> `aa(7)`
[1] 0
> `aa(8)`
[1] 0

I don't know why only aa(3) and aa(6) gives me the desired outcome, while aa(4) and aa(5) won't return 1 and aa(7) and aa(8) won't return 2. How can I correct my code so that a value of either 3, 4, or 5 returns 1, and 6, 7, or 8 returns 2, and 0 otherwise?

vendredi 28 août 2015

am I using strpos correctly!? Not getting the results

I've got a php while loop going (creating a search script), and I'm looking to match up values to see which items should go into the search results. strpos seems to work just fine until all of a sudden when it refuses to work correctly on this particular spot...

if (strpos('a', 'a')) {
 continue;
}

Shouldn't that NOT reach continue? "a" does contains "a" after all, but in my script it's reaching the continue.

if-else output in C [duplicate]

This question already has an answer here:

What should be the output of the code :

#include <stdio.h>
   main()
   {
       if (sizeof(int) > -1)
           printf("True");
       else
           printf("False");
   }

According to my programming knowledge, sizeof() operator returns the size of datatype. Suppose sizeof(int) returns 4, which is obviously grater then -1 i.e. 4 > -1 . That means condition of "if" is satisfied and it should print "True". But the compiler prints "False".

Can anyone explain ?

Google Sheets; arrayformular(if x=1 write 1 BUT if x=2 write 2)

I've got this working: =IF(AND(B3 = "Hverdag");"Hverdag";IF(AND(B3 = "Weekend");"Weekend";""))

What I want is: =ARRAYFORMULA(IF(AND(B3:B = "Hverdag");"Hverdag";IF(AND(B3:B = "Weekend");"Weekend";"")))

Did I miss something or is there a better way doing this math?

If cell equals with a value in another cell then cellX

i am trying to use IF in the following arguement:

I have a sheet with a list of products next to it a list with manufacturer. In each product corresponds to a certain manufacturer of the list.

Now how i can tell a cell that if it found in the cell A1 on another sheet the a value from the list of products in the previous sheet to give me as a result the corresponded manufacturer.

I tried the following as a test:

=IF(COUNTIF(B9;data!A:A);data!B:B;"product not found")

were B9 is the cell that i put the product manually, data!A:A is the range of the sheet that i have the list of the products and data!B:B is the list with the manufucturers.

The syntax i guess is ok since its working properly in excel but the thing is that i get always (product not found).

Could please someone help me? Thanks in advance!

Why do command line arguments behave strangely inside an ELSE?

I have a Windows batch-file named arg_parse.cmd that parses command line arguments under certain conditions. Under other conditions, it does something else. A minimal (not) working example is below:

@ECHO OFF

IF 0 == 1 (
    REM Do nothing
) ELSE (
    :parse
        REM Print input argument.
        ECHO.
        ECHO 1 = %1

        REM Set argument to local variable.
        SET arg1=%1

        REM Break after parsing all arguments.
        IF "%~1" == "" GOTO :endcmd

        REM Print local variable.
        ECHO arg1 = %arg1%

        SHIFT
        GOTO :parse
    :endcmd
    REM Do not remove this comment.
)

On the first iteration though the parse "loop", there is clearly an argument, however the SET appears to do nothing, as arg1 is an empty string. On further iterations, it behaves normally. For example, if I run the script with a few arguments:

arg_parse.cmd test some arguments

I get this output:

1 = test
arg1 =

1 = some
arg1 = some

1 = arguments
arg1 = arguments

1 =

Why does it behave like this on the first iteration? Further, why do I get a ) was unexpected at this time error if I remove the final comment?

Why is my if statement not being called?

I'm using if statements in cellForRowAtIndexPath: so I can populate cells with the right images.

if ([object objectForKey:@"type"] == [NSNumber numberWithInt:0]) {

    self.cell.typeImage.image = [UIImage imageNamed:@"type1"];
}

else if ([object objectForKey:@"type"] == [NSNumber numberWithInt:1]) {

    self.cell.artTypeImage.image = [UIImage imageNamed:@"type2"];
}

else if ([object objectForKey:@"type"] == [NSNumber numberWithInt:2]) {

    self.cell.artTypeImage.image = [UIImage imageNamed:@"type3"];
}

I do get a value for [object objectForKey:@"type"] as it does not return nil.

Is there a way to see if a certain page is visited with $_SERVER?

I'm currently working on a simple CMS for my blog where you can look on the user, modify and create new posts, check on the main page to see how it all looks like and have a logout/login button that actually works.

And here's the case. All the button works, I did found my way to insert a admin menu into a main page that pop up only when you're logged in. But I don't want to the "Main Page" button shows up when you actually are on the main page for obvious reasons, and I want to do it in menu file which is .php.

The way I thought would be efficient was

    <?php
if ($_SERVER['PHP_SELF'] !== 'blog_dm/index.php')
echo "<li id='blog-menu'><a href="blog_dm/index.php" target="_blank">Zobacz strone</a></li>"?>

But it show pop up an error massage

Parse error: syntax error, unexpected 'blog_dm' (T_STRING), expecting ',' or ';

What am I doing wrong?

ELSE was unexpected at this time batch file

This is the script:

@echo off

set BSL_Scripter_go="BSL_Scripter.exe"
set BSL_Script=WriteMain_s.txt
set yes=Y
set no=N


::%BSL_Scripter_go% %BSL_Script%

:LABEL1
set /p answer=Have you turned device off?[Y\N]

IF "%answer%"=="%yes%" (GOTO LABEL_DEVICE_RUN
) ELSE (IF "%answer%"=="%no%"(GOTO LABEL1) ELSE (GOTO LABEL_TYPO))

:LABEL_DEVICE_RUN
echo Device is runing..
GOTO END

:LABEL_TYPO
echo UNCORRECT ANSWER, PLEASE TYPE 'Y' or 'N'
GOTO LABEL1

:END

and I got the error:

ELSE was unexpected at this time

Little help?

execute rule if only the target is defined in node js

I am replacing color, font and font size in the server according to the users choice in the client side. In my program user can proceed without choosing all 3 of them (the user can choose only color and font etc.), so those variable values will be undefined. My code below is only to changes all 3 variables and if its undefined, it replaces it as undefined.

    var userId = req.userId;
    var appId = req.body.appId;
    var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';

    var color = req.body.color;
    var font = req.body.font;
    var fontSize = req.body.fontSize;

    function updateFile(filename, replacements) {
        return new Promise(function (resolve) {
            fs.readFile(filename, 'utf-8', function (err, data) {
                var regex, replaceStr;
                if (err) {
                    throw (err);
                } else {
                    for (var i = 0; i < replacements.length; i++) {
                        regex = new RegExp("(\\" + replacements[i].rule + "\\s*{[^}]*" + replacements[i].target + "\\s*:\\s*)([^\\n;}]+)([\\s*;}])");
                        replaceStr = "$1" + replacements[i].replacer + "$3";
                        data = data.replace(regex, replaceStr);
             if(replacements[i].target == undefined){
                    replacements[i].rule = !replacements[i].rule;
                }//if condition which I have tried
                  }

                  fs.writeFile(filename, data, 'utf-8', function (err) {
                        if (err) {
                            throw (err);
                        } else {
                            resolve();
                        }
                    });
                }
            });
        });
    }

    updateFile(main, [

        {rule: ".made-easy-themeColor", target: "color", replacer: color},
        {rule: ".made-easy-themeFont", target: "font-family", replacer: font},
        {rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
    ], function (err) {
        console.log((err));
    });

My aim is only to execut rule if target according to that is defined. I have tried putting,

 if(replacements[i].target == undefined){
    replacements[i].rule = !replacements[i].rule;
   } 

as I have mentioned above in the code but it is not working. Please can anyone tell me how to put the conditions in the above code

mandrill logic if/else statement to provide a fallback option if condition not satisifed

I am trying to figure out mandrill conditional statements and have done a lot of reseach but cannot figure this out.

My logic looks like this:

*|IF:house=true|*
   House,  
*|END:IF|* 

*|IF:garden=true|*
    Garden,  
*|END:IF|*  

*|house!=true && garden=!true|*                                        
    House and Garden not included
*|END:IF|*   

I thought this answer would help me solve it but still cannot figure it out. I have tried all sorts of variations, but it is still not working.

Any help would be greatly appreciated.

Double if else without brackets

I recently discovered that you can use the following syntax for if/else statements:

if (a)
    b = true;
else
    b = false;

when you nest another if clause inside this, it gets confusing

if (a)
    if (b)
         c = 3;
else
    c = 1;

but since the compiler ignores line indents, the compiler always parses this as (from what I understand)

if (a)
    if (b)
         c = 3;
    else
         c = 1;

Is it possible to achieve the second clause without using brackets? (I am aware that this makes no difference, but it is cleaner in my opinion)

jeudi 27 août 2015

find a string in list with if and do until

i am more than 100 true or false value in list . i have get the true in a array in order where if a false value comes it has to create a separate array and store value true value after the false value until another false value. i write the program like this to put the true value . any suggestion ?

Dim array1 As New List(Of String)()
For Each var As String In numbers
   If var = "true" Then
      Do
        array1.Add(var)
        numbers.IndexOf(var + 1)
      Loop Until var = "false"
   End If
Next  

change card layout based on object type

I am using a card layout to display a list.I have a fragment in which I am displaying the list. I have a image of circle in card view. I want to change the image from small to big based on card type. For that I have created two card layout in which circle image size differs. I have created two different adapters respectively. I have a class Expense in which I have a object of expenseType based on this type I want to change card layouts. How can i achieve this????

Help will be appreciated...Thank You..

Class code

 public class Expense {

    String amount;
    String expense;
    public int expenseType;

Expense(){}
    Expense(String amount,String expense,int expenseType)
    {
        this.amount=amount;
        this.expense=expense;
        this.expenseType=expenseType;
    }

    public void setExpenseType(int expenseType)
    {
        this.expenseType=expenseType;
    }
    public int getExpenseType()
    {
        return expenseType;
    }

}

Fragment code

public class ItemFragment extends Fragment {
    ArrayList<Expense> items=new ArrayList<Expense>();

    RecyclerView recyclerView;
    public ItemFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        Expense e=new Expense();

        recyclerView=(RecyclerView)view.findViewById(R.id.RecyclerView);
        ImageButton imageButton = (ImageButton)view.findViewById(R.id.imgbtn_fab);
        LinearLayoutManager llm = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(llm);

        recyclerView.setHasFixedSize(true);

        initializeDataType1();
        int type= e.getExpenseType();



            ItemAdapter adapter = new ItemAdapter(items);
            recyclerView.setAdapter(adapter);



          //  bigCircleAdapter ad = new bigCircleAdapter(items);
            //recyclerView.setAdapter(ad);



        return view;

    }

    private void initializeDataType1() {

        items = new ArrayList<>();
        items.add(new Expense("1000", "2000", 1));
        items.add(new Expense("2000", "5000", 1));
        items.add(new Expense("3000", "400", 2));
        items.add(new Expense("1000", "4000", 1));
        items.add(new Expense("3000", "3000", 2));
        items.add(new Expense("2000", "100", 1));
        items.add(new Expense("2000", "3333", 2));
        items.add(new Expense("3000", "shopping", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("1000", "food", 2));
        items.add(new Expense("2000", "drink", 1));
        items.add(new Expense("3000", "shopping", 2));
        items.add(new Expense("2000", "3333", 1));
        items.add(new Expense("3000", "shopping", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("2000", "drink", 1));
        items.add(new Expense("3000", "shopping", 1));
    }
}

I have inserted dummy data in list. Based on the expenseType object i want to change the layout. I am new to java and android. can anybody help plz... Thank You...

How do i exclude negative numbers in an if loop?

For my project, the user enters a set of numbers, and some calculations are performed to give the desired output. One of the calculations is the find the sum of the odd numbers that are inputted. Looking at the given test cases, I noticed my code was adding the negative odd numbers, while the correct test cases do not. Is there any easy fix for this?

Thanks

Here is some of the code, what I have written minus a few parts.

import java.util.Scanner;

public class Test 
{
public static void main (String[] args)
{
    int min_interger = 0;
    int sum_of_pos = 0;
    int sum_of_odd = 0;
    int count_of_pos = 0;
    int userInput;

    Scanner consoleInput = new Scanner(System.in);

    do {userInput = consoleInput.nextInt();


    if(userInput % 2 != 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

    while (userInput != 0);

    System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}

}

Initilaized variable in if statement, used later in code but says it isnt defined

  import java.util.Scanner;
  import java.lang.Math;

  public class pizzasMazboudi
  {
     public static void main(String[] args)
     {
    double shapeOfPizza;
    double toppings;
    double pizzaCrust;
    double baseCost;
    double areaOfPizza;
    double numberOfToppings;
    final double COST_OF_ONE_TOPPING = 0.025;
    final double COST_OF_DOUGH = 0.019;
    final double COST_OF_SAUCE = 0.036;
    double diameterOfPizza;
    double lengthOfPizza;
    double widthOfPizza;
    double volumeOfDough;
    final double THIN_AND_CRISPY = .1;
    final double PAN = .5;
    final double CLASSIC_HAND_TOSSED = .25;
    final double TEXAS_TOAST = .9;
    double sizeOfCrust;
    double cheesyCrust;
    final double COST_OF_MATERIALS = .02;
    double numberOfPizzas;
    double costOfDelivery;
    double tax;
    double pizzaDelivery;
    final double PI = 3.14159;
    double typeOfCrust;
  double costOfCheesyCrust;
    double costOfPizzaDelivery;

  Scanner keyboard = new Scanner(System.in);
  System.out.println("Hello customer! Welcome to Guiseppi's Just Pizza!");
  System.out.println("Where we make the pizza just for you!");
  System.out.println("\n What kind of pizza do you want on" + 
                     " this beautiful day?");
  do
     {
     System.out.print("Press 1 for a square pizza,");  
     System.out.print(" or press 2 for a circle pizza: ");
     shapeOfPizza = keyboard.nextDouble();

        if(shapeOfPizza != 1 && shapeOfPizza != 2)
           {
           System.out.println("That is an incorrect input, please enter 1 or 2");
           }
      }  
  while(shapeOfPizza != 1 && shapeOfPizza != 2);

  if(shapeOfPizza == 1)
     {
     System.out.println("And how big would you like your pizza?");

        do
           {
           System.out.print("Please enter the length of your pizza (under 60 inches: ");
           lengthOfPizza = keyboard.nextDouble();

              if(lengthOfPizza > 60 && lengthOfPizza < 0)
                 {
                 System.out.println("That is an incorrect input, please enter a number between 0 and 60");
                 }
           }
        while(lengthOfPizza > 60 && lengthOfPizza < 0);

        do
           {   
           System.out.print("Please enter the width of your pizza: ");
           widthOfPizza = keyboard.nextDouble();

              if(widthOfPizza >60 && widthOfPizza <0)
                 {
                 System.out.println("That is an incorrect input, please enter a number between 0 and 60.");
                 }
           }
        while(widthOfPizza > 60 && widthOfPizza < 0);

        areaOfPizza = lengthOfPizza * widthOfPizza;
        System.out.println("Your pizza is " + areaOfPizza + "inches large");
        sizeOfCrust = 2 * (lengthOfPizza + widthOfPizza);
     }   

  else if(shapeOfPizza == 2)
     {
     System.out.println("And how big would you like your pizza?");
     do
        {
        System.out.print("Please enter the diameter of your pizza: ");
        diameterOfPizza = keyboard.nextDouble();
           if(diameterOfPizza > 60 && diameterOfPizza <= 0)
              {
              System.out.println("That is an incorrect input, please enter a number that is between 0 and 60.");
              }
        }
     while(diameterOfPizza > 60 && diameterOfPizza <= 0);

        sizeOfCrust = 2*PI*(diameterOfPizza/2);
        areaOfPizza = PI*((diameterOfPizza/2)*(diameterOfPizza/2));
        System.out.println("The area of your pizza is" + areaOfPizza + " inches large");
     }

  System.out.println("What type of crust would you like?");
  do
     {
     System.out.println("Enter 1 for Thin and Crispy, 2 for Pan,"); 
     System.out.println("3 for Classic Hand-Tossed, and 4 for Texas Toast");
     pizzaCrust = keyboard.nextDouble();
        if(pizzaCrust != 2 && pizzaCrust != 3 && pizzaCrust != 4)
           {
           System.out.println("That is an incorrect input, please enter 1, 2, 3, or 4");
           }
     }
  while(pizzaCrust != 2 && pizzaCrust != 3 && pizzaCrust != 4);

  if(pizzaCrust == 1);
     {
     typeOfCrust = THIN_AND_CRISPY;
     }
  if(pizzaCrust == 2);
     {
     typeOfCrust = PAN;
     }
  if(pizzaCrust == 3);
     {
     typeOfCrust = CLASSIC_HAND_TOSSED;
     }
  if(pizzaCrust == 4);
     {
     typeOfCrust = TEXAS_TOAST;
     }

  if(pizzaCrust == 2 && pizzaCrust == 3 && pizzaCrust == 4)
     {
     System.out.println("Would you like to try our new cheesy crust today?");
     do
        {
        System.out.print("Enter 1 for yes or 2 for no");
        cheesyCrust = keyboard.nextDouble();
           if(cheesyCrust != 1 && cheesyCrust != 2)
              {
              System.out.println("That is an incorrect input, please enter 1 or 2");
              }
        }
     while(cheesyCrust != 1 && cheesyCrust != 2);
     }
  System.out.println("Would you like any toppings today?");
  do
     {
     System.out.println("Enter 1 for toppings, enter 2 if you do not want toppings");
     toppings = keyboard.nextDouble(); 
        if(toppings != 1 && toppings !=2)
           {
           System.out.println("That is an incorrect input, please enter 1 or 2");
           }
     }
  while(toppings != 1 && toppings !=2);

  if(toppings == 1)
     {
        do
           {
           System.out.println("How many toppings do you want? (10 toppings limit)");
           numberOfToppings = keyboard.nextDouble();
              if(numberOfToppings <=0 && numberOfToppings > 10)
                 {
                 System.out.println("That is an incorrect input, please enter a number 1 through ten");
                 }
           }
        while(numberOfToppings <=0 && numberOfToppings > 10);
     }

  do
     {
     System.out.println("How many identical pizza's would you like?");
     numberOfPizzas = keyboard.nextDouble();
        if(numberOfPizzas <= 0)
           {
           System.out.println("That is an incorrect input, please enter a number above 0");
           }
     }
  while(numberOfPizzas <= 0);

  System.out.println("Will you come pick up your order, or will you like delivery?");
  do
     {
     System.out.println("Enter 1 for delivery, enter 2 for pick-up");
     pizzaDelivery = keyboard.nextInt();
        if(pizzaDelivery != 1 && pizzaDelivery != 2)
           {
           System.out.println("That is an incorrect input, please enter a 1 or 2");
           }
     }
  while(pizzaDelivery != 1 && pizzaDelivery != 2);

  costOfCheesyCrust = sizeOfCrust * COST_OF_MATERIALS;
  volumeOfDough = typeOfCrust * areaOfPizza;
  baseCost = areaOfPizza * (COST_OF_SAUCE + numberOfToppings * COST_OF_ONE_TOPPING) + COST_OF_DOUGH * volumeOfDough;

  if(cheesyCrust == 1)
     {
     costOfCheesyCrust = sizeOfCrust * COST_OF_MATERIALS;
     baseCost = baseCost + costOfCheesyCrust;
     }
  if(pizzaDelivery == 1)
     {
     if(baseCost < 10)
        {
        costOfPizzaDelivery = 3.00;
        }
     else if(baseCost < 20 || baseCost >= 10)
        {
        costOfPizzaDelivery = 2.00;
        }
     else if(baseCost < 30 || baseCost >= 20)
        {
        costOfPizzaDelivery = 1.00;
        }
     else if(baseCost >= 30)
        {
        costOfPizzaDelivery = 0;
        }
     }
 }

}

So when i try to compile this, the variables numberOfTopping, areaOfPizza, and sizeOfCrust are all causes of errors because "they aren't initialized", but i have have defined them all as doubles and set numberOfTopping as keyboard.nextDouble and given the other 2 formulas, any help would be appreciated.

using multiple If then statements in python corectly

I am trying to write a program where a shortest path is found between nodes in a list such as the one below. The nodes are A, B, C, D and the path length between them is listed as "A|B|1" or "B|D|9". The program is supposed to iterate through the paths and find the shortest path from first to last node, if the path exists. The part where I'm stuck is the very last for statement of the code (even though this code is not final and I still need to work on it). This last "for" statement crashes my python shell and then I have to restart it. Maybe an infinite loop?

In this statement I am trying to compare values in the dictionary i created to values to the nextpath variable which is continuously updated with values from the dictionary. For example if AB is in nextpath, it should be compared to other values in the dictionary (eg: BD) and since AB contains B, this path can link to BD. The problem is when I try to do this the program crashes and i=I'm stuck.

# input given to code "4","A","B","C","D","A|B|1","B|D|9","B|C|3","C|D|4"
import re

def WeightedPath(strarr): 
    exclude2=[',','"',"|"]
    strarr=list(s for s in strarr if s not in exclude2)

    numnodes = int(strarr[0])+1
    actualnodes=strarr[1:int(strarr[0])+1]
    end = len(strarr)
    print "____________________________________________________"
    paths = strarr[numnodes:end]
    paths2=""
    for i in paths:
        paths2+=i
    paths3=re.split('(\d+)',paths2)
    paths3=paths3[0:-1] #last item was empty quotes so i got rid of it
    print "paths",paths3

    paths_2=[] # second item behind weight
    paths_1=[] # first item behind weight
    pathsnum=[] # actual weight of path
    for i in paths3:  
        if i.isdigit() == True:
            paths_2.append(paths3[paths3.index(i)-2])
            paths_1.append(paths3[paths3.index(i)-1])
            pathsnum.append(paths3[paths3.index(i)])

    dictname=paths3[0::2] #names of dict items
    dictionary=dict(zip(dictname,pathsnum))

    print "names of nodes: ",actualnodes
    print "dictionary: ",dictionary

    fromnode= actualnodes[0]
    tonode= actualnodes[-1]

    tohere=[]
    for i in dictionary.keys():
        if tonode in i:
            tohere.append(i)     

    nextpath=[]
    for i in dictionary.keys():
        if fromnode in i:
            nextpath.append(i)

    for i in dictionary.keys():
        if i not in nextpath:
            for j in nextpath:
                if j[0] in i or j[1] in i:
                    nextpath.append(i)



    print "nextpath",nextpath


print WeightedPath(raw_input())  

my if this AND this then that statement doesnt work

i want it to log small if both requirement are met, but i cant get it to work

//change css on scroll
$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    var Wwidth = $(window).width();

    if ((scroll <= 550) && (Wwidth <= 550)) {
        console.log(small);
    } else {

        console.log(big);
    }
});

Replace largo if, else if... else with FOR or something more compact

I receive via POST a value. Then, I´m comparing the value received (1, 2, 3, 4, 5) with variables pre defined in my code. Is it possible to do it with FOR or another way to simplify it without changing the functionality of the code? Yes, I need to receive the value as number and compare it with variables (no MYSQL).

I set on each test the name, eg: $varname = "Paul";

Here´s what I´m doing and what I´d like to change. Thanks a lot

// from previous page with input name thenumber
$thenumber = $_POST['thenumber'];

$option1 = "1";
$option1 = "2";
$option1 = "3";
$option1 = "4";
$option1 = "5";
$option1 = "6";
...
...
More options

if($thename == $option1)
{
$varname = "Paul";
}
else if ($thename == $option2)
{
$varname = "Louie";
}
else if ($thename == $option3)
{
$varname = "Dimitri";
}
...
...
...

eval as if statement condition

Why is the output of the following statement true?

VAR="[[ "x"=="y" ]]"
if eval $VAR ; then
    echo "true"
else
    echo "false"
fi

Is there any other way to use a variable as condition for an if statement in bash?

Download files with wget. If wget downloads files, move them, otherwise use wget to download different files

I am trying to run a shell script that includes if statements and a set of initial conditions. If wget downloads the files, I would like the script to check if the files with the "grib2" extension exists in the folder. if the files do exist, then it moves them to another directory. If after running wget the files don't download or exist in the directory, then I would like wget to download from a different source. The script is meant to filter.

The issue I am encountering is the second wget script never runs, even if there are zero files with that extension in the folder.

#!/bin/sh

#
# variables
#

basedir="http://ift.tt/1PATK9X"
basename1="hur/prod/hur."

date=`date +"%Y%m%d"`
date1=`date +"%Y%m%d" -d "+1 days"`
date2=`date +"%Y%m%d" -d "-1 days"`
hour=`date +"%H"`
file=`ls -l /awips2/edex/data/gfdl/*.grib2 2>/dev/null`
#
# main
#

if [ $hour -ge "13" ] && [ $hour -le "18" ]
then
datetime="${date}12"
url1="${basedir}/${basename1}${datetime}/"
wget -r -nd --no-parent -e robots=off -R 'index.*' -A '*9*l*.0p16.*.grib2' -P /awips2/edex/data/gfdl/ $url1 
   if [[ "$file" != "0" ]]; then
   mv /awips2/edex/data/gfdl/* /awips2/edex/data/manual/
   else [[ "$file" != "1" ]]; then
   wget -r -nd --no-parent -e robots=off -R 'index.*' -A '*0*l*.0p16.*.grib2' -P /awips2/edex/data/gfdl/ $url1
   mv /awips2/edex/data/gfdl/* /awips2/edex/data/manual/
   fi



elif [ $hour -ge "19" ] && [ $hour -le "23" ]
then
datetime="${date}18"
url1="${basedir}/${basename1}${datetime}/"
wget -r -nd --no-parent -e robots=off -R 'index.*' -A '*9*l*.0p16.*.grib2' -P /awips2/edex/data/gfdl/ $url1 
   if [[ "$file" != "0" ]]; then
   mv /awips2/edex/data/gfdl/* /awips2/edex/data/manual/
   else [[ "$file" != "1" ]]; then
   wget -r -nd --no-parent -e robots=off -R 'index.*' -A   '*0*l*.0p16.*.grib2' -P /awips2/edex/data/gfdl/ $url1
   mv /awips2/edex/data/gfdl/* /awips2/edex/data/manual/
   fi
fi

Simple rock, paper, scissors game [Python]

I'm trying to write a simple RPS game but I'm having trouble getting the program to display the result of the game. Mind you, I'm a total beginner in programming and I've written all this from what I've learned previously so it probably isn't the most efficent way to write a game like this.

import random
rps = ['rock', 'paper', 'scissors']
rps2 = (random.choice(rps))

print 'Welcome to RPS'
print 'Press 1 to pick Rock'
print 'Press 2 to pick Paper'
print 'Press 3 to pick Scissors'
print 'Press 4 to quit.'


while True:
    game = int(raw_input('What do you pick? '))
    if game == 1:
        print 'You picked rock.'
        print 'The computer picked...' + (random.choice(rps))
        if rps2 == [0]:
            print 'It\'s a tie!'
        elif rps2 == [1]:
            print 'You lose!'
        elif rps2 == [2]:
            print 'You win!'
    elif game == 2:
        print 'You picked paper.'
        print 'The computer picked...' + (random.choice(rps))
        if rps2 == [0]:
            print 'You win!'
        elif rps2 == [1]:
            print 'It\'s a tie!'
        elif rps2 == [2]:
            print 'You lose!'
    elif game == 3:
        print 'You picked scissors.'
        print 'The computer picked...' + (random.choice(rps))
    if rps2 == [0]:
        print 'You lose!'
    elif rps2 == [1]:
        print 'You win!'
    elif rps2 == [2]:
        print 'It\'s a tie!'
    elif game == 4:
        print 'Thank you for playing!'
        break
    else:
        continue

Current CultureName for if else or a switch?

I need for an if or switch statement the current name. I couldn't find a solution.

This code doesn't work.

        if (Thread.CurrentThread.CurrentCulture == new CultureInfo("en"))
        {
            // EN (default)
        }

        if (Thread.CurrentThread.CurrentCulture == new CultureInfo("de"))
        {
            // DE
        }

Bash or condition in IF

Why does the OR condition not work in the following bash script?

read number

if [ "$number" != 1 -o "$number" != 2 ] ; then echo not 1 or 2 fi

if [ "$number" == 1 -o "$number" == 2] ; then echo 1 or 2 fi

exit

If-statement error [on hold]

Hello im doing some coding homework and i stumbled upon an error while writing some if-statements.

        if ((my_weight / (my_height * my_height)) < 18.5) { bmi_state = "Underviktig" }
        if ((my_weight / (my_height * my_height)) < 18.5) { bmi_state = "Normalviktig" }
        if ((my_weight / (my_height * my_height)) < 18.5) { bmi_state = "Överviktig" }
        if ((my_weight / (my_height * my_height)) < 18.5) { bmi_state = "Fet" }

And with the error: CS1002 (; expected)

Great regards, Oscar Andersson from Sweden.

Can I use an if statement inside an if statement

Is it possible to use an if statement inside of an if statement? For example:

If answer=10:
     answer2=input("Do you agree")
     if answer2=yes
         print("You agree")
     else: 
         print("You disagree")


else:
print("You don't answer")

IF statement using Python 3 tkinter

What I would like to do is create a password mechanism for a GUI I have previously created. This is what I have so far:

   import tkinter as tk
   from tkinter import*
   import ctypes

   def runUnturned():
       ctypes.windll.shell32.ShellExecuteW(0, 'open', 'C:\\Program Files (x86)\\Steam\\steamapps\\common\\Unturned\\UnturnedServer', None, None, 10)

   def RUNCMD():
       ctypes.windll.shell32.ShellExecuteW(0, 'open', 'cmd.exe', '/k ipconfig', None, 10)

   class PasswordDialog(tk.Toplevel):
         def __init__(self, parent):
             tk.Toplevel.__init__(self)
             self.parent = parent
             self.entry = tk.Entry(self, show='*')
             self.entry.bind("<KeyRelease-Return>", self.StorePassEvent)
             self.entry.pack()
             self.button = tk.Button(self)
             self.button["text"] = "Submit"
             self.button["command"] = self.StorePass
             self.button.pack()

def StorePassEvent(self, event):
    self.StorePass()

def StorePass(self):
    self.parent.password = self.entry.get()
    self.destroy()

class UsernameDialog(tk.Toplevel):
     def __init__(self, parent):
         tk.Toplevel.__init__(self)
         self.parent = parent
         self.entry = tk.Entry(self)
         self.entry.bind("<KeyRelease-Return>", self.StorePassEvent)
         self.entry.pack()
         self.button = tk.Button(self)
         self.button["text"] = "Submit"
         self.button["command"] = self.StorePass
         self.button.pack()

    def StorePassEvent(self, event):
        self.StorePass()

   def StorePass(self):
       self.parent.username = self.entry.get()
       self.destroy()

class Application1(tk.Frame):
     def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.password = None
        self.username = None
        self.button = tk.Button(self)
        self.button1 = tk.Button(self)
        self.button1["text"] = "Username"
        self.button1["command"] = self.GetUsername
        self.button1.pack()
        self.button = tk.Button(self)
        self.button["text"] = "Password"
        self.button["command"] = self.GetPassword
        self.button.pack()

   def GetPassword(self):
       self.wait_window(PasswordDialog(self))
       print("Password: ", self.password)

   def GetUsername(self):
       self.wait_window(UsernameDialog(self))
       print("Username: ", self.username)

class MainApplication(tk.Frame):
      def __init__(self, master):
          super(Application, self).__init__(master)
          self.grid()
          self.create_widgets()

      def create_widgets(self):
          btnb = Button(app, text = "Run CMD", command=RUNCMD)
          btnb.grid()
          btna = Button(app, text = 'Unturned Server', command=runUnturned)
          btna.grid()

if __name__ == "__main__":
   root = tk.Tk()
   root.geometry("200x100")
   Application1(root).pack(side="top", fill="both", expand=True)
   root.mainloop()

if ??? == "excelsior":
   root = tk.Tk()
   root.title("My Servers")
   root.geometry("400x400")
   MainApplication(root).pack(side="top", fill="both", expand=True)
   root.mainloop()

Notice that the final if statement has a "???" instead of "password". That is because I am unsure of what to put there and there is no predefined class or variable called password. Can someone help me figure out what I have done?

Can get variable to set on javascript

Trying to make a variable __lc.group dynamic so that the group number is set based on the URL of the page, this is the code I have tried but it doesn't seem to have worked.

Not sure why it wouldn't be working. This is to dynamically set the group variable for a live chat function on site so I can set different operators for differnet pages of the site.

if(window.location.href.indexOf("netball") > -1) {
       __lc.group = 1;
    }
if(window.location.href.indexOf("football") > -1) {
       __lc.group = 5;
    }
if(window.location.href.indexOf("basketball") > -1) {
       __lc.group = 2;
    }
if(window.location.href.indexOf("social") > -1) {
       __lc.group = 3;
    }
if(window.location.href.indexOf("fitness") > -1) {
       __lc.group = 6;
    }
if(window.location.href.indexOf("softball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("volleyball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("dodgeball") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("american") > -1) {
       __lc.group = 4;
    }
if(window.location.href.indexOf("ultimate") > -1) {
       __lc.group = 4;
    }

PHP If Statement Logic

I am a bit stuck on an if statement on my PHP code. I know this is probably a basic question for most of you out there, but i am stuck, and i would like some assistance.

I have 2 variables $max and $ min, which i have to compare with 2 other max and mins called $valor and $minimo in order to check if they are meeting somewhere. What i basically have is a set of values like min=20 and max=30.

I want to compare those with the other max and min, and check if somewhere the values meet, like if the min of the second one is 29. I want it to enter the if statement.

Here's the statement i got right now. But it's not working, and i just can't get the logic on it. Any help?

if ($min >= $valor && $min <= $minimo || $max >= $valor && $max <= $minimo)
    {
        //Do nothing
    }
else
    {
        $queryq = "INSERT INTO precos_area (id_tecido,area_minima,area_maxima,preco) VALUES ('".$id_tipo."', '".$min."', '".$max."', '".$price."')";
        $resultsq = mysql_query($queryq) or die(mysql_error());
    }

If condition in shell script with multiple conditions including check for null strings

What is wrong with the below syntax, I keep getting [: too many arguments

All the variables are strings, also I have introduced var3 and str3, two make sure we are not comparing two null values, is there any other better option to deal with it

if [ "$var1" = "$var2" = "$var3" && "$str1" = "$str2" = "$str3" ] then echo " something" elif [ "$var1" = "$var2" = "$var3"] then echo something else elif [ "$str1" = "str2" = "str3" ] then echo something else else exit fi

Condition based where clause sql procedure

Hi can some one suggest me how to add a condition in where clause of my stored procedure? Here is my procedure

CREATE Procedure getAllEmployeesByDeptAndFlag
@Dept int,
@sal int,
@Flag int
as
if @flag = 1
    select * from employee where Department = @dept and @sal < 10000
else 
    select * from employee where Department = @dept

Is there any way to simplify above procedure?

dplyr-how to insert NA values when the column sort order changes

I'm trying to figure out a simple way to insert NA values when the column values are changed from the decreasing order to mixed order. But if decreasing order continues logically after this mixed ordered rows, its ok to keep this rows too.

If the column does not have decreasing order row values replace values with NA.

Any column which can keep the sort sequence at least 5 numbers can pass. Else replace NA values.

Its best for me to do this process with dplyr . I tried to do this but cannot came up with the idea:(.

dt_new <- dt%>%
    mutate_each(funs(replace(., which(ifelse(.....

example data

C1 = c(1:10,7,8,11,12)
C2 = c(2:12,7,13,12)
C3 = sample(1:14)
C4 = c(1:14)

dt <- data.frame(C1,C2,C3,C4)

       C1 C2 C3 C4 C5
#   1   1  2  4  1  1
#   2   2  3 12  2  2
#   3   3  4  6  3  8
#   4   4  5 10  4  5
#   5   5  6  7  5  7
#   6   6  7  5  6  4
#   7   7  8 13  7  6
#   8   8  9 14  8  3
#   9   9 10  8  9  9
#   10 10 11  1 10  5
#   11  7 12  9 11  6
#   12  8  7  2 12  7 
#   13 11 13  3 13  8
#   14 12 12 11 14 10

the output Which I look for

       C1 C2 C3 C4 C5
#   1   1  2 NA  1 NA
#   2   2  3 NA  2 NA
#   3   3  4 NA  3 NA 
#   4   4  5 NA  4 NA
#   5   5  6 NA  5 NA
#   6   6  7 NA  6 NA
#   7   7  8 NA  7 NA
#   8   8  9 NA  8 NA
#   9   9 10 NA  9 NA
#   10 10 11 NA 10 5
#   11 NA 12 NA 11 6
#   12 NA NA NA 12 7
#   13 11 13 NA 13 8
#   14 12 NA NA 14 10

Checking whether nested/hierarchy of properties are null?

I have:

label.Text = myObject.myNestedObject.MyNestedObject2.Description;

Where label is asp.net label. The problem is that sometimes myObject, myNestedObject, MyNestedObject2 or Description is null and I must check it in if statement which looks like:

if(myObject!=null&&myNestedObject!=null&&MyNestedObject2!=null&&Description!=null)
{
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
}

In this statement I check four times whether properties is null. Does exist any other way to check entire hierarchy?

mercredi 26 août 2015

How to compare two long value at runtime in java

How to compare two long value at runtime. When I got the value of both of long type variable at runtime which same so it should be print else part but the both value is different from each other so it should be print if part.

Long dbData = 54188439.... // Got the value at run time
Long spreadSheet = 54188439.....//Got the value at run time

if(dbData != spreadSheet)
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}  

Here I always got if part whatever be the condition. Please help me out.

C - What's the best way for checking if any value is NULL or empty?

I was wondering what was the best (I mean performance and proper) of checking an empty value ?

I know these 2 ways :

First (I think the best) :

For any pointer check : if (value == NULL) ... For an Int : if (value == 0)...


Second : if (value) ...

Thank you in advance!

Error with the for loop code. The loop is not overwriting the values in the cloumn

I want to add a new column consisting different colors to my data frame. So that I can use that column in the arg col while plotting the points of that variable.

I want to assign same color for a values falling in same range and different colors for those falling in different range.

For example, I have a certain dataset consisting of following values:

> CN 

A    X
1    0.05
2    0.09
3    NA
4    0.12
5    0.35
6    0.21
7    NA
8    0.01
9    0.14
10   0.32
11   0.43
12   0.19

I would like to add a separate column (Col) to my dataframe CN

> CN$Col <= "white" 

Its a success in creating a new column. I would like to assign different colors to each of these values. And assign either white or a transparent color for NA values. i.e

<0.05      -- red
0.05 - 0.1 -- orange
0.1  - 0.2 -- yellow
0.2  - 0.3 -- green
0.3  - 0.4 -- darkviolet
0.4  - 0.5 -- blue

Here is the code I have written

CN$Col <- "white"

for (i in 1:length(CN)) {
d <- is.na(CN$X[i])
 if (d == "FALSE") {
   if (CN$X[i] <= 0.05)
     CN$Col[i] <- "red"
   else if (CN$X[i] <= 0.1 && CN$X[i] > 0.05)
     CN$Col[i] <= "orange"
   else if (CN$X[i] <= 0.2 && CN$X[i] > 0.1)
     CN$Col[i] <- "yellow"
   else if (CN$X[i] <= 0.3 && CN$X[i] > 0.2)
     CN$Col[i] <- "green"
   else if (CN$X[i] <= 0.4 && CN$X[i] > 0.3)
     CN$Col[i] <- "darkviolet"
   else if (CN$X[i] <= 0.5 && CN$X[i] > 0.4)
     CN$Col[i] <- "blue"
 }
else
CN$Col[i] <- rgb(0, 0 , 0, alpha = 0) # rgb command can be replaced with color white
}

This code does not overwrite the white I have fed to the column earlier.

Thanks in advance.