mercredi 31 mai 2017

Using arrays in PHP, how to always change the key1 by key2 or change key2 by key1?

$myWords=array(
,array('funny','sad')
,array('fast','slow')
,array('beautiful','ugly')
,array('left','right')
,array('5','five')
,array('strong','weak')

,);


$myVar = 'This girl is very funny and fast and kick to left';

When the system finds the value of any key contained in the array, always switch to it for another value, I have these system ready, but it does a rand that sometimes falls on the same key found, and in 50% of cases it does not Value, I would always like to change.

I want to change to: 'This girl is very sad and slow and kick to right'

Or

if you find another key: 'This girl is very sad and slow and kick to right'

Switch to:

'This girl is very funny and fast and kick to left';

When one of the keys is found in the $myVar variable always make the exchange for the other key.

Thanks.

show data only if currentmonth and currentyear are larger than

Let say currentmonth is 06 and currentyear 2017

i have dropdown of year and month .. if i select year 2017 and month of July which is larger then currentmonth
how do i show there is not data available yet

my current code..and its not working..i'm a newbie and not sure im doing this right or not...

$mystartingyear=2017;
$mystartingmonth=01;

$currentmonth=date("m");
$currentyear=date("Y");

if ($currentyear >= $mystartingyear && $currentmonth >= $mystartingmonth)
{
echo "Show Data":
}
else
{
echo "No Data yet";
}

Ruby wont print variable

I've been trying to work on a fake little pin-cracking script, but somethings wrong and it's making me frustrated. It randomizes 4 numbers and checks them against 4 other numbers, but for some reason, after the numbers are guessed, it won't print them anymore.

#RubyCodeStart

pass1 = 4
pass2 = 9
pass3 = 2
pass4 = 8
guess = 0
flag1 = 0
flag2 = 0
flag3 = 0
flag4 = 0
loop do
    if flag1 == 0
        crack1 = rand(0..9)
    end
    if flag2 == 0
        crack2 = rand(0..9)
    end
    if flag3 == 0
        crack3 = rand(0..9)
    end
    if flag4 == 0
        crack4 = rand(0..9)
    end
    if crack1 == pass1
        crack1 = pass1
        flag1 = 1
    end
    if crack2 == pass2
        crack2 = pass2
        flag2 = 1
    end
    if crack3 == pass3
        crack3 = pass3
        flag3 = 1
    end
    if crack4 == pass4
        crack4 = pass4
        flag4 = 1
    end
    guess += 1
    puts "#{crack1} \| #{crack2} \| #{crack3} \| #{crack4} === Guess \# #{guess}"
#   if crack == pass
#       break
#   end
end
sleep(30)

Nothing I do works, and it refuses to print it pass it being found. I'll add data if needed.

Output:

8 | 0 | 6 | 1 === Guess # 1
4 | 6 | 1 | 8 === Guess # 2
 | 1 | 3 |  === Guess # 3
 | 1 | 5 |  === Guess # 4
 | 3 | 9 |  === Guess # 5
 | 3 | 3 |  === Guess # 6
 | 5 | 4 |  === Guess # 7
 | 3 | 4 |  === Guess # 8
 | 4 | 3 |  === Guess # 9
 | 0 | 6 |  === Guess # 10
 | 3 | 8 |  === Guess # 11
 | 4 | 5 |  === Guess # 12
 | 2 | 4 |  === Guess # 13
 | 8 | 7 |  === Guess # 14
 | 8 | 4 |  === Guess # 15
 | 9 | 5 |  === Guess # 16
 |  | 7 |  === Guess # 17
 |  | 5 |  === Guess # 18
 |  | 7 |  === Guess # 19
 |  | 7 |  === Guess # 20
 |  | 7 |  === Guess # 21
 |  | 1 |  === Guess # 22
 |  | 2 |  === Guess # 23
 |  |  |  === Guess # 24
 |  |  |  === Guess # 25
 |  |  |  === Guess # 26
 |  |  |  === Guess # 27
 |  |  |  === Guess # 28
 |  |  |  === Guess # 29
 |  |  |  === Guess # 30
 |  |  |  === Guess # 31
 |  |  |  === Guess # 32
 |  |  |  === Guess # 33
 |  |  |  === Guess # 34
 |  |  |  === Guess # 35
 |  |  |  === Guess # 36
 |  |  |  === Guess # 37
 |  |  |  === Guess # 38
 |  |  |  === Guess # 39
 |  |  |  === Guess # 40

MySQL - IF/THEN statement determines INSERT INTO

I'm trying to set up an If/Then statement that determines what is inserted into the "course" table in my database. The first INSERT INTO limits the insert to 6 rows, and the second limits it to 7.

Here is what the code looks like:

If @courseprogram = 'PharmTech' Then
    INSERT INTO course (fameid, course_id, enroll_status)
    SELECT @fameid fame_id, course_id, 'S' enroll_status FROM calendar
    WHERE startdate >= @startdate AND program = @courseprogram ORDER BY startdate LIMIT 6;
Elseif @fullprogram = 'Medical Assisting'
    INSERT INTO course (fameid, course_id, enroll_status)
    SELECT @fameid fame_id, course_id, 'S' enroll_status FROM calendar
    WHERE startdate >= @startdate AND program = @courseprogram ORDER BY startdate LIMIT 7;
End if

When I try running this, I get the following error message:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'If @courseprogram = 'PharmTech' Then INSERT INTO course (fameid, course_id, enr' at line 1

Does anyone know what might be the issue here?

Also, I've read in a couple of posts around this issue that IF/THEN statements should be avoided in MySQL all together. Could anyone explain why this is and how else to approach the problem?

Javascript: Convert a text box number entry into a corresponding letter grade

So far this is what I have but I can't get it to display the result. I want to be able to enter a number such as "75", click the button, and then the bottom textbox to say "C" and so on with other numbers. So far my code looks like this:

<!DOCTYPE html>
<html>
<head>
<script>

    function myFunction() {
        var score = document.getElementById("score").value;

        if (90 <= score) 
            {document.write ("A");}
        else if (80 <= score && score < 90) 
            {document.write ("B");}
        else if (70 <= score && score < 80) 
            {document.write ("C");}
        else if (60 <= score && score < 70) 
            {document.write ("D");}
        else 
            {document.write ("E");} 
        }
    }
</script>
</head>
<body>
    Grade % <input type="number" id="score" value=""><br>
    <p><button onclick="myFunction()">CLICK HERE</button></p>
    Letter Grade <input type="text" id="letter" readonly><br><br>
</body>
</html>

Print number if it matches the sum and product with Shell Script

I am having syntax error with my script, I'm sure i have the logic set but seem to be having issues with the formatting of the script.

The expected workflow is

if n = ((sum) + (product)) then print n and n++ repeat. else n++ repeat.

function sum() {
    local n=$1
    local res=0
    while [ $n -gt 0 ]
    do
        local sdigit=$(( $n % 10 ))
        local n=$(( $n / 10 ))
        local res=$(( $res + $sdigit ))
    done
    echo $res
}

function prod() {
    len=$(echo $1 | wc -c)
    len=$(( $len - 1 ))

    res=1

    for (( i=1; i <= $len; i++ )) 
    do 
         res=$(($res * $(echo $1 | cut -c $i) )) 
    done 
    echo $res
}

#####################################################

n=0
my_prod=$(prod $n)
my_sum=$(sum $n)

while [ $n -le 10 ];
do
    if [ $n = (($my_prod + $my_sum)) ]
    then
        echo "$n"
        n++
    brake
    else
        n++
    fi
done

is there a way to shorten the following code into one if statement?

I have the following code:

if (!isFinishing()) {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
         if (!isDestroyed()) {
              showScoreScreenFragment(chronoText);
         }
     } else {
          howScoreScreenFragment(chronoText);
     }
}

That I need write before I'm commiting fragment transactions. is there s way to make this test in one if statement instead of 3?

because this:

if (!isFinishing() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && !isDestroyed())

doesn't have the same meaning.

Thanks in advance.

Python tkinter - Arguing String Input for Entry( )

I am learning Python tkinter fundamentals, and cannot get my method called "Submit()" to argue the string value for my Entry1 variable. I have tried the .get() method for Entry1, but the console says the get attribute does not exist for Entry1. So I have resorted to asking the amazing wizards of stackoverflow. Thanks for your time, tkinter pros!

from tkinter import *

Window = Tk()

def Submit():
    Answer = Entry1.text
    if Answer == "byte":
    print("correct")

Label(Window, text="What do you call 8 bits?").grid(row=0)
Entry1 = Entry(Window, text="").grid(row=1)
Button(Window, text="SUBMIT", command=Submit).grid(row=2)

Window.mainloop()

How i make the code skip to a certain point in the loop?

I'm working on a basic game. I'd like to know how I can make the code go to a specific point in the loop, rather than starting off at the beginning.

For example, in my code at line 19: kithcen() I don't want to redirect it to the start of loop again going on the describe the kitchen and then asking for an input: choice02 = raw_input("What do you do?"), but rather i want it to directly skip to the input part.

def kitchen():
print "You see a dusty old kitchen, nobody has probably used it for quite a while."
print "There are 3 different cupboards(0, 1, 2) or a letter(3) placed on the counter."
choice02 = raw_input("What do you do? >")

if choice02 == "0" or choice02 == "first cupboard" or choice02 == "check first cupboard" or choice02 == "open first cupboard":
    print "You see a dusty empty bottles of milks, with spiderwebs at the corners of the cupboard. Nothing of Interest here."
    raw_input(">")
    kitchen()

elif choice02 == "1" or choice02 == "second cupbaord" or choice02 == "check second cupboard" or choice02 == "open second cupboard":
    print "You see some packs of likely expired cereal and a key(0)."
    choice_02_A = raw_input("What do you do? >")

   #----------------------------------------------------------------------------------------------------------#
    if choice02_A == "pick key" or choice02_A == "key" or choice02_A == "0" or choice02_A == "get key":
        print "You picked the key. This probably unlocks some door."
        raw_input("> ")
        kitchen()

    elif choice02_A == "close cupboard" or choice02_A == "kitchen" or choice02_A == "go back to kitchen":
        kitchen()

    else:
        print "Not a valid option."
   #-----------------------------------------------------------------------------------------------------------#

elif choice02 == "2" or choice02 == "third cupboard" or choice02 == "check third cupboard" or choice02 == "open third cupboard":
    print "You see an empty or dusty cupboard. Nothing of interest here."
    raw_input("> ")
    kitchen()

elif choice02 == "3" or choice02 == "check letter" or choice02 == "letter" or choice02 == "read letter":
    print """
    You read the letter:
    \n"Dear Shawn............\n"
    It makes no sense to you.
    """


elif choice02 == "go back" or choice02 == "entrance hall" or choice02 == "go to entrance hall":
    entrance_hall()

else:
    "Not a valid Option."

If (Variable == Variable + 5) in Swift3

I am trying to show a certain medal in my scene depending on what your high score is based on the goal of the level.

// Get Medal Colour
    if levelHighscore < goalScore {
        scoreMedal = SKSpriteNode(imageNamed: "noMedal")
    } else if levelHighscore == goalScore {
        scoreMedal = SKSpriteNode(imageNamed: "bronzeMedal")
    } else if levelHighscore > goalScore {
        scoreMedal = SKSpriteNode(imageNamed: "silverMedal")
    }

