mardi 30 juin 2015

which way is correct way of checking not null variable

Which is the more effective way of checking $value is not null

if ($value > 0 && $value !== 'null') { }

OR

if (empty($value)) { }

Why isn't the function being called in the if statement? (python)

I have recently begun learning programming and more specifically python. I am a total beginner and I started working on my first small project of converting inches and pounds. I can't figure out why the function isn't being called in the if statement. Please help! Thanks.

# Convert inches to centimeters and pounds to kilograms


# Converts inches to centimeters
def convic():
    amti = raw_input("How many inches? **Integers only!** ")
    if amti.isdigit():
        amti = int(float(amti))
        centi = amti * 2.54
        print "%d inches equals %d centimeters." % (amti, centi)
    else:
        print "Sorry that is not a number and/or integer."

# Converts pounds to kilograms  
def convpk():   
    amtp = raw_input("How many pounds? **Integers only!** ")
    if amtp.isdigit():
        amtp = int(float(amtp))
        kilo = amtp * 0.45359
        print "%d pounds equals %d kilograms." % (amtp, kilo)
    else:
        print "Sorry that is not a number and/or integer."

answer = raw_input("Would you like to convert inches to centimeters or    pounds to kilograms? ")   
if answer == "inches to centimenters":
    convic()
if answer == "pounds to kilograms":
    convpk()

# Not a correct response        
else:
    while answer != "inches to centimeters" and "pounds to kilograms":
        answer = raw_input("Sorry please enter inches to centimeters or  pounds to kilograms. ")
        if answer == "inches to centimenters":
            convic()
        if answer == "pounds to kilograms":
            convpk()

Switching which XML file is parsed in Jquery using radio form

I am trying to change which dropdown menu is populated depending on which radio button I choose. The data for each dropdown menu is located in a different XML file. I am trying to use if-else statement to select which xml file i use, but after using alert(saddress);I discovered that changing the radio form does not even engage the else statement. Do any of you have an idea why?

Here is my JS `$(document).ready(function(){

if($('input[name=EMVAD]:checked','#usrform').val()==$('#SenatorCheck').val()){

$.ajax({
    type: "GET",
    url: "senators_cfm.xml",
    dataType: "xml",
    success: function(xml) {

        $('#StateSelect').change(function(){
            $('#SenatorSelect').empty();
            $('#HouseSelect').empty();
            var state = $(this).val();
            var select1 = $('#SenatorSelect');
            var SAD = $('#SenatorAddress');
            select1.append('<option value="Select a senator">Select a Senator</option>');
        $(xml).find('member').each(function(){
            if(state == $(this).find('state').text()){
            var fname = $(this).find('first_name').text();
            var lname = $(this).find('last_name').text();
            select1.append("<option>"+fname+"&nbsp"+lname+"</option>");
            var saddress = $(this).find('address').text();
             SAD.val(saddress);

        }




                });

        });
    }

});
}else if($('input[name=EMVAD]:checked','#usrform').val()==$('#HouseCheck').val()) {

$.ajax({
    type: "GET",
    url: "MemberData.xml",
    dataType: "xml",
    success: function(xml) {

        $('#StateSelect').change(function(){
            $('#SenatorSelect').empty();
            $('#HouseSelect').empty();
            select1.empty();
            var state = $(this).val();
            var select1 = $('#SenatorSelect');
            var HAD = $('#HouseSelect');
            HAD.append('<option value="Select a House Representative">Select a House Representative</option>');
        $(xml).find('member-info').each(function(){
            if(state == $(this).find('state postal-code').text()){
            var name = $(this).find('official-name').text();
            HAD.append(name);
            var saddress = $(this).find('address').text();
             HAD.val(saddress);
             alert(saddress);

        }




                });

        });
    }
});}

}); `

Here is my html: <select id="SenatorSelect" name="senatornames" form="usrform"></select> <select id="HouseSelect" name="housenames" form="usrform"</select> <input onclick= id="StartButton" name="Start" type="button" value="Begin!" />

Lastly, here is the sample xml from the else statement code: <members> <member> <statedistrict>AK00</statedistrict> <member-info> <namelist>Young, Don</namelist> <bioguideID>Y000033</bioguideID> <lastname>Young</lastname> <firstname>Don</firstname> <middlename/> <sort-name>YOUNG,DON</sort-name> <suffix/> <courtesy>Mr.</courtesy> <prior-congress>113</prior-congress> <official-name>Don Young</official-name> <formal-name>Mr. Young of Alaska</formal-name> <party>R</party> <caucus>R</caucus> <state postal-code="AK"> <state-fullname>Alaska</state-fullname> </state> <district>At Large</district> <townname>Fort Yukon</townname> <office-building>RHOB</office-building> <office-room>2314</office-room> <office-zip>20515</office-zip> <office-zip-suffix>0200</office-zip-suffix> <phone>(202) 225-5765</phone> <elected-date date="20141104">November 4, 2014</elected-date> <sworn-date date="20150112">January 12, 2015</sworn-date> </member-info> <committee-assignments> <committee comcode="II00" rank="2"/> <committee comcode="PW00" rank="2"/> <subcommittee subcomcode="II10" rank="2"/> <subcommittee subcomcode="II13" rank="2"/> <subcommittee subcomcode="II24" rank="1" leadership="Chairman"/> <subcommittee subcomcode="PW05" rank="2"/> <subcommittee subcomcode="PW07" rank="2"/> <subcommittee subcomcode="PW12" rank="2"/> </committee-assignments>

Php Array Count to run script run for each reply till 3rd reply and not more than that

I have a Forum in which adscript is displayed after every reply

<?php if( count( $replies ) <= 3 ){ ?>

---- script ----

<?php } ?>  

Earlier there was a clause that there could be maximum 3 replies per Forum post - but now that clause is changed and there are 5, 7 or 10 replies even

I want to modify code so EVEN If there are more than 3 replies - then script should run after each reply till 1st 3 replies and not from 4th reply onwards

I believe an array is to used likely

<?php
$replyCount = 0;
foreach( $replies as $reply )
{
$replyCount++;
$replyNumber = array(1, 2, 3);

if (in_array($replyCount, $replyNumber)) {
echo "script";
}
?>

But - what the above script is doing is that

Its displaying the script in all replies

Its displaying script 3 times after each reply

Can some one help and advise in modification so that

Script should run once after each reply

Script should run till 3rd reply and not more than that

Pls help and advise

Codeigniter Controller View table->add_row "if else statement"

Its been a few days I am stuck with this. I am trying to add different views in add_row function in my Codeigniter Controller.

What we have done recently is; adding new type of memberships to Business Directory. So one is called gold membership one is normal membership. Gold Membership to show more info of different info than normal members.

Here is existing code for my controller:

$checkAllData = array("name"=>"action_to_all","id"=>"action_to_all","onclick"=>"toggleChecked(this.checked)" );

    // table  headder
    $this->table->set_heading("Logo",
          "Company Name",
          "Membership Type",
          "Address - Phone Number"
        );

    $i = 0 + $offset;

    foreach ( $companies_list as $dataList) {
    $checkBox = array("name"=>"action_to[]","id"=>"action_to[]", "class"=>"checkbox", "value"=>$dataList->id );
    $this->table->add_row(
    anchor(base_url()."business/view/".$dataList->id."/".$this->MCommon->seo_url($dataList->business_name),
    '<img src="'.base_url().$this->image_path.$dataList->image.'" />' ,array("class"=>"list_action_view")),

    anchor(base_url()."business/view/".$dataList->id."/".$this->MCommon->seo_url($dataList->business_name),$dataList->business_name, array("class"=>"list_action_view")).$this->commonlib->setValue($this->business_type_list, $dataList->business_type_id),

    $dataList->membership_type,

    $dataList->address.$dataList->tel_no
        );
    }

What I want to do is to display a basic Logo and no address to display for normal members. Something like this:

// table  headder
    $this->table->set_heading("Fotoğraf",
          "Company Name - Sector",
          "Membership Type",
          "Address - Phone Number"
        );

    $i = 0 + $offset;

    foreach ( $companies_list as $dataList) {
    $checkBox = array("name"=>"action_to[]","id"=>"action_to[]", "class"=>"checkbox", "value"=>$dataList->id );
    $this->table->add_row(

    **if($datalist->membership_type==gold_member) {**

    anchor(base_url()."business/view/".$dataList->id."/".$this->MCommon->seo_url($dataList->business_name),
    '<img src="'.base_url().$this->image_path.$dataList->image.'" />' ,array("class"=>"list_action_view")),

    anchor(base_url()."business/view/".$dataList->id."/".$this->MCommon->seo_url($dataList->business_name),$dataList->business_name, array("class"=>"list_action_view")).$this->commonlib->setValue($this->business_type_list, $dataList->business_type_id),

    $dataList->membership_type,

    $dataList->address.$dataList->tel_no

    **}
    else    
    {
    'Set New View'
    }**
        );
    }

We called Membership Types as "membership_type" which are gold_member and normal_member.

Thank you for any clue that you can give me

How to create a new column of data in R with if statements?

I want to create a new column D of data where:

  • if column A is less than 5, then column D = column A
  • if column A is = 5, then column D = 0
  • if column A is = 6, then column D = column B

What would be the syntax?

Nested SEARCH and IF grid

Column A lists the categories for individual products. Each product will have between 1 to 14 categories. The goal is to split all categories into separate cells (Columns B through O), to become easier to sort.

I've created formulas for columns B through O, to SEARCH for hyphens "-" and separate each category into its own column. Here's what the output should look like (except for the bottom row):

A                       B       C       D       E       F       G       ...     O
Categories              Cat 1   Cat 2   Cat 3   Cat 4   Cat 5   Cat 6   ...     Cat 14

UX                      UX      
CFT-WET                 CFT     WET 
WEM-US-CFT              WEM     US      CFT
NC-US-CFT               NC      US      CFT
TP-OB-SB-WEB            TP      OB      SB      WEB
DB-B-FC                 DB      B       FC
P-TP-SB-CP-DT           P       TP      SB      CP      DT
DP-S-OB-WB-SB-FC DP     S       OB      WB      SB      FC
P-TP-SB-CP-WEB-WS-S-TP-OB-C-CT-G-FC-MCB

I initially built these formulas:

Col B:  =if(iserror(search("-",$A5)),$A5,search("-",$A5))
Col C:  =if(iserror(search("-",$A5,sum(search("-",$A5)+1))),"",mid($A5,sum(search("-",$A5),1),sum(search("-",$A5,sum(search("-",$A5)+1)),-search("-",$A5),-1)))
Col D:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5)+1)+1),-search("-",$A5,search("-",$A5)+1),-1)))
Col E:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5)+1)+1),-1)))
Col F:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1),-1)))
Col G:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1),-1)))
Col H:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1),-1)))
Col I:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1),-1)))
Col J:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1),-1)))
Col K:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1),-1)))
Col L:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1),-1)))
Col M:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-1)))
Col N:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-1)))
Col O:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)),"",mid($A5,sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1)+1),-1)))

