jeudi 31 mars 2016

"confirm" in function. How can "confirm" starts if it's located only inside "if"?

Here is the code. Could you please explain how the "confirm" works here. It just says, that: "if there is the "confirm" but the is no command "confirm" in fact.

function ask(question, yes, no) {
    if (confirm(question)) {
        yes()
    }
    else {
        no();
    }
  }
function showOk() {
  alert( "You are agree." );
}

function showCancel() {
  alert( "You cancelled." );
}
ask("Are you agree?", showOk, showCancel);

Convert Perl script to C

I create a perl script via following code:

my $LicenseServerCheck = get('http://my-domain.com/');

if ($LicenseServerCheck == 1){
print 'You Have license'; }
else{ print ' You dont have License'; }

i need it perl script convert to C .

How to do it?

Thank you.

SWIFT if statement and segue

I have a problem with if statement and segue can I make a connection between them ! I have an array of these states ["Florida","NY"]()

my idea, for example, if I clicked "Florida"<(this is "string") on table view I want the segue moves me from this table view to another table view

and if I clicked "NewYork" on tableView I want the segue moves me from this table view to another that has information about NY

thanks

If And statement with a foreach for AD Users in Powershell

$names = Import-CSV C:\PowerShell\TerminatedEmployees.csv $Date = Get-Date foreach ($name in $names) { Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | select Name | Out-File "C:\Powershell\ADUserMemberships\$($name.TextBox37)Memberships.txt" $ADgroups = Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | where {$_.Name -ne "Domain Users"} Remove-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" -MemberOf $ADgroups -Confirm:$false Disable-ADAccount -Identity "$($name.TextBox37)" Get-ADUser -Identity "$($name.TextBox37)" | Move-ADObject -TargetPath "OU=DisabledAccounts,OU=XXX,DC=XXX,DC=XXXX,DC=XXX" Set-ADUser -Identity "$($name.TextBox37)" -Description "Disabled $Date" }

This is an already working script I have. However, I realized I need to check 2 properties on the AD user to determine if they need to need to go through my foreach statement. Both properties need to be met. If they are then there's no reason for the AD users to be processed.

  1. The AD user is already disabled.

  2. The AD user already resides in the Disabled OU.

I'm thinking this needs to be done in an If -And statement. But does this need to be done before the foreach or inside the foreach?

How to compare two shell command output in Makefile?

My Makefile is:

.PHONY: check
check:
        ifneq $(shell echo 123), $(shell echo 123)
                $(error Not equal)
        endif

When I run, I've got the error:

$ make
Makefile:3: *** Not equal.  Stop.

But this should happen only when they're different, but they're not. Why?

Open Office If Else funktion for two columns

I try to check the value of one cell to get a value for teh second cell in a other column. if B1 is '0' than i want in C1 also '0' and if B1 is '1' than i need to get in C1 30 (or at least greater than 1). But it downs't work.

I try

=if(B1=0;C1=0;30)

and get 'False'

and with

=if(B1>1;C1>1;30)

or

=IF(BJ1=0;BI1=0;30)

i get 30 but i need 0 in this case.

How can i make it working?

Keep getting error#1502 for this loop in as3

It's supposed to be for a rhythm game, where while the mc is on the stage, the boolean keeps switching back and forth from true to flase and you have to catch it at the right time. But I keep getting an error...

while (theBeat)
{
  if (theBeat.currentFrame < 5)
    {
    onBeat = true
    trace(onBeat)
    }

  if (theBeat.currentFrame > 5)
    {
    onBeat = false
    trace(onBeat)
    }
}

Need to change TableName being passed in to Java SQLite query

I am passing VariableA (barTableName ) to an SQLite query, "SELECT * FROM " + barTableName + " WHERE DRINKTYPE='Beer';". I need barTableName to be able to change, based on what a user chooses. When I hardcode the variable, it works. If I try to change it at all, no matter how far back in the "variable timeline", it gives me a null point exception. Does anyone know how I could acomplish this?

DBHelper

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.sixth/databases/";
    private static String DB_NAME = "BarSample.db"; 
    private final Context myContext;    
    public static String tableName = "BARS";
    String barTableName, sqlquery ;
    public static String firstBarTableName = MainActivity.upperCaseName;//Pass in the specific bar from the spinner choice
    private SQLiteDatabase myDataBase;


    public DBHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     */
    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {
                this.close();
                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {

        SQLiteDatabase checkDB = null;

        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     */
    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {

        // Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

        if (myDataBase != null)
            myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + tableName;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1) + " " + cursor.getString(2)+ ", " + cursor.getString(3));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return labels;

    } // will returns all labels stored in database

    public List<String> getBeerDrinkLabels(){
        //naming();
        List<String> allBeerDrinkLabels = new ArrayList<String>();

        if (firstBarTableName.equals("CHANGOS")){
            sqlquery = "SELECT * FROM CHANGOS WHERE DRINKTYPE='Beer';";
        }
        else if(firstBarTableName.equals("LANDOS")){
            sqlquery = "SELECT * FROM LANDOS WHERE DRINKTYPE='Beer';";
        }
        else{
            sqlquery = "SELECT * FROM ANTHONYS WHERE DRINKTYPE='Beer';";
        }


        //String sqlquery="SELECT * FROM " + barTableName + " WHERE DRINKTYPE='Beer';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allBeerDrinkLabels.add(cursor.getString(1) + " Price: " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allBeerDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getWineDrinkLabels(){
        List<String> allWineDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Wine';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allWineDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allWineDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getMixedDrinkDrinkLabels(){
        List<String> allMixedDrinkDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Mixed Drink';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allMixedDrinkDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allMixedDrinkDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getOtherDrinkLabels(){
        List<String> allOtherDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Other';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allOtherDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allOtherDrinkLabels;

    } // will returns all labels stored in database

    public List<String> getShotsDrinkLabels(){
        List<String> allShotsDrinkLabels = new ArrayList<String>();

        // Select All Query
        String sqlquery="SELECT * FROM "+barTableName + " WHERE DRINKTYPE='Shots';";
        String selectQuery = sqlquery;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                allShotsDrinkLabels.add(cursor.getString(1) + ", " + cursor.getString(2));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning labels
        return allShotsDrinkLabels;

    } // will returns all labels stored in database
}

I'm currently try to assign it to splquery with an If statement, based on what is coming in from the other class. I have double, triple checked. The variable coming in IS one of the 3 that are in the if statement, all in caps like is in the statement. I've been working on this for a long while and am beating my head against the wall. Any help would be VERY appreciated.

(Java) Bowling object storing incorectly

Im and trying to make a program to calculate a bowling score base on a string. I have created a class that stores each frame as a seperate object, which stores 3 intergers for each roll, and two boolean variables that store wethere or not the frame is a strike or a spare. I am having trouble getting the spare to store the rolls correctly. Below is the code I am using to create the objects and sgtore the data.

        String gameTemp = "1 0 1 / 2 2 X 3 3 X 1 / 3 / X 1 2";
    game = gameTemp.replace(" ", "");

    temp = game.charAt(i);

    if( temp == 'X'){
        roll1 = 10;
        roll2 = 0;
        strike = true;
        i++;
    }
    else{
        if( temp == '0'){
            roll1 = 0;
            i++;
        }
        else{
            roll1 = Character.getNumericValue( temp);
            i++;
        }
        temp = game.charAt(i);
        if( temp == '/'){
            roll2 = 10 - roll1;
            spare = true;
            i++;
        }
        else if( temp == '0'){
            roll2 = 0;
            i++;
        }
        else{
            roll2 = Character.getNumericValue( temp);
            i++;
        }
    }
    bowlingObj f1 = new bowlingObj( roll1, roll2, strike, spare);
    strike = false;
    spare = false;
    roll1 = 0;
    roll2 = 0;

    if( temp == 'X'){
        roll1 = 10;
        roll2 = 0;
        strike = true;
        i++;
    }
    else{
        if( temp == '0'){
            roll1 = 0;
            i++;
        }
        else{
            roll1 = Character.getNumericValue( temp);
            System.out.println(roll1);
            i++;
        }
        temp = game.charAt(i);
        if( temp == '/'){
            roll2 = 10 - roll1;
            spare = true;
            i++;
        }
        else if( temp == '0'){
            roll2 = 0;
            i++;
        }
        else{
            roll2 = Character.getNumericValue( temp);
            i++;
        }
    }
    bowlingObj f2 = new bowlingObj( roll1, roll2, strike, spare);

    System.out.println( f1);
    System.out.println( f2);
  }

This is the output. A number represents one roll:

[ 1 0]
[ 0 10]

This is the input:

1 0 1 /

it should store:

   [ 1 0]
   [ 1 9]

If statements php

I have a form, which collects a load of user data, before submitting the information to my database, it should check to see if the username is already taken, and if the two passwords entered are the same.

If I remove the password if statement, usernameError gets set and displays correctly.

If I remove the username statement the passwordError gets set and displays correctly

I need it to check both of these statements THEN submit to the database if the username doesn't exist AND the two passwords are the same.

The reason I'm using usernameError in the final part is just because it'll display a result if it is successful, once I get it working, I will change that to run an sql query. as it is now, no matter that I enter into the form, nothing happens.

The usernameError variable is declared at the start and is blank, it's always printed out onto the page it works, I've tested it, it just assigns it a value and it prints the value.

 if ($userQuery->execute()) {

    while ($row = $userQuery->fetch()) {

        if ($userQuery->rowCount() > 0) {

            $usernameError = 'username is already taken!';

        } else if ($_POST['passwordOne'] != $_POST['passwordTwo']) {

            $passwordError = 'passwords do not match!';

        } else {

            $usernameError = 'user saved';

        }
    }
}

Java 8 Lambda To Handle for > if > else

I need to run two different tasks based on a whole mess of filters

I'm just now grasping the concept of Lambdas, so I guess my question is, how do you handle multiple "else" conditions containing complicated logic... within a Lambda?

I know I can use filter and map to select certain pieces of data. How does "nesting" work with filters?

Could I do something like:

//Iterate over list of sites
sites.stream()
//Check if current site is active
.map(isActive ? 
//{Do something with site because site is active};
//Set a variable for later user maybe?
:
//{Do something else involving the current site because it's not?};
//Set a different variable maybe?
);

//use variable from first map?

Can someone provide me with some proper syntax and maybe a basic explanation of what I'm doing to my data when I run through these abstract processes that are doing me a bamboozle.

Secondly, if I wanted to run these two map processes in parallel, would I just do this?

sites.stream().parallel()?

As usual, thanks for helping with my ignorance!

Method without repeat

I have class called QuestionsAll with constructor

(label question, Button b1, Button b2, Button b3, Button b4)

and method called

questions(string question, string answer1, string answer2, string answer3, string answer4, Button correctanswer)

How I use it in my form:

Random rd = new Random();
int qu = rd.Next(0,4)
QuestionsAll q = new QuestionsAll(label1,Button1,Button2,Button3,Button4) //my question will be in label1, answer1 in Button1......)

if(qu == 1) q.questions("1+1 =", "1", "2", "3", "4", Button2)
if(qu == 2) q.questions("1+2 =", "1", "2", "3", "4", Button3)

And when you click in right question, question changes, but questions and answers repeat. How can i do it with no repeat?

If Statement in MySQL Select

According to the docs a if works as follows:

IF(expr1,expr2,expr3)

If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3 [...].

Here is a random fiddle that represents my problem: http://ift.tt/1pO2Rgr

Basically what I'm trying to do is the following:

SELECT IF(whatever, 1, 2) FROM testing WHERE whatever = 'abc';

Since there is a record there that matches my WHERE clause it basically means that whatever won't be 0 or NULL like specified in the docs. Then why am I getting expression3 as result?

Javascript for loop with if statement not reaching the else if statement

why wont this reach the else if and return (i + 0) / 2? Also, why wont the alert give me i + 0 for a 2 digit value? (ie: 10, 20, 30, 40, etc. Any help would be appreciated.

var key= "OSN0MSA9991UNAAM8ELDPBD9F57BD6PU6BVBN54CDLEGDSUSNS";
var x = 0;
if (key[20] != "P" || key[18] != "P") {
 x = 0;
 for (i=0;i<10;i++) {
  if (key[26] == i) {
   x = i + 0;
   alert(x);
  }
 };
} else if (key[20] == "P") {
 for (i=9;i>-1;i--) {
  if (key[26] == i) {
    x = (i + 0) / 2;
   alert(x);
  }
 };     
};

If Else in R, if product ID is X then change Product Name

I am trying to figure our what is it working and the other why is not working for me. At the moment I have a list of shops I use and I need to change the naming every time, I have decided to go by the product_id which never change but my code is not working product_id <- vector()

This one is not working:

product_name[product_id == '40600000003'] <- 'my cool store']

but this one, do work

product_name[product_name == 'my#cool@Store'] <- 'my cool store'

now, I am not sure what am I doing wrong, I tried to do if

  if (product_id == '40600000003') {product_name = 'my cool shop'

}

Your help will be much welcomed I have a list of 15 shops that I need to change the naming as they arrive in the wrong format from the api connection.

Thanks in advance

Using an if function in controller

I'm trying to make an application to store played FIFA games.

Now I'm already able to make accounts, store games, etc. But when I'm storing a game into the DB, I would also like to store the winner and loser of the game in a way that I can use the count function later to count how many wins or losses a user has.

Controller:

class GamesController < ApplicationController
    before_action :authenticate_user!, exept: [:index, :show]

    def index
        @games = Game.all
    end

    def new
        @game = current_user.games.build
        @user_options = User.all.map{|u| [ u.user_name, u.id ] }
    end

    def create
        @user_options = User.all.map{|u| [ u.user_name, u.id ] }

        @game = Game.new(game_params)
        @game.home_team_user_id = current_user.id

        if @game.home_score > @game.away_score
            @game.winner_id = @game.home_team_user_id
            @game.loser_id = @game.away_team_user_id     
        else if @game.home_score < @game.away_score   
            @game.winner_id = @game.away_team_user_id
            @game.loser_id = @game.home_team_user_id  
        else
        end

        if @game.save
            redirect_to games_path, :notice => "Successfully added game!"
        else
            render 'index'
        end
    end

    def show
        @games = Game.all
    end

    def destroy
        @game = Game.find(params[:id])
        @game.destroy
        redirect_to games_path
    end

    private
    def find_game
        @game = Game.find(params[:id])    
    end

    def game_params
        params.require(:game).permit(:home_team_user_name, :home_score, :away_team_user_name, :away_score, :home_team_user_id, :away_team_user_id, :winner_id, :loser_id)
    end
end
end

View:

<div class="col-md-12" style="text-align:center">
  <div class="panel panel-default" style="margin-right:10px">
    <div class="panel-heading">
      <h3 class="panel-title">Submit New Match</h3>
    </div>
    <div class="panel-body">
      <%= simple_form_for(@game) do |f| %>
      <%= f.text_field :home_score, :placeholder => "Your score" %>
      <%= f.text_field :away_score, :placeholder => "Your Opponents score" %> <br><br>
      <p>Opponent:</p>
      <%= f.select(:away_team_user_id, @user_options) %>
      <br> <br> <%= f.submit "Submit Match", class: "btn-submit" %>
      <% end %>
    </div>
</div>

Is this the correct way to make this calculation? Or do you have other suggestions?

If this is the correct way, then why do I get this error when I try to submit the form:

undefined local variable or method `game_params' for

As you can see in the controller, the game_params is not missing. I've added an end at the end though, because this gave an error to load the form.

Using If Large Statement and Populating Remainder of Table in Excel

I have a dataset that looks like the example below. I want to pull a list of the last ten transactions, ordered by Transaction Date, while capturing all columns of information in the original dataset; and I want to do this only IF the Salesman is Jimmy.

I'm stumped. Any ideas how to do this?

Example dataset below:

    Customer Name   Customer Group  Salesman    Transaction Date
    Sam                    1          Jimmy     3/21/2015
    Jill                   2          Johnny    3/21/2015
    Scott                  3          Joanny    3/21/2015
    Sean                   4          Slippy    3/24/2015
    Dave                   5          Slappy    3/25/2015
    Amber                  4          Slummy    3/26/2015
    Shawn                  3          Jimmy     3/24/2015
    Matt                   2          Johnny    3/26/2015
    Matthew                4          Joanny    3/24/2015
    Mark                   3          Slippy    3/21/2015
    Luke                   2          Slappy    3/26/2015
    John                   1          Slummy    3/26/2015
    Jonathan               5          Jimmy     3/24/2015
    Zach                   3          Johnny    3/26/2015
    Asher                  2          Joanny    3/21/2015

Desired output is of last 10 transactions ordered by Forecast Transaction Date

Customer Name   Customer Group  Salesman    Forecast Transaction Date

Android quiz app concept not showing correct score

At this phase below code runs like when any user-

  • press the radio button and press next button score increments on correct answer.
  • press the radio button and press next button score decrements on incorrect answer.
  • but when user press the back button my radio button get unchecked and if again i press the correct answer it increments the score.

I want that- when either user press the back or next question button the previous answered questions should remain checked and does not increment the score again when the user press the next question button.

    quizQuestion = (TextView) findViewById(R.id.quiz_question);

            radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
            optionOne = (RadioButton) findViewById(R.id.radio0);
            optionTwo = (RadioButton) findViewById(R.id.radio1);
            optionThree = (RadioButton) findViewById(R.id.radio2);
            optionFour = (RadioButton) findViewById(R.id.radio3);

            Button previousButton = (Button) findViewById(R.id.previousquiz);
            Button nextButton = (Button) findViewById(R.id.nextquiz);
            text1 = (TextView) findViewById(R.id.t);

            new CountDownTimer(50000, 1000) { // adjust the milli seconds here

                public void onTick(long millisUntilFinished) {

                    text1.setText("" + String.format(FORMAT,
                            TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                    TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
                }

                public void onFinish() {
                    text1.setText("Time Over!");
                }
            }.start();

            AsyncJsonObject asyncObject = new AsyncJsonObject();
            asyncObject.execute("");

            nextButton.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    int radioSelected = radioGroup.getCheckedRadioButtonId();

                    int userSelection = getSelectedAnswer(radioSelected);

                    int correctAnswerForQuestion = firstQuestion.getCorrectAnswer();

                    if ((radioGroup.getCheckedRadioButtonId() == -1)) {

                        score = correct - wrong;
                        Toast.makeText(getApplicationContext(), "Select an  Answer Please" + score, Toast.LENGTH_LONG).show();
                        currentQuizQuestion++;
                        radioGroup.clearCheck();
                        if (currentQuizQuestion >= quizCount) {

                            Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                            return;

                        } else {

                            firstQuestion = parsedObject.get(currentQuizQuestion);

                            quizQuestion.setText(firstQuestion.getQuestion());

                            String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                            optionOne.setText(possibleAnswers[0]);

                            optionTwo.setText(possibleAnswers[1]);

                            optionThree.setText(possibleAnswers[2]);

                            optionFour.setText(possibleAnswers[3]);

                        }
                    } else if (radioGroup.getCheckedRadioButtonId() != -1 && userSelection == correctAnswerForQuestion) {

                        // correct answer

                        correct++;
                        Toast.makeText(QuizActivity.this, "You got the answer correct" + "Correct-" + correct + "Wrong" + wrong, Toast.LENGTH_LONG).show();
                        currentQuizQuestion++;
                        radioGroup.clearCheck();
                        if (currentQuizQuestion >= quizCount) {

                            Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                            return;

                        } else {

                            firstQuestion = parsedObject.get(currentQuizQuestion);

                            quizQuestion.setText(firstQuestion.getQuestion());

                            String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                            optionOne.setText(possibleAnswers[0]);

                            optionTwo.setText(possibleAnswers[1]);

                            optionThree.setText(possibleAnswers[2]);

                            optionFour.setText(possibleAnswers[3]);

                        }

                    } else if (radioGroup.getCheckedRadioButtonId() != -1) {

                        // failed question
                        wrong++;

                        Toast.makeText(QuizActivity.this, "You got the answer correct" + "Correct-" + correct + "Wrong" + wrong, Toast.LENGTH_LONG).show();
                        currentQuizQuestion++;
                        radioGroup.clearCheck();
                        if (currentQuizQuestion >= quizCount) {

                            Toast.makeText(QuizActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();

                            return;

                        } else {

                            firstQuestion = parsedObject.get(currentQuizQuestion);

                            quizQuestion.setText(firstQuestion.getQuestion());

                            String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                            optionOne.setText(possibleAnswers[0]);

                            optionTwo.setText(possibleAnswers[1]);

                            optionThree.setText(possibleAnswers[2]);

                            optionFour.setText(possibleAnswers[3]);

                        }

                    } else {
                        Toast.makeText(QuizActivity.this, "UNKNOWN ERROR", Toast.LENGTH_LONG).show();
                    }
                }

            });


            previousButton.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    currentQuizQuestion--;

                    if (currentQuizQuestion < 0) {

                        return;

                    }
                    radioGroup.clearCheck();
                   // uncheckedRadioButton();

                    firstQuestion = parsedObject.get(currentQuizQuestion);

                    quizQuestion.setText(firstQuestion.getQuestion());

                    String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                    optionOne.setText(possibleAnswers[0]);

                    optionTwo.setText(possibleAnswers[1]);

                    optionThree.setText(possibleAnswers[2]);

                    optionFour.setText(possibleAnswers[3]);

                }

            });

        }

        @Override

        public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

            getMenuInflater().inflate(R.menu.menu_quiz, menu);

            return true;

        }

        @Override

        public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will

    // automatically handle clicks on the Home/Up button, so long

    // as you specify a parent activity in AndroidManifest.xml.

            int id = item.getItemId();

    //noinspection SimplifiableIfStatement

            if (id == R.id.action_settings) {

                return true;

            }

            return super.onOptionsItemSelected(item);

        }

        private class AsyncJsonObject extends AsyncTask<String, Void, String> {

            private ProgressDialog progressDialog;

            @Override

            protected String doInBackground(String... params) {

                HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

                HttpPost httpPost = new HttpPost("https://xyz.php");

                String jsonResult = "";

                try {

                    HttpResponse response = httpClient.execute(httpPost);

                    jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

                    System.out.println("Returned Json object " + jsonResult.toString());

                } catch (ClientProtocolException e) {

    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IOException e) {

    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

                return jsonResult;

            }

            @Override

            protected void onPreExecute() {

    // TODO Auto-generated method stub

                super.onPreExecute();

                progressDialog = ProgressDialog.show(QuizActivity.this, "Downloading Quiz", "Wait....", true);

            }

            @Override

            protected void onPostExecute(String result) {

                super.onPostExecute(result);

                progressDialog.dismiss();

                System.out.println("Resulted Value: " + result);

                parsedObject = returnParsedJsonObject(result);

                if (parsedObject == null) {

                    return;

                }

                quizCount = parsedObject.size();

                firstQuestion = parsedObject.get(0);

                quizQuestion.setText(firstQuestion.getQuestion());

                String[] possibleAnswers = firstQuestion.getAnswers().split(",");

                optionOne.setText(possibleAnswers[0]);

                optionTwo.setText(possibleAnswers[1]);

                optionThree.setText(possibleAnswers[2]);

                optionFour.setText(possibleAnswers[3]);

            }

            private StringBuilder inputStreamToString(InputStream is) {

                String rLine = "";

                StringBuilder answer = new StringBuilder();

                BufferedReader br = new BufferedReader(new InputStreamReader(is));

                try {

                    while ((rLine = br.readLine()) != null) {

                        answer.append(rLine);

                    }

                } catch (IOException e) {

    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

                return answer;

            }

        }

        private List<QuizWrapper> returnParsedJsonObject(String result) {

            List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();

            JSONObject resultObject = null;

            JSONArray jsonArray = null;

            QuizWrapper newItemObject = null;

            try {

                resultObject = new JSONObject(result);

                System.out.println("Testing the water " + resultObject.toString());

                jsonArray = resultObject.optJSONArray("quiz_questions");

            } catch (JSONException e) {

                e.printStackTrace();

            }

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

                JSONObject jsonChildNode = null;

                try {

                    jsonChildNode = jsonArray.getJSONObject(i);

                    int id = jsonChildNode.getInt("id");

                    String question = jsonChildNode.getString("question");

                    String answerOptions = jsonChildNode.getString("possible_answers");

                    int correctAnswer = jsonChildNode.getInt("correct_answer");

                    newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);

                    jsonObject.add(newItemObject);

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

            return jsonObject;

        }

        private int getSelectedAnswer(int radioSelected) {

            int answerSelected = 0;

            if (radioSelected == R.id.radio0) {

                answerSelected = 1;

            }

            if (radioSelected == R.id.radio1) {

                answerSelected = 2;

            }

            if (radioSelected == R.id.radio2) {

                answerSelected = 3;

            }

            if (radioSelected == R.id.radio3) {

                answerSelected = 4;

            }

            return answerSelected;

        }

        private void uncheckedRadioButton() {

            optionOne.setChecked(false);

            optionTwo.setChecked(false);

            optionThree.setChecked(false);

            optionFour.setChecked(false);

        }

    }
**I want that user can also see the previous answered questions and can also change their answered options.**

More pythonic way for a conditional variable

This is what I am trying to do:

  1. Get few arguments
  2. Based on the arguments, form a string
  3. Return the string

However, for this, I could see 3 potential ways:

def form_statement(subject, verb, object):
    greetings = ""
    if subject in ("Paul", "Raj"):
        greetings = "mister"
    return "%s %s %s %s" % (subject, verb, object, greetings)

Second way of doing this is:

def form_statement(subject, verb, object):
    if subject in ("Paul", "Raj"):
        greetings = "mister"
    else:
        greetings = ""
    return "%s %s %s %s" % (subject, verb, object, greetings)

And third way is:

def form_statement(subject, verb, object):
    greetings = "mister" if subject in ("Paul", "Raj") else ""
    return "%s %s %s %s" % (subject, verb, object, greetings)

Is there any other better way to do something like this? Right now I am opting for the first way as the "processing" to get the greetings string is a function in itself and makes the line to go beyond 80 characters when third way is used.

Approach for flag based process [on hold]

background

I have multiple attributes for user. Based on the attribute I do certain alteration to client request.

The problem

I have many such attributes which impacts alteration of client request. As of now I am maintaining it in SQL table. Because of this my code looks clumsy.

My question

what is the best approach for solving the problem ? is there any design pattern for that?

Best way to handle one time execution in a block of code in asp.net mvc

I am new to MVC. Can some one suggest me what is the best way to handle one time pass logic in a if statement in MVC Model Binder?

In my ModelBinder class, I want to put some logic in a if statement which need to be executed only once. ( Like !Page.IsPostBack in web applications). If you have any other suggestions, you are welcome.

Sorry for the Typo.

Regards, Viswa V.

mercredi 30 mars 2016

if statements and textinput value

If I have a textfield, and I want to use an IF statement to check that text field, for example, I can do this

if (thistxt.text=="query")
{  
thisbool = "true";
}

Now let's say I want to use an IF statement to call upon that same textfield but I don't want to pull that entire phrase, (query) maybe just the beginning or end of it, how could I do something like that? Let's say I want to activate the IF statement if that textfield contains or ends with "ery" but is not necessary perfectly equal to "ery".

Text color not changing correctly for textfields

When I enter the numbers correctly into the textfields, why does the text color only work for the "else" statement option and not for the "if" option ?

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var questionOne: UILabel!
@IBOutlet weak var fieldOne: UITextField! // textFields should be set as labels

@IBOutlet weak var questionTwo: UILabel!
@IBOutlet weak var fieldTwo: UITextField!

@IBOutlet weak var questionThree: UILabel!
@IBOutlet weak var fieldThree: UITextField!


@IBOutlet weak var questionFour: UILabel!
@IBOutlet weak var fieldFour: UITextField!


@IBAction func submitButton(sender: UIButton) {
    fieldOneColorChange()
    fieldTwoColorChange()
    fieldThreeColorChange()
    fieldFourColorChange()
}

@IBAction func resetButton(sender: UIButton) {
}

// Text color changes

func fieldOneColorChange() {
    if fieldOne == 1 {
        questionOne.textColor = UIColor.redColor()
    } else {
        questionOne.textColor = UIColor.blueColor()

    } 
}

func fieldTwoColorChange() {
    if fieldTwo == 2 {
        questionTwo.textColor = UIColor.brownColor()
    } else {
       questionTwo.textColor = UIColor.redColor()

    } 
}

func fieldThreeColorChange(){
    if fieldThree == 3 {
        questionThree.textColor = UIColor.blueColor()
    } else {
        questionThree.textColor = UIColor.purpleColor()
    }
}

func fieldFourColorChange(){
    if fieldFour == 4 {
        questionFour.textColor = UIColor.blueColor()
    } else {
        questionFour.textColor = UIColor.redColor()

    } 
}

Javascript doesn't return the value / used creatElement() and element.id

I'm new in Javascript, I'm doing a project that its main idea is having a conversation with 'Alex', however, it was working well till I wanted to input and output in -messaging way-, everthing went wrong after it. I used createElement() , appendChild() and element.id="id" in the write() and getVal() functions I do think that the error are from there. Console: There's no errors have been given by the console , but when I type anything in the textbox it type in the div but the function write doesn't return the value. Sorry for my English ^_^

I don't know if the issue from css or not.

Body:

userName = " Medardo";
var date = new Date().toTimeString().split(" ")[0];
var d = new Date();
var weekdays = new Array(7);
weekdays[0] = "Sunday";
weekdays[1] = "Monday";
weekdays[2] = "Tuesday";
weekdays[3] = "Wednesday";
weekdays[4] = "Thursday";
weekdays[5] = "Friday";
weekdays[6] = "Saturday";
var today = weekdays[d.getDay()];

//
var firstHello = [
  [greatings() + userName + ", How can I help you ?"],
  ["Hi" + userName + " how can I help ?"],
  [greatings() + ", how can I  help?"]
];

//
var noWords = ["?", "!", "?!", "!?", "alex", "alex!", "alex?"];

//
function randomArray(array) {
    var index = Math.floor(Math.random() * array.length);

    return array[index];
  }
  //find index !

function findIndex(array, something) {

  for (var i = 0; i < array.length; i++) {

    if (array[i] === something) {
      return i;
    }

  }


};
/////////////////////////////////////////////////////////
function deleteVals(array, array2) {
    var return_val;
    console.log("starting the function , array,array2 = " + array + "    " + array2);
    if (typeof array == "string") {
      array = array.split(" ");
    }

    if (array[length - 1] === " ") {
      array.splice(length - 1, 1);
    }

    console.log("spilted array, array= " + array);
    for (var i = 0; i < array.length; i++) {
      console.log("We made the for loop with i as variable , i = " + i);

      for (var x = 0; x < array2.length; x++) {
        console.log("We made the second for loop with x as variable" + x);
        console.log("We made the if condation the condtoin is 'array[i] ===     array[x] ,in another way = array[" + i + "] === array[" + x + "] ... in another   way     = " + array[i] + "===" + array2[x])

        if (array[i] === array2[x]) {
          array.splice(i, 1);
          console.log("we deleted array[i] in another way = array[" + i + "]     the result of delere array[i]=" + array[i]);
          console.log("definding return_val as : return_val = array a-way = return_val =" + array)
          return_val = deleteVals(array, noWords);

        } else {
          console.log("starting else atatment ")
          console.log("definding return_val as : return_val = array a-way = return_val =" + array)

          return_val = array;


        }



      }
      console.log("finishing the second for loop");

    }

    console.log("finishing the first for loop");
    console.log("finishing the function deleteVal() ... and it's return :     return_val.join(' ') a-way =" + return_val.join(" "));

    return return_val.join(" ");
  }
  //////////////////////////////////////////////////////////

function getVal() {
    var xxx = document.getElementById("textbox").value;
    var para = document.createElement("p");
    var newLine = document.createTextNode(xxx);
    para.appendChild(newLine);
    para.id = "userText";
    document.getElementById("contText").appendChild(para);
    console.log("newline=" + newLine);
    log("para= " + para);
    xxx = para.innerHTML;
    log("xxx=" + xxx)
    return deleteVals(minimize(xxx), noWords);
  }
  //var ask = prompt ("Ask me anything >>").toLowerCase ();
  //*********Check here

function write(x) {
  var para = document.createElement("P");
  var newLine = document.createTextNode(x);
  para.appendChild(newLine);
  para.id = "compText";
  document.getElementById("contText").appendChild(para);
};

function log(x) {
  console.log(x)
}


//Capitalize the first letter func :
function capitalize(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function minimize(string) {
  return string.toLowerCase();
};

//..............You can ignore all of this

function greatings() {
  var greating;
  if (date >= "06:00:00" && date <= "11:00:00") {
    var x = [
      ["Good morning"],
      ["It' such a great morning ! "],
      ["It's look like a great morning !"],
      ["Morning ! "],
      ["<strong>I remind myself every morning: Nothing I say this day will teach me anything. So if I'm going to learn, I must do it by listening.</strong> "],
      ["I get up in the morning looking for an adventure. "],
      ["If you're changing the world, you're working on important things. You're excited to get up in the morning. "],
      ["SET A GOAL THAT MAKES YOU WANT TO JUMP OUT OF THE BED IN THE MORNING. "],
      ["Sir ,,, you open two gifts this morning ther were your eyes. "],
      ["YOU WILL NEVER HAVE THIS DAY AGAIN , SO MAKE IT COUNT. "],
      ["Each good morning we are born again, what we do today is what matters most "],
      ["TRY TO NOT STOP THIS MORNING "],
      ["Learn somthing new everyday ! that's the rule. "]
    ]

    greating = "Good morning ";
  } else if (date > "11:00:00" && date <= "15:00:00") {
    var x = [
      ["Good afternoon "],
      ["It' such a great afternoon ! "],
      ["It's look like a great afternoon ! "],
      ["Hope you having great day "],
      ["Hope you having great day "],
      ["Hope you having great day "]
    ]

    greating = randomArray(x);

  } else if (date > "15:00:00" && date <= "22:00:00") {
    var x = [
      ["Good evening "],
      ["How such a great evening ! "],
      ["It's look like a great evening ! "],
      ["What a nice night for an evening. "]
    ]
    greating = randomArray(x);
  } else {
    var x = [
      ["You should have some rest !"],
      ["Close your eyes a lil bit !"],
      ["I think you must  sleep now !"],
      ["It's Late for a human !"]
    ];

    greating = randomArray(x);
  };
  return greating;
};

function randomAnswer(array) {


  for (var i = 0; i < array[0].length; i++) {
    if (getVal() === array[0][i]) {
      write((randomArray(array[1])));
    }
  }
};
write(randomArray(firstHello));
//...............................
function dosome() {
  //arrays ^_^

  var hellos = [
    ["hi", "hello", "what's up", "hey", "heyyy", "heyyyy", "hola", "marhaba",
      "hla", "shini aljo", "shini algo"
    ],
    ["Hi" + userName, "Hi there", greatings() + userName]
  ];

  var hows = [
    ["how are you", "what's up", "hows you", "how is you", "how you  doing"],
    ["I'm fine , thanks", "I'm great" + userName + ", thanks",
      "I'm pretty good , thanks you"
    ]
  ]

  var who_are_u = [
    ["who are you", "what are you", "you are ?", "what is you", "what is your name", "what can I call you"],
    ["I'm Alex !", "I'm Alex.", "I am Alex", "My name is Alex"]
  ];

  var what_time = [
    ["what time is it", "what's the time", "guess what time is it", "tell me the time", "the time ?"],
    ["It's :" + date, "I'm pretty sure that the time is :" + date, "The time is :" + date, "I'm sure that it's :" + date]
  ];

  var when_lastModified = [
    ["what time is that i last modified", "when i last modified", "when the last time i visted you", "when last time i opened you"],
    ["That was: " + document.lastModified, "It was: " + document.lastModified, "According to my info , it was: " + document.lastModified,
      "I'm pretty sure it was: " + document.lastModified
    ]
  ];

  var thanks = [
    ["thanks", "thank you", "thank you very much", "thanks a lot", "thank you a lot", "thanks very much"],
    ["No need to thank me" + userName, "That's my work" + userName, "Anytime" + userName, "Welcome !"]
  ];


  //calls ----------->

  randomAnswer(hellos);
  randomAnswer(hows);
  randomAnswer(who_are_u);
  randomAnswer(what_time);
  randomAnswer(when_lastModified);
  randomAnswer(thanks);

  ////

  //
  var spilted_q = getVal().split(" ");
  switch (spilted_q[0]) {
    case "my":
      switch (spilted_q[1]) {
        case "name":
          switch (spilted_q[2]) {
            case "is":
              userName = " " + capitalize(spilted_q[3]) + " ";

              alert("Your name has been saved" + userName)
              write("Hi" + userName)
              break;
          }
          break;
      }
      break;

  }
  return userName
};

function deleteVal() {

  var x = document.getElementById("compText").innerHTML = "";
  var y = document.getElementById("userText").innerHTML = "";
  return x, y;
}
body {
  background-color: #808080;
  font-family: 'Times New Roman', Times, serif;
  color: red;
}
#contText {
  text-align: center;
  border: 3px black solid;
  position: relative;
  left: auto;
  right: auto;
  top: 30px;
  width: 400px;
  height: 300px;
  background-color: white;
}
#allthings {
  text-align: center;
  position: relative;
  top: 50px
}
#compText {
  text-align: left;
}
#userText {
  text-align: right;
}
<div id="contText"></div>
<div id="allthings">
  <input id="textbox" type="text" placeholder="Write your question here..."></input>
  <input id="send" type="button" value="Send" onclick="getVal()"></input>
  <input id="delete" type="button" value="Delete" onclick="deleteVal()"></input>
</div>

New to C++ Looking for help revising a program by using arrays

I'm not expecting anyone to just hand me the answer, but I am looking for some guidance. For my C++ class we wrote a program last week where we had 5 judges each had a score that the user had to put in, then we needed to find the average without the highest and lowest score being used. I did this using loops and a lot of if statements. Now my teacher asked us to go back and use arrays, and said we should be able to just modify the original code a bit, but to now have it so there can be 5 to 20 judges, the user should be able to input that number in. I'm just having a hard time figuring out which spots could be replaced with arrays. I already have it where a person can put in the amount of judges, but I'm not sure how to put that in an array either, so judges is an unused variable at the moment.This is what my code looks like right now. Thanks in advance!

 #include <iostream>

using namespace std;

//Function prototypes

void getJudgeData(double &x);

double findLowest(double ,double ,double ,double,double);

double findHighest(double,double,double,double,double);

void calcAverage(double,double,double,double,double);

double judges;
//Program begins with a main function

int main()

{

//Declare variables

double judgeScore1,judgeScore2,judgeScore3;

double judgeScore4,judgeScore5;

cout<<"Scores given by all five judges: \n\n";

//Function calls to get each judge data
cout<< "How many Judges are there? (Must be 5 to 20): ";
cin>> judges;
while(judges<5||judges>20){
    cout<< "Sorry there must be 5 to 20 judges\n";
    cout<< "How many Judges are there? (Must be 5 to 20): ";
    cin>> judges;

getJudgeData(judgeScore1);

getJudgeData(judgeScore2);

getJudgeData(judgeScore3);

getJudgeData(judgeScore4);

getJudgeData(judgeScore5);

//Function call to obtain average

calcAverage(judgeScore1,judgeScore2,judgeScore3,

judgeScore4,judgeScore5);

//Pause the system for a while



}
}
//Method definition of getJudgeData

void getJudgeData(double &x)

{

//Prompt and read the input from the user and check //input validation

cout<<"Enter score of a Judge (you will do this 5 times): ";

cin>>x;

while (x < 0 || x > 10)

{

cout<<"ERROR: Do not take judge scores lower than 0 or higher than 10.Re-enter again: ";

cin>>x;

}

}

//Method definition of findLowest

double findLowest(double a,double b,double c,

double d,double e)

{

double lowest;

lowest=a;

if (b<lowest)

lowest=b;

if (c<lowest)

lowest=c;

if (d<lowest)

lowest=d;

if (e<lowest)

lowest=e;

return lowest;

}


//Method definition of findHighest

double findHighest(double a,double b,double c,

double d,double e)

{

double highest;

highest=a;

if (b>highest)

highest=b;

if (c>highest)

highest=c;

if (d>highest)

highest=d;

if (e>highest)

highest=e;

return highest;

}




void calcAverage(double a,double b,double c,double d,

double e)

{

//Declare variables

double lowest;

double highest;

double sum;

double average;

//Function call to retrieve lowest score

lowest=findLowest(a,b,c,d,e);

//Function call to retrieve highest score

highest=findHighest(a,b,c,d,e);

//Calculate the total sum

sum=a+b+c+d+e;

//Subtract highest and lowest scores from the total

sum=sum-highest;

sum=sum-lowest;

//Calculate the average of the three number after

//dropping the highest and lowest scores

average=sum/3;

//Display output

cout<<"Highest score of five numbers:"<<highest<<endl;

cout<<"Lowest score of five numbers:"<<lowest<<endl;

cout<<"Average when highest and lowest scores are removed: "<<average<<endl;

}

How do I write a code that says: "if I can do this, do this. Otherwise do nothing", in Python 2.7?

How do I write a code that says: "if I can do this, do this. Otherwise do nothing", in Python 2.7?

I added the code that is not working below.

words = ["glad", "lycklig", "fin", "vacker", "sot", "blomming"]

word_index = words.index("sot")
focus_word = words[word_index]
tre = words[word_index+1]
if words[word_index+2] == True:
    fyra = words[word_index+2]
else:
print "the list is not long enough"

So I want to get the word that is two words after "sot" if there is one. In this case there isn't, and then I just want to skip that command.

if conditions on datetime - Pyhton [duplicate]

This question already has an answer here:

I'm trying to run some code at certain times of the day, I understand datetime is an object, new to python and don't understand why working with dates have to be such a pain.

t = time.strftime("%H%M")
print(t) # this displays 1809

if 2359 > t > 900:
    # if condition not meet

However when I set t as an int my if condition is meet. I did see a couple of solutions on here but none seemed to actually work.

The following code using str() seems to work but I would think there is a better way to do this

t = str(time.strftime("%H%M"))
print(t) # this displays 1809

if "2359" > t > "0900":
    # if condition not meet

Excel: 3 Conditions Issue

Below is an excel formula i created that will result in either of the following:

Weekend, Week Night, or Week Day

If Saturday or Sunday shows in column AL my result is 'Weekend'. If result falls on a Week day (Monday-Friday) between hours of 12a-7:59p the result will be 'Week Day'; and 'Week Night' as my false value.

Below is my fomula:

=IF(OR(AL2="Saturday",AL2="Sunday"),"Weekend",IF(AND(AL2="Monday",AL2="Tuesday",AL2="Wednesday",AL2="Thursday",AL2="Friday",D2>TIME(12,0,0),D2

The Weekend part of the formula works; but all my others result in Week Night

Please help!

Python IF condition with multiple variables

Could someone clarify this. What happens if I try to write this code:

if tomato = 1 or tomato = 2 or tomato = 3

... like this:

if tomato = 1 or 2 or 3 

I know Python doesn't consider it the same but what does it think I'm doing?

Most importantly, what's the best way to do this if I have a whole bunch of conditions for tomato. Writing "tomato =" each time doesn't seem very neat. Thank you

c++ if statements always return true

I have a bunch of maths manipulations that have thresholds, yet no matter what I change, the if statements always return true. No compile errors, can't get the debugger to work. This is a function, the X Y and Z arrays are all correct (I printed them to check earlier), the maths is right at least for the blade distance check, yet that always returns true. I ran the same code (rewritten obviously) through matlab and that returns true or false depending on my data, so clearly its something with the way I've written this that's wrong. Also is there any way to slimline this?

bool Device::_SafeD(char _Type, float _Data[20][3]) {
bool S;
double x[20], y[20], z[20];
for (int i=0; i<20; i++){
    x[i] = _Data[i][0];
    y[i] = _Data[i][1];
    z[i] = _Data[i][2];

}

// Check angles for needle
if (_Type == 'n'){
    for (int i=0; i<20; i++) {
        float dot, moda, modb, c, angle;
        dot = ((x[i]*x[i+1]) + (y[i]*y[i+1]) + (z[i]*z[i+1]));
        moda = sqrt(pow(x[i],2)+pow(y[i],2)+pow(z[i],2));
        modb = sqrt(pow(x[i+1],2)+(y[i+1],2)+(z[i+1],2));
        c = dot/(moda*modb);
        angle = acos(c);

        if (angle > 45){
          S = 0;}
        else {
          S = 1;
        }
      }

}

// Check distance for blade
if (_Type == 'b'){
      for (int i=0; i<19; i++) {

          float distance = (x[i+1]-x[i]) + (y[i+1]-y[i]) + (z[i+1]-z[i]);
          cout << "distance " << distance << endl;


        if (distance > 5.0) {
          S  = 0;}

        else {
          S =  1;
        }
      }
}
if (S==0){
    return 0;
}
if(S==1){
    return 1;
}

}

Cheers

Excel, more efficient formula for multiple IF ANDS

I have a spreadsheet that I am making that looks as follows:

Index   Diff    Exc    Sym      Sec    Result   Criteria Met

3.42    -2.07   0.86    0.92    1.83    1.95    
-0.38   -2.93   0.87    0.23    -2.01   0.09    
-2.67   -1.84   0.87    -2.49   -3.48   1.32    
-0.65   -0.98   0.46    0.98    -2.01   0.00    
-0.73   -2.79   -1.07   -2.15   -1.44   -0.10   
0.15    2.33    -0.46   -0.66   3.17    0.38    0.38
0.90    -3.68   -0.72   -1.01   -1.36   1.69    
0.68    -1.12   -0.36   0.73    -1.34   -0.29   
-1.19   -1.70   -0.56   -1.31   1.45    0.49    
-0.45   -0.69   -0.56   -1.22   0.00    -0.49   
2.94    8.38    2.21    6.25    4.96    1.74    
-1.04   7.36    2.59    3.00    2.17    2.97    
1.21    1.73    3.05    1.48    3.56    0.77    
-1.10   1.86    0.60    1.18    1.07    -0.49   
-0.89   -3.19   -1.78   -2.24   -4.26   -0.81   
-1.17   -3.44   0.11    -1.22   3.66    0.36    
0.52    0.92    -1.02   0.38    1.96    -1.40   -1.40
-0.90   3.01    -0.86   0.62    0.97    -0.50   -0.50
2.78    1.46    0.00    0.47    1.95    0.84    

        Max     Min             
Index    2.00   -2.00               
Diff    10.00   0.00                
Exc      0.00   -10.00              
Sym     10.00   -10.00              
Sec     20.00   0.00    

Under the headings Index, Diff, Exc, Sym, Sec, Result is all data, In the criteria met column i have a formula that checks if the prior headings fall within the Max and Min limits of the smaller table underneath, and if they do it posts the result, if they dont all fall within the Max and Min boundaries it leaves it blank. I did that by using this formula:

=IF(AND(A3<$B$24,A3>$C$24,B3<$B$25,B3>$C$25,C3<$B$26,C3>$C$26,D3<$B$27,D3>$C$27,E3<$B$28,E3>$C$28),F3,"")

copied down the criteria met column. It works perfectly fine for what I want it to achieve but as this spreadsheet grows and I add more columns it seems like it will be incredibly inefficient and prone to alot of human error. Is there a way to achieve the same results but by using a more efficient formula?

a picture for reference as well: enter image description here

two connected comboboxes are not working

I have two comboboxes. When I change value of category combobox, it should automatically change value of size combobox.

private void New_Item_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'pitauzDBDataSet.Item' table. You can move, or remove it, as needed.
    this.itemTableAdapter.Fill(this.pitauzDBDataSet.Item);

    cbx_product_category.Items.Add("Pita");
    cbx_product_category.Items.Add("Drinks");
    cbx_product_category.Items.Add("Other Foods");
}

private void cbx_product_category_SelectedIndexChanged(object sender, EventArgs e)
{
    string ItemSelected = cbx_product_category.SelectedIndex.ToString();
    if(ItemSelected == "Pita")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("Small");
        cbx_product_size.Items.Add("Regular");
        cbx_product_size.Items.Add("Large");
        cbx_product_size.Items.Add("Very-Large");
    }
    if(ItemSelected == "Drinks")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("0.5L");
        cbx_product_size.Items.Add("1L");
        cbx_product_size.Items.Add("1.5L");
    }
    if (ItemSelected == "Other Foods")
    {
        cbx_product_size.Items.Clear();
        cbx_product_size.Items.Add("Half");
        cbx_product_size.Items.Add("Full");
    }
}

It is not giving any error. Just logic not working.

Random value witout if?

Random rd = new Random();
int question;
question = rd.Next(1,2);
if(question ==1)
{
label1.Text = "What is your name?";
}
if(question ==2)
{
label1.Text = "How old are you?";
}

Is there a way how to make it shorter? I need to do it this way, but find the shorter option, preferably witout if.

If statements not working properly

Ok so what I wasn't to do is loop the program using a while loop. The user will select stock e.g. Sony enter whether he/she wants to buy or sell shares and then enter the quantity. They will be redirected back to the button until he/she clicks on print total to view the cost of all shares. What I want to do is set an overall price using if statements, but if the user does not go over one of the if statements e.g. does not buy Apple then an nullpointerexception is thrown, help me, how do I fix my if statements. The method where the If statements go is called setOverallTotal()

public class RunProject extends JPanel{

JTable jt;
int option;
private double overall=0;
private double fullApple;
private double fullSony;
private double fullFacebook;
private double fullNokia;
Account account = new Account("","");
Apple apple = new Apple ("",0,"");
Sony sony = new Sony ("",0,"");
Facebook facebook = new Facebook ("",0,"");
Nokia nokia = new Nokia ("",0,"");
NumberFormat money = NumberFormat.getCurrencyInstance();

public RunProject (){

    apple.setPrice();
    sony.setPrice();
    facebook.setPrice();
    nokia.setPrice();

    String [] columns = {"Stock Name","Stock Founded", "Stock Status", "Stock Price(atm)" };
    String [][]data = {{apple.getStockName(),"Started April 1st, 1976",apple.getStockStatus(),String.valueOf(money.format(apple.getPrice()))+" from £74.75"},
        {sony.getStockName(), "Started 7th May, 1946", sony.getStockStatus(),String.valueOf(money.format(sony.getPrice()))+" from £18.17"},
        {facebook.getStockName(), "Started 4th February, 2004", facebook.getStockStatus(),String.valueOf(money.format(facebook.getPrice()))+" from £80.60"},
    {nokia.getStockName(),"Started 1st January, 1865", nokia.getStockStatus(),String.valueOf(money.format(nokia.getPrice()))+" from £4.18"}};

    jt = new JTable(data,columns);
    jt.setPreferredScrollableViewportSize(new Dimension(550,80));
    jt.setFillsViewportHeight(true);

    JFrame jf = new JFrame();
    jf.setTitle("Alireza Shahali's Stock Market");
    jf.setSize(900, 200);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.add(jt);

    account.setFirstName();
    account.setSurname();
    account.setAccountNumber();
    JOptionPane.showMessageDialog(null,"YOUR ACCOUNT DETAILS\n\nFirst Name: "+account.getFirstName()+"\nSurname: "+account.getSurname()+
    "\nAccount Number: "+account.getAccountNumber());

    do{
        ArrayList<String> buttonChoice = new ArrayList<String>();
        buttonChoice.add("Apple");
        buttonChoice.add("Sony");
        buttonChoice.add("Facebook");
        buttonChoice.add("Nokia");
        buttonChoice.add("Print Total");
        buttonChoice.add("Exit");
        // making an arraylist of strings called buttonChoice

        Object [] options = buttonChoice.toArray();
        // turning the arraylist to standard array and saving it in Object array called options

        option = JOptionPane.showOptionDialog(null, "Select a Stock. Click on Print Total to display cost of selected Shares.", "Alireza's Stock Market",
        JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE, null, options,buttonChoice.get(0));

        setOverallTotal();

        switch(option){
            case 0:
                apple.setBuyingOrSelling();
                apple.shares();
                break;

            case 1:
                sony.setBuyingOrSelling();
                sony.shares();
                break;

            case 2:
                facebook.setBuyingOrSelling();
                facebook.shares();
                break;

            case 3:
                nokia.setBuyingOrSelling();
                nokia.shares();
                break;

            case 4:
                fullApple = apple.getPrice() * apple.getShares();
                fullSony = sony.getPrice() * sony.getShares();
                fullNokia = nokia.getPrice() * nokia.getShares();
                fullFacebook = facebook.getPrice() * facebook.getShares();

                JOptionPane.showMessageDialog(null, apple.getStockName()+"\nStock ID: "+apple.getStockID()+"\n"+apple.getStockDescription()+
                "\n\nYou would like to: "+apple.getBuyingOrSelling() + "\n" +apple.getShares()+ " shares.\nStock is currently: "+apple.getStockStatus()
                +"\nCost of each Share: "+money.format(apple.getPrice())+"\nTotal: " + money.format(fullApple)+"\n-------------------------------------------------------"
                + "\n"+sony.getStockName()+"\nStock ID: "+sony.getStockID()+"\n"+sony.getStockDescription()+
                "\n\nYou would like to: "+sony.getBuyingOrSelling() + "\n" +sony.getShares()+ " shares.\nStock is currently: "+sony.getStockStatus()
                +"\nCost of each Share: "+money.format(sony.getPrice())+"\nTotal: " + money.format(fullSony)+"\n-------------------------------------------------------"
                + "\n"+facebook.getStockName()+"\nStock ID: "+facebook.getStockID()+"\n"+facebook.getStockDescription()+
                "\n\nYou would like to: "+facebook.getBuyingOrSelling() + "\n" +facebook.getShares()+ " shares.\nStock is currently: "+facebook.getStockStatus()
                +"\nCost of each Share: "+money.format(facebook.getPrice())+"\nTotal: " + money.format(fullFacebook)+"\n-------------------------------------------------------"
                + "\n"+nokia.getStockName()+"\nStock ID: "+nokia.getStockID()+"\n"+nokia.getStockDescription()+
                "\n\nYou would like to: "+nokia.getBuyingOrSelling() + "\n" +nokia.getShares()+ " shares.\nStock is currently: "+nokia.getStockStatus()
                +"\nCost of each Share: "+money.format(nokia.getPrice())+"\nTotal: " + money.format(fullNokia)+"\n-------------------------------------------------------"
                + "\nAccount Holder: "+account.getFirstName()+" "+account.getSurname()+ "//Account Number: " + account.getAccountNumber()
                +" //Account changes: "+money.format(getOverallTotal()));
                break;

            case 5:
                System.exit(0);
        }
    }while(option!=5);

}

public void setOverallTotal(){
    if (apple.getBuyingOrSelling().equals("BUY")){
        overall -= fullApple;
    }
    else if(apple.getBuyingOrSelling().equals("SELL")){          
        overall+= fullApple;
    } 
}

public double getOverallTotal (){
    return overall;
}

Java - Need to fix a simple algorithm

This method test if the string 'chaine' contain only (ABCDE... abcd...) or only number ('0' a '9'). OR can contain caracther that are in the string 'plus'

If the string chaine is empty or null it return false. If the string plus is empty or null it doesnt a matter.

@param chaine
@param plus
@return True if the string chaine contain only letter or number OR a caracther in the string plus

Expected EXAMPLE:

param : chaine = null,                plus = null         return false  Iget: false
param : chaine = null,                plus = ""           return false  Iget: false
param : chaine = null,                plus = "?%t64*"     return false  Iget: false
param : chaine = "",                  plus = null         return false  Iget: false
param : chaine = "",                  plus = ""           return false  Iget: false
param : chaine = "",                  plus = "?%t64*"     return false  Iget: false
param : chaine = "aBNghy",            plus = "?%t64*"     return true   Iget: false
param : chaine = "897654999",         plus = "?%t64*"     return true   Iget: false
param : chaine = "1abb876BR",         plus = "?%t64*"     return true   Iget: false
param : chaine = "1aB&b876(B)R",      plus = "?%t64*"     return false   Iget: false 
param : chaine = "1aB?b876(B**R%",    plus = "?%t64*"     return false   Iget: true
param : chaine = "1aB?b876B**R%",     plus = "?%t64*"     return true    Iget: true
param : chaine = "?**?",              plus = "?%t64*"     return true    Iget: true
param : chaine = "?*",                plus = ""           return false   Iget: false
param : chaine = "aBcD12Ef8",         plus = ""           return true   Iget: true
param : chaine = "98003119",          plus = ""           return true   Iget: true
param : chaine = "aBcdefG",           plus = null.        return true   Iget: true


 NOTE:
 *    - This method MUST use these method: 
 *          - estUneLettre(...) (isALetter)
 *          - estUnCarNum(...)  (isANumber)

public static boolean estUneLettre (char car) {
    return (car >= 'a' && car <= 'z') || (car >= 'A' && car <= 'Z');
}
public static boolean estUnCarNum (char car) {
    return (car >= '0' && car <= '9');
}     

My code that I need to fix:

    public static boolean estAlphaNumPlus (String chaine, String plus) {

    boolean chainePlus = false;
    String chaineNew;

    if (chaine == null || chaine.isEmpty()) {
        chainePlus = false;

    } else if (plus == null || plus.isEmpty()) { 

        for (int i = 0 ; i < chaine.length(); i++) {
            if (estUneLettre (chaine.charAt(i)) || estUnCarNum (chaine.charAt(i))) {
                chainePlus = true;

            }
        }

    } else {
        for (int j = 0 ; j < plus.length(); j++) {
            if (!estUnCarNum(plus.charAt(j)) && !estUneLettre(plus.charAt(j))) {
                chaineNew = plus.charAt(j) + "";

                if (chaine.contains (chaineNew)) {
                    chainePlus = true;

                }
                chaineNew = "";
            }
        }
    }

    return chainePlus; 
}

Converting Check Amount to Words , working code need modification

Hello This code was given to us in class, and I don't quite understand it and I currently cant see my professor before my assignment is due.

I need to expand this code to convert up to $1,000,000 Not the intended $99.99

Any help that you guys can offer would be very helpful.

the code is in c

#include<stdio.h>

int main(void)
{
    char *digits[ 10 ] = {"", "ONE", "TWO", "THREE", "FOUR",
        "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};
    char *teens[ 10 ] = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN",
        "FOURTEEN", "FIFTEEN", "SIXTEEN",
        "SEVENTEEN", "EIGHTEEN", "NINETEEN"};
    char *tens[ 10 ] = {"", "TEN", "TWENTY", "THIRTY", "FORTY",
        "FIFTY", "SIXTY", "SEVENTY", "EIGHTY",
        "NINETY"};

    int dollars;
    int cents;
    int digit1;
    int digit2;

    printf("%s", "Enter the check amount ( 0.00 to 99.99 ): ");
    scanf("%d%d", &dollars, &cents);
    puts("\nThe check amount in words is:" );

    if ( dollars < 10 ){
        printf("%s ", digits[ dollars ]);
    }
    else if ( dollars < 20 ){
        printf("%s ", teens[dollars - 10]);
    }
    else {
        digit1 = dollars / 10;
        digit2 = dollars % 10;

        if ( 0 == digit2 ){
            printf("%s ", tens[digit1]);
        }
        else {
            printf("%s-%s ", tens[digit1], digits[digit2]);
        }
    }

    printf("and %d / 100\n", cents);
}

Comparing ConsoleKey variable type

this is my code. Basically it gives a compiler error

teclaPulsada=Console.ReadKey(true);

        if (teclaPulsada.Key=ConsoleKey.Q | teclaPulsada.Key=ConsoleKey.A | teclaPulsada.Key=ConsoleKey.Z)
        {
            //I do something
        }

Then another question, I have this code, that it seems to be equal to the previous one, but this also uses ConsoleKey and int

if ((teclaPulsada.Key=ConsoleKey.Q & Pregunta.retornarPosicioRespostaCorrecta()==0) | (teclaPulsada.Key=ConsoleKey.A & Pregunta.retornarPosicioRespostaCorrecta()==1) || (teclaPulsada=ConsoleKey.Z & Pregunta.retornarPosicioRespostaCorrecta()==2))
{
        //I do something
}

In both cases I have tried diffrent systems, like using && or & and || or |. I have also tried using .key. But I'm stucked.

Thanks

shorthand "||" in if statements

In GML: If I have the following if statement:

if (x == y || x == z) {//commands};

Can I type this in the shorter form of:

if (x == y || z) {//commands};

And achieve the same result? All three variable (x, y, and z) are real numbers.

How to compare timespan before and after?

I wanted to compare a timespan before and after 3 hours. For example, a cinema halls, I wanted to check the hall on the specific date is the hours chosen can fit into it. If that day has movie on that hall, then the hours can only be 3 hours before or 3 hours after the movie.

I know that timespan can add but I can't think of a way to actually do the algorithm.Here's the part of the code I'm trying to figure out TimeSpan.Parse(cbxTime.Text) part what should be added

  If hall1.Checked = True Then
                For Each g In db.Shows

                    If g.hallId = "H1" Then
                        If g.showDate = CDate(dtpDate.Text) Then
                            If g.showTime > TimeSpan.Parse(cbxTime.Text) 3 hours OR < TimeSpan.Parse(cbxTime.Text)3 hours   Then
                                Can proceed to Adding Show Time
                            End If
                        End If
                    End If
                Next
                a.hallId = "H1"

Any help will be much appreciated.

How can I do select case to this query?

SQL FIDDLE DEMO HERE

I have this structure of tables:

    CREATE TABLE Users

            ([UserId] int, 
            [IdDepartment] int);

    INSERT INTO Users
        ([UserId], [IdDepartment])
    VALUES
        (1, 5),
        (2, 0),
        (3, -1),
        (4, 0),
        (5, -1),
        (6, 0);

    CREATE TABLE Department
        ([IdDepartment] int, [Name] varchar(23), [IdUser] int);

    INSERT INTO Department
        ([IdDepartment], [Name], [IdUser])
    VALUES
        (1, 'Sales', 3),
        (2, 'Finance', null ),
        (3, 'Accounting' , 5),
        (4, 'IT' ,3),
        (5, 'Secretary',null),
        (6, 'Sport',3);

I want to get a query with this results: In the Users table if the IdDepartment is 0 ist means that the user is an admin so he can see all the departments. If the user has a -1 in the idpartment it means that the user can access to limited departments, so in this case I do a inner join to the Department table to get the list of this departments. The last case is if the user has a number for the idDepartament in the user table diferent to 0 and diferent to -1 it means that the user can access only to this department.

I tried to do something like that, but it is not well structured:

select
    case idDepartment
       when  0 then (select Name from Department)
       when -1 then (select Name from Department where IdUser = 3)
       else         (select Name from Department 
                      inner join Users on Department.idDepartment = Users.Department         
                      where Users.UserId = 3)
    end
from 
    Department
where 
    IdUser = 3

How can I do this? thanks.

I add an example for what I want to get:

 -For the user that has the userid (1) -->

    Department Name
    ---------------
    Secretary




-For the user that has the userid (2) -->

    Department Name
    ---------------
    Sales
    Finance
    Accounting
    IT
    Secretary
    Sport




-For the user that has the userid (3) -->

    Department Name
    ---------------
    Sales
    IT

I would like to know what's wrong with this code

I want to use if statement for a multiple choice with string variable... However, I can't input an answer or letter of my choice and it just immediately outputs "Input Error" even though I haven't input anything yet... Can I ask what's wrong with this code?

    System.out.println("Pick your choice: \na. Add Node\nb. Delete Node\nc. Insert Node");
    String letterChoice = scan.nextLine();

    if(letterChoice.equalsIgnoreCase("A")){
        System.out.println("Enter node value: ");
        int nodeValue = scan.nextInt();
        list.addNodes(nodeValue);
    }
    else if(letterChoice.equalsIgnoreCase("B")){
        System.out.println("Which node to delete? Node #: ");
        int thisNode = scan.nextInt();
        list.deleteNode(thisNode);
    }
    else if(letterChoice.equalsIgnoreCase("C")){
        System.out.println("Input node number: ");
        int thisNode = scan.nextInt();
        int prevNode = thisNode - 1;

        System.out.println("Input node value: ");
        int nodeValue = scan.nextInt();

        list.insertNode(nodeValue, prevNode);
    }
    else{
        System.out.println("Input Error");
    }

I couldn't find help from previous questions here unless I change my code... I don't want to, so I had to ask... Thanks...

Full Code...

    import java.util.*;

    public class DoublyLinkedList {


        static DNode root;
        static DNode temp;
        static DNode current;


        public void addNodes(int data){

            DNode dNode = new DNode(data);

            if(root==null){

                root = dNode;
                root.previousNode = null;
                root.nextNode = null;

            }else{

                current = root;

                while(current.nextNode!=null){

                    current = current.nextNode;

                }

                current.nextNode = dNode;
                dNode.previousNode = current;
                dNode.nextNode = null;

            }

        }

        public void insertNode(int data, int after){

            DNode dNode = new DNode(data);

            int ithNode = 1;

            current = root;

            while(ithNode != after){

                current = current.nextNode;

                ithNode++;

            }

            temp = current.nextNode;

            current.nextNode = dNode;
            dNode.nextNode = temp;
            temp.previousNode = dNode;
            dNode.previousNode = current;

        }

        public void deleteNode(int nodeNumber){

            int ithNode = 1;

            current = root;

            if(nodeNumber==1){

                root = current.nextNode;
                current.nextNode = null;
                current.previousNode = null;

            }else{

                while(ithNode != nodeNumber){

                    current = current.nextNode;

                    ithNode++;

                }

                if(current.nextNode == null){

                    current.previousNode.nextNode = null;
                    current.previousNode = null;

                }else{

                    current.previousNode.nextNode = current.nextNode;
                    current.nextNode.previousNode = current.previousNode;

                }

            }

        }

        public void print(){

            current = root;

            System.out.print("The Linked List: ");

            do{

                System.out.print(" " + current.data + " ");


                current = current.nextNode;

            }while(current!=null);

        }

        public void printBackwards(){

            current = root;

            while(current.nextNode!=null){

                current = current.nextNode;

            }

            System.out.print("Inverse: ");

            do{

                System.out.print(" " + current.data + " ");

                current = current.previousNode;

            }while(current.previousNode!=null);

            System.out.print(" " + current.data + " " );

        }

        public static void main(String[] args){

            DoublyLinkedList list = new DoublyLinkedList();
            Scanner scan = new Scanner(System.in);

            String letterChoice = "";
            int nodesNum;

            System.out.print("Input number of nodes: ");
            nodesNum = scan.nextInt();

            for(int x = 1; x <= nodesNum; x++){
                System.out.print("Input value of node #" + x + ": ");
                int value = scan.nextInt(); 
                list.addNodes(value);
            }

            list.print();


            System.out.println("Pick your choice: \na. Add Node\nb. Delete Node\nc. Insert Node");
            letterChoice = scan.nextLine();

            if(letterChoice.equalsIgnoreCase("A.")){
                System.out.println("Enter node value: ");
                int nodeValue = scan.nextInt();
                list.addNodes(nodeValue);
            }
            else if(letterChoice.equalsIgnoreCase("B.")){
                System.out.println("Which node to delete? Node #: ");
                int thisNode = scan.nextInt();
                list.deleteNode(thisNode);
            }
            else if(letterChoice.equalsIgnoreCase("C.")){
                System.out.println("Input node number: ");
                int thisNode = scan.nextInt();
                int prevNode = thisNode - 1;

                System.out.println("Input node value: ");
                int nodeValue = scan.nextInt();

                list.insertNode(nodeValue, prevNode);
            }
            else{
                System.out.println("Input Error");
            }

            list.print();
            System.out.println();
            list.printBackwards();

            System.out.println();
            System.out.println("The number of DNodes in the Linked List is " + DNode.noOfLinkedList);


        }

    }


     class DNode {

        static int noOfLinkedList = 0;

        int data;

        DNode previousNode;
        DNode nextNode;

        DNode(int data){

            this.data = data;
            noOfLinkedList++;

        }

    }

Excel if then statement

I have a long list of points on a spreadsheet. I need a cell to say the point (m1-1), (m1-2) and so on. And I don't need it to say m 1 minus 1. I need it m1 dash 1. That is the point type. I want it to where I can just type the number 1 or 2 or 3 and m1-1, m1-2, m1-3 will appear in that cell. Is this possible?

Thanks!

php link between td if file exists

i am trying add a link to my search results but i want that to check if the file exists before adding the link i want that to be something like that.

 echo'<tr>
<td style=font-family:Gadugi;font-size:16px; width:50px; align:"left";>'.$result["BASECODE"].'

<?php
if (file_exists("images/'.$result["BASECODE"].'.png")) 
{
echo "<a href="images/'.$result["BASECODE"].'.png">img</a>";
}
?>
</td>

<td style=font-family:Gadugi;font-size:16px; width:50px;align:"left";>'.$result["KNITTYPE"].'</td>
<td style=font-family:Gadugi;font-size:16px; width:250px;align:"left";>'.$result["COMPOSITION"].'</td>
<td style=font-family:Gadugi;font-size:16px; width:100px;align:"left";>'.$result['REALWEIGHT'].'</td>
<td style=font-family:Gadugi;font-size:16px; width:100px;align:"left";>'.$result["REALWIDTH"].'</td></tr>';

Excel offset with if formula

I have been scratching my head trying to work this out, I would be grateful if you can help. The formula below offsets 3 places when it finds “Earnings for Period”. However if that cell is enter or zero “0”, I want it to offset 4 places. Any suggestions?

=OFFSET(INDEX($C$2:$C$100,MATCH("Earnings for Period",$C$2:$C$100,0),1),0,3)

PHP: IF() Equal TO Not working

if($_SESSION['auth'] != 2 || $_SESSION['auth'] != 3){
    header("location:../login/login.php");
}

what am i doing wrong, it keeps sending me back,

its only when session is 1 or not set, it should run the header()

Is it possible to use die/echo etc without {?

So, Well I was wondering, Is it possible to do this;

if($pro == true)
    echo "He's";
    echo "a";
    echo "pro.";

Or do I need to use { } ? Thanks.

IF(VLOOKUP) vs INDEX(MATCH) to find values based on multiple criteria

I'm trying to perfect one, but so far both formulas do not return what i'm after. I am trying to create a formula to return a cell in column FHE!E:E such that FHE!C:C matches DS!C5 and DS!G5="text".

I have tried 2 methods, IF(VLOOKUP):

=IF(DS!G5="text",VLOOKUP(DS!C5,FHE!A:Z,5),"")

This produces the same number (-81) for all cells where DS!G5="text" but -81 is not the value it should bring back from FHE!E:E

Also INDEX(MATCH):

=INDEX(FHE!E:E,MATCH(DS!C5 & DS!G5,FHE!C:C & "text"))

This just produces #VALUE

Any help on where I might be going wrong would be greatly appreciated

if statement when so much is loaded, it begins a new row

So I need to make an if statement that, whenever id 0 to 3 (4 images) are loaded, make a new row of 0 to 3 images, this same do i need to do with words (probably works the same)

I'm quite new with if statements etc. I just don't know where to start with this.. The images and words load from a JSON file, and I already have the first bit of codes.

Like the var html = '<div class="row">'; to the html += '</div>'; I need an if statement to let the images load in a row of 4 images/words nexto eachother. And then make a new row, automaticly.

I guess it sounds complicated.. I hope someone can help me.

JSON,

{"main_object": {
    "imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
    "wordsJ": ["næb", "kat", "æg", "mel", "mælk", "pas", "ske", "te"]
}
}

var jsonData = "noJson";
var hr = new XMLHttpRequest();

$(document).ready(function(){
var jsonData = 'empty';
  $.ajax({
    async: false,
    url: "./js/data.json",
    dataType: 'html',
      success: function(response){
        jsonData = JSON.parse(response);

        console.log('ok');
          var imagesJ = jsonData.main_object.imagesJ;
          var wordsJ = jsonData.main_object.wordsJ;
          var html = '<div class="row">';
          var html2 = '';

          for(i = 0; i < imagesJ.length; i++) {
//html += '</div><div class="row">';
//if statement that whenthere are 0-3 = 4 pictures it begins a new block of code wich makes 0-3 = 4 pictures, that are in bootstrap row PROBEER DIT ALLEEN MET STACKOVERFLOW OF ANDERE INTERNET DINGEN
            html += '<div class="col-md-2"><img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'"></div>';
          }
          html += '</div>';

          document.getElementById('images').innerHTML = html;

          for (i = 0; i < wordsJ.length; i++) {
            html2 += '<p>'+wordsJ[i]+'</p>';
          }
          document.getElementById('words').innerHTML = html2;

      },
      error: function(){
        console.log('JSON could not be loaded.');
      }
    });

        console.log(jsonData);

});
header {
  position: relative;
  height: 20%;
  /*border-bottom: thick solid grey;*/
}

body {
  background-color: #f0f0f0;
}
.container {
  position: relative;
  height: 50%;
}
.images img {
  position: relative;
  height: 100px;
  width: 100px;
}
#img4, #img5, #img6, #img7 {
  top: 5%;
}

footer {
  position: relative;
  height: 5%;
  /*border-top: thick solid grey;*/
}
<!DOCTYPE html>
<html>
<head>
  <title>Sleepopdracht</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="http://ift.tt/1JetChn">
      <script src="http://ift.tt/1ROJ5xx"></script>
      <script src="http://ift.tt/1RY4jZJ"></script>
      <link rel="stylesheet" href="http://ift.tt/1iJFeCG">
      <link rel="stylesheet" href="css/css.css">
</head>
<body>
  <header>

  </header>

    <div class="container" id="container">
      <div class="row">
        <div class="col-md-2">
          <img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">
        </div>
        <div class="col-md-2">
          a
        </div>
        <div class="col-md-2">
          a
        </div>
        <div class="col-md-2">
          a
        </div>
      </div>
      <div class="row">
        <div class="col-md-2">
          a
        </div>
        <div class="col-md-2">
          a
        </div>
        <div class="col-md-2">
          a
        </div>
        <div class="col-md-2">
          a
        </div>
      </div>
      <div class="images" id="images"></div>
                                          <div class="words" id="words"></div>
    </div>


  <footer>
  </footer>
    <script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>

As you can see in HTML I have made those rows, they need to become one and loop themselfes a little like <div class="col-md-2"> <img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'"> </div>

This is my result right now.

And this is what it needs to resemble closely.

Improve condition code

I've the following code

var oDataEn = aData[0][aProperties[0].split('/')[0]];
if (!(oDataEn != null && oDataEn.results && oDataEn.results.length > 0)) {
    ...
    else

...

This is working OK except when

aData[0] = 'undfiend'

my question is if there a better way to write it instead of just adding before

 if(aData[0] != null)
  {
    var oDataEn = aData[0][aProperties[0].split('/')[0]];
  }

mardi 29 mars 2016

JavaScript Beginner Syntax Errors

I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)

function main(){
alert("Welcome to the program");
 var fatGrams;
 var calories;
 var percentage;
 function getFatGrams(fatGrams);
 function getCalories(calories);
 function caloriesPercentage; 
 function displayPercentage(percentage); 
}

function getFatGrams(fatGrams){ 
prompt("Enter the number of fat grams in your food item");
while fatGrams < 0{
  alert("Error, the fat grams cannot be less than 0.");
  prompt("Enter the new number of fat grams.");
}
return fatGrams
}

function getCalories(fatGrams,calories,getFatGrams){
prompt("Enter the number of calories in your food item.");
 while calories < 9 OR calories > fatGrams * 9{
  alert("Error, the calories cannot be less than 9 or exceed the fat    grams * 9");
 prompt("Enter the new number of calories");
}
return calories;
}

function caloriesPercentage(fatGrams,calories){

set percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " percentage);
return percentage;
}

function displayPercentage(percentage){
if percentage < 0.3 then {
 alert("The food is low in fat.");
 else
end if 
}
}
main(); 
alert("End of program"); 

Python IF multiple "and" "or" in one statement

I am just wondering if this following if statement works:

    value=[1,2,3,4,5,f]
    target = [1,2,3,4,5,6,f]
    if value[0] in target OR value[1] in target AND value[6] in target:
       print ("good")

My goal is to make sure the following 2 requirements are all met at the same time: 1. value[6] must be in target 2. either value[0] or value[1] in target Apologize if I made a bad example but my question is that if I could make three AND & OR in one statement? Many thanks!

How do I use switch statements inside if else statements

I'm trying to write a program that can decide what mechanism a organic reaction will go through using a series of if else and switch statements.

Could you guys help me figure out what I'm doing wrong here? I'm having a problem getting the first if else statement to work. The program runs on my computer(I'm using the BlueJ editor), but when I respond to the first question "Is it soluble in solution?" it defaults to the else statement. The switch statements on the inside of the if else statement works fine by itself.

Can I use switch statements inside if else statements? Is there an easier way to program this?

Could you also explain why it doesn't work, or why another method would be more efficient?

Thanks a ton :)

import java.util.Scanner;
      /**
        * This program will decide what mechanism a reaction will undergo given information about the reactants.
        * I will also include a mechanism to give a rudimentary explanation of the decision making process to
       * get the reaction mechanism.
       */
public class mechanism
{
    public static void main(String[] args)
    {
        System.out.println("Hello, this program is designed to figure out what mechanism a reaction will under go.");
        //The decision tree will be a series of if-else statements. If I find a better method, I will use that

        System.out.println("Is the reactant soluble in the solvent? Answer in yes or no.");

        Scanner keyboard = new Scanner(System.in);

        String Solubility = keyboard.next(); //Defines if the reactant is soluble in the solvent
        String functional = "unassigned";//Defines if the functional roup is primary secondary or tertiary
        String Base = "unassigned";//Defines the strength of the base if needed
        String Polar = "unassigned";//Defines if the reactant is polarizable
        String Solvent = "unassigned"; //Defines if the solvent is protic or aprotic

        if ( Solubility == "yes" )
        {

            System.out.println("Is the functional group attached to a primary, secondary, or tertiary carbon?");
            System.out.println(" Answer in p for primary, s for secondary, and t for tertiary.");

            keyboard = new Scanner(System.in);
            functional = keyboard.next();

                  switch (functional){
                      case "p":   System.out.println("All unimolecular reactions are ruled out, leaving E2 and Sn2.");
                            System.out.println("Is the reactant a strong base? Answer in y for yes or n for no");

                            keyboard = new Scanner(System.in);
                            Base = keyboard.next();
                                if (Base == "y" ){
                                    System.out.println("The reaction undergoes E2");
                            }    else{
                                    System.out.println("The reaction undergoes Sn2");
                        }

                            break;
                        case "s":  System.out.println("No reactions have been ruled out.");
                                   System.out.println("Is the reactant a strong base? Answer in y or n");

                                   keyboard = new Scanner(System.in);
                                   Base = keyboard.next();
                                   if( Base == "y" ){
                                       System.out.println("yay");
                                    } else {
                                        System.out.println("whatever");
                                    }
                                   break;
                        case "t": System.out.println("tertiary");
                            break;

                    }
        } 
        else{
            System.out.println("No reaction will occur");
        }
    }
}