At the moment i get the high score and compare it to the goal - if it is less than the goal show noMedal image. If it equals the goal show a bronzeMedal, If the high score is 5 more than the goal show silverMedal and if the high score is 10 higher than the goal show a goldMedal.

Been on this for a while trying all different bits and bobs and for some reason it works in the setup above but when i write

    // Get Medal Colour
    if levelHighscore == goalScore+5 {
        scoreMedal = SKSpriteNode(imageNamed: "silverMedal")
    } 

it shows nothing.

compare values in R when within a string of letters

I need to check if the values of two columns fulfil certain conditions, but the value in one column is within a string of letters.

If the value of CURRENT_ID is equal to the value of CURRENT_TEXT_1 or CURRENT_TEXT_2 minus 2, when CURRENT_TEXT_1 or CURRENT_TEXT_2 are equal to DISPLAY_BOUNDARY, then I need in the OUTPUT column a value of 1, otherwise a value of zero.

Here are some example lines of my datafile (df) and the output I would like to obtain:

 PARTICIPANT     ITEM   CONDITION      CURRENT_TEXT_1               CURRENT_TEXT_2                 CURRENT_ID            OUTPUT
 ppt01          1         1            DISPLAY_BOUNDARY 1 the       iaRegion 4 rd 0 x width 333    7                     0
 ppt01          3         1            iaRegion 2 rd 0 x width 1    DISPLAY_BOUNDARY 9 a           11                    1
 ppt01          4         2            DISPLAY_BOUNDARY 2 aware     iaRegion 6 rd 0 x width 768    3                     0
 ppt01          6         3            DISPLAY_BOUNDARY 3 door      iaRegion 8 rd 0 x width 534    4                     0
 ppt01          9         4            DISPLAY_BOUNDARY 6 in        iaRegion 9 rd 0 x width 924    5                     0
 ppt01          48        5            DISPLAY_BOUNDARY 6 the       iaRegion 10 rd 0 x width 712   8                     1
 ppt02          3         4            iaRegion 14 rd 0 x width 756 DISPLAY_BOUNDARY 15 put        17                    1
 ppt02          7         5            iaRegion 1 rd 0 x width 334  DISPLAY_BOUNDARY 1 where       3                     1
 ppt02          8         6            DISPLAY_BOUNDARY 3 At        iaRegion 2 rd 0 x width 215    5                     1
 ppt02          35        2            iaRegion 3 rd 0 x width 524  DISPLAY_BOUNDARY 1 outside     2                     0
 ppt03          10        1            iaRegion 11 rd 0 x width 190 DISPLAY_BOUNDARY 2 school      4                     1
 ppt03          56        1            DISPLAY_BOUNDARY 8 blue      iaRegion 11 red 0 x width 383  9                     0

My attempt is:

df$OUTPUT <- ifelse(df$CURRENT_ID==((grepl("DISPLAY_BOUNDARY",df$CURRENT_TEXT_1)|grepl("DISPLAY_BOUNDARY",df$CURRENT_TEXT_2))-2, 1, 0)

But I don't know how to extract the value associated with DISPLAY_BOUNDARY. Any help would be appreciated.

How to make a if-else Angular template with only ng-container?

I would like to make an if-else statement in my angular template. I started with that :

<ng-container *ngIf="contributeur.deb; else newDeb" >
    [... HERE IS A RESULT 1]
</ng-container>
<ng-template #newDeb>
    [... HERE IS A RESULT 2]
</ng-template>

And I tried to only use ng-container :

<ng-container *ngIf="contributeur.deb; else newDeb" >
    [... HERE IS A RESULT 1]
</ng-container>
<ng-container #newDeb>
    [... HERE IS A RESULT 2]
</ng-container >

Unfortunately, this does not work. I have this error :

ERROR TypeError: templateRef.createEmbeddedView is not a function
    at ViewContainerRef_.createEmbeddedView (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:10200:52)
    at NgIf._updateView (eval at <anonymous> (vendor.bundle.js:96), <anonymous>:2013:45)
    at NgIf.set [as ngIfElse] (eval at <anonymous> (vendor.bundle.js:96), <anonymous>:1988:18)
    at updateProp (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:11172:37)
    at checkAndUpdateDirectiveInline (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:10873:19)
    at checkAndUpdateNodeInline (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12290:17)
    at checkAndUpdateNode (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12258:16)
    at debugCheckAndUpdateNode (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12887:59)
    at debugCheckDirectivesFn (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12828:13)
    at Object.eval [as updateDirectives] (ActionsButtons.html:5)

Can anyone explain me what is going wrong in this code ?

Loop nesting issue - values not correct

I have a dataframe that has two relevant columns (actually has >2, but don't think that's important), and one of the columns has duplicates in it.

The duplicates are in the column, HAB_slice['Radial Position'], and are in increments of 0.1.

Ideally, I want to say if two values in HAB_slice['Radial Position'] are equal to each other, find the absolute value difference between them and add them to a running total.

The current code looks like this:

    possible_pos = np.linspace(0, 1, 1 / stepsize+1) 
    center_sum = 0
    for i in range(0, len(possible_pos)): 
        temp = HAB_slice[HAB_slice['Radial Position']==possible_pos[i]]
        if len(temp) == 2:
            center_sum += np.abs(temp['I'].diff().values[1])
    print center_sum

And while it does return a value and doesn't throw errors, the value for center_sum is different than when I manually calculate it. I think it's just something wrong with the nesting but I'm pretty new to loops and am not really sure.

Example of the error: the following data yields a center_sum = 0 in this code, but if you manually calculate the absolute value differences in I when the Radial positions are equal to each other, it equals 0.0045878.

I           Radial Position
0.14289522  1
0.14298554  0.9
0.1430356   0.8
0.1430454   0.7
0.1430552   0.6
0.14266456  0.5
0.14227392  0.4
0.14234106  0.3
0.14286598  0.2
0.1433909   0.1
0.14309062  0
0.14279034  0.1
0.14271344  0.2
0.14285992  0.3
0.1430064   0.4
0.14327248  0.5
0.14353856  0.6
0.14356664  0.7
0.14335672  0.8
0.1431468   0.9
0.14338368  1

Assistance with IF and ANDs

I am struggling with the formula shown in the picture. I need to add to the formula so that; IF the E column has the phrase "FD" anywhere in it, the formula will show the phrase "Correct" in the P column.

The E column contains a large variety of codes such as 1-FD, 2-FD, 3-FD and so on. There are too many to list in a formula easily. In access I could type in "*" or "?" if I didn't know all the values. How can I do that in an excel formula?

enter image description here

Merging 2 df into one based on 2 conditions

I'm a newbe in R and have the following question:

I have two datasets (df1 and df2) that slightly differ from each other.

df1=(city=c("A", "B", "C"),Niscode = 100:110, province=c("NA", "Ant"))
df2=(city=c("A", "B", "C"), province=c("NA", "Ant"), Lokstat=1:5)

Now I want to merge them based on the following criteria because the same city can appear in differnt provinces:

If the name of the city in df1 and df2 and the province name in df1 and df2 are the same than add the Lokstat from df2 in df1.

I guess I have to programm loops but I'm not sure how.

Thanks for your help!

Java - How to check if a mathematical argument is true

Today I am trying to find out how to see if a mathematical argument is true...

For Example:

if 1+1 is true do this, if false, do this...

Code Example (that I tried):

if (1+1 : true) {
     \\Some code in here if it is true
} else {
     \\Code in a Crash screen here if it is false
}

As this is only an example, the 1+1 would not be in the actual program itself...

I have looked all across StackOverflow, and all across Google, and a bunch of other places to find this, and I could not, if yall could help me, that would be great... Thanks!

Describe if statement. Write an if statement to multiply even numbers by 3 and odd numbers by 4

Describe if statement. Write an if statement to multiply even numbers by 3 and odd numbers by 4.

Python, if clause in regards to continuous '!=' [on hold]

>>> a=2
>>> b=3
>>> c=4
>>> a<b<c
True
>>> a=2
>>> b=3
>>> c=2
>>> a<b<c
False
>>> a=2
>>> b=3
>>> c=2
>>> a!=b!=c
True

The '<' we could find it can adjust a and b, b and c,what is more, a and c,because if a

How to optimize the 5,6 conditions if else if Statements

here is the some sample line of codes..

if(loc > 0 || cat > 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) {    
 /// Condition to checn all true
    return true;
} else if(loc < 0 || cat > 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) { 
   /////// 1 false other are true 

} else if(loc > 0 || cat < 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) { 

}

How to handle these condition. if i have 5 statement. Then it must be almost 12+ condition one by one.. if i am checking all the 5 combinations its going to more lines of code do we have any better option to check all the conditions.

mardi 30 mai 2017

Regex if or else

Currently i have 2 types of logs, one of which i want to select using regex and the other one i need to discard.

If I am getting a log, with hostname after the timestamp, then i want to select it.. hostname pattern will be same always (like, aabvabcw74.def.co.uk, aaxptac103.def.co.uk etc) Eg: 2017-04-24T09:20:01.687387+00:00 aabvabcw74.def.co.uk hostd-probe:

Anything other than this pattern i want to discard it..

2017-04-14T15:18:34.727042+00:00 Fri Apr 14 15:18:34 2017 aalesxbs029.def.co.uk lacp: DEBUG]:147, Recv signal 15, LACP service is about to stop -- It has 2 timestamp so i want to discard this log

2017-04-24T09:20:01.687387+00:00 hostd probing is done. aabvabcw74.def.co.uk hostd-probe: --- here hostd is coming as the hostname, which is wrong so i want to discard this log as well

2017-04-24T20:53:29.334348+00:00 10.199.6.5 .def.co.uk aabvabcs15.def.co.uk Fdm: sslThumbprint>95:43:64:71:A3:60:D8:17:C8:6F:68:83:92:CE:E4:3B:53:4E:1D:AD10.199.6.5a2:0e:09:01:0a:00a2:0e:09:01:0b:01/vmfs/volumes/b01f388c-aaa4889f/vmfs/volumes/6ad2d8d7-86746df14435.5.03568722host-619286aabvabcs16.def.co.uk ---- here i am getting ip address after the timestamp so i want to discard this as well

Please help me with a solution

Row by Row (pandas) - If Column A = 'Something' and Column B > 25 Then Column C = "Category"

I'm trying to have a script go Row by Row in Python using (pandas). I want it so that if Column A = 'Something' and Column B > 25 then write to Column C = "Category".

I have a Month Column and a Day Column. So, for example:

When Month = August and Day >= 25 then Week = August 25

I tried a couple of things, neither worked...

First I tried:

import os               ### OS library is imported.
import pandas as pd     ### Pandas library is imporated as 'pd'.

counter = 1             ### Counter starts at the first iteration.