...but these fail to recognize the final category for each row. Col B's formula has no problems, so I began to edit the formulas in Columns C to O:

Col C:  =if(iserror(search("-",$A5,sum(search("-",$A5)+1))),if($B5<>"",right($A5,sum(len($A5),-search("-",$A5))),""),mid($A5,sum(search("-",$A5),1),sum(search("-",$A5,sum(search("-",$A5)+1)),-search("-",$A5),-1)))
Col D:  =if(iserror(search("-",$A5,search("-",$A5,search("-",$A5)+1)+1)),if($C5<>"",if(iserror(search("-",$A5,search("-",$A5)+1)),"",right($A5,len(sum($A5,-search("-",$A5,search("-",$A5)+1))))),""),mid($A5,sum(search("-",$A5,search("-",$A5)+1),1),sum(search("-",$A5,search("-",$A5,search("-",$A5)+1)+1),-search("-",$A5,search("-",$A5)+1),-1)))

It appears this solution will work for all situations except when Column A has only one category. When that happens, a #VALUE! error will populate all columns to the right of Col B. How do I solve this?

For now, I'm stuck with this:

A                       B       C       D       E       F       G       ...     O
Categories              Cat 1   Cat 2   Cat 3   Cat 4   Cat 5   Cat 6   ...     Cat 14

UX                      UX      #VALUE! #VALUE! #VALUE! #VALUE! #VALUE! ...     #VALUE! 
CFT-WET                 CFT     WET 
WEM-US-CFT              WEM     US      CFT
NC-US-CFT               NC      US      CFT
TP-OB-SB-WEB            TP      OB      SB      WEB
DB-B-FC                 DB      B       FC
P-TP-SB-CP-DT           P       TP      SB      CP      DT
DP-S-OB-WB-SB-FC DP     S       OB      WB      SB      FC
P-TP-SB-CP-WEB-WS-S-TP-OB-C-CT-G-FC-MCB

i need help from you guys in an excel formula

i am trying to create a formula in excel where i can select certain entries to be posted in another sheet or table so basically what i have here is a tender for digital devices computers laptops mainframe and there is 4 companies that applied for the tender so after the technical and commercial study of the tender offers there is companies that passed in certain items and failed in others so i put the unit price in USD for each company for the items and iam trying to create a formula to pick up the lowest price for each company BUT with the condition that it should be labeled PASSED not failed so i can make the report with the lowest passed companies for each item with their company name i tried using minimum and match and index but that got me the lowest price including the failed companies so i don't know what to do i attached a copy of the dummy excel sheet for you to check it out and help me.

Best regardsDumy Excel sheet

VBA loop to find entries and copy items

I am trying to figure out how to create a loop that will check the values of E until column E is empty. If there is a 1, I want to select the adjacent information in columns B & C, and copy the selection.

B C E
Item Cases to send Helper Column
22935 270 0 24504 1080 0 40070 189 1 41883 360 0 41884 312 1 AX001 156 1 AX003 396 1 AX024 1320 1 AX025 198 1 AX032 594 1 AX033 264 1 AX042 297 0 AX081 1224 1 AX102 210 1 AX202 1260 0 AX310 840 1 AX312 910 1 AX508 840 1 AX833 576 0 B0052 144 1 H1012 165 1 K0120 243 1 MP804 594 0 OG101 660 1 W2100 81 0 W3628 2331 0

Python - get object - Is dictionary or if statements faster?

I am making a POST to a python script, the POST has 2 parameters. Name and Location, and then it returns one string. My question is I am going to have 100's of these options, is it faster to do it in a dictionary like this:

myDictionary = {{"Name":{"Location":"result"},{"LocationB":"resultB"}},
        {"Name2":{"Location2":"result2A"},{"Location2B":"result2B"}}}

And then I would use.get("Name").get("Location") to get the results

OR do something like this:

if Name = "Name":
     if Location = "Location":
         result = "result"
     elif Location = "LocationB":
         result = "resultB"
elif Name = "Name2":
         if Location = "Location2B":
             result = "result2A"
         elif Location = "LocationB":
             result = "result2B"

Now if there are hundreds or thousands of these what is faster? Or is there a better way all together?

Why does return statement close the program in python

def settings(data):
    print("1- Show key")
    print("2- Set key")
    key = raw_input()
    if key == "1":
        print("".join(data))
        choose()
    elif key == "2":
        data = list(raw_input())
        return data
        choose()
    else:
        settings(data)

when I run this function, and i choose key == 2 option it lets me insert data but it close the program after.

Header location php

I've made this block of code:

$tag = $_GET['tag']

if ($_SERVER[HTTP_REFERER'] == 'http://ift.tt/1C5WAC8' ||       $_SERVER['HTTP_REFERER'] == 'http://ift.tt/1CHqG9W' . $tag ) : ?>

<figure class="folio-item">
    <img src="<?php echo $mod->src; ?>" alt="">
</figure>

<?php  else : ?>
   <?php header('http://ift.tt/1C5WAC8'); ?>
<?php endif ?>

So if the statement is true it has to make the figure, which does work. but when the statement isn't true it gives me a empty file instead of heading me to http://ift.tt/1C5WAC8

how can i make this work?

Not sure if I can use array_intersect or array_search in this case

I have an array ($entry) that could have either of two sets of keys:

"custom_0_first" AND "custom_0_last";

OR

"custom_1_first" AND "custom_1_last";

I'm trying to do the following, but it doesn't seem to be setting the variables:

$firstname = array_search('custom_0_first', $entry) || array_search('custom_1_first', $entry);
$lastname = array_search('custom_0_last', $entry) || array_search('custom_1_last', $entry);

Note that $entry['custom_0_first'] does work fine. I was trying to avoid an IF statement here.

Is my understanding of how array_search or PHP works incorrect? As I understand it, if the first array_search doesn't find the key, the function returns FALSE and then it will check the right side of the OR statement. Is this incorrect? I saw array_intersect that I thought might work, but it looks like that doesn't work with arrays with associative keys.

If variable not empty display variable without repeating variable name

Hello there do you know a way for writing this in PHP without repeating the variable name?

if($abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
} else if($abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
} else if($abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"]!=="") {
    echo $abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];
}

Of course you can write

$a = $abcdefg["blaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
$b = $abcdefg["evenMoreBlaBlaBlaBlaBlaBlaBlaBlaBlaBla"];
$c = $abcdefg["stillAlotBlaBlaBlaBlaBlaBlaBlaBlaBla"];

if($a) { echo $a; } else if($b) { echo $b; } else if ($c) { echo $c; }

This is a bit shorter but I still wonder if there is some syntactical nice thing to write it without variable repetition.

Ternary operator does not solve the problem because of the "elseif" I think.

ifelse stripping POSIXct attribute from vector of timestamps?

This is weird: R's ifelse() seems to do some (unwanted) casting: Lets say I have a vector of timestamps (possibly NA) and NA values should be treated differently than existing dates, for example, just ignored:

formatString = "%Y-%m-%d %H:%M:%OS"
timestamp = c(as.POSIXct(strptime("2000-01-01 12:00:00.000000", formatString)) + (1:3)*30, NA)

Now

timestamp
#[1] "2000-01-01 12:00:30 CET" "2000-01-01 12:01:00 CET" "2000-01-01 12:01:30 CET"
#[6] NA    

as desired but translation by 30 seconds results in

ifelse(is.na(timestamp), NA, timestamp+30)
#[1] 946724460 946724490 946724520        NA

Notice that still, timestamp+30 works as expected but lets say I want to replace NA dates by a fixed date and translate all the others by 30 secs:

fixedDate = as.POSIXct(strptime("2000-01-01 12:00:00.000000", formatString))
ifelse(is.na(timestamp), fixedDate, timestamp+30)
#[1] 946724460 946724490 946724520 946724400

Question: whats wrong with this solution and why doesn't it work as expected?

Edit: the desired output is a vector of timestamps (not of integers) translated by 30 secs and the NA's being replaced by whatever...

If statement do nothing javascript

Okay so here's a simple question that i understood but got asked... let say you have and if statement

if (window.location.href == 'http://' ||
    window.location.href == 'http://?pg=pgOldMainMenu' ||
    window.location.href == 'http://default.asp#') 

else {

how can you say if positive do nothing else load this html

Use PHP if statement on query result

I'm having a problem getting useful information from my query results. I want to query the database for a postID, and if it is the same with the current post, I want to then leave a message, if not the same, I want to show an input. This is so that the user cannot enter more than one posts, so once the user has entered one posts, the input box vanishes and the mentioned messaged appears "Already Entered". Here's my code:

$wpdbtest_maindb = new mysqli('localhost', 'xxx', 'yyy', 'i1593382_wp1');

                    $result = mysqli_query($wpdbtest_maindb,"SELECT user_id, post_id
                                            FROM giveaways
                        WHERE user_id= $user_ID");



                    if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_assoc($result)){
                        $post_id = $row[post_id];
} 
                        if ($id == $post_id)
                        {
                            echo "Already Entered";
                        }else{?>
<form action="../../giveaways.php" method="post">                                   
                    <input type="hidden" name="postid" value="<?=$id?>" />
                    <input type="hidden" name="userid" value="<?=$user_ID?>" />
                    <p align="right"><input type="submit" value="<?=$user_ID?>-<?=$id?> Enter" class="submit" />        </p>
                    </form> 
<?php
}
 } 
}


?>                  

Why does this AND system not work?

So, I'm making an RPG where the player can fight using various weapons, and I was testing this code:

:TEST
set /a bottomlimit=25
set /a upperlimit=50
set /a hp = %bottomlimit% + %random% %% (%upperlimit% - %bottomlimit% + 1)
cls
echo Oh no! goblins are attacking!
echo The party has 3 members, and they have %hp% health!
echo.
echo You can use:
if %fists% equ 1 echo fists
if %glass% equ 1 echo glass
if %knife% equ 1 echo knife
if %sword% equ 1 echo sword
if %ender_scythe% equ 1 echo ender_scythe
set /p answer=
if %fists% equ 1 (
   if %answer% equ fists set /a "hp=hp-5"
)
if %glass% equ 1 (
   if %answer% equ glass set /a "hp=hp-10"
)
if %knife% equ 1 (
    if %answer% equ knife set /a "hp=hp-14"
)
if %sword% equ 1 (
    if %answer% equ sword set /a "hp=hp-20"
)
if %ender_scythe% equ 1 (
    if %answer% equ ender_scythe set /a "hp=hp-50"
)
if %hp% equ 0 goto Win

When I attempt to fight using the weapons, it ALWAYS goes to Win. I have set the weapon's variables to 1 previously, so it should work, right?

Weird failure in PHP if statement

OK, so here's my code. (I'll sanitize it later. Don't worry about it.)

<?php
include_once('../basics.php'); //Site configs
include_once('class.user.php'); //For storing user data and stuff
include_once('class.image.php');
include_once('auth.php'); // The user authenticator

// Check if user wants to upload to existing or new album
if (isset($_POST['album'])) {
    if ($_POST['album'] == '') {
        $_POST['album'] = $_POST['new_album'];
    }
}

// Populate album dropdown menu
$albums = $database->query("SELECT DISTINCT(album) FROM images")->fetchAll(PDO::FETCH_COLUMN); 

// Load the 'upload new photo' interface if user's not uploading it already
if (!isset($_FILES['image_link']) || !isset($_POST['caption']) || $_POST['caption'] == '') {
    //var_dump($_FILES);
    //var_dump($_POST);
    include('views/gallery_upload_new.php');

// Otherwise store the image file, register it into database, and put the user back in the list of photos
} else {
    $new_image = new Image($_POST['caption'], $_POST['album']);
    $new_image->register($_FILES['image_link']['tmp_name'], $_FILES['image_link']['name']);
    header('location: gallery_management.php'); 
}
?>

Here's the weird part: without those two var_dump's up there, the else block won't execute. I've made sure the indexes in the $_POST and $_FILES are correct. Yet without those dummy dumps, this thing won't work. It doesn't even matter if they're commented out or not. They just need to be there.

What did I do wrong? Did I made a syntax error somewhere?

Java: difference of first and last number in a deque [on hold]

I have to write a program which does the removal of numbers such that if the difference between the first number and the last number in the deque is even, the number at the head of the deque will be removed else if it is odd, the number at the tail will be removed. It should print out which number is being removed from the deque. I need some guidance in where I have gone wrong in my codes as I am getting exception error. Here is what I have come up so far.

package lesson1;
import java.util.*;

     public class MyClass1{

     public static void main(String[] args) {

     LinkedList<Integer> al= new LinkedList<Integer>();
     Deque<Integer> d = new LinkedList<Integer>();

        al.add(70);
        al.add(3);
        al.add(5);
        al.add(6);
        al.add(15);
        al.add(60);

        Integer first= al.getFirst();
        Integer last= al.getLast();

        Integer diff= first-last;
        Integer diff2= last-first;
        for(Integer i: al){

            if(diff%2==0|| diff2%2==0){

                d.removeFirst();
            }else{

                d.removeLast();
            }               
        }
        System.out.println(d);    
       }
     }

JavaScript play/pause button for YouTube iframe

I'm working on a website, and i'm trying to get an youtube video in an <iframe> tag to play and pause with one button. I can get it to play or pause with separate buttons, but I can't seem to get the if statement to work in order to control the video with just one button. I'm still relatively new to JavaScript, so it may just bee something simple I missed, but I'v searched online for a while now, and could not find anything that solved my problem.

Below is the code I use right now. The first time I click the button the YouTube video play's, but the second time nothing happens. I also tried turning autoplay on for the embedded video, but then when I press the button, nothing happens at all.

This is the code I'm currently using:

HTML

<div class="iframe">
  <iframe id="iframe1" width="360" height="203" src="http://ift.tt/1g6Ew0I" frameborder="0" allowfullscreen></iframe>
  <a href="#" onclick="iframe1play();return false;">
    <div id="iframe1play">
    </div>
  </a>
</div>

JavaScript

function onYouTubePlayerAPIReady() {
    iframe1 = new YT.Player('iframe1');
} 

function iframe1play() {
    if (event.data == YT.PlayerState.PLAYING && !done) {
        iframe1.pauseVideo();
        document.getElementById("iframe1").style.opacity = "0";
    } else {
        iframe1.playVideo();
        document.getElementById("iframe1").style.opacity = "1";
    }   
}

var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Any suggestions are appreciated!

Why won't my input Scanner and the rest of my program work?

Could someone help me to fix my code to get it to work. In the console it doesn't allow me to type anything. Could someone test the code on their computer and send me a comment with the fixed code? If not could you just tell me the problem with my code?

String yes= "yes";

    System.out.println("Do you have gym this semester?");
    input.nextLine();
    if (input.equals(yes)){

        int Gym;
        double GymGpa = 0;
        System.out.println("Gym = ");
        Gym= input.nextInt();
        input.close();
        if (Gym >100){
            System.out.println("You have mistyped something");
        }
        if (Gym >= 94 && Gym < 101){
            System.out.println("You have an A");
            GymGpa = 4.0;
            System.out.println(GymGpa);
        }
        if (Gym < 94 && Gym >=90){
            System.out.println("You have an A-");
            GymGpa = 3.7;
            System.out.println(GymGpa);
        }
        if (Gym < 90 && Gym >=87){
            System.out.println("You have a B+");
            GymGpa = 3.3;
            System.out.println(GymGpa);
        }
        if (Gym < 87 && Gym >=80){
            System.out.println("You have a B");
            GymGpa = 3.0;
            System.out.println(GymGpa);
        }
        if (Gym < 80 && Gym >=77){
            System.out.println("You have a B-");
            GymGpa = 2.7;
            System.out.println(GymGpa);
        }
        if (Gym < 77 && Gym >=73){
            System.out.println("You have a C+");
            GymGpa = 2.3;
            System.out.println(GymGpa);
        }
        if (Gym < 73 && Gym >=70){
            System.out.println("You have a C");
            GymGpa = 2.0;
            System.out.println(GymGpa);
        }
        if (Gym < 70 && Gym >=67){
            System.out.println("You have a C-");
            GymGpa = 1.7;
            System.out.println(GymGpa);
        }
        if (Gym < 67 && Gym >=67){
            System.out.println("You have a D+");
            GymGpa = 1.3;
            System.out.println(GymGpa);
        }
        if (Gym < 67 && Gym >=63){
            System.out.println("You have a D");
            GymGpa = 1.0;
            System.out.println(GymGpa);
        }
        if (Gym < 63 && Gym >=60){
            System.out.println("You have a D-");
            GymGpa = 0.7;
            System.out.println(GymGpa);
        }
        if (Gym < 60){
            System.out.println("You have a F");
            GymGpa = 0.0;
            System.out.println(GymGpa);
        }//End of Gym
    }else if (input.equals("no")){

    }

How to "do, if expression increased"?

How can I code following pattern in C++ in order to execute statements inside if:

if ("vVector.size() did not increase")
//do whatever is here

?

NOTE: vVector is incremented automatically from time to time. It's actually a clone of another vector that collects things and expands without me having and willing to have control on it.

When I do:

if (!(vVector.size()++))
//do whatever is here

I get following error: lvalue required as increment operand

Update table with SET command IF / ELSE

I'm trying to update a table and i want to runt 2 different SET senarios depending on a stock value.

Working CODE that does one senario.

UPDATE dbo.ar

    SET webPublish = '0', 
        ArtProdKlass = '9999',
        VaruGruppKod = '9999',
        ItemStatusCode = '9' --Utgått ur sortimentet+
        FROM tmp_9999
        WHERE ar.ArtNr = tmp_9999.art AND ar.lagsadloartikel < '1'    

What i would like to do is that IF last statement (ar.lagsaldoartikel) is >'1'
Then i would like it to run this SET:

  SET   webPublish = '1', 
        ArtProdKlass = '1',
        VaruGruppKod = '9999',
        ItemStatusCode = '8' 

So something like this i have tested:

    IF  AR.lagsaldoartikel < '1'

    SET webPublish = '0', 
        ArtProdKlass = '9999',
        VaruGruppKod = '9999',
        ItemStatusCode = '9' --Utgått ur sortimentet+

    FROM tmp_9999
    WHERE ar.ArtNr = tmp_9999.art --Väljer ut artiklar som enbart finns i textfilen och har lagersaldo mindre än 1
ELSE

    SET webPublish = '1', 
        ArtProdKlass = '1',
        VaruGruppKod = '9999',
        ItemStatusCode = '8' --Utgått ur sortimentet

    FROM tmp_9999
    WHERE ar.ArtNr = tmp_9999.art --Väljer ut artiklar som enbart finns i textfilen och har lagersaldo mindre än 1

Ifs, else ifs and multiple returns

This is not a question about chained ifs or ifs and else ifs. I've seen quite a few of those questions posted in SO already.

My question is also not about performance, its more about coding standards and readability.

Consider the following trivial pseudocode I'm seeing a lot in a project I'm working in:

if (expression > 0)
{
    return 1;
}
else if (expression < 0)
{
    return -1;
}
else
{
    return 0;
}

I usually write this kind of construct in a slightly different way:

if (expression > 0)
{
    return 1;
}

if (expression < 0)
{
    return -1;
}

return 0;

And of course there is the third option that goes by the rule that no method should have more than one return statement which I find too restrictive and cumbersome when the complexity of the method is low:

int retVal;

if (expression > 0)
{
    retVal = 1;
}
else if (expression < 0)
{
    retVal = -1;
}
else
{
    retVal = 0;
}

return retVal;

Is one of options listed above more correct when writing these type of constructs? Performance wise I know the choice is completely irrelevant but from a readability point of view I kind of prefer avoiding the if - else if statements. That said, many co-workers don't agree with me even though they can't give me any convincing arguments.

How to make an ifelse statement for each row in a table

I'm trying to make an ifelse statement giving a result for each row in a table with undefined rows based on certain columns. I have tried to do following: (phyto is the name of my data set)

l=ifelse((Phyto[,8]!="" && Phyto[,2]!="" && Phyto[,9]!="" && Phyto[,3]!="" && Phyto[,1]!=""),0,1)

However, the result does not come from each row but from the entire table.

Does anyone has a suggestion for the problem?

How to write if else to get value from edit text android

I have this 3 types of edit text input. I want to compare the 3 edit text to get the FreeTime.

xml codes

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="@string/morningLabel"
    android:id="@+id/MorningLabel"
    android:textStyle="bold"
    android:layout_alignTop="@+id/textView2"
    android:layout_alignRight="@+id/MorningText"
    android:layout_alignEnd="@+id/MorningText" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Working Hour(s)"
    android:id="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:textStyle="bold" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Afternoon"
    android:id="@+id/textView2"
    android:textStyle="bold"
    android:layout_alignTop="@+id/textView5"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Evening"
    android:id="@+id/textView5"
    android:textStyle="bold"
    android:layout_marginBottom="41dp"
    android:layout_above="@+id/AfternoonText"
    android:layout_toRightOf="@+id/textView3"
    android:layout_toEndOf="@+id/textView3" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text=" 6.01 a.m. \n       to \n12.00 p.m."
    android:id="@+id/morningTime"
    android:textStyle="italic"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/textView3"
    android:layout_toStartOf="@+id/textView3" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text=" 12.01 p.m. \n       to \n 6.00 p.m."
    android:id="@+id/afternoonTime"
    android:textStyle="italic"
    android:layout_alignTop="@+id/morningTime"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignStart="@+id/textView2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text=" 6.01 p.m. \n       to \n12.00 a.m."
    android:id="@+id/eveningTime"
    android:textStyle="italic"
    android:layout_alignTop="@+id/afternoonTime"
    android:layout_alignLeft="@+id/EveningText"
    android:layout_alignStart="@+id/EveningText" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Result"
    android:id="@+id/btnNext"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="38dp"
    android:layout_alignRight="@+id/eveningTime"
    android:layout_alignEnd="@+id/eveningTime"
    android:layout_alignLeft="@+id/morningTime"
    android:layout_alignStart="@+id/morningTime"
    android:textStyle="bold" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/MorningText"
    android:hint="0-6"
    android:layout_marginBottom="22dp"
    android:autoText="true"
    android:background="#ffd1d1d1"
    android:editable="false"
    android:textSize="@dimen/abc_text_size_display_1_material"
    android:layout_above="@+id/morningTime"
    android:layout_toLeftOf="@+id/textView3"
    android:layout_alignLeft="@+id/morningTime"
    android:layout_alignStart="@+id/morningTime"
    android:text="@string/MorningInput"
    android:singleLine="false"
    android:textAlignment="center"
    android:numeric="integer" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/AfternoonText"
    android:hint="0-6"
    android:autoText="true"
    android:background="#ffd1d1d1"
    android:editable="false"
    android:textSize="@dimen/abc_text_size_display_1_material"
    android:layout_alignTop="@+id/MorningText"
    android:layout_alignLeft="@+id/afternoonTime"
    android:layout_alignStart="@+id/afternoonTime"
    android:layout_alignRight="@+id/afternoonTime"
    android:layout_alignEnd="@+id/afternoonTime"
    android:text="@string/AfternoonInput"
    android:textAlignment="center"
    android:numeric="integer" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/EveningText"
    android:hint="0-6"
    android:autoText="true"
    android:background="#ffd1d1d1"
    android:editable="false"
    android:textSize="@dimen/abc_text_size_display_1_material"
    android:layout_alignBaseline="@+id/AfternoonText"
    android:layout_alignBottom="@+id/AfternoonText"
    android:layout_alignRight="@+id/textView5"
    android:layout_alignEnd="@+id/textView5"
    android:text="@string/EveningInput"
    android:textAlignment="center"
    android:numeric="integer"
    android:layout_alignLeft="@+id/textView5"
    android:layout_alignStart="@+id/textView5" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="@string/timeLabel"
    android:id="@+id/TimeText"
    android:layout_above="@+id/btnNext"
    android:layout_alignLeft="@+id/btnNext"
    android:layout_alignStart="@+id/btnNext" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="c"
    android:onClick="calculateClickHandler"
    android:id="@+id/btnc"
    android:layout_above="@+id/TimeText"
    android:layout_toRightOf="@+id/afternoonTime"
    android:layout_toEndOf="@+id/afternoonTime"
    android:layout_marginBottom="42dp" />

this is the java codes. I think I put the wrong if else. How can I solve this? Anyone help~

public class WorkingHour extends Activity {

public void calculateClickHandler(View view)
{

    if (view.getId() == R.id.btnc)
    {
        Intent i=new Intent(this, Result.class);

        // get the references to the widgets
        EditText MorningInput = (EditText)findViewById(R.id.MorningText);
        EditText AfternoonInput = (EditText)findViewById(R.id.AfternoonText);
        EditText EveningInput = (EditText)findViewById(R.id.EveningText);
        TextView TimeText = (TextView)findViewById(R.id.TimeText);

        // get the users values from the widget references
        int morninghour = Integer.parseInt(MorningInput.getText().toString());
        int afternoonhour = Integer.parseInt(AfternoonInput.getText().toString());
        int eveninghour = Integer.parseInt(EveningInput.getText().toString());

        // calculate the free time
        int freeTimeValue = calculateFreeTime(morninghour,afternoonhour,eveninghour);

        // interpret the meaning of the bmi value
        String freetimeInterpretation = interpretFT(freeTimeValue);

        // now set the value in the result text
        TimeText.setText(freeTimeValue + "-" + freetimeInterpretation);

        SharedPreferences sp2 = getSharedPreferences("name2",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp2.edit();
        editor.putString("rslt 3",TimeText.getText().toString());
        editor.commit();
    }
}

// the formula to calculate the free time
private int calculateFreeTime (int morninghour, int afternoonhour, int eveninghour)
{
    if (((6- morninghour)> (6-afternoonhour)) && ((6- morninghour)> (6-eveninghour)))
    {
        return (int) (6 - morninghour);
    }
    else if (((6- afternoonhour)> (6-morninghour)) && ((6- afternoonhour)> (6-eveninghour)))
    {
        return (int) (6 - afternoonhour);
    }
    else if (((6- eveninghour)> (6-morninghour)) && ((6-eveninghour)> (6-afternoonhour)))
    {
        return (int) (6 - eveninghour);
    }
    return 0;
}

// interpret what free time

private String interpretFT(int freetime)
{
    if (freetime < )
    {
        return "morning";
    }
    else if (freetime < )
    {
        return "Afternoon";
    }

}

Complex "IF", "OR", "AND" functions in Google Spreadsheet

here is what I have done so far: (See screenshot attached) When Something is added under "Laden" it gets a certain status. If this status is either "Warte auf GO" or "Warte auf Daten" AND the Date in the Datefield D2 is more than 6 days ago, I want the color of the Cell under "Laden" which has now "Baretta" in it to become yellow. To do so, I have added the simple function:

=OR(AND(L4="warte auf GO"; 6<DAYS360(D4; today())); AND(L4="warte auf DATEN"; 6<DAYS360(D4; today())))

And used conditional formatting. So if this returns true, color A2 in yellow. This worked.

But now to the problem: Secondly if the field turns yellow, I have three more "reminder"-cells. So the first stage is (1) I have been reminded with a yellow field A2 and put the date I have reacted on the reminder in field N2. If 6 days are over, A2 turns yellow again. (2) So I have been reminded with a yellow field A2 for the second time and put the date I have reacted on the reminder in field O2. If 6 days are over, A2 turns yellow again. (3) Again like (2).

So basically I use this sheet as a "reminder"-system with different stages. I have tried to solve it with the following formular. It does return some "false" and "trues", but not in an order, that I fully understand. I guess this is a logical problem, but I do not really see it.

Here is the formular i used:

=IF(AND(OR(L4="warte auf GO"; L4="warte auf DATEN"); 6<DAYS360(D4; today()); (OR(N4=""; AND

(6

Again without code =IF(AND(OR(L4="warte auf GO"; L4="warte auf DATEN"); 6

Can you help me on that one? Thanks Flo

Check a certain field for not null based on a parameter in sql

I get data from a stored procedure. Based on a passed Parameter I want to Change the SQL Statement in the where clause

The Statement Looks like this

    SELECT 
      CC.Id,
      CC.TId,
      CC.PId,
      CC.Date
    FROM Mytable CC
    WHERE CC.TId IS NOT NULL

I pass a Parameter @Qualifier to the procedure so I want to check this param. If it is '1' this SQL Statement should be executed, otherwise the second SQL Statement should be executed:

    SELECT 
      CC.Id,
      CC.TId,
      CC.PId,
      CC.Date
    FROM Mytable CC
    WHERE CC.PId IS NOT NULL

I tried to achieve this using the where clause like this

    SELECT 
      CC.Id,
      CC.TId,
      CC.PId,
      CC.Date
    FROM Mytable CC
    WHERE 
     (CASE
WHEN @Qualifier = '1'
  THEN CC.TId IS NOT NULL
ELSE CC.PId IS NOT NULL)

But that is not working. Anyone knows how to solve this?

Logical "or" (||) operator in an "if" statement

I have the following logic

if(a || b)
{
  if(a)
  // Do something if a is true
  else
  // Do something if b is true
}

is there any way to determine wether a was true in this if(a||b) condition or b was true in thr if(a||b) condition rather than agian checking in the if block which was true.

Note: I have put both a and b in the same if condition because of some same logic.

lundi 29 juin 2015

How to create variable inside if and else if become global variable?

I have collection view but currently still use variable of some strings :

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var urlku = NSURL(string: "http://ift.tt/1efOUC2")
    var data = NSData(contentsOfURL: urlku!)
    if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
        if let dict = json as? [String: AnyObject] {
            println(dict)
            if let weatherDictionary = dict["data"]! as? [AnyObject] {
                println("\nWeather dictionary:\n\n\(weatherDictionary)")
                if let descriptionString = weatherDictionary[0]["challengeName"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString)")
                    var judul1 = "\(descriptionString)"
                }else if let descriptionString1 = weatherDictionary[1]["challengeName"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString1)")
                    var judul2 = "\(descriptionString1)"
                }else if let descriptionString2 = weatherDictionary[1]["currentPhaseName"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString2)")
                    var judul3 = "\(descriptionString2)"
                }else if let descriptionString3 = weatherDictionary[1]["currentPhaseRemainingTime"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString3)")
                    var judul4 = "\(descriptionString3)"
                }else if let descriptionString4 = weatherDictionary[0]["challengeType"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString4)")
                    var judul5 = "\(descriptionString4)"
                }else if let descriptionString5 = weatherDictionary[0]["challengeId"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString5)")
                    var judul6 = "\(descriptionString5)"
                }else if let descriptionString6 = weatherDictionary[1]["currentStatus"]! as? String {
                    println("\nDescription of the weather is: \(descriptionString6)")
                    var judul7 = "\(descriptionString6)"
                }
            }
        }
    }
    var names: [String] = ["Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor", "Lorem ipsum dolor sit er elit lamet, Lorem ipsum dolor"]
    // Create the cell and return the cell
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ImageUICollectionViewCell

    // Add image to cell
    cell.image.image = model.images[indexPath.row]
    cell.labelku.text = names[indexPath.row]
    cell.labelku.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
    return cell
}

what I want to do is get that var names become this :

var names: [String] = ["\(judul1)", "\(judul2)", "\(judul3)", "\(judul4)", "\(judul5)", "\(judul6)", "\(judul7)"]

If judul1 to judul7 not create become global variable, it will produce error "use of unresolved identifier", so I need to make judul1 to judul7 become global variable.

How to create judul1 to judul7 become global variable?

Regards.

Java if condition for empty validations

I'm new to java and i want to do a condition check and return a message

PersonalDetails Request: It holds the value for all the below infos

getID();

getName();

getDesignation();

getHomeAddress();

getOfficeAddress();

getEmailID();

getMobile();

getHomePhone();

getOfficePhone();

i want to check all values for empty then return message.

Like "Your ID,Name, Mobile cannot be empty" if i pass empty values to ID, Name, Mobile

Below is the sample snippet which has to do the check for all PersonalDetails Request

public static String checkValue(PersonalDetails Request) {
    String str="Your ";
    if(request.getID().isEmpty())
    {
         str="ID,";
    }
    if(request.getName().isEmpty())
    {
     str="Name";
    }
if(request.getDesignation().isEmpty())
    {
     str="Designation";
    }
if(request.HomeAddress.isEmpty())
    {
     str="Address";
    }
   str+= "cannot be empty"

    return str;
}

Is this right or any other easy approach will address the issue

Thanks in advance

How to insert doubles into the main method?

I am trying to write a program that calculates my math and English GPA. I can't get the main to recognize my two floats, mathGpa and englishGpa. It tells me to make them static but making them static means that they become strings and I need them to remain doubles.

import java.util.Scanner;
public class GPA {

    public static void main(String[] args)
    {
        double finalGpa=0;

        mathGpa();
        englishGpa();

        finalGpa= (mathGpa + englishGpa)/2;


    }

    public double mathGpa() {//Begin mathGpa
        int Math;
        double mathGpa = 0;
        System.out.println("Math = ");
        Scanner math = new Scanner(System.in);
        Math= math.nextInt();
        math.close();

        if (Math >100){
            System.out.println("You have mistyped something");
        }
        if (Math >= 94){
            System.out.println("You have an A");
            mathGpa = 4.0;
            System.out.println(mathGpa);
        }
        if (Math < 94 && Math >=90){
            System.out.println("You have an A-");
            mathGpa = 3.7;
            System.out.println(mathGpa);
        }
        if (Math < 90 && Math >=87){
            System.out.println("You have a B+");
            mathGpa = 3.3;
            System.out.println(mathGpa);
        }
        if (Math < 87 && Math >=80){
            System.out.println("You have a B");
            mathGpa = 3.0;
            System.out.println(mathGpa);
        }
        if (Math < 80 && Math >=77){
            System.out.println("You have a B-");
            mathGpa = 2.7;
            System.out.println(mathGpa);
        }
        if (Math < 77 && Math >=73){
            System.out.println("You have a C+");
            mathGpa = 2.3;
            System.out.println(mathGpa);
        }
        if (Math < 73 && Math >=70){
            System.out.println("You have a C");
            mathGpa = 2.0;
            System.out.println(mathGpa);
        }
        if (Math < 70 && Math >=67){
            System.out.println("You have a C-");
            mathGpa = 1.7;
            System.out.println(mathGpa);
        }
        if (Math < 67 && Math >=67){
            System.out.println("You have a D+");
            mathGpa = 1.3;
            System.out.println(mathGpa);
        }
        if (Math < 67 && Math >=63){
            System.out.println("You have a D");
            mathGpa = 1.0;
            System.out.println(mathGpa);
        }
        if (Math < 63 && Math >=60){
            System.out.println("You have a D-");
            mathGpa = 0.7;
            System.out.println(mathGpa);
        }
        if (Math < 60){
            System.out.println("You have a F");
            mathGpa = 1.7;
            System.out.println(mathGpa);
        }

        return mathGpa;
    }//End mathGpa

    public double englishGpa() {//Begin englishGpa
        int English;
        double englishGpa = 0;
        System.out.println("English = ");
        Scanner english = new Scanner(System.in);
        English= english.nextInt();
        english.close();

        if (English >100){
            System.out.println("You have mistyped something");
        }
        if (English >= 94){
            englishGpa = 4.0;
        }
        if (English < 94 && English >=90){
            englishGpa = 3.7;
        }
        if (English < 90 && English >=87){
            englishGpa = 3.3;
        }
        if (English < 87 && English >=80){
            englishGpa = 3.0;
        }
        if (English < 80 && English >=77){
            englishGpa = 2.7;
        }
        if (English < 77 && English >=73){
            englishGpa = 2.3;
        }
        if (English < 73 && English >=70){
            englishGpa = 2.0;
        }
        if (English < 70 && English >=67){
            englishGpa = 1.7;
        }
        if (English < 67 && English >=67){
            englishGpa = 1.3;
        }
        if (English < 67 && English >=63){
            englishGpa = 1.0;
        }
        if (English < 63 && English >=60){
            englishGpa = 0.7;
        }
        if (English < 60){
            englishGpa = 1.7;
        }

        return englishGpa;
    }//End englishGpa

}//End Class

Java: placing integers first or last in a deque based on whether it is odd or even

I have to write a program which adds integers in a deque such that the odd numbers are added last in the deque and the even numbers are added first. I don't know where to add the if statement for the addition of the numbers and how to make my code work. Sorry if my codes seem to be wrong as this is my first program on deque.

package lesson1;
import java.util.*;


     public class MyClass1{

     public static void main(String[] args) {

     Deque<Integer> d= new LinkedList<Integer>();

     d.add(10);
     d.add(3);
     d.add(5);
     d.add(6);
     d.add(15);

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

         Integer head= d.poll();

         if(head%2==1){
             d.addLast(head);

         }

         else{
             d.addFirst(head);
         }

     }

     System.out.println(d);


  }

}

Wordpress issue with if condition when using it inside Loop

am using if condition inside post loop to display only post have thumbnail ,it work just fine but the loop counting the hidden posts which haven't any thumbnail and pagination also keep giving me blank page for the hidden post how can i force the loop to counting just the result of if condition posts here's my code

        <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
    'paged' => $paged,
    'post_type' => array('post','news','video'),
    );
    query_posts($args);
    while(have_posts()) : the_post(); ?>
    <?php if(has_post_thumbnail()) { ?>
       <?php echo get_the_title(); ?>
    <?php }else{} ?>
    <?php endwhile; ?>
    <?php wpbeginner_numeric_posts_nav(); ?>