while os.path.exists("CSV-Iteration-"'{0}'"/".format(counter)):     ### Runs the loop until all iteration's folders have been processed.

    a = pd.read_csv("output-"'{0}'".csv".format(counter))           ### Sets 'a' dataframe as holding data from a CSV file.
    a['Week'] = ""

    a[(a['Month'] is 'June') & (a['Day'] < 25)]['Week'] = 'June 18'
    a[(a['Month'] is 'June') & (a['Day'] >= 25)]['Week'] = 'June 25'
    a[(a['Month'] is 'July') & (a['Day'] < 2)]['Week'] = 'June 25'
    a[(a['Month'] is 'July') & (a['Day'] >= 2) & (a['Day'] < 9)]['Week'] = 'July 2'
    a[(a['Month'] is 'July') & (a['Day'] >= 9) & (a['Day'] < 16)]['Week'] = 'July 9'
    a[(a['Month'] is 'July') & (a['Day'] >= 16) & (a['Day'] < 23)]['Week'] = 'July 16'
    a[(a['Month'] is 'July') & (a['Day'] >= 23) & (a['Day'] < 30)]['Week'] = 'July 23'
    a[(a['Month'] is 'July') & (a['Day'] >= 31) & (a['Day'] < 16)]['Week'] = 'July 30'
    a[(a['Month'] is 'August') & (a['Day'] < 6)]['Week'] = 'July 30'

    a[(a['Month'] is 'August') & (a['Day'] >= 6) & (a['Day'] < 13)]['Week'] = 'August 6'
    a[(a['Month'] is 'August') & (a['Day'] >= 13) & (a['Day'] < 20)]['Week'] = 'August 13'
    a[(a['Month'] is 'August') & (a['Day'] >= 20) & (a['Day'] < 27)]['Week'] = 'August 20'
    a[(a['Month'] is 'August') & (a['Day'] >= 27)]['Week'] = 'August 27'
    a[(a['Month'] is 'September') & (a['Day'] < 3)]['Week'] = 'August 27'

    a[(a['Month'] is 'September') & (a['Day'] >= 3) & (a['Day'] < 10)]['Week'] = 'September 3'
    a[(a['Month'] is 'September') & (a['Day'] >= 10) & (a['Day'] < 17)]['Week'] = 'September 10'
    a[(a['Month'] is 'September') & (a['Day'] >= 17) & (a['Day'] < 24)]['Week'] = 'September 17'
    a[(a['Month'] is 'September') & (a['Day'] >= 24)] = 'September 24'

    a[(a['Month'] is 'October') & (a['Day'] >= 1) & (a['Day'] < 8)]['Week'] = 'October 1'
    a[(a['Month'] is 'October') & (a['Day'] >= 8) & (a['Day'] < 15)]['Week'] = 'October 8'
    a[(a['Month'] is 'October') & (a['Day'] >= 15) & (a['Day'] < 22)]['Week'] = 'October 15'
    a[(a['Month'] is 'October') & (a['Day'] >= 22) & (a['Day'] < 29)]['Week'] = 'October 22'
    a[(a['Month'] is 'October') & (a['Day'] >= 29)]['Week'] = 'October 29'
    a[(a['Month'] is 'November') & (a['Day'] < 5)]['Week'] = 'October 29'

    a[(a['Month'] is 'November') & (a['Day'] >= 5) & (a['Day'] < 12)]['Week'] = 'November 5'
    a[(a['Month'] is 'November') & (a['Day'] >= 12) & (a['Day'] < 19)]['Week'] = 'November 12'
    a[(a['Month'] is 'November') & (a['Day'] >= 19) & (a['Day'] < 26)]['Week'] = 'November 19'
    a[(a['Month'] is 'November') & (a['Day'] >= 26)]['Week'] = 'November 26'
    a[(a['Month'] is 'December') & (a['Day'] < 3)]['Week'] = 'November 26'

    a[(a['Month'] is 'December') & (a['Day'] >= 3) & (a['Day'] < 10)]['Week'] = 'December 3'
    a[(a['Month'] is 'December') & (a['Day'] >= 10) & (a['Day'] < 17)]['Week'] = 'December 10'
    a[(a['Month'] is 'December') & (a['Day'] >= 17) & (a['Day'] < 24)]['Week'] = 'December 17'
    a[(a['Month'] is 'December') & (a['Day'] >= 24) & (a['Day'] < 31)]['Week'] = 'December 24'
    a[(a['Month'] is 'December') & (a['Day'] >= 31)]['Week'] = 'December 31'
    a[(a['Month'] is 'January') & (a['Day'] < 7)]['Week'] = 'December 31'

    a[(a['Month'] is 'January') & (a['Day'] >= 7) & (a['Day'] < 14)]['Week'] = 'January 7'
    a[(a['Month'] is 'January') & (a['Day'] >= 14) & (a['Day'] < 21)]['Week'] = 'January 14'
    a[(a['Month'] is 'January') & (a['Day'] >= 21) & (a['Day'] < 28)]['Week'] = 'January 21'
    a[(a['Month'] is 'January') & (a['Day'] >= 28)]['Week'] = 'January 28'

    a.to_csv("TESToutput-"'{0}'".csv".format(counter), index=False)         ### 'a' dataframe becomes 'TESToutput-#.csv' and does not print fields for indexing (index=False).

    counter += 1        ### Adds 1 to the counter.

print 'Date Corrections - All Done!'

Then I tried:

import os               ### OS library is imported.
import pandas as pd     ### Pandas library is imporated as 'pd'.

counter = 1             ### Counter starts at the first iteration.

while os.path.exists("CSV-Iteration-"'{0}'"/".format(counter)):     ### Runs the loop until all iteration's folders have been processed.

    a = pd.read_csv("output-"'{0}'".csv".format(counter))           ### Sets 'a' dataframe as holding data from a CSV file.
    a['Week'] = ""

    def this_week (row):
        if row[(a['Month'] is 'June') + (a['Day'] < 25)]:
            return 'June 18'
        if row[(a['Month'] is 'June') + (a['Day'] >= 25)]:
            return 'June 25'
        if row[(a['Month'] is 'July') + (a['Day'] < 2)]:
            return 'June 25'
        if row[(a['Month'] is 'July') + (a['Day'] >= 2) + (a['Day'] < 9)]:
            return 'July 2'
        if row[(a['Month'] is 'July') + (a['Day'] >= 9) + (a['Day'] < 16)]:
            return 'July 9'
        if row[(a['Month'] is 'July') + (a['Day'] >= 16) + (a['Day'] < 23)]:
            return 'July 16'
        if row[(a['Month'] is 'July') + (a['Day'] >= 23) + (a['Day'] < 30)]:
            return 'July 23'
        if row[(a['Month'] is 'July') + (a['Day'] >= 31) + (a['Day'] < 16)]:
            return 'July 30'
        if row[(a['Month'] is 'August') + (a['Day'] < 6)]:
            return 'July 30'
        if row[(a['Month'] is 'August') + (a['Day'] >= 6) + (a['Day'] < 13)]:
            return 'August 6'
        if row[(a['Month'] is 'August') + (a['Day'] >= 13) + (a['Day'] < 20)]:
            return 'August 13'
        if row[(a['Month'] is 'August') + (a['Day'] >= 20) + (a['Day'] < 27)]:
            return 'August 20'
        if row[(a['Month'] is 'August') + (a['Day'] >= 27)]:
            return 'August 27'
        if row[(a['Month'] is 'September') + (a['Day'] < 3)]:
            return 'August 27'
        if row[(a['Month'] is 'September') + (a['Day'] >= 3) + (a['Day'] < 10)]:
            return 'September 3'
        if row[(a['Month'] is 'September') + (a['Day'] >= 10) + (a['Day'] < 17)]:
            return 'September 10'
        if row[(a['Month'] is 'September') + (a['Day'] >= 17) + (a['Day'] < 24)]:
            return 'September 17'
        if row[(a['Month'] is 'September') + (a['Day'] >= 24)]:
            return 'September 24'
        if row[(a['Month'] is 'October') + (a['Day'] >= 1) + (a['Day'] < 8)]:
            return 'October 1'
        if row[(a['Month'] is 'October') + (a['Day'] >= 8) + (a['Day'] < 15)]:
            return 'October 8'
        if row[(a['Month'] is 'October') + (a['Day'] >= 15) + (a['Day'] < 22)]:
            return 'October 15'
        if row[(a['Month'] is 'October') + (a['Day'] >= 22) + (a['Day'] < 29)]:
            return 'October 22'
        if row[(a['Month'] is 'October') + (a['Day'] >= 29)]:
            return 'October 29'
        if row[(a['Month'] is 'November') + (a['Day'] < 5)]:
            return 'October 29'
        if row[(a['Month'] is 'November') + (a['Day'] >= 5) + (a['Day'] < 12)]:
            return 'November 5'
        if row[(a['Month'] is 'November') + (a['Day'] >= 12) + (a['Day'] < 19)]:
            return 'November 12'
        if row[(a['Month'] is 'November') + (a['Day'] >= 19) + (a['Day'] < 26)]:
            return 'November 19'
        if row[(a['Month'] is 'November') + (a['Day'] >= 26)]:
            return 'November 26'
        if row[(a['Month'] is 'December') + (a['Day'] < 3)]:
            return 'November 26'
        if row[(a['Month'] is 'December') + (a['Day'] >= 3) + (a['Day'] < 10)]:
            return 'December 3'
        if row[(a['Month'] is 'December') + (a['Day'] >= 10) + (a['Day'] < 17)]:
            return 'December 10'
        if row[(a['Month'] is 'December') + (a['Day'] >= 17) + (a['Day'] < 24)]:
            return 'December 17'
        if row[(a['Month'] is 'December') + (a['Day'] >= 24) + (a['Day'] < 31)]:
            return 'December 24'
        if row[(a['Month'] is 'December') + (a['Day'] >= 31)]:
            return 'December 31'
        if row[(a['Month'] is 'January') + (a['Day'] < 7)]:
            return 'December 31'
        if row[(a['Month'] is 'January') + (a['Day'] >= 7) + (a['Day'] < 14)]:
            return 'January 7'
        if row[(a['Month'] is 'January') + (a['Day'] >= 14) + (a['Day'] < 21)]:
            return 'January 14'
        if row[(a['Month'] is 'January') + (a['Day'] >= 21) + (a['Day'] < 28)]:
            return 'January 21'
        if row[(a['Month'] is 'January') + (a['Day'] >= 28)]:
            return 'January 28'

    a['Week'] = a.apply (lambda row: this_week (row), axis=1)

    a.to_csv("TESToutput-"'{0}'".csv".format(counter), index=False)         ### 'a' dataframe becomes 'TESToutput-#.csv' and does not print fields for indexing (index=False).

    counter += 1        ### Adds 1 to the counter.

print 'Date Corrections - All Done!'

The second gives me this error: "IndexingError: ('Unalignable boolean Series key provided', u'occurred at index 0')"

I'm very new to Python so I put these together based on what I've read in the forums. Please let me know if there is a simpler way to do it or if there is a correction or addition to make one of these two scripts work.

Thanks!

If statement with then clause (LISP)

So I'm trying to teach myself lisp, I'm currently using this site as a reference: http://ift.tt/2qz4Ciy

I don't quite understand why the then clause is executed, despite the fact that the if clause is false?