C, if statements and strcmp

I don't understand why it does not pick up on the inputs. It always displays "Invalid Input"... Help!

while(1)
{
    fgets(input, MAX, stdin);
    printf("%s", input);

    if(strcmp(input, "1") == 0)
    {
        add();
    }
    else if(strcmp(input, "2") == 0)
    {
        delete();
    }
    else if(strcmp(input, "3") == 0)
    {
        view();
    }
    else if(strcmp(input, "4") == 0)
    {
        break;
    }
    else
    {
        printf("Invalid Input!\n");
    }
}

I can't figure out why my program isn't looping

I am trying to make this file loop. But I keep getting an error on at the last if statement (Marked by an arrow). The program is supposed to read in a file with the first line being the name of the customer. On the second line, the first number is the amount of trees to be removed(150 per tree), the second number is tree trimming to be done(50 an hour). The third line are all the stumps to be removed and their diameter(one number is one stump and also it's diameter). Thanks for the help.

This is the file that is supposed to be read in (http://ift.tt/1Jtso6r).

public class Prog_5 {

    public static void main(String[] args) throws FileNotFoundException {
        String name = "Joe";
        double trees = 0;
        double treeTrimming = 0;
        double stumpInches = 0;
        double stumpTotal = 0;
        double total = 0;
        double totalRev = 0;

        Scanner in = new Scanner(System.in);
        System.out.print("Input file: ");
        String inputFile = in.nextLine();

        System.out.print("Output file: ");
        String outputFile = in.nextLine();
        in.close();

        File input = new File(inputFile);
        in = new Scanner(input);
        PrintWriter output = new PrintWriter(outputFile);

        while(in.hasNext()){

        name = in.nextLine();
        output.println("Customer: " + name);
        System.out.println("Customer: " + name);

        trees = in.nextDouble();
        trees *= 150;
        output.println("Tree Removal: $" + trees);
        System.out.println("Tree Removal: $" + trees);

        treeTrimming = in.nextDouble();
        treeTrimming *= 50;
        output.println("Tree Trimming: $" + treeTrimming);
        System.out.println("Tree Trimming: $" + treeTrimming);

        while (in.hasNextDouble()) {
            stumpInches = in.nextDouble();
            if (stumpInches != -1) {
                stumpTotal = stumpTotal + 30;
                if (stumpInches > 12) {
                    stumpInches -= 12;
                    stumpInches *= 2;
                }
                stumpTotal += stumpInches;
            }

        }
        output.println("Stump Removal: $" + stumpTotal);
        System.out.println("Stump Removal: $" + stumpTotal);

        total = (trees + treeTrimming + stumpTotal);
        output.println("Total: $" + total);
        System.out.println("Total: $" + total);

        totalRev += total;
        stumpTotal = 0;
        trees = 0;
        treeTrimming = 0;

        if(in.hasNext());
            in.next();
        }

        output.close();

    }

}

Close programs with Vbs one click.

I am trying to get my script to loop through the if statment(s) and close the programs if they are open. However with what I have now I am only able to close the programs in the if statement by clicking the script twice. I suspect I may need a different loop but im not sure which one. This is what I have now.

Set oShell = CreateObject("WScript.Shell") 
Do 
if oShell.AppActivate("Untitled - Notepad") then
   WScript.Sleep 500
   oShell.SendKeys "%{F4}"

end if

if oShell.AppActivate("Cisco Packet tracer") then
   WScript.Sleep 500
   oShell.SendKeys "%{F4}"

end if

exit do
loop

How to use multiple condition in if statement in bash?

Actually I am a new bash learner. I can use one condition in bash command. But how to use multiple condition in bash? I can use if statement like this:

read a
if [ $a = "y" ] ; then
   echo "YES"
elif [ $a = "Y" ] ; then
   echo "YES"
else
   echo "NO"
fi

I am finding something like this:

read a b c

if [ $a -eq $b and $b -eq $c ] ; then
    echo "EQUILATERAL"
elif [ $a -eq $b or $b -eq $c ] ; then
    echo "ISOSCELES"
else
    echo "SCALENE"
fi

I just want to know, what to use instead of and and or?

mysqli display rows based on row value - (if row value=1 display, else hide)

I want to display 30 rows from an data base,on an TABLE, but just the approved entries. This "approved entries" are defined for an row with values "1 for approved" and "0 for NOT approved"

This is the code wath I need to change:

<?php
$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 1";
$result = $last_id = $conn->query($sql);


if ($result->num_rows > 0)
 {
    echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
        echo "<td><a href=";
        if (empty($row['episode'])) {
     echo '/peliculas-online/'.$row["title_id"];
    }
    else {
     echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
        }
        echo ">".$row["title_id"]."</a></td>";
        echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>

Like you can see, this code list all (approved or not)... how to get something like this:

if row approved=1 display rows, else hide (hide all not just the approved row)

Need to HIDE all entries from this table row if entry is not approved -> id-label-title_id-season-episode-approved

Thanks

I wonder whats happens when if(i%2) what does it checks to come to continue. It misses == but it prints out the sum as 20? Why?

#import <stdio.h>
int main(void)
{
int sum,i;
sum = 0;
for(i=0;i<10;i++){
    if(i%2)
    continue;
    sum+=i;
}
printf("\n%d",sum);
return 0;
}

How does if(i%2) works in the above code?

if statement with multiple or condition

Consider the following code

if (  stripos($a,'something1')===0 || stripos($a,'something2')===0  ) {
        return '';
}

Is there a performance benefit for using in_array or does php stops testing if first condition evaluate to true ?

how to add loop in c++

im new to this programming stuff and I was wondering if someone could help me add a loop to my program?

cout << "What do you do?" "\n";
    cout << "\n";
    cout << "(Press Enter...)";
    cin.ignore();
       cout << "\n";
        cout << "Stay in bed?" "\n";
        cout << "Go to the bathroom?" "\n";
        cout << "Go downstairs?" "\n";
    cout << "\n";

    string answer;
    getline(cin, answer);

        if (answer == "stay in bed", "Stay in bed")
            {
                cout << "You lay there, motionless. Silent.";
            }

        else if (answer == "go to the bathroom", "Go to the bathroom")
            {
                cout << "You get up and walk across the hall to the bathroom";
            }
        else if (answer == "go downstairs", "Go downstairs")
            {
                cout << "You get up and walk downstairs to the kitchen.";
            }
        else
            {
                cout << "That is not a valid answer...";
            }
           cin.ignore();

Heres the code. How should I add a loop to where when user enters something falling under the condition of "else", the loop returns to ask "What do you do?". Any help is greatly appreciated. And like I said Im very new to all of this so sorry if this question is so basic that its stupid...

"if" in method on the BroadcastReceiver service will not work

I have a problem with checking variables in the "if". I get a userPhoneNumber variable from SharedPreferences and phoneNumber of SmsMessage.

I will displaying Toast with both variables and they are the same, but the if didn't work. Where is the problem?

My BroadcastReceiver class:

public class IncomingSms extends BroadcastReceiver {
String userPhoneNumber = "";
String senderNum= "";
String message= "";
final String TAG="LocationService";
GPSTracker gps;
double latitude = 0.0;
double longitude = 0.0;


// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();


public void onReceive(Context context, Intent intent) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    userPhoneNumber = settings.getString("userPhoneNumber", "");

    Log.e(TAG, "userPhoneNumber:"+userPhoneNumber);
    int duration = Toast.LENGTH_LONG;

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {
        if (bundle != null) {
            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress().toString();

                senderNum = phoneNumber;
                message = currentMessage.getDisplayMessageBody();

                turnOn(context);
            } // end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);
    }
    Log.i("SmsReceiver", "senderNum: " + senderNum + "userPhoneNumber: "+ userPhoneNumber + "; message: " + message);


}

public void turnOn (Context context){
    Intent i  = new Intent(context, MyService.class);
    gps = new GPSTracker(context);

    Toast.makeText(context,"Method turnOn!\nsenderNum: "+senderNum + "\n userPhoneNumber: " + userPhoneNumber, Toast.LENGTH_LONG).show();

    if (senderNum == userPhoneNumber) {
        Toast.makeText(context,"works in IF", Toast.LENGTH_LONG).show();
        if(gps.canGetLocation()){
            latitude =  gps.getLatitude();
            longitude = gps.getLongitude();
            i.putExtra("Latitude", latitude);
            i.putExtra("Longitude", longitude);

            context.startService(i);
        }else
        {
            gps.showSettingsAlert();
        }
    }
    gps.stopUsingGPS();
}

One line if statement in bash

I've never programed in bash... yet I'm trying to solve a problem for an anchievement in a game (cogingame.com)

I have the following code:

for (( i=0; i<N-1; i++ )); do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ));
   if [ $tmp < $result ]; then result=$tmp fi
done

And this error: /tmp/Answer.sh: line 42: syntax error near unexpected token done' at Answer.sh. on line 42 /tmp/Answer.sh: line 42:done' at Answer.sh. on line 42

I want to compare adjacent values of my array and store the minimun diference between them... but I cant figure how to do an If statement in bash

bash if statement issue

Would someone mind giving me a hand with the following IF Statement?

read -e -p "Would you like to reboot now?: " -i " " REBOOT

if $REBOOT = 'yes' ; then
   echo 'System will now reboot'
   shutdown -r now
else $REBOOT != 'yes'
   echo 'You have chosen to reboot later'
fi

If I enter 'yes' I get the following as an endless result

= yes
= yes
= yes
...
= yes

And if I enter 'no' I get the following:

./test.sh: line 7: no: command not found
./test.sh: line 10: no: command not found
You have chosen to reboot later

Any ideas?

US phone conversion from letters to numbers

Think I have gone wrong somewhere so I could use some help. OK the idea is to have the letters you usually find on phones. e.g. if I wanted to find the number for HAIRCUT it should output like 4247288.

public class PhoneNumber
{
    String s;
    int i;

    private void PhoneNumber()
    { 
      if ("ABC".contains(""+s.charAt(i))){
          i=2;
        }
          else if ("DEF".contains(""+s.charAt(i))){
              i=3;
            }
            else if ("GHI".contains(""+s.charAt(i))){
                i=4;
            }
            else if ("JKL".contains(""+s.charAt(i))){
                 i=5;
            }
            else if ("MNO".contains(""+s.charAt(i))){
                i=6;
            }
            else if ("PQRS".contains(""+s.charAt(i))){
                i=7;
            }
            else if ("TUV".contains(""+s.charAt(i))){
                i=8;
            }
            else if ("WXYZ".contains(""+s.charAt(i))){
                i=9;
            }                     
    }
    public void decode(){
        PhoneNumber pn = new PhoneNumber();
        pn.decode("HAIRCUT")
        pn.decode("NEWCARS"); 
    }
   }

I know i am missing stuff and even the println at the end but need guidance on how to do this. if you look at the code ABC will come out as 2, DEF as 3 etc. Any ideas? I'm very new to Java apologies in advance for my failed attempt.

Errorlevel is different

I've been trying to write this batch script. What I want it to do is open msinfo.exe, then using the wmic check the manufacturer & depending on the manufacturer it will open that manufacturers website. Here's what I have written all ready without success:

@echo off

start %windir%\System32\msinfo32.exe

if exist c:\BIOS.txt (
      start c:\BIOS.txt
) else (
      wmic /output:c:\BIOS.txt bios get smbiosbiosversion
)

:asus

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "asus" > NUL

if %errorlevel% equ 1 (
      %programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto dell
)

:dell

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "dell" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto gateway
)

:gateway

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "gateway" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto hp
)

:hp

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "hewlett-packard" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto lenovo
)

:lenovo

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "lenovo" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto samsung
)

:samsung

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "samsung" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto sony
)

:sony

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "sony" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto toshiba
)

:toshiba

wmic /output:c:\Manufacturer.txt Computersystem get Manufacturer | FINDSTR "toshiba" > NUL

if %errorlevel% equ 1 (
      "%programfiles%\Internet Explorer\iexplore.exe" **place support site here**
      goto exit
) else (
      goto exit
)

:exit

Any help with making me understand would be greatly appreciated. Everything I'm reading & trying just isn't getting me results. I've read everything on here about errorlevel & I guess it's not making sense?

Break statement

If I'm in for loop like this:

for(i=0; i<1000; i++) 
{
     if(TRUE) 
     {
        break;
     }
}

Will this break; statement inside IF exit from this for loop?

Compromising Python IF function

I have to work with a bunch of if statement in one code. They are all the same with slight changes. Is there any way how I can compromise all this code and make it more elegant and shorter ?

Code below:

if con_name == 'coh':
    coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
    coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
    return coh, coh_surro, freqs, freqs_surro

if con_name == 'imcoh':
    imcoh = my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
    imcoh_surro = my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
    return imcoh, imcoh_surro, freqs, freqs_surro