(setq a 10)
(if (> a 20)
   then (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)

The output is:

a is less than 20
value of a is 10 

Does the then clause just always execute, even when the if statement is false? (which in this case it is).

Any help would be appreciated, also sorry if my terminology is totally incorrect I'm still new to Lisp!

ArcGIS 10.2 Python code block: indentation error

I have an attribute table with a GRIDCODE column that only has values 1, 2 or 3. I need my new field to be either A, B or C depending on the value of GRIDCODE. The attribute table has thousands of features so doing the selection by attributes would be tiresome.

I tried the following code but I keep getting error 000989 : Python syntax error: . So apparently my code has improper syntax. I've tried the following:

def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
  else:
     return 8.21

Also

def yieldCalc(value):
 if (value=1):
     return 6.2
  elif (value=2):
     return 7.9
 else:
     return 8.21

And

def yieldCalc(value):
 if (value=1):
     return 6.2
 elif (value=2):
     return 7.9
 else:
     return 8.21

What is the proper way to indent the python code block in Arcmap?

Many thanks

Minesweeper Java Colouring Pegs

I am making a minesweeper game where it follows the standard rules. When a mine is hit the game ends and if all spots are filled then the user wins. What I am trying to do is make the pegs have different colours according to the amount of mines it hits. I have declared a local variable to keep track of the number of surrounding mines. Then used if statements, if you find a mine, use a count++. I am not quite sure how to fix this line in particular to make it do what I want it to do. if((currentClick.getRow() == ships.get(i).getRow()) && (currentClick.getCol() == ships.get(i).getCol())){ count++; }

Here is my code so far:

import java.util.*;

public class Minesweeper2{


static int dim = userSize(); //call to userSize method is stored as static value
static Board board = new Board(dim, dim);//and immediately built to Board object of user-defined size

//this method uses Terminal to ask the user what size the board should be
public static int userSize(){

Scanner scan = new Scanner(System.in);
System.out.println("What size should the board be? (Numbers only (5-1000))");
int dim = scan.nextInt();
return dim;
}

public static void main(String[] args){

boolean unWon = true;//variable to determine if game is over
Random random = new Random();//call random method
int totalClicks = 0;
int mineHit = 0;

board.displayMessage("Welcome to Minesweeper!  White=0, Blue = 1, Green = 2, Red = 3, Yellow = 4");

//initialize each row and column interger for the ten coordinates that are red
int[] nums = new int[20];

//initialize array list and store values of ship inside
ArrayList<Coordinate> ships = new ArrayList<Coordinate>();

for(int i = 0; i < nums.length; i++){
  nums[i] = random.nextInt(10);
  if(i%2 == 1)
    ships.add(new Coordinate(nums[i-1],nums[i]));
}

Boolean isHit = false;//set boolean is hit to false

while(unWon && totalClicks < 100){
  isHit = false; // reset isHit
  Coordinate currentClick = board.getClick(); //Get the current click
  totalClicks++;//increment counter for each click

  //Check the ship coordinates to see whether it is hit
  for(Coordinate c: ships) {
    if((c.getRow() == currentClick.getRow()) && (c.getCol() == currentClick.getCol())){
      //board.putPeg("black", currentClick.getRow(), currentClick.getCol());//output red pegs
      isHit = true;//reset is hit boolean
      mineHit++;//initialize counter for each red peg

      //if all ten red pegs are found, set the game to won
      if (mineHit == 10){
        unWon = false;
        break;
      }

    }

    for (int i = 0; i < ships.size(); i++) {

    if(isHit){
      board.putPeg("black", currentClick.getRow(), currentClick.getCol());
    }

    //this needs to get more complicated
    if((currentClick.getRow() == ships.get(i).getRow()) && (currentClick.getCol() == ships.get(i).getCol())){
    count++;
    }



    else if(count==1){
      board.putPeg("blue", currentClick.getRow(), currentClick.getCol()); 
    }

    else if(count==2){
      board.putPeg("green", currentClick.getRow(), currentClick.getCol());
    }  

    else if(count==3){
      board.putPeg("red", currentClick.getRow(), currentClick.getCol());
    }  

    else if(count==4){
      board.putPeg("yellow", currentClick.getRow(), currentClick.getCol());
    }


    else{
        board.putPeg("white",currentClick.getRow(), currentClick.getCol());
      }
  }

    board.displayMessage("It has been " + totalClicks + " click(s)" + ";      White = 0, Blue = 1, Green = 2, Red = 3, Yellow = 4");

      for(int red = 0; red<10; red++){
        System.out.println(ships.get(red).getRow() + " " + ships.get(red).getCol());
      }
} 
}
}

Any help is appreciated.

For loops? Including rows in a dataframe by the missing values of factor levels

Good morning

I have a dataset of fisheries data with several variables that look like this:

ID              Day      Month   Year  Depth  Haul number  Count LengthClass     
H111200840       11        1     2008   -80       40        4      10-20
H111200840       11        1     2008   -80       40        15     20-30
H29320105        29        3     2010   -40       5         3      50-60
H29320105        29        3     2010   -40       5         8      60-70

The column ID is a unique ID made by paste the columns day,month,Year and Haul.number. As you can see for the same ID I have data of different Length Class. En each Haul, fish from different lengths are captured.

However, LengthClass is a factor variable with the following levels: 10-20, 20-30, 30-40, 40-50 and fish of a certain length class that is not captured in a Haul is not recorded in the dataset.

I need to include in the above data.frame example new rows for each ID with the missing levels of LengthClass.

The missing Length classes should have a Count of 0 but the rest of the variables have to be the same.

This is an example of what I would like

 ID              Day      Month   Year  Depth  Haul number  Count LengthClass     
  H111200840       11        1     2008   -80       40        4      10-20
  H111200840       11        1     2008   -80       40        15     20-30
  H111200840       11        1     2008   -80       40        0      30-40
  H111200840       11        1     2008   -80       40        0      40-50
  H111200840       11        1     2008   -80       40        0      50-60
  H29320105        29        3     2010   -40       5         3      40-60
  H29320105        29        3     2010   -40       5         8      50-60
  H29320105        29        3     2010   -40       5         0      10-20
  H29320105        29        3     2010   -40       5         0      20-30
  H29320105        29        3     2010   -40       5         0      30-40

Is there anyway to do this? I have tried for loops with if arguments but with no luck and also the example of this post:

Thanks for any advice in advance

How can I use an if-else statement to select elements in different matrices?

I have been stuck on the following issue for days and would appreciate any help. I have 2 different matrices, A and B. I have a starting x and y position (xpos, ypos), and want to first, identify whether there is an element within a certain range that has a value of "0" in the matrix B. If there is an element of such kind, I want the x and y position of this element to be the new x and y position. If there aren't any elements with a value of "0", I want to select the element with the highest value within a certain range from the starting positions in matrix A. The position and this element then becomes the new x and y position. I have the following code:

for i=1:5
    range=5
    xpos=100
    ypos=100
    xstart=xpos-range
    ystart=ypos-range

    for gg=1:10; %double the range
        for hh=1:10;

            if  ystart+gg <= 652 && ystart+gg>0 && xstart+hh <= 653 &&  xstart+hh> 0 &&  B(xstart+hh,ystart+gg)== 0;

                xpos = xstart+hh %this becomes the new xposition
                ypos = ystart+gg

            else

                if  ystart+gg <= 652 && ystart+gg >0 && xstart+hh <= 653 && xstart + hh >0 && B(xstart+hh,ystart+gg)~= 0;



                    if  ystart+gg <= 652 && ystart +gg>0 && xstart+hh <= 653 && xstart+hh>0 && A(ystart + gg, xstart +hh) >= 0.0;
                        maxtreecover = A(ystart + gg, xstart + hh)

                        xpos = xstart + gg %this becomes the new xpos
                        ypos = ystart + hh %this becomes the new ypos

                    end
                end
            end
        end
    end
end

The problem with this is that it does not search ALL of the elements within the range for a "0" (in the B matrix) before moving into searching the A matrix. How can I modify this code to reflect what I intend it to do?

Regex condition and extract

I'm parsing a file in bash, and I need to test if the current line is like this AND extract what's after "interface" :

interface EthernetXXXX/YYY

or

interface port-channelZZZZZ

where X, Y or Z is a number

Text sample :

 channel-group 105 mode active
   no shutdown

 interface Ethernet4/20
   description *** SW1-DT-A05-DC7 -> e1/37 ***
   switchport

For example :

$REGEX = "^interface (REGEX)"
if [[ $line =~ $REGEX ]];
then
    ifname = $XXX #the extracted part from the regex, i.e Ethernet4/20
fi

Do you know how to do this, if possible all in the if-statement ?

How to search a char in a char array in if condition statement

Is there any function which can help me do the following in an efficient way?

char ch = '+';
if (( ch == '+') || (ch == '-') || (ch == '*'))
{
    //do something
}

Since have to check this several times in my code, I would prefer if there was any to do it similar to

char arr ={'+','-','*'};
if (ch in arr)
{
    //do something 
}

lundi 29 mai 2017

Writing a better IF condition

I need help writing a better code for the following logic:

if [[ "$CONDITION1" == "BAD" && "$PERCENT1" -ge 10 && "$PERCENT1" -le 30 ]] || [[ "$CONDITION1" == "GOOD" && "$PERCENT1" -ge 30 && "$PERCENT1" -le 60 ]] || [[ "$CONDITION2" == "BAD" && "$PERCENT2" -ge 10 && "$PERCENT2" -le 30 ]] || [[ "$CONDITION2" == "GOOD" && "$PERCENT2" -ge 30 && "$PERCENT2" -le 60 ]];
then
        echo "RESULT 1"
elif [[ "$CONDITION1" == "BAD" && "$PERCENT1" -gt 30 ]] || [[ "$CONDITION1" == "GOOD" && "$PERCENT1" -gt 60 && "$PERCENT1" -le 100 ]] || [[ "$CONDITION2" == "BAD" && "$PERCENT2" -gt 30 ]] || [[ "$CONDITION2" == "GOOD" && "$PERCENT2" -gt 60 && "$PERCENT2" -le 100 ]];
then
        echo "RESULT 2"
else
        echo "RESULT 3"
fi

This is the basis for the conditions:

RESULT 1: PERCENT1 is 10-30% if CONDITION1=BAD

OR PERCENT1 is 30-60% if CONDITION1=GOOD

RESULT 2: PERCENT1>30% if CONDITION1=BAD

OR PERCENT1 is 60-100% if CONDITION1=GOOD

MS Access: If/else condition to display data in a Form

I have created a form that allows a user to select a Company and input an Amount.
e.g.
Company Name | Taxable
ABC | YES
BCD | YES
CDE | NO
DEF | NO
...... and the list goes on

Currently, the form will display 2 calculated amounts for each company (YES and NO), with and without tax. How and where do I insert a condition such that my Form only displays the Amount with tax for YES and Amount without tax for NO?

Nested ifelse: improved syntax

Description

ifelse() function allows to filter the values in a vector through a series of tests, each of them producing different actions in case of a positive result. For instance, let xx be a data.frame, as follows:

xx <- data.frame(a=c(1,2,1,3), b=1:4)
xx

a b
1 1
2 2
1 3
3 4

Suppose that you want to create a new column, c, from column b, but depending on the values in column a in the following way:

For each row,

  • if the value in column a is 1, the value in column c, is the same value in column b.
  • if the value in column a is 2, the value in column c, is 100 times the value in column b.
  • in any other case, the value in column c is the negative of the value in column b.

Using ifelse(), a solution could be:

xx$c <- ifelse(xx$a==1, xx$b, 
               ifelse(xx$a==2, xx$b*100,
                      -xx$b))
xx

a b c
1 1 1
2 2 200
1 3 3
3 4 -4

Problem 1

An aesthetic problem arises when the number of tests increases, say, four tests:

xx$c <- ifelse(xx$a==1, xx$b, 
           ifelse(xx$a==2, xx$b*100,
                  ifelse(xx$a==3, ...,
                         ifelse(xx$a==4, ...,
                                ...))))

I found partial solution to the problem in this page, which consists in the definition of the functions if.else_(), i_(), e_(), as follows:

library(lazyeval)
i_ <- function(if_stat, then) {
    if_stat <- lazyeval::expr_text(if_stat)
    then    <- lazyeval::expr_text(then)
    sprintf("ifelse(%s, %s, ", if_stat, then)
}

e_ <- function(else_ret) {
    else_ret <- lazyeval::expr_text(else_ret)
    else_ret
}

if.else_ <- function(...) {
    args <- list(...)

    for (i in 1:(length(args) - 1) ) {
        if (substr(args[[i]], 1, 6) != "ifelse") {
            stop("All but the last argument, need to be if.then_ functions.", call. = FALSE)
        }
    }
    if (substr(args[[length(args)]], 1, 6) == "ifelse"){
        stop("Last argument needs to be an else_ function.", call. = FALSE)
    }
    args$final <- paste(rep(')', length(args) - 1), collapse = '')
    eval_string <- do.call('paste', args)
    eval(parse(text = eval_string))
}

In this way, the problem given in the Description, can be rewritten as follows:

xx <- data.frame(a=c(1,2,1,3), b=1:4)
xx$c <- if.else_(
    i_(xx$a==1, xx$b),
    i_(xx$a==2, xx$b*100),
    e_(-xx$b)
) 
xx

a b c
1 1 1
2 2 200
1 3 3
3 4 -4

And the code for the four tests will simply be:

xx$c <- if.else_(
    i_(xx$a==1, xx$b),
    i_(xx$a==2, xx$b*100),
    i_(xx$a==3, ...), # dots meaning actions for xx$a==3
    i_(xx$a==4, ...), # dots meaning actions for xx$a==4
    e_(...)           # dots meaning actions for any other case
) 

Problem 2 & Question

The given code apparently solves the problem. Then, I wrote the following test function:

test.ie <- function() {
    dd <- data.frame(a=c(1,2,1,3), b=1:4)
    if.else_(
        i_(dd$a==1, dd$b),
        i_(dd$a==2, dd$b*100),
        e_(-dd$b)
    ) # it should give c(1, 200, 3, -4)
}

When I tried the test:

 test.ie()

it spit the following error message:

Error in ifelse(dd$a == 1, dd$b, ifelse(dd$a == 2, dd$b * 100, -dd$b)) :
object 'dd' not found

Question

Since the if.else_() syntactic constructor is not supposed to run only from the console, is there a way for it to 'know' the variables from the function that calls it?

Using an else-if statement with in a try-catch-finally

I am trying to use a try-catch-finally statement to error check user input and then advance to the next page if there are no error (I know there's easier ways to do this but I'm being required to use a try-catch-finally). In this case: foo is the user's input, the input needs to be a number between 0 and 100, and displayDiagram() will advance the user to the next page.

Everything works for me up until the finally block. If the user does not enter anything at all, it advances to the next slide. How do I stop it from advancing if nothing has been entered?

Here's the code:

 try {
      if (foo == "") throw "Enter your estimated score";
      if (isNaN(foo)) throw "Only use numbers for your estimated score";
      if (foo < 0) throw "Estimated score is not valid. Enter a higher number";
      if (foo > 100) throw "Estimated score is too high. Enter a lower number";

  }
  catch(err) {
    document.getElementById("fooMessage").innerHTML = err;
    document.getElementById("fooInput").style.borderColor = "red";

  }
  finally {
    if (err = undefined) {
     displayDiagram();
   }
 }

Another finally block I have tried includes:

finally {
        if (preScore >= 0 && preScore <= 100) {
         displayDiagram();
       } else if (typeof preScore != "string") {
         displayDiagram();
        }
      }

Any ideas? Thanks!

When condition inside if statement is fractional

void main(void)
{
    int i;
    for(i=1;i<=5;i++)
    {
if(i/5)
    continue;
        printf("%d",i);
}
}

My simple query is,if the condition inside "if" is evaluated to a fraction,is it treated as 0?As here the output is 1234,so when condition is 1/5,2/5,3/5,4/5 it is prinnting values of i,when 5/5=1 it is executing continue statement.

if statement to determine String or Integer from Scanner(System.in)

Is it possible to implement the commented lines in order to distinguish between an Integer and a String when a user inputs said value into the console? The code works with the rest of my program, but I want the user to be able to input the Employee ID (an int) in addition to name and/or address.

public void query(){

    String newValue;

    System.out.println("Please enter the name, address, or employee "
            + "ID you are looking for");
    Scanner input = new Scanner(System.in);
    //if (Integer.parseInt(input);
        //newValue = input.nextInt();
    //else
    newValue = input.nextLine();
    input.close();

    if (name.equals(newValue) | address.equals(newValue) )
        System.out.println(toString());
    else System.out.println("There is no employee with that name, address, or ID");


}

if else condition with and operator

void main()
{
int i=4,j=12;
if(i=5 && j>5)
    printf("Hi!");
else
        printf("Hello!");
}

First of all,the output of the above code is Hi!.Acording to me it should show a syntax error as i=5 is an assingment operator not i==5,if i==5 then also it is false and should print Hello,but how could it print Hi?

How to use % for float numbers?

I am trying to filter through a float number given by the user and find the largest digit within. However, I keep getting the error:

error: invalid operands to binary % (have 'float' and 'int')

I have read other forums stating us the fmod function, how would I apply that with a simple piece of code that I just want to find the remainder of a float?

Cyclomatic Complexity - Cobol

I have to calculate Cyclomatic Complexity for a Cobol program that contains only an EVALUATE like this one:

EVALUATE x
   WHEN x<0 ...
   WHEN x=0 ...
   WHEN x between 1 and 10 ...
   WHEN OTHER ...`
END EVALUATE.`

I have also to calculate Cyclomatic Complexity for a Cobol program that contains only an IF statement like this one:`

IF x<0 ...
ELSE IF x=0 ...
ELSE ...

What is the algorithm to calculate CC? Thanks for your time.

Next command required For?

I'm not trained in vba and would be very grateful for advice about the following Thanks Geoff

I have 2 columns of data; left date & time, right col with half hourly meter readings. From a start date I need to run down the left column to find the last entry of the first date then copy the readings fromt he right col and paste them into a new sheet as a row & then repeat the process so that the data is in rows by date until I've copied all of the data. I've got a loop to read and compare the date cells row by row & an if statement. I'm getting an error warning that the first " Next a " needs a For.

Within the structure of the code I have :

'do the following until cell in col A is blank ' Select cell startdate, first line of data ' Set loop to stop when an empty cell is reached

     For a = 1 To LastRow Step 1

            checkdate = DateValue("A" & startdaterow + a)

            If startdate = checkdate Then

            Next a

          Else: Range("B" & startdate.Row, "B" & startdaterow + a).Copy

          Sheets("Output").Select

                Range("C" & b + 1).PasteSpecial
                  Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=True

           .Cells(b & "B") = startdate

                b = b + 1

     startdaterow = startdaterow + a
     enddaterow = enddaterow + a
     Range("B" & enddaterow).Select

            Next a

            End If

combining IF with Concatenate to get desired result with a "." between and no spaces

Hi I have Microsoft Office Professional 2013.

I'm using instructions from 2014 to add a formula to a spreadsheet to combine task and subtask into one column. The formula as written returns error #NAME?.

G Col.      H Col.          I Added column to combine 1st and 2nd.
Task Number Subtask Number  TaskSubtask Number
                            (desired result)
1                           1.0
1            1              1.1
1            2              1.2

there are 2624 rows.

most columns in the subtask number are blank. Some have a subtask number.

Here is the formula previously used:

=if(H2=””,concatenate(G2,”.0”),concatenate(G2,”.”,H2))

When I try to use the check formula, and change concatenate to concat the only error is in the first part if(H2="",

I've looked all over, Can you help me? Thanks!

creating an If statement to remove elements from an array

I have a numpy array called stack, lets say 50 by 50, which has a specific value at each positions (for example stack[23, 19] = -0.13). I am trying to create and if statement where if the value at any position is below a certain value, that value is turned into 0. so if stack[23, 19] = -0.13 before the if statement, it would turn into stack[23, 19] = 0 after the statement. So far I have

peaks = stack
if abs(peaks[i, i]) > -1.2 or abs(peaks[i, i]) < 1.2:
    peaks[i, i] = 0

And I wants 'peaks' to retain the same 50 by 50 shape of 'stack', but this doesn't seem to work.

Any help would be appreciated! Thank you!

Creating an if statement for a 2d contour plot to append lowest values

this may be a very simple/dumb question because I'm new to coding but I have a 2d contour plot where there is an X and Y position and also an intensity at each position (Like a 2d plot with a colourbar representing the intensity at each point). I would like to make an if statement where all points below or above a certain intensity get picked out (with their relative X and Y positions) and added to a new list which I could plot later.

I have

peaks = []
if stack[i, j] < -1.0 or stack[i, j] > 1.0:
    peaks.append(i, j)

And i'm just stuck and have no clue where to take it from here.

Thank you!

C# Can't find checkbox in Controls (System.Web.UI.Control)

I'm trying to select the drawings that a user made, so I start like this:

while (reader.Read())
{
    System.Web.UI.WebControls.CheckBox checkb = new System.Web.UI.WebControls.CheckBox();
    DropForm.Controls.Add(new LiteralControl("<br/>Desenho "+ (i +1) +":  "));
    DropForm.Controls.Add(checkb);
    Button1.Visible = true;
    i = i + 1;
}

And when the user clicks the button:

public void Button1_Click(object sender, EventArgs e)
{
    foreach (System.Web.UI.Control control in DropForm.Controls)
    {
        if (control is System.Web.UI.WebControls.CheckBox)
        {
            if (((System.Web.UI.WebControls.CheckBox)control).Checked == true)
            {
                Response.Write("Yes");
            }
            else
            {
                Response.Write("no");
            }
        }
        else
        {
            Response.Write("cicle");
        }
     }
 }

I have 13 Controls on the page so it shows 13 'cicle', but it's not recognizing any checkbox, am I doing something wrong?

AttributeError: 'NoneType' object has no attribute 'lower'

I'm trying to run a python file, but I get this error:

  File "/home/hadi/Software/tensorflow/TEST_FRCN_ROOT/tools/../lib/datasets/pascal_voc.py", line 212, in _load_pascal_annotation
    cls = self._class_to_ind[obj.find('name').text.lower().strip()]
AttributeError: 'NoneType' object has no attribute 'lower'

This is the part of the code which makes the error:

%%  Load object bounding boxes into a data frame.
        for ix, obj in enumerate(objs):
            bbox = obj.find('bndbox')
            # Make pixel indexes 0-based
            x1 = float(bbox.find('xmin').text) - 1
            y1 = float(bbox.find('ymin').text) - 1
            x2 = float(bbox.find('xmax').text) - 1
            y2 = float(bbox.find('ymax').text) - 1
            cls = self._class_to_ind[obj.find('name').text.lower().strip()]
            boxes[ix, :] = [x1, y1, x2, y2]
            gt_classes[ix] = cls
            overlaps[ix, cls] = 1.0
            seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)

Can I add a condition to deal with any none object here?

Using try-catch over if conditions to safely set values with minimum performance impact in java

Here, my main goal is setting the value safely, without having a performance (speed, memory, cpu etc) impact.

I have a silly option (in a bad style) also mentioned below. So, what is the best way to do this? option 1? option 2? or another one?

Option 1 :

if(
    animalData!=null && 
    animalData.getBreedData()!=null && 
    dogx.getBreed() != null && dogx.getBreed().getBreedCode() != null && 
    animalData.getBreedData().get(dogx.getBreed().getBreedCode()) != null
){
    dogx.getBreed().setBreedId(animalData.getBreedData().get(dogx.getBreed().getBreedCode()));
}

Option 2 :

try{dogx.getBreed().setBreedId(animalData.getBreedData().get(dogx.getBreed().getBreedCode()));}catch(Exception e){}

Note : this piece of code is in a loop having many thousands of iterarations.

multiple if/and statement returning #value! error

I need help with a statement that is returning #value!

I need to my statement to work out if both k4 and i4 are blank then it will return the value in H4. However if only k4 is blank then I want it to show the value of i4 minus h4. This is what I have but it isn't working. Please help.

=IF(AND(K4="",I4=""),H4),IF(K4="",I4-H4)

Are `if model.variable` and `unless model.variable.nil?` equivalent?

There are two if-statements to evaluate whether the object is nil.

Method: A

if object
  blahblahblah
end

Method: B

unless object.nil?
  blahblahblah
end

Are A and B identical?

How to Hide and Show a button with if statements

I am trying to make a button visible = false if a quantity in a text box is less than or equal to 0. The problem I am having is that you have to click the button in order to activate the function.

Here is my code so far

        int quantity = int.Parse(textBox33.Text);

        if (quantity <= 0)
            button13.Visible = false;

        if (quantity > 0)
            button13.Visible = true;

do I have to disable the visibility of the text box beforehand?

If no conditions are met, return message

So I'm really new to Java, and what I'm trying to do is let the user input a keyword, which will be passed to different conditions. If the keyword starts with "c", it will execute cmethod. If the keyword starts with "n", it will execute nmethod. The problem is, I also want to display a message if the user inputs neither something that starts with "c" or "n". Here's what I've been able to think through (I'm aware that this code won't work though)

    public static void main(String[] args) {
    System.out.println("This program can randomize characters or numbers.");
    System.out.println("Please input \"c\" for characters, and \"n\" for numbers. ");
    Scanner choices = new Scanner(System.in);

    if (choices.next().startsWith("c")) {
        cmethod();
    }

    else {
        nmethod();
    }

    //how do I execute the code below if none of the conditions are met?
    else {
        System.out.println("Keyword is wrong.");
    }
}

How to minifiy jquery code?

i'm beginner web publisher in Republic of Korea.

[1]Press each button to change the wording.

I want to minimize this code efficiently. Thank you for telling me a lot of ways.

http://ift.tt/2scFVcg

enter code here

If and Else If instruction

I have a directory with doc files (name firstname) For example I have this

Doe John Doe Phil Doe Robert Poe Dameron

I have a listbox with all the persons from a database, I choose a name and I click ‘open file’

My piece of code :

       string fullname = Name + " " + Firstname; 

       string[] allFiles = Directory.GetFiles((Doc_Path));
       foreach (string file in allFiles)
       {
           if (file.Contains(fullname))
           {
               Process.Start(file);
               return;
           }
       // if it cant found fullname, try to open by Name only
           else if(file.Contains(Name)) 
           {
               Process.Start(file);
               return;
           }
       }

My problem :

If I choose Doe Robert it opens Doe John in all case, but it should stop at the first IF instruction

I don't understand even if its the basic of basics :/

After if condition hide two divs

How to hide two divs after true if condition?

if (Auth.getId() > 0) {
    document.getElementById('Div1').style.display = 'none';
    document.getElementById('Div2').style.display = 'none';
} else {
    document.getElementById('Div3').style.display = 'none';
}

It returns div2 and div3, but it should return only div3.

IF Statement with wildcards and text and NOT logic

I am trying to create an array formula that will exclude any values that contain PTIC or Station Mated. Within the data there are various permutations of PTIC and station mated e.g. PTIC heifers, PTIC heifer, PTIC cows etc.

If I write the formula without wild cards and type in all the possible permutations of PTIC and station mated, the formula has worked. However, I want to make it more robust, in case new permutations appear in the future. I've tried this but it hasn't excluded them:

={IF(OR(Results!$K:$K<>"PTIC",Results!$K:$K<>"Station Mated"),1,0)}

Any ideas? Thanks!

dimanche 28 mai 2017

Merge columns where cells have same values, excluding "0"s

I've seen many questions on merging, but nothing that I can manipulate (in my entry-level abilities) to answer this particular question and would be forever be grateful for your expertise and help!!!

I am looking to merge different groups of cells with the same values for particular ranges.

Below is an example of inputs and the desired outcome. I have the file formatted so that the "0"s and "no"s don't show, however the actual descriptions (substituted with like 50% off) are quite long and cannot be viewed in a single cell, hence the need for merge cells to better display information. There are also multiple stores with new stores being added weekly, thus I would like to avoid merging cells manually.

Input

Month January February March April May Store 1 Campaign Period no yes yes yes no Campaign Details 0 50% off 50% off 50% off 0 Store 2 Campaign Period no no no yes yes Campaign Details 0 0 0 spring fling spring fling

Desired Output

Month January February March April May Store 1 Campaign Period no yes yes yes no Campaign Details 0 50% off 0 Store 2 Campaign Period no no no yes yes Campaign Details 0 0 0 spring fling

how to compare a unicode string in model field and choices? django

I am not sure which part I am doing wrong but somehow I am trying to compare two values and I am 100% sure they matches but somehow code would not execute.

Let's say I have this model (please forgive for a bit typos for models and field names)

class TestOne(models):
    gender = models.Charfield(max_length=10, choices=GENDER_CHOICES)

my choices

GENDER_CHOICES = (("MALE", "MALE"), ("FEMALE", "FEMALE"))

I am so sure my gender field is MALE for the object so I am doing this statement as check that if it's MALE do something.

if a.gender is `MALE`:
    # do something here

but it never reaches it as true. I checked a.gender is a unicode type so I even did str(a.gender) to make sure it's also a string but still no luck.

Am I doing anything wrong here?

P.S. I did a print with a.gender and made sure that the output is MALE

Thanks in advance

Why is this happening in python? python if-else statement

The below two if-else statements shows different results.

1

if value in twins:
    tmp = twins[value] + [box]
else:
    tmp = [box]
twins[value] = tmp

2

if value in twins:
    tmp = twins[value] + [box]
    twins[value] = tmp
else:
    tmp = [box]
    twins[value] = tmp

Why is this happening?

How to call a method when a value reaches multiples of 5

I have Firebase database where a number value is stored for a specific user. I want to show an advert when the value reaches multiples of 5, starting at 0.

I can get it to call the method from for the first multiple of 5 using an if statement like this

  if (ads < 5 && dls > 5) {
        Toast.makeText(c,"Testing it worked here",Toast.LENGTH_LONG).show();

How can I edit this so it calls it at 10, 15, 20, 25 and so on?

if statment fails to check a currect value

i have a function that translate a string coordiante to an int number from 0-9 now the function seems to fail to get the string A10(for example) and translte it to 0,9 maybe can some one tell me why?

Point TranslateCoordinate(char* c){
        Point newpoint;
        newpoint=malloc(sizeof(Point));
        int row=c[0];
        int collum;
        newpoint->x=row-'A';
        printf("%c%c\n",c[1],c[2]);
        if(c[1]== '1' && c[2]== '0'){
            newpoint->y=9;
            return newpoint;
        }
        collum=c[1];
        newpoint->y=collum-'1';
        return newpoint;

}

i should note that the values of the string range from 1 to 10 and from A to J

Resolving too many else-if statements in Swift 3

Problem: Given the inputs of the function, test each user to make sure they conform to the following conditions: 1. Each user in the users array cannot share a chatroom with the current user. (The Chatroom object has two properties 'firstUserId', and 'secondUserId'.
2. Each user in the users array is not the current user. 3. Each user in the users array is within 5 mile radius of current user.

At the call sight of the completion handler, I check if a User object has a value of true, if so, I show it to the current user as a potential match.

Now, I quickly brute forced this solution, but cringe every time I look at it. It just seems very inefficient. Any tips on a more elegant solution is much appreciated!

typealias validUsersCompletionHandler = (_ users: [User: Bool]) -> Void

private func validateNewUsers(currentUser: User, users: [User], chatrooms: [Chatroom], completionHandler: validUsersCompletionHandler?) {

    var results: [User: Bool] = [:]

    let currentUserCoords = CLLocation(latitude: currentUser.latitude, longitude: currentUser.longitude)

    for user in users {
        let newUserCoords = CLLocation(latitude: user.latitude, longitude: user.longitude)
        let distance = currentUserCoords.distance(from: newUserCoords)
        // // 1 mile = 1609 meters, 8046.72 = 5 miles.
        for chatroom in chatrooms {
            if currentUser.id == chatroom.firstUserId && user.id == chatroom.secondUserId {
                results[user] = false
            } else if currentUser.id == chatroom.secondUserId && user.id == chatroom.firstUserId {
                results[user] =  false
            } else if user.id == currentUser.id {
                results[user] = false
            } else if distance > 8046.72 {
                results[user] = false
            } else {
                results[user] = true
            }
        }
    }
    completionHandler?(results)
}

Combining 'for' loop with if-else statements with multiple conditions inside each 'if' statement

I have a dataframe as follows with 4 character columns

df <- data.frame(2016=c("light", "", "", "", ""), 2017=c("radio", "", "", "", ""), after2017=c("", "Utility grid connection for lighting", "", "", "light"), dkcs=c("", "", "TV", "TV", ""))

I want to create a 5th column, "db" such that it has a value 0 if either all 4 columns are empty for that row or the value of the column "contains" the string "Utility grid", otherwise value of "db" is 1.

I wrote the following code which runs but it is giving all values of db as 1 irrespective of whether it should be 0. The code works correctly if I remove the 'or' condition inside the 'if' condition. What do you think is wrong? Also is the way I am using "contains" correct? I appreciate your help!

for(i in 1:nrow(df)) {

  if(df$2016[i]!= "" | df$2016H2[i]!= "Utility grid.") {
    df$db[i] <- 1
  } else if (df$2017[i]!="" | df$2017[i]!="Utility grid.") {
    df$db[i] <- 1
  } else if (df$after2017[i]!="" | df$after2017[i]!="Utility grid.") {
    df$db[i] <- 1
  } else if (df$dkcs[i]!="" | df$dkcs[i]!="Utility grid.") {
    df$db[i] <- 1
  }
  else df$db[i] <- 0
}

Scala: if inside match case

Is there any way to put a if inside a match case in scala?

Something like this:

def createSchedules(listTask: List[TaskOrder], physicalResources: List[Physical], humanResources: List[Human], previousTime: Duration): List[TaskSchedule] = listTask match {
    case TaskOrder(id, time, physicalRes, order) :: t =>
      val taskScheduleHumanResources = setHumanResources(physicalRes, humanResources)
      if (physicalRes != null) 
        new TaskSchedule(
          order, 
          order.getProduct(), 
          Task(id, time, physicalRes), 
          physicalRes, 
          taskScheduleHumanResources, 
          order.quantity, 
          previousTime, 
          previousTime + time) :: createSchedules(t, physicalRes, humanResources, previousTime + time)
    case Nil => Nil
  }

Doing that I get an error saying:

type mismatch; found : Unit required: List[Objects.TaskSchedule]

What would be the best way to do it?

recursion and if-else satement

Am new to programming I am trying to use recursion and if-else statement only to print the 99 beers lyrics. here is my code.How can i make it better, to print the lyrics well.

public static void countdown(int n)
{   
    if (n== 0){
        System.out.println ("no beers");
    }
      else{
          System.out.println ("more beers");
          countdown(n-1);
        }
}

public static void countdownB (int x)
{   
    if (x==0){
        System.out.print ("");
    }
      else{
          System.out.print (x);
          countdownB (x-1);
        }
}



public static void main (String[] args)
{

   countdownB (3);
   countdown (3);

}

Modify object properties in javascript if condition applies

Game

So i'm making a game, if i catch the ball i should go to the next level and the plank under the cat should go lower.

this is my plank object.

 var Plank = function (c, top, fill) {
                this.left = 20;
                this.top = top;
                this.width = c.width - 52;
                this.height = 6;
                this.fill = fill;
                this.draw = function () {
                    var rectangle = new fabric.Rect({
                        left: this.left,
                        top: this.top,
                        fill: this.fill,
                        width: this.width,
                        height: this.height
                    });
                    rectangle.selectable = false;
                    c.add(rectangle);
                };
            };

I make a new object instance.

var plank = new Plank(canvas, canvas.height / 4 + 20, '#FFFF00');
        plank.draw();

And here's how i define what's gonna happen if the ball gets caught.

function checkBalls() {
        for (var i = 0; i < balls.length; i++) {
            console.log(balls);
            var ball = balls[i];



            var x = ball.pokeBall.left;
            var y = ball.pokeBall.top;


            if (ball.hasFallen) {
                //remove from array
                ball.pokeBall.ball = null;
                balls.splice(i, 1);
            }
            if (y > 400 && ball.hasFallen == false) {
                var pikaPosition = somePika.pika.left;
                var pikaPadding = 50;

                var plankpos = plank.top;

                if ((pikaPosition - pikaPadding) < x && x < (pikaPosition + pikaPadding)) {
                    ball.hasFallen = true;
                    score++;
                    plankpos =+ 30;
                    elScore.textContent = score;

                        if (score == 2) {
                            alert("UP TO LEVEL 2! CATCH 10 MORE POKEBALLS.");
                            planktop += 10;


                        }

                        else if (score == 4) {
                            alert("LEVEL 3! NICE!");
                              planktop += 10;
                        }

                        else if (score == 6) {
                            alert("YOU WIN, CONGRATULATIONS!");
                            document.location.reload();
                        }
                }
            }
        }
    }

But for some reason i can't get the plank to move when i call its property.

Excel - IF AND formula not working

Love this website been using it for years, but I have come to a point where I am struggling with my formula.

What I am trying to achieve:

If disposal date = "NO" AND contractdate

If disposal date = "NO" AND contractdate>start date, =YearEnd-Contractdate+1

IF disposal date ="YES", AND ContractDate

IF disposal date ="YES", AND ContractDate>StartDate, =DisposalDate-contractDate

My actual formula is:

=IF(AND(DisposalDate="NO",ContractDateStartDate),YearEnd-ContractDate+1),IF(AND(DisposalDate="YES",ContractDateStartDate),DisposalDate-ContractDate,0))

If light BackColor then white ForeColor - VB.net

so I'm trying to make it so that text over the BackColor will change depending on how Light/dark the BackColor is, so that you can see the text.

So say I pick a dark color then the text should be white, but if I pick a white color then the text should be dark.

This is what I have done so far but it doesn't seem to work:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  
 Using colorDialog As New ColorDialog
            If colorDialog.ShowDialog() = DialogResult.OK Then
                My.Settings.TextBackground = colorDialog.Color
                UpdateTextBack(sender, e)
            End If
        End Using
End sub
 Private Sub UpdateTextBack(sender As Object, e As EventArgs)
        HTML_Edit.RichTextBox1.BackColor = My.Settings.TextBackground
        Text_Edit.RichTextBox1.BackColor = My.Settings.TextBackground
        Button2.BackColor = My.Settings.TextBackground
        If My.Settings.TextBackground.GetBrightness < 0.5 Then
            Button1.ForeColor = Color.White
        Else
            Button2.ForeColor = Color.Black
        End If
    End Sub

python If and in statement

so i'm writing a code that is checking if input is in two seperate places. one being a dictionary and another being a list. my code is something like this:

a_list = ['north', 'south', 'east', 'west']
a_dictionary = {'north', 'south'}

action = input(">>")
action = action.lower().pop(0)
if action in a_list and action in a_dictionary:
    print("you move %s." % action)
else:
     print("you are confused.")

obviously this is a simplified version of what i have but that is the mainly what i'm doing. my problem is that it only seems to be checkin the first in statement and will 'move' even when both conditions aren't met. or if the positions are swapped it will use the else statement everytime. i also tried this:

if action in a_list:
    if action in a_dictionary:
        print("you move %s." % action)
    else:
        print("you are confused.")

didn't seem to help. just uses else statement.

samedi 27 mai 2017

Add a column with an image of the invoice status Canceled or open c#

I want to put a cell in every row I have a cell that contains an invoice if it is open I want to display a certain picture and if it is closed I want to display another picture in cell

this is my code but I have Problems

error pic

this.dgvBills.DataSource = bill.SearchBills(txtSearch.Text, coBoxState.Text);
                DataGridViewImageColumn img = new DataGridViewImageColumn();
                img.Name = "img";
                img.HeaderText = "Image Column";
                img.ValuesAreIcons = true;
                dgvBills.Columns.Add(img);
                int number_of_rows = dgvBills.RowCount;
                for (int i = 0; i < number_of_rows; i++)
                {
                    if (dgvBills.Rows[i].Cells[11].Value.ToString() == "open")
                    {

                        dgvBills.Rows[i].Cells["img"].Value = pbox.Image;
                    }
                    else
                    {

                        dgvBills.Rows[i].Cells["img"].Value = pbox.InitialImage;
                    }

How to delete specific line from text file by user input?

I have a text file that stores and outputs data line by line. How can I take an input from the user to delete a specific line of data in the text file?

Adding an element on specific rows of a grid using Tkinter

Is there a way to add a button in specifics rows on a grid using Tkinter toolkit?

I am currently trying to get a grid setup like this, where the red rectangles are the elements of the grid (buttons). As you can see, the second line has one additional button compared to the first, and so on.

So, am looking for a way to display one additional button to specifics rows in my grid, if possible.

Here is the code :

import sys
import tkinter as tk
from tkinter import * 


fenetre = Tk()

#frame 1
Frame1 = Frame(fenetre, borderwidth=2, relief=GROOVE)
Frame1.pack(fill=BOTH)

#frame2
Frame2 = Frame(fenetre, borderwidth=2, relief=GROOVE)
Frame2.pack(fill=BOTH)

#affichage du tableau
def afficheGrille():

    tailleGrille=(int(s.get()))

    for ligne in range((tailleGrille * 2) +1):
        for colonne in range(tailleGrille):
            if(ligne == 0 or (ligne % 2) == 0):
                #boutons horizontaux
                Button(Frame2, borderwidth=1, height=1, width=8).grid(row=ligne, column=colonne)
            else:
                #boutons verticaux
                Button(Frame2, borderwidth=1, height=5, width=2).grid(row=ligne, column=colonne)



label = Label(Frame1, text="Jeu du carré")
label.pack()

boutonJvIA=Button(Frame1, text="1 joueur vs IA", width=30, command=afficheGrille)
boutonJvIA.pack()

boutonJvJ=Button(Frame1, text="1 joueur vs 1 joueur", width=30, command=afficheGrille)
boutonJvJ.pack()

s = Spinbox(Frame1, from_= 0, to = 100)
s.pack()



fenetre.mainloop()

Thank you by advance

If statement checks time differences

I'm trying to create an if statement that checks if there has been less than 48 hours since the creation of an order, i.e. COrderDate ,and there is still more than 48 hours until the delivery date. i.e. CDeliveryDate

 if (order.COrderDate < 48 hours since DateTime.Now && DateTime.Now < 48 hours from order.CDeliveryDate)

Pandas Throwing Error in Loop Using If/Then/Else Statement

I have a strange error occurring that I can't figure out.

Hoping for some help.

I have an if statement in my code as follows:

if my_df.ix[my_df['SOMEINTEGER'] == another_df.ix[i,'SOMECOMPARABLEINTEGER'],'SOMECOLUMN'] == 'I':

    *** DO SOMETHING ***
    i+=1

What this statement does is choose the row in my_df where 'SOMEINTEGER' equals the integer value in another_df.ix[i,'SOMECOMPARABLEINTEGER'] and check to see if the column value in 'SOMECOLUMN' in my_df is equal to 'I'

If I run the if statement as a single line of code with the value i set to an integer corresponding to a dataframe index value it works.

If I include this if statment in a larger iteration (and similiarly move the incrementing i out so it increments properly I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I'm unable to isolate the source of the error.

Any help/insight appreciated.

Thanks in advance.

How can i use a var in c# over {}

How can i use a var in c# over {} like:

if
{
   var test;
   while
   {
      test = "12345";
      //test is defined
   } 
   var test2 = test;
   //test is undefined
}

I do not understand it.

My batch code skips past if statements

NOTE: This is not a duplicate because the other questions I found are not the same goal as mine and is a different if statement.

I wanted to make a batch file that can remember your name, even after being closed. It saves the name in a text file and then reads from it. My question is it skips past my first if statement. Why does it do this? When I type y it goes to :no. I think this is because right after the if statement is the :no part, but what am I doing wrong? If you don't understand this, just copy this code and paste in notepad and then save as ANYTHING.bat and run it, and you'll see what I mean.

Anyway, here is the code:

@echo off
title The logger
echo NAME> log1.txt
set /p name=<log1.txt

:start
cls
echo Your name is %name%, right? (Y/N)
set /p input=
if %input%=="Y" goto yes
if %input%=="y" goto yes
if %input%=="N" goto no
if %input%=="n" goto no

:no
echo Oh... then what is it?
set /p name=
echo OK! Thanks, %name%
echo %name%>log1.txt
pause
goto start

:yes
echo hahahaha i knew it
echo Would you like to change it? (Y/N)
set /p input=

if %input%=="Y" goto namechange
if %input%=="y" goto namechange
if %input%=="N" (
    echo Ok.
    pause
    goto start
)
if %input%=="n" (
    echo Ok.
    pause
    goto start
)
goto start

:namechange
echo What should it be?
set /p name=
echo %name%>log1.txt
echo Thanks, %name%
pause
goto start

How to make an if function work in a tkinter output box

The premise of my code is to ask for a password and the tkinter gui will return whether it thinks that it is secure or not. However, I cannot seem to get the if function displayed in the output box. Here is the code:

from tkinter import *

password = Tk()
password.title('Password tester')

Label(password, text="Password:").grid(row=1, column=0, sticky=W) 
entry= Entry(width=20, bg='light blue')
entry.grid(row=2, column=0, sticky=W)

def click():
entered_text = entry.get()
Button(password, text='SUBMIT',width=5
command=click).grid(row=3,column=0, sticky=W)

Label(password, text='\n\nPassword strength:').grid(row=4, column=0, sticky=W)

output = Text(password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)

if Label == 'password':
     print('This is a very insecure password.') in output

How can I get this function into the output box?

Two very similar object.extend() codes to fill a list, one works one does not

The program below should put words in a list. The test for it to work is 'print(allwords[1])'. Funny thing is that the bottom part works, but when I use the top part it does not. The list apparently stays empty. How is what I am doing any different?

# DOES NOT WORK
print ('On what difficulty do you want to play?\n')
diffculty = input('1.Easy\n2.Medium\n3.Hard\n\n')
if diffculty == 1 or input == 'Easy' or input == 'easy' or input == 'EASY':
    with open('google-10000-english-usa-no-swears-short.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))
elif diffculty == 2 or input == 'Medium' or input == 'medium' or input == 'MEDIUM':
    with open('google-10000-english-usa-no-swears-medium.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))
elif diffculty == 3 or input == 'Hard' or input == 'hard' or input == 'HARD':
    with open('google-10000-english-usa-no-swears-long.txt') as inputfile:
        for line in inputfile:
            allwords.extend(line.strip().split(','))

# WORKS
print ('Okay then, let us begin with your first word.\n')
with open('google-10000-english-usa-no-swears-long.txt') as inputfile:
    for line in inputfile:
        allwords.extend(line.strip().split(','))

print (allwords[1])

multiple if statements used to update database entries

Have the following:

if ($row['college4'] == null) {
                        $sql = "UPDATE colleges SET college3 = NULL, sports3 = NULL";
                    }
                    if ($row['college3'] == null) {
                        $sql = "UPDATE colleges SET college2 = NULL, sports2 = NULL";
                    }
                    if ($row['college2'] == null) {
                        $sql = "UPDATE colleges SET college1 = NULL, sports1 = NULL";
                    }

Essentially, if a specific column in the database equals NULL, then set the preceding column to NULL. The prior coding works, however, only for the most recent if statement (In this case, college2). Once that executes, the remaining if statements are ignored (i.e. college 4 and college 3.

If more explanation is needed please let me know. I think I am just looking for a how to on having the sql queries recognize in a cascading manner. Thanks.

jquery each if statement addclass

I am trying to select all portlet elements that are due today and add them to the class highlight. The problem is, that it adds the class to all portlet elements if it finds one that is due today, not only to the due portlet. It doesn´t work neither with a for loop, nor with the jQuery each().

$("#todayBugs").click(function (){
    var d = new Date();
    var portlet = $(".portlet");
    var twoDigitMonth = ((d.getMonth().length+1) === 1)? (d.getMonth()+1) : '0' + (d.getMonth()+1);
    var today = (twoDigitMonth + '/'  + d.getDate() + '/' + d.getFullYear());
    /*for(var i=0; i<=count; i++) {
        if(today == $("#datepicker").val()) {
            $(portlet[i]).addClass("highlight");
        }
    }*/
    $(portlet).each(function () {
        if(today == $("#datepicker").val()) {
            $(this).addClass("highlight");
        }
    })
});

Why condition returns True using regular expressions for finding special characters in the string?

I need to validate the variable names:

name = ["2w2", " variable", "variable0", "va[riable0", "var_1__Int", "a", "qq-q"]

And just names "variable0", "var_1__Int" and "a" are correct.

I could Identify most of "wrong" name of variables using regex:

import re
if re.match("^\d|\W|.*-|[()[]{}]", name):
    print(False)
else:
    print(True)

However, I still become True result for va[riable0. Why is it the case? I control for all type of parentheses.

SQL Server - What is the correct syntax?

Do I write the correct syntax?

pseudo code


select * from products
if @value is not null begin where category = @value end
+ if @value is not null begin where other1 = @value1 end
+ if @value is not null begin where other2 = @value2 end
+ if @value is not null begin where other3 = @value3 end

I am noob. I do not want to write a dynamic query. How to write the above query?

If Condition doesn't work with fgets (STDIN) in PHP

When I use fgets (STDIN) and enter "Yes" in the console, it doesn't return "Works" why? What am I doing wrong?

enter image description here

Else if statement executing unexpectedly, behaving as else statement [duplicate]

This question already has an answer here:

I'm working on a simple function to convert ascii codes to array indexes, and I'm have a bit of trouble with the else-if statement.

int getIndex(char character) {
    int code = int(character);
    int index = -1;

    if (code == int(' ')){
         index = 26;
    }  else if (int('a') <= code <= int('z')) {  
        index = code - int('a');
    }     
    return index;
}

The if condition works fine and fires on spaces, but the else if statement fires in every other case, regardless of whether the character is in the range a to z or not. Is there a problem I can't see with the condition?

Python inline if statement

Could someone help me with the syntax of the following or tell me if it is possible or not? As I am going to modify the inline IF condition, I don't want to add duplicated values in the list, but I got a KeyError. Please give me any ideas for a workaround.

Actually, I am not familiar with this kind of statements:

twins[value] = twins[value] + [box] if value in twins else [box]

what does this exactly mean?

Thanks in advance.

sample code

    #dictionary
    twins = dict()                  
    #iterate unitlist
    for unit in unitlist:                                              
        #finding each twin in the unit
        for box in unit:                            
            value = values[box]                               
            if len(value) == 2: 
                twins[value] = twins[value] + [box] if value in twins else [box]

I modified the condition

    #dictionary
    twins = dict()                  
    #iterate unitlist
    for unit in unitlist:                                              
        #finding each twin in the unit
        for box in unit:                            
            value = values[box]                               
            if len(value) == 2:                            
                if value not in twins:                    
                    twins[value] = twins[value] + [box]

if statement (jQuery)

I'm unable to figure out what is causing 10 that keeps to be displayed red. Other numbers are displaying like it should, but only on number 10 if statement fails to compare proper value.

$( document ).ready(function() {
$("thead tr td:nth-child(3)").each(function(){

    var compare = $(this).text()

        if( compare == 'null' ) {
             $(this).text('No rating found').parent('tr').addClass("table-danger");
        }
          else if ( compare <= '5' ) { //Number 10 keeps comparing whit this statement       
                        $(this).parent('tr').addClass("table-danger");    
          }
          else if ( compare > '5' &&  compare < '7' ) {       
                        $(this).parent('tr').addClass("table-info");    
          }
           else if ( compare >= '7' ) {       
                        $(this).parent('tr').addClass("table-success");    
          }
     });
});

Something is wrong whit first else if statement.

Live Demo: http://ift.tt/2s0UWyv

SQL (1064) : IF

1064 error when executing query with the following code:

IF (SELECT COUNT(*) FROM arrest WHERE player = 0) > 0 THEN SELECT * FROM arrest END IF

Can anyone help me please with getting this to the right format? Thank you very much!

vendredi 26 mai 2017

swift if statement

I have an if statement in swift that I can not figure out how to set up. I want to check two variables and check if they do not equal a certain value, The variable that does not equal the certain value should be set to a new variable.

if (message.ReceiverId != self.loggedInUserUid  || message.senderId != self.loggedInUserUid) {

//Print the variable that is not equal to the loggedInUserUid
//and set it to a variable.

}

if statements not properly giving right answer on strings

SO everytime i run this code I basically get random ratios for my tax, even when i type in 'washington' for strState

def main():

strState = input(str("Please enter a state: "))

fltSubtotal = 21

print(strState)

fltTax = 0.0

if strState == 'oregon' or 'florida':
    fltTax += (fltSubtotal * .00)

    if strState == 'washington' or 'california' or 'texas':
        fltTax += (fltSubtotal * .09)

else:
    fltTax += (fltSubtotal * .07)

print(fltTax)

main()

For in Python stops working after raw_input

I am creating a program where the hero saves two hostages in 10 seconds. The first things he needs to do is decide who to save first, then type the code for bomb to rescue the hostage, if the user types the name of the hostage wrong he can type it again. But after I type wrong once the loops stops or after i finnished saving the first hostage the loop stops.

This is the code:

holly = True
molly = True

for i in range(0,11):
    print "Who will you save?"
    print "Time paste:", i

    decide = raw_input("> ")

    if decide == "Holly" and holly:
        print "You decided to save Holly."
        print "Whats the code?"
        code = random.randint(100,1000)
        print code
        decide = int(raw_input("> "))
        if decide != code:
            exit('You are dead!')
        print "You saved Holly!"
        holly = False
    elif decide == "Molly" and molly:
        print "You decided to save Molly."
        print "Whats the code?"
        code = random.randint(100,1000)
        print code
        decide = int(raw_input("> "))
        if decide != code:
            exit('You are dead!')
        print "You saved Molly!"
        molly = False
    elif not holly and not molly:
        print "You saved both of them!"
        break
    else:
        print "Try again!"

Increase the size of the height of a label (swift3)

In a if else statement I am increasing the height of my scrollview like this.

 THESCROOL.contentSize.height = 5000

I would like to do this exact same thing with a label that is above the sol view. Labels name is entry.

 //somehow make entry's height 5000
entry

for loop + 2 else if R

I'm having problems puting two if...else inside my for loop. I have a condition for my if...else. But in any of both cases, I want to do the second part of the code. But for the moment I think I'm only doing the second part if I'm on my first ELSE :

for (i in 2:M){

  #####  1  #####

  theta.prop_1 = theta[i-1,1] + rnorm(1,0,sd.prop)
  theta.prop = c(theta.prop_1, theta[i-1,2:4])
  prob = min(1, exp(lpost(theta.prop) - lpost(theta[i-1,])))
  accept1 = (runif(1) <= prob)
  if (accept1){
    n.accept1 = n.accept1 + 1
    theta[i,] = theta.prop
  }
  else theta[i,] = theta[i-1,]

  #####  2  #####

  theta.prop_2 = theta[i-1,2]+
    rnorm(1,0,sd.prop)
  theta.prop = c(theta[i,1], theta.prop_2, theta[i-1,3:4])
  prob = min(1, exp(lpost(theta.prop) - lpost(theta[i-1,])))
  accept2 = (runif(1) <= prob)
  if (accept2){
    n.accept2 = n.accept2 + 1
    theta[i,] = theta.prop
  }
  else theta[i,] = theta[i-1,]
}

(Not sure if my english was clear enough)

Is there a way in MySQL to execute a result set from information_schema

This gives me a list of queries I would like to execute:

select CONCAT('ALTER TABLE ',table_name,' DROP edit_time;') AS query FROM information_schema.COLUMNS    where column_name = 'edit_time' AND table_schema = 'homestead';

Result:

|query|
ALTER TABLE node_fields DROP edit_time;
ALTER TABLE node_list_role DROP edit_time;
ALTER TABLE node_list_versions DROP edit_time;
ALTER TABLE node_lists DROP edit_time;
.. (etc) ..

This returns rows of all tables that I want to drop that field on. But is there any way to do something like:

EXECUTE {that query}

or

FOREACH {results of that query} EXECUTE( {that row} )

I don't know mysql procedures or logical statements that well so this is new to me.

When i try to use method it give error

i have a switch statement in which i try to check for string values, i want that after checking for name it should ask for marks. But when i try to make an if else statement in a method it gives error.

here is the code which runs fine :

  import java.util.Scanner;
public class java {
    public static void main(String args[])
    {
        Scanner obj=new Scanner(System.in);
        int num;
        final int pass=33;
        String Student;
        System.out.println("Please enter your name");
        Student=obj.nextLine();
        switch(Student)
        {
        case "Ram":
            System.out.println("Students name is "+ Student);
            break;
        case "Shyaam":
            System.out.println("Students name is "+ Student);
            break;
            default:
                System.out.println("This name is not recognised");

        }


            System.out.println("Enter your marks");
            num=obj.nextInt();
            if(num<pass)
            {   
                System.out.println(Student+" You have failed the subject");
            }   

            else
            {
                System.out.println(Student+" You have passed the subject");
            }
    }


}
}

but in this even if name does not get verified it still ask for marks.

what should i do. Please help.