if con_name == 'cohy':
    cohy = my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
    cohy_surro = my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
    return cohy, cohy_surro, freqs, freqs_surro

if con_name == 'plv':
    plv = my_plv(n_freqs, Rxy, Rxy_mean)
    plv_surro = my_plv(n_freqs, Rxy_s, Rxy_s_mean)
    return plv, plv_surro, freqs, freqs_surro

if con_name == 'pli':
    pli = my_pli(n_freqs, Rxy, Rxy_mean)
    pli_surro = my_pli(n_freqs, Rxy_s, Rxy_s_mean)
    return pli, pli_surro, freqs, freqs_surro

if con_name == 'wpli':
    wpli = my_wpli(n_freqs, Rxy, Rxy_mean)
    wpli_surro = my_wpli(n_freqs, Rxy_s, Rxy_s_mean)
    return wpli, wpli_surro, freqs, freqs_surro

I am sorry if this is to easy, but I tried and tried and can't figure out a way.

switch statement having only one case

I only have one case in switch statement

switch ($coreName) {
    case 'stock':
        $result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
    break;
}

My question is this a good practice or shall I use an if statement for this? Any performance differences or anything?

How to loop through a date range in which dates are stored as Integers?

I have to develop a system, where user will specify a starting range and an ending range (By Range, I mean to say a particular period, where PERIOD is given as a concatenation of YEAR AND MONTH). For example, PERIOD = 201304, where 2013 is the user entered Year and 04 is the MONTH. The user can specify a maximum range of upto 2 years only.

Data needs to be selected on the basis of the user entered range. The problem is whenever I try to loop through the period, the PERIOD changes after 201312 to 201313. I have separate variables for user selected year and month (start_year, start_month, end_year, end_month)

I did a IF loop there in which I tried to do the following

  FOR p_tmpyear = p_tempfrom TO p_tempto

        IF (p_monthfrm < 12) THEN
        LET p_yearfrm = p_yearfrm + 1
        LET p_monthfrm = 01
        LET p_fromperiod = p_yearfrm + 1,p_monthfrm >p_fromperiod is an integer storing concatenated Month and Year, to achieve the desired PERIOD format as mentioned above.
        LET p_tempfrom  = p_fromperiod
    END IF
    DISPLAY p_tmpyear
END FOR

I even tried thsi one :

IF (p_fromperiod MOD p_yearfrm = 13) THEN

    LET p_yearfrm = p_yearfrm + 1

    LET p_monthfrm = 01

    LET p_fromperiod = p_yearfrm + 1,p_monthfrm

Still the period changes after reaching 201212 to 201213. I want this to be 201301. Please help.

Nested if condition in kendo grid column template

While trying to implement condition function in kendo grid column template, there is a problem happening, data from my grid are not shown, my function is

function material() {
  if (PCommonPortalMethods.GetSiteLanguage() == 'en') {
    if (data.Unit._Key) {
      Unit.UnitGlobalName
    }
    else ('')
  }
  else {
    if (data.Unit._Key) {
      Unit.UnitLocalName
    }
    else ('')
  }
}      

and I call it from template like : template:'#= material() #'

I tried something like that also:

template: "#if (PCommonPortalMethods.GetSiteLanguage() == 'en') {# if(data.Unit._Key) #=Unit.UnitGlobalName#  else(" ") #} else { # if(data.Unit._Key) #=Unit.UnitLocalName#  else(" ") #} #"

can someone help me? what am I doing wrong? Thanks

applying multiple if and elif statements to substrings in a list of strings in a for loop

I have a spreadsheet filled with disorganized open text fields in column (C1:C3159) that I want to sort by various key-words within the text. I am trying to write a bit of python code that loops through the column, looks for key words, and appends the category of the string in that cell to an empty list depending on what words are found in the text. So far my code looks like this.

## make an object attr for the column    
attr = ['C1:C3159']
## make all lower case
[x.lower() for x in attr]
## initialize an empty list
categories = []
## loop through attr object and append categories to the "categories" list
for i in attr:
    if 'pest' or 'weed' or 'disease' or 'cide' or 'incid' or 'trap'/
    or 'virus' or 'IPM' or 'blight' or 'incid' or 'rot' or 'suck' in i:
        categories.append("pest management")

    elif 'fert' or 'dap' or 'urea' or 'manga' or 'npk' pr 'inm' in i:
        categories.append("fertilizer")

    elif 'wind' or 'rain' or 'irr' or 'alt' or 'moist' or 'soil' or 'ph'\
    or 'drip'or 'environ' or 'ec' in i:
        categories.append("environment")

    elif 'spac' or 'name' or 'stor' or 'yield' or 'rogu' or 'maint'\
    or 'cond' or 'prod' or 'fenc' or 'child' or 'row' or 'prun' or 'hoe'\
    or 'weight' or 'prep' or 'plot' or 'pull' or 'topp' in i:
        categories.append("operations")

    elif 'plant' or 'germin' or 'age' or 'bulk' or 'buds'  or 'matur'\
    or 'harvest' or 'surviv' or 'health' or 'height' or 'grow' in i:
        categories.append("life cycle")

    elif 'price' or 'sold' or 'inr' or 'cost' in i:
        categories.append("market")

    elif 'shed' or 'post' or 'fenc' or 'pond' or 'stor' in i:
        categories.append("PPE")

    else:
        categories.append("uncategorized")

The problem I am having is that after the first if statement the elif statements are not being evaluated in the loop and the list I get returned only contains the few things categorized as "pest management." Does anyone have any idea how to do what I am attempting to do here so that the full loop gets evaluated? A small sample of the strings in the list is posted below.

attr = [Age of plantation, Altitude of Plantation, Annual production Last year (In Kg), Average Price paid per kg in NPR (Last Year), Majority Bush type, Pruning Cycle, Tea sold to ( Last Year), Boll weight in grams, CLCuV incidence %, Dibbles per row, Gap Filling, Germination %, Hoeing, Land preparation, Land preparation date, Pest & disease incidence, Plot size in metre Square, Rows per entry, Spacing between plants in cms]

dimanche 28 juin 2015

Java executing only last part of if condition

I'm a java beginner. i face the below issue.

I'm setting the remarks and returning the response, but i only get the remarks printed as Date is invalid for all the iterations. if i pass all inputs as empty it has to print just ID is empty but it prints Date is invalid all the time

 public Response getInfoDetails(RequestDetails request)
{
Response response = new Response();
if(Utils.isEmpty(request.getID()))
{
response.setREMARKS("ID is empty);
}

 if(Utils.isEmpty(request.getName()))
 {
 response.setREMARKS("Name is empty);
}
if(Utils.isIpAddressValid(request.getIP()))
{
response.setREMARKS("IP is invalid");
}
if(Utils.isDateValid(request.getDate()))
{
response.setREMARKS("Date is invalid");
}
return response;
}

please advise

Thanks

Can you provide tips to implement a simple control system in an OOP Approach?

I'm writing a complex control system for several machines. I'm using C# for convenience, since no true-real time is required, just fast response.

My question is regarding the sampling of sensors in the physical controlled systems: I want to perform actions depending on their values (e.g. if the temperature drops below X do Action A, if the pressure is higher than Y do action B).

There's the simple loop-with-value-querying approach, and there's the option to implement a clock that periodically (hmmm, every 0.01 second) checks the value of about 50 different sensors.

Any finer, more efficient, smarter, more OOP-ish approaches?

Thanks!

"If" statement does not execute properly c++

I am having a small issue regarding the if statement in c++. Here is a snippet of the code:

string answer;
cin >> answer;

if (answer == "stay in bed")
    {
        cout << "You lay there, motionless. Silent.";
    }
else if (answer == "go to the bathroom")
    {
        cout << "You get up and walk across the hall to the bathroom.";
    }
else if (answer == "go downstairs")
    {
        cout << "You get up and walk down the stairs to the kitchen.";
    }
else
    {
        cout << "That is not a valid answer...";
    }

When I input any value, I get the output from the else statement. As in, "That is not a valid answer..."

Any advice? Also I'm doing all this in Code::Blocks.

Conditional Logic with floats not evaluating correctly

I have the following code and despite numerous attempts to get it to evaluate properly, I can't get it to work. I have a work around to check each item individually (in which case it works) but the fact that I can write what appears to be a simple math statement and it doesn't work is troubling.

I've checked the values of the points and they are well within the rectangle it will return false. If I check each individually, it will evaluate them properly and I get a true value.

Thanks in advance for your time!



public static boolean checkIfPointInRectangle(RectF rect, float canvasRotateAngle, float objRotationAngle, int sketchPadHeight, int sketchPadWidth, float pointX, float pointY) {




float[] points = new float[] { pointX, pointY }; // Transform the points to the current rotation Matrix transform = new Matrix(); transform.setRotate(objRotationAngle - canvasRotateAngle, sketchPadWidth / 2, sketchPadHeight / 2); transform.mapPoints(points); if(((rect.left <= points[0]) && (points[0] < rect.right) && (rect.top <= points[1]) && (points[1] < rect.bottom))){ return true; } else{ return false; } }

How to group the codes correctly

currently I have this set of codes. I have created an array to produce only one title (parent folder) for each group.

$already_output = array();
foreach ($it as $fileinfo) {

if ($fileinfo->isDir()) {
 $parent = $fileinfo->getFilename();
} 
    elseif ($fileinfo->isFile()) {

    $link  = str_replace('/NiamsDsmbFiles/Monitoring Committee Materials/', "http://ift.tt/1drcmf5", $parentFolderNameOfFile);


        if (!in_array($parent, $already_output)) {
            echo "Parent folder: " . $parent . ""; 
            $link =  $link . '/' . $parent . '/' . $fileinfo->getFilename();
            $already_output[] = $parent;
             else {echo '<li><a href="' . $link . '">';
            printf($fileinfo->getFilename(), $it->getSubPath(), $fileinfo->getFilename());
            echo '</a>';
        echo '</li>';                              }}



} 

}

This is displaying like this below:

Parent Folder 1: abcdef
name_of_the_pdf.pdf

Parent Folder 2: abcdef
name_of_the_pdf2.pdf
name_of_the_pdf3.pdf
name_of_the_pdf4.pdf

Parent Folder 3: abcdef
name_of_the_pdf5.pdf
name_of_the_pdf6.pdf
name_of_the_pdf7.pdf

I would like to know how I can group each parent folder together so I can make it collapsible using jquery accordion. When I apply jquery accordion to this, it groups only the first attachment to each parent folder like this.

+Parent Folder 1: abcedf
(Inside) name_of_the_pdf.pdf

Parent Folder 2: abcdef
(Inside) name_of_the_pdf2.pdf
name_of_the_pdf3.pdf
name_of_the_pdf4.pdf

Parent Folder 3: abcdef
(Inside)name_of_the_pdf5.pdf
name_of_the_pdf6.pdf
name_of_the_pdf7.pdf

Could you assist me so that all of the attachments are grouped under each parent folder please?

Thank you so much in advance.

(C++) Random numbers are equal, but program says they aren't

I am a beginner, and I created a slot machine simulator. The wheel is spun and x, y, and z are set to random numbers. I have an if statement that checks to see if x == y == z. When the program runs, and the numbers are in fact equal, it runs my code that says they are not equal. Why does this happen?

For example, the cout statement will say 1 -- 1 -- 1, then it goes to my if statement for when they are not equal, and I get the "you lose" code.

I should add, this does not happen every time. Sometimes it properly executes the if statement for when they are equal. It is very odd.

    srand(time(0));

    int x = (rand() % 2) + 1;
    int y = (rand() % 2) + 1;
    int z = (rand() % 2) + 1;

    std::cout << "The spin results are... " << x << " -- " << y << " -- " << z << std::endl << std::endl;

    if( x == y == z)
    {
    std::cout << "You win!\n\n";
    playerCoins = playerCoins + (coinsBet * 2);
    }
    else 
    {   
        std::cout << "You lose!\n\n";
    }

Why is my java program not calculating? [duplicate]

This question already has an answer here:

I am making a program that finds out your status of part time or full time worker and calculates the commission rate you get based on your sales. Then I just have to print out the status, sales, commisionType, CommissionEarned, and Profit.

I first learned programming on ruby so im trying to figure out if its just indentation or my syntax. Please don't call me a noob because, I know I am...In java at least.

Here is my code:

    import java.util.Scanner;

public class commissionCalculator {

public static void main(String[] args) 
{

    //Variable setting
    Scanner input = new Scanner(System.in);
    String status;
    double sales = 0;
    double parTimeRate = 3.5;
    double fullTimeRateLow = 5;
    double fullTimeRateHigh = 7.5;
    double commissionEarned = 0.0;
    String commisssionType = null;
    double profit;

    //Gathering input from user

    System.out.println("Please enter your status Part-Time (p) or Full-Time (f): ");
    status = input.nextLine();
    status = status.toLowerCase();

    System.out.println("How much did you make in sales?");
    sales = input.nextDouble();

    //Starting of calculations

    if (status == "p" && sales > 0)
    {
        commissionEarned = (sales * parTimeRate) / 100;
        commisssionType = "Rate Applied: 3.5%";
        status = "Part Time";
    }
        if (status == "f" && sales <= 100000.00)
        {
            commissionEarned = (sales * fullTimeRateLow) / 100;
            commisssionType = "Rate Applied: 5%";
            status = "Full Time";

        }
        if (status == "f" && sales >= 10000.00)
        {
        commissionEarned = (sales * fullTimeRateHigh) / 100;
        commisssionType = "Rate Applied: 7.5%";
        status = "Full Time";
        }

    profit = sales - commissionEarned;

    System.out.println(status);
    System.out.println(sales);
    System.out.println(commisssionType);
    System.out.println(commissionEarned);
    System.out.println(profit);
}

}

And my output will see if its full time (f) or part time (p)and the number input but after that is ignoring any calculation. Please help me.

Here is the output: Please enter your status Part-Time (p) or Full-Time (f):

f

How much did you make in sales?

100000

f

100000.0

null

0.0

100000.0

Continue to next elif after elif condition is met

I am checking for a large number of conditions (hundreds), where each one looks something like this:

s = "string"
match = True

if "x" in s:
   var_1 = "something"
elif "y" in s:
   var_2 = "something else"
elif "z" in s:
   var_1 = "something something"
   var_2 = "some thing"
else match = False

Problem is that I want to continue to check the rest of the elifs even if an elif condition is met.

Running everything as if instead of elif does not work for what I'm trying to do, since I need else match = False to trigger if no condition is met.

Is there a work-around?

Something wrong with my IF statement

I created a simple code for my web game, there are no errors but some part of the code does not work. Parts which do not work are last two if statements, it won't give users an Antimatter, but it prints out correct message. Why it won't update DB correctly ?

CODE:

    ///////////////////////////////BLACKBOX////////////////
function buyblackbox(){
global $USER, $PLANET, $LNG, $UNI, $CONF,$resource,$pricelist;
$blackbox = HTTP::_GP('blackbox', 0);
$price = 10000 * $blackbox;
$loli   = mt_rand(1,2);
if ($price < 0) {
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
}
if($USER['antimatter'] < $price){
$this->printMessage("You do not have enough antimatter", true, array('game.php?page=premium', 2));
die();
}
elseif($blackbox < 0){
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
die();
}else{
    $USER['antimatter'] -= $price;
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkbox` = '".$loli."', `antimatter` = `antimatter` - '".$price."' WHERE `id` = ".$USER['id'].";");

if($USER['darkbox'] == 1)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` - '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('vins nem sit has succesfully be bought', true, array('game.php?page=premium', 2));
}
if($USER['darkbox'] == 2)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('BlackBox has succesfully be bought', true, array('game.php?page=premium', 2));
}
}
die();
}
/////////////////////////////////END BLACKBOX///////////////////////