samedi 31 décembre 2016

Finding the first item in a foreach?

I am trying to add the class 'active' if tis the first item in a foreach but I keep getting a parse error? I am using Laravel and Blade, this is how I pass $members

public function getView()
    {
        Cache::remember('members.members', 1, function() {
            return Player::orderBy('id', 'DESC')->where('display_member', '=', '1')->limit(10)->get();
        });

        return view('frontend.members')->withMembers(Cache::get('members.members'));
    }

Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH), expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF)

<div class="tab-content">
    @if ($members->count() > 0)
        @foreach ($members as $key => $member)
        <div role="tabpanel" class="tab-pane @if($members->first() == $member)active@endif" id="">
            <div class="col-md-12">
                <h1></h1>
                <br>
                <p>Personal Website: <a href=""></a></p>
                <p>Last Login: 1st January, 2017</p>
            </div>
        </div>
        @endforeach
    @endif
</div>

C++ calling superclass with if statment

I think I am missing something here but can't figure out what..

If I do this, I get compile error "error C2446: ':': no conversion from 'const boost::defer_lock_t' to 'const boost::try_to_lock_t'"

public: 
explicit BasicScopedLock( CCondition& condition, bool initiallyLocked = true ) 
    : LockType( condition.mutex, (initiallyLocked == true ? (boost::try_to_lock) : (boost::defer_lock)) ) 
    , m_condition( condition ) 
{ 
} 

But if I do this, it compiles.

public: 
explicit BasicScopedLock( CCondition& condition, bool initiallyLocked = true ) 
    : LockType( condition.mutex, boost::try_to_lock ) 
    , m_condition( condition ) 
{ 
} 

This works too...

public: 
explicit BasicScopedLock( CCondition& condition, bool initiallyLocked = true ) 
    : LockType( condition.mutex, boost::defer_lock ) 
    , m_condition( condition ) 
{ 
} 

Does anyone have a clue on why compiler doesn't like the if statement here?

Thank you!

Validate fields with isset

I try to create a basic calculator, and that works perfectly but i need validate the fields. I' trying with if() but php ignores this. If fields is empty not showing the menssage 'Complete all fields' and execute the function operadora(); resulting 0.

What am I doing wrong?

Sorry for my bad english :(

This is the form:

<form action="calcular.php" method="post">
<input name="valor1" type="number">
  <select name="operacion" id="">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
   </select>
<input name="valor2" type="number">
<input type="submit" name="enviar" value="enviar">
</form>

And this is the php code:

<?php

if(isset($_POST['enviar'])){
  if(!isset($_POST['valor1']) ||
  !isset($_POST['valor2'])){
    echo 'complete all fields';
  }
  else{
    $valor1 = $_POST['valor1'];
    $valor2 = $_POST['valor2'];
    $operacion = $_POST['operacion'];
    operadora($operacion,$valor1,$valor2);
  }
}

function operadora($operador, $valor1, $valor2){
if(!strcmp($operador,"+")){
     $resultado = $valor1+$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"-")){
     $resultado = $valor1-$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"*")){
     $resultado = $valor1*$valor2;
     echo $resultado;
   }
if(!strcmp($operador,"/")){
     $resultado = $valor1/$valor2;
     echo $resultado;
   }
};

 ?>

Why is the second ifelse not evaluated?

In the code below, I do not understand why the second ifelse() is not evaluated. Can someone explain it? How to rewrite the ifelse statement?

The y1==1 and y2==1 in the last row are matched, and the column result should be filled with 1.

df <- data.frame(x1=c(0,0,NA,NA,NA),y1=c(NA,NA,NA,NA,1),x2=c(0,NA,NA,0,NA),
                 y2=c(1,NA,NA,NA,1))

df$result <- with(df, ifelse((x1==0 & x2==0), 0, ifelse((y1==1 & y2==1), 1, 100)))

if a buttons text is empty, then

In this code I want to make a buttons visibility gone, if the text of the button is "":

        if (button TEXT IS "")
    {
        button.setVisibility(View.GONE);
    }    

    else 
    {

        button.setVisibility(View.VISIBLE);
    }   

How can I form the if-Statement to get a result? Thank you!

Android Studio activity - using onCreate(), onResume() etc

So, I have an activity where the user can view words he has collected, then enter a word, press the submit button, and if this word exists and uses the letters the user has available then he will be given a score which appears in a textView. Issues I have: when the user exits the activity (e.g. goes to collect more letters) and then goes back to the activity where he enters words, the current score is no longer there and the all the letters he has collected are back in there even if has used them and been removed. I understand that this issue is because the activity gets reset each time the user leaves it and enters it I just don't quite understand how to use the onCreate, onResume, onPause methods. Second issue: it seems the user can only enter one word. when I try to enter another word after having entered the first word, nothing happens even though he has letters for that word available.

my code has this structure currently

public class calculateScoreActivity extends AppcompactActivity{
//initialise variables to be used
public void onCreate(Bundle savedInstanceState){
//set variables to textViews etc
//then go to method buttonClicked()
}
public void buttonClicked(){
if the button is pressed and user input is correct go to:
updateDictionary()
calculateScore()
}
public void updateDictionary(){
remove letters used in the word the user inputted
}
public void calculateScore(){
calculate the user score
}

Am I correct writing these methods outside the onCreate? Where and how would I use onPause and onResume so that the user can pick up from where he left?

How to make conditional calculations in a table using loop mechanisms? (Matlab)

I have the following table ('ABC'): enter image description here


Goal: For each date, create 2 new variables (e.g. 'LSum' and 'USum'). 'LSum' should calculate the sum of all cell values across the column universe (4-281), but only with those values whose header is in the cell array of ABC.L, for that specific date. In the same fashion, 'USum' should calculate the sum of all cell values across the columns, but only with those values whose header is in the cell array of ABC.U, for that specific date.


Thanks in advance for your help, especially for the looping through date and the cell arrays of 'L' and 'U' at the same time.

vendredi 30 décembre 2016

Missing return statements, loops

A method I'm using requires loops, and I have managed to work myself into a corner trying to split up the loops up by adding new methods. I've pasted part of my code below. I'm currently receiving the error message "missing return statement" and although I realise why this is happening I am unsure as how to continue. Any help or suggestions would be appreciated! Thanks.

public String addJob(String cust,boolean onSite, boolean sHand, String lang)
 {   int nt = 100;

    if (customers.containsKey(cust))
    {
             if (0 >= getCustomerCredit(cust)) { 
             return " Customer over credit limit "; }

             if (nt >= getCustomerCredit(cust))
             {
                Job jb = new Job(cust, onSite, sHand, lang);
                job.put(jb, getNewJobNo());
                    if(lang != "English")
                      { 
                        isStaffAvailableWork(trnsltr);}
                    if(sHand == false)
                      { isStaffAvailableWork(clk);
                      }
                    else { isStaffAvailableWork(typst);
                      }

            }

    }
     else { 
           Customer c = new Customer(cust);
           customers.put(cust, ntnt);
           Job jb = new Job(cust, onSite, sHand, lang);
           job.put(jb, getNewJobNo());
                if(lang != "English")
                  { 
                    isStaffAvailableWork(trnsltr);}
                if(sHand == false)
                  { isStaffAvailableWork(clk);
                  }
                else { isStaffAvailableWork(typst);
                      }

    }    
 }

 public String isStaffAvailableWork(Staff stf)
 {    
      if (staff.containsKey(stf)&&(stf.isStaffAvailable()==true))
      { 
           jb.setJobStatusOnGoing();
           stf.setStaffBusy();
           jobNoAndstaffId.put(staff.get(stf), job.get(jb));
           return "Staff allocated: " + stf;

       }

      if (staff.containsKey(stf)&&(stf.isStaffAvailable()==false))
      { 
           jb.setJobStatusWaiting(); 
           return "Job Waiting";

       }
      else return null;
    }

what can be a statement after if?

def check():
    if [1,2,3]:
        return [2,3,4]

check()
[2, 3, 4]

I thought [1,2,3] is a list but not a Boolean expression that can be True or False? But why does the function consider the list ([1,2,3]) to be True?

.animate() in jQuery and if condition seems to don't work

I'm not an expert in jQuery and I try to create a kind of button-toggle : When I click on the switch-button "Home/News", the content should switch too.

But that seems to don't work... Despite the if condition, the condition AND the else are executed... I don't get it. Someone can tell me where do I failed ?

Here is the jsfiddle : http://ift.tt/2iNQ8Hu

The jQuery :

$(document).ready(function(){ function switchButton(){ console.log("coucou") $('.onoffswitch').click(function(){ if($('.onoffswitch').hasClass('nothere')){ $('.container_slide_actu').animate({ left : 0}, 700); $('.onoffswitch').removeClass('nothere'); }else{ $('.container_slide_actu').animate({ left : '-100%'}, 700); $('.onoffswitch').addClass('nothere'); } }); } switchButton(); });

Thanks in advance.

how do i exit a for loop in an if else statement? groovy - java

my code work fine until i add the else bit

String getInputSearch = JOptionPane.showInputDialog("city")

       for(int i=0; i < listArray.length; i++) {
         if(getInputSearch == loadData()[i][0]) {
         for(int j=0; j< loadData()[i].length; j++) {
            println(loadData()[i][j])
            }
             println("")
        }
        else{
            println( getInputSearch+ "not a valid city");
     }

   }

if i add a break to the else bit, the loop only works once and if i dont it keeps printing not a valid city, even if the city is valid until it reaches the the right index in the array. (data is read from a text file btw) help would be appreciated.

module inside if in verilog

i'm not that much in verilog i'm trying to call a module inside if statement i can't find the answer in google or may i didn't understand what should i do with MY CODE

my code is a full adder addition i need the IF cause i want to add other things

this is my code:

module top (a,b,cin,Cout,Ctemp,sum,clk,X);
input [3:0] a,b;
input  X;
input cin,clk;
output reg[3:0] sum;
output reg[2:0] Ctemp;
output  reg Cout;
always@(posedge clk)
begin
generate
if (X==1)
add bit0(a[0], b[0], cin,  sum[0], Ctemp[0]); //here i need to call add module
add bit1(a[1], b[1], Ctemp[0], sum[1], Ctemp[1]);
add bit2(a[2], b[2], Ctemp[1], sum[2], Ctemp[2]);
add bit3(a[3], b[3], Ctemp[2], sum[3], Cout);
end
endgenerate
endmodule

module add(a, b, cin, sum, cout); 
input  a; 
input  b;
input  cin;
output sum;
output cout;
assign sum = (~a*~b*cin)+(~a*b*~cin)+(a*~b*~cin)+(a*b*cin);
assign cout = (a*b)+(a*cin)+(b*cin);
endmodule

if one input of two are not empty

How can i make an "if" condition that is mean if one input of two are not empty then cann go further.

enter image description here I make a condition

if(empty($username)||empty($email)|| empty($f_name) ||empty($l_name) || empty($password) || empty($repassword) || empty($mobile)
|| empty($iban) ||empty($bic) || empty($kartennumer) || empty($cvv) {
    echo "
        <div class='alert alert-warning'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><b>Bitte geben Sie alle Felder ein...!</b>
        </div>
    ";
    exit();

}

But I want to make if $iban and $bic are complete than I don't need to complete $kartennumer and $cvv. How can I make that ? I try more solution and I can't finde it?

Repeat in try catch function after close function in GUI

I have 2 guides. From "Main" guide i called "Search" guide. In search guide have code which check or input value is true if is true got new guide with info. But if input value is false i got popup-message, and still new guide just without info. When i add close function it makes loop and always popup new window and new guide. Please help me. Thanks in advise. Sorry for english.

conn = database('baze', 'root', 'root', 'Vendor', 'MYSQL', 'Server', 'localhost', 'PortNumber', 3306);
setdbprefs('datareturnformat','structure');
a = getappdata(0,'numeris');
if iscell(a) && numel(a) == 1
    a = a{1};
end
if ~ischar(a) || isempty(a);
    error('A valid string must be supplied!');
end
sqlquery = ['select vardas, pavarde, laipsnis, pareigos, telefonas, marke, numeris, tarnyba, nuotrauka from info '...
       'where numeris = ' '''' a '''']; 
curs = exec(conn, sqlquery);
setdbprefs('DataReturnFormat','cellarray');
curs = fetch(curs);
if isempty(curs) || ~isstruct(curs) || ~isfield(curs, 'data') || size(curs.data,2) < 7
try
numeris = curs.data{7};
vardas = curs.data{1};
pavarde = curs.data{2};
laipsnis = curs.data{3};
pareigos = curs.data{4};
telefonas = curs.data{5};
marke = curs.data{6};
tarnyba = curs.data{8};
nuotrauka = curs.data(9);
set(handles.edit1,'string',vardas);
set(handles.edit2,'string',pavarde);
set(handles.edit3,'string',laipsnis);
set(handles.edit4,'string',pareigos);
set(handles.edit5,'string',telefonas);
set(handles.edit6,'string',marke);
set(handles.edit7,'string',numeris);
set(handles.edit8,'string',tarnyba);
axes(handles.axes1);
nuotrauka = nuotrauka{1};
jimage = javax.imageio.ImageIO.read(java.io.ByteArrayInputStream(typecast(nuotrauka, 'uint8')));
height = jimage.getHeight;
width = jimage.getWidth;
pixels = reshape(typecast(jimage.getData.getDataStorage, 'uint8'), [3,width,height]);
img = cat(3, ...
      transpose(reshape(pixels(3,:,:), [width,height])), ...
      transpose(reshape(pixels(2,:,:), [width,height])), ...
      transpose(reshape(pixels(1,:,:), [width,height])));
imshow(img);
catch
    h = msgbox('Patikrinkite ar teisingai įvesti automobilio numeriai','Įspėjimas','Warn');
    close (paieska)
    return
end
end
close(curs);
close(conn);

Java poll() inside if statement

I had a little question over the execution of functions inside of an if statement.
For example this list of edges(integers), will all the values be removed from the list until it pull's 5 from the list? Or what will happen exactly.

LinkedList<Integer> edges = new LinkedList<>();

for (int i = 0; i < edges.size(); i++) {
        if(edges.poll() == 5){
            break;
        }
}

how to put a 2 button condition in a game in swift 3

My code below is a traffic light game. When the light goes green the user has 6 seconds to to hit a button to respond to the green light. If the user does not hit the button within 6 seconds the game goes to the game over scene. On the 4th loop of the game I would like the user to have to hit 2 of the button( which in the code is button xq and startStop) within 6 seconds if not the user is taken to the game over scene. Right now in the game during the 4th loop the game is automatically taken to the game over scene. I have heard about possibly using the .isSeletected command I am not sure if that is useful.

 import UIKit
     class ViewController: UIViewController {
   @IBOutlet var light: UIImageView!
   @IBOutlet var labzel: UILabel!
   @IBOutlet var startStop: UIButton!
   @IBOutlet var xq: UIButton!
     let button = UIButton()


 var timer = Timer()
 var scoreTimer = Timer()
 var s = Timer()

var timerInt = 0
var secondsOfTimer = 0
var sucessfullCompletionofOneTimeOfGame = 0

override func viewDidLoad() {
    super.viewDidLoad()
    secondsOfTimer = 0
    labzel.text = String(secondsOfTimer)

}

@IBAction func hitTheButton(_ sender: AnyObject) {
    if secondsOfTimer == 0{
        timerInt = 3
        light.image = UIImage(named: "r.png")
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
        startStop.isEnabled = false
        startStop.setTitle("Hit", for: [])
        secondsOfTimer = 0
        labzel.text = String(secondsOfTimer)
    } else {
        scoreTimer.invalidate()

    }
    if timerInt == 0 {
        secondsOfTimer = 0
        startStop.setTitle("Restart", for: [])
        }}
    func updateCounter(){

    timerInt -= 1
    if timerInt == 2{
        light.image = UIImage(named: "r.png")
    } else if timerInt == 1 {
        light.image = UIImage(named: "yellow.png")
    } else if timerInt == 0 {
        light.image = UIImage(named: "g.png")


            if sucessfullCompletionofOneTimeOfGame > 3
            {
                timer.invalidate()
                xq.isEnabled = true
                xq.alpha = 1.0
                startStop.isEnabled = true
                scoreTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)
                if self.xq.isSelected && self.startStop.isSelected {
                    return
                } else {
                    endGame()
                }
        }


            else {

                timer.invalidate()
                startStop.isEnabled = true
                scoreTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)
        }


    }}
    func endGame(){
        let next = self.storyboard?.instantiateViewController(withIdentifier: "tViewController") as? tViewController
        self.present(next!, animated: true, completion: nil)

    }
func updateScoreTime(){
    secondsOfTimer += 1
    labzel.text = String(secondsOfTimer)

    if secondsOfTimer <= 6 {
        sucessfullCompletionofOneTimeOfGame +=  1
        return
    }
    else {
    endGame()
    }}}

Javascript Radio buttons issue

I have two radio buttons - 'Italian' & 'Spanish'. When one is selected, I wont the autocomplete for 'Main' and 'Starter' inputs to be populated from different files. So when 'Spanish' is checked, it does autocomplete from http://xxx/spanish.php, and when 'Italian' is check, it does it from http://xxx/italian.php.

var radio1 = document.getElementById("radio1");
var radio3 = document.getElementById("radio3");

if (radio1.checked){
    alert("radio1 selected");


        //Starter Autocomplete  (Spanish)         
        var starterSearchData;
        $(function() {
            $.ajax({
                url: "http://ift.tt/2hU3guN",
                dataType: "jsonp",
                async: false,
                success: function(data) {
                    starterSearchData = $.map(data, function(item) {
                        if (item.course == "starter")
                            return item.name;
                    });
                    EnableAutoComplete();
                },
                error: function(xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

            function EnableAutoComplete() {
                $("#starter").autocomplete({
                    source: starterSearchData,
                    minLength: 2,
                    delay: 010
                });
            }
        });

        //Main Autocomplete   (Spanish)          
        var mainSearchData;
        $(function() {
            $.ajax({
                url: "http://ift.tt/2hU3guN",
                dataType: "jsonp",
                async: false,
                success: function(data) {
                    mainSearchData = $.map(data, function(item) {
                        if (item.course == "main")
                            return item.name;
                    });
                    EnableAutoComplete();
                },
                error: function(xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

            function EnableAutoComplete() {
                $("#main").autocomplete({
                    source: mainSearchData,
                    minLength: 2,
                    delay: 010
                });
            }
        });

}else if (radio3.checked) { .... same code, except url changed to http://xxx/italian.php... }

HTML:

<div id="radio">
    <input type="radio" id="radio1" name="radio"><label for="radio1">Spanish</label>
    <input type="radio" id="radio3" name="radio"><label for="radio3">Italian</label>
</div>
<label for="starter">Choose starter</label>
<input type="text" name="starter" id="starter"><br>
<label for="main">Choose main</label>
<input type="text" name="main" id="main"><br>

The ajax call, etc, works, but when i try the if statement, the fields do not populate/autocomplete.

Thanks.

Why Am I getting "Not All paths return a value" when using if inside a foreach

I'm trying to return a value once it finds the string match. I'm using the following code.

MetadataIcons mi = new MetadataIcons();
Type me = mi.GetType();
PropertyInfo[] pi = me.GetProperties();

foreach (var property in pi)
    if (property.Name.ToLower().Equals(prop.ToLower()))
        return property.GetValue(prop).ToString();

But, I get the error "Not all paths return a value" I thought I was able to do so that way. Do I really need to specific a return variable?

How can I debug this FOR loop?

I am a beginner in C.

I have a program which is not working due to a for loop in it. I'm pasting a working snippet of code here (it is not the exact program)-

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int numLoop = 19;
    int counter;
    int maxloops = 25;
    int takenNum1 = 9, takenNum2 = 14, takenNum3 = 17, takenNum4 = 21, takenNum5 = 24;

    for (counter=1; counter==maxloops; counter++)
    {
        printf("%d \n", counter);

        if (counter == numLoop)
        {
            break;
        }

        if (counter == takenNum1 || counter == takenNum2 || counter == takenNum3 || counter == takenNum4 || counter == takenNum5)
        {
            counter++;
            continue;
        }
    }

    return 0;
}

The expected output is: 1 2 3 4 5 6 7 8 10 11 12 13 15 16 18 19

The output I am getting is: Literally nothing. Nothing is being printed.

How can I fix this?

How to make a very simple countdown timer in Javascript?

I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension) Heres the part of my timer code:

if(timer <= 30)
    {
        for(var i = 0;i >= 30;i++)
        {
            setInterval(null,1000);
            timer++;
            document.getElementById("counter").innerHTML = timer+" seconds wasted";
        }
        alert("Time is over, you lost by "+s);
    }

If loop in tkinter - button pressed

How to get tkinter to enter the if loop when button pressed to print? I do not want the print command to be in the button function. Please help

Code:

from tkinter import *

class Player:
   N = 0
   def __init__(self, name, points):
    # instance variables goes here
    self.name   = name
    self.score  = points
    # increment class variable
    Player.N      = Player.N+1

class G_501:

  def __init__(self,players=[]):
    self.NoPlayers = len(players)
    print("Number of players",self.NoPlayers)
    Spillere = []
    Score = []
    Runde = 0


    for i in range(0,len(players)):
        P = Player(players[i],501)
        print("Player",Player.N,P.name,"- Point:",P.score)
        Spillere.append(P.name)
        Score.append(P.score)
        Score = list(map(int, Score))


    root = Tk()
    c = [False]

    def half_bull(c,event=None):
        c.append(True)
        return c

    b1 = Button(root, text="Half Bull", bg="green", fg="black", command=lambda c=c: half_bull(c))
    b1.pack()

    print(c)
    if c[-1] == True:
        print("Fedt")

    root.mainloop()

S = G_501(["Chr"])

Only need help with the tkinter part... Please help!

For loops concatenated – beginner python exercise

Hi everyone I’m writing because I’m stuck with an exercise in which I should only use for loops and if/else statements. I found a way but practically I’m iterating the same block of code four times and I’m really looking for a way to automate it. I know that probably this is not the best way to solve the exercise but now I’m not looking for the most efficient way (I already found on the solutions of the exercise), I’m asking you how can I use for to iterate the block of code

The exercise tells me to create a program that takes an IP address from the keyboard and validates that it can be interpreted as a valid IP address. An IP address consists of 4 numbers, separated from each other with a full stop. Each number can have no more than 3 digits. (Examples: 127.0.0.1) Important This challenge is intended to practise for loops, and if/else statements, so although it would probably be written for real using regular expressions we don't want you to use them here even if you know what they are.

This is what I made:

# ipAddress = input("please enter an ipAddress: ")
ipAddress = "192.168.7.7"  #test ip address


# check if number of dots is 3
numberOfDot = 0
for char in ipAddress:
    if char == '.':
        numberOfDot += 1
totNumbOfDot = numberOfDot  # output of this section is totNumberOfDot, to be checked at the end
if totNumbOfDot != 3:
    print("You inserted a wrong ip address")


# first number check            # THIS IS THE BLOCK OF CODE I WANT TO 
number1 = ''                    # ITERATE WITH FOR IF POSSIBLE
for char in ipAddress:
    if char in "0123456789":
        number1 += char
    if char == '.':
        break
if 1 <= len(number1) <= 3:
    print("First number:   OK")
else:
    print("First number:   Fail")
digitN1 = len(number1) + 1
print(number1)


# second number check
numberMinus2 = ipAddress[digitN1:]
number2 = ''
for char in numberMinus2:
    if char in "0123456789":
        number2 += char
    if char == '.':
        break
if 1 <= len(number2) <= 3:
    print("Second number:  OK")
else:
    print("Second number: Fail")
digitN2 = len(number2) + digitN1 +1
print(number2)


# third number check
numberMinus3 = ipAddress[digitN2:]
number3 = ''
for char in numberMinus3:
    if char in "0123456789":
        number3 += char
    if char == '.':
        break
if 1 <= len(number3) <= 3:
    print("Third number:   OK")
else:
    print("Third number:   Fail")
digitN3 = len(number3) + digitN2 + 1
print(number3)


# fourth number check
numberMinus4 = ipAddress[digitN3:]
number4 = ''
for char in numberMinus4:
    if char in "0123456789":
        number4 += char
    if char == '.':
        break
if 0 < len(number4) <= 3:
    print("Fourth number:  OK")
else:
    print("Fourth number:  Fail")
digitN4 = len(number4) + digitN3 + 1
print(number4)

jeudi 29 décembre 2016

>= and <= signs getting error in thymeleaf

javascript compound if condition cannot processed in thymeleaf although i wrapped in "CDATA".

<script  th:inline="javascript">
    /*<![CDATA[*/
         if(value =< 0 && value >= 100){
              return 'Please enter a value between 0 to 100';
         }
 /*]]>*/
</script>

I am getting error "Uncaught SyntaxError: Unexpected token <"

Python single line if-for combination written in block [duplicate]

This question already has an answer here:

I was learning Scientific Programing with Python and found this single line if-for combination (To count the number of times a letter is in a string):

def count_v11(dna, base):
    return len([i for i in range(len(dna)) if dna[i] == base])

Where dna is a string combination of 'ATGC' and base just a single string. Example:

dna = 'ATGCGGACCTAT'
base = 'C'

That should return 3 in this case.

As I understand, in the cases of if of single lines is

a = (value1 if condition else value2)

and the for are

newlist = [E(e) for e in list]

I would think that the if is evaluated first before the for, but in that case, there would be no i to evaluate the condition dna[i]==base because the for is not running yet. I'm trying to think how that code would be if the if and for where written in blocks instead of that compact way to understand it better, but I cant find how.

Can someone please write this in block to understand it?

Else Statement doesn't work in unity?

Alright so here is my code. This should be really simple but it doesn't want to work with me for some reason. Raycast sends a ray from the mouse, if it hits an object with a tag, it assigns a number to a variable. If it doesn't hit an object, then it sets the variable as -99. For some reason mine is hanging on:

A. I don't hit the objects, it outputs -99 the first time but after that it hangs on getting assigned 4.

B.I hit the objects and it will work just fine. After I click OFF the objects it hangs on the variable from the object I just hit previously.

RaycastHit hit; 
            Ray ray = camera.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, 10000.0f)) {
                if (hit.collider.tag == "Box") {
                    Hitnum = 1;
                } else if (hit.collider.tag == "Sphere") {
                    Hitnum = 2;
                } else if (hit.collider.tag == "Pyramid") {
                    Hitnum = 3;
                } else if (hit.collider.tag == "Trapezoid") {
                    Hitnum = 4;
                } else {
                    Hitnum = -99;
                }
            }
            Debug.Log (Hitnum);
        }

Thanks in advance. This is driving me nuts because it should be simple.

LUA If Statement

I was trying to use the LUA if function to represent the result with a “*” in front of the value under a circumstance using an if function.

C1      C2      C3
------------------
 2       5     *10
 3       5      15 

When the value in C1 is smaller than 3, the product of C1 and C2 needs to be shown as * with the actual product in C3. When the value in C1 is equal or greater than 3, the product of C1 and C2 is shown as 15. Could you please help me to find the if statement for this case?

Thank you!

Joy Li

LESS How to check if max-width is 100% and change background color

Hi I'm just getting started with LESS, CSS, Javascript, and HTML as I a building a website. I was wondering if it was possible to use LESS to check to see if the width of an element is 100% and once it is change the background color. Like a progress bar being completed. If it's not possible would I use Javascript? Where would I define that statement using the example:

.page-level-progress-menu-item-indicator-bar {
        width:0%;
        height:8px;
        background-color:@primary-color;
    }

SQL. Looping trough colums from different tables to calculate value

I want to calculate how many drivers have drove too fast. I have a table traffic. In this table on each row I can see how many cars drove in different speed categories. For this issue I only need the colums amount_drivers1 until amount_drivers10.

I have ten different speed categories (for example the values of speed_categorie colums 1-10 are: 20,30,40,50,60,70,80,90,100,110) in the table speedcategories These are different per way. For each row I have to find the speed categories per way. Speed_categorie1 is related to amount_drivers1, speed_categorie2 is related to amount_drivers2...

Then I have to use the column max_speed from the table MAX_SPEED. I have to loop trough every speed_categorie column to see if the speed_categorie is above the max_speed column. If not do nothing, if yes the amount of cars from the traffic table (the value of the column amount_drivers) has to taken into the column 'to_hard'.

The relation between the max_speed, speed_categories and traffic tables is the column 'way'. This is the foreign key.

For example the max_speed=60 (from the max_speed_table). Then only the the speed categories 70,80,90,100 and 110 (from speed_categorie table) are eligible. Then the amount of drivers from the amount_drivers6, amount_drivers7,amount_drivers8,amount_drivers9 andamount_drivers10 (from traffic table) have to go in the column 'to_hard'. So this is a sum of the columns amount_drivers6, amount_drivers7,amount_drivers8,amount_drivers9 andamount_drivers10 in this case. This sum must go in the column 'to_hard'.

I've tried using a case statement:

declare @AMOUNT INT=0

SELECT @AMOUNT=CASE WHEN VALUE_OF_SPEED_CATEGORIES_COLUMNS_FROM_TABLE_SPEED_CATEGORIES >ST.MAX_SPEED THEN
@AMOUNT += AMOUNT_DRIVERS_FROM_TABLE_TRAFFIC
ELSE 'DO NOTHING'
END
FROM MAX_SPEED ST INNER JOIN SPEED_CATEGORIES SC ON ST.WAY=SC.WAY
INNER JOIN TRAFFIC T ON SC.WAY=T.WAY

But I guess I have to use a while or for loop. Please help!

Thanks for the help!

If statement condition not running

I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.

The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.

I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {

Does anyone see anything I am missing?

$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
    $click_sql = "
    SELECT *
    FROM click_count
    WHERE user_id = ?
    AND page_url = ?
    ";
    $click_stmt = $con->prepare($click_sql);
    $click_stmt->execute(array($user_id, $curPage));
    $click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
    $page_count = $click_stmt->rowCount();
    foreach ($click_stmt_rows as $click_stmt_row) {
        $setup_status = $click_stmt_row['setup'];
        $page_total_count = $click_stmt_row['page_count'];
    }
    if ($page_count == 0) {
        $click_insert_sql = "
            INSERT INTO click_count
            (user_id, page_url, page_count, setup)
            VALUES(?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE page_count=page_count+1;
        ";
        $click_insert_stmt = $con->prepare($click_insert_sql);
        $click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
    }
    else {      
        $click_update_sql = "
            UPDATE click_count
            SET page_count=page_count+1
            WHERE user_id = ?
            AND page_url = ?
        ";
        $click_update_stmt = $con->prepare($click_update_sql);
        $click_update_stmt->execute(array($user_id, $curPage));
    }

If statement is not working with my getText().toString()

Before I start explaining I'll just get you into the code.

EditText br = (EditText) findViewById(R.id.editText);

if ( br.getText().toString() == "0") {

                Toast.makeText(MainActivity.this, "It works", Toast.LENGTH_LONG).show();

}

It's that simple. But I don't understand why it doesn't work! I typed in ("1" == "1") in the if statements just to see if there is anything else wrong. But the message shows up on my phone.

The edittext field has the number 0 on it. I have no clue why this simple if statement would not work. I also have little knowledge so please do help.

            }

How to iterate over each value stored in a List

I have a function whose parameter is List<Long> l.

In the function there is a if statement for which I have to iterate over each value stored in the List<Long> l.

I'm trying to do this:

    public void myFunction(final List<Long> l) {

        final int size = l.size();

        for (int i = 0; i < size; i++){
           if (l.get(i) <= 900) {
              ...       
           Log.d("resultL", String.valueOf(l.get(i)));
           } else {
           }
        }

    }

here resultL logged only -64338

the values stored in the List<Long> l are [-64338, -15512, -15224, 8344], but what is happening is that the if statement is using only -64338 and doing the logic instead of using all the 4 values.

Why is this happening?

How to iterate over all the 4 values stored here and not just one?

Please help with this issue.

How to use expr inside if statement?

I have not managed to understand how to embed expr in other constructs. I can easily type

set i {1 2 3}
expr {[llength $i]} #result is 3

However after long research I have not managed to find a way to put that inside if

if {"magic tcl code with expr and llength==3 required here"} {
   puts "length is 3"
}

Add condition to Woocommerce plugin for default setting

I'm trying to add a condition to a Woocommerce plugin to limit the default enabling function to only be for certain product categories. I've got the functions to return the category names working, but I'm not sure how to add it into this plugin.

The constructor uses this line to set it:

$this->gift_wrap_enabled         = get_option( 'product_gift_wrap_enabled' ) == 'yes' ? true : false;

Then it gets the option from the settings:

add_option( 'product_gift_wrap_enabled', 'no' )

$this->settings = array(
        array(
            'name'      => __( 'Gift Wrapping Enabled by Default?', 'woocommerce-product-gift-wrap' ),
            'desc'      => __( 'Enable this to allow gift wrapping for products by default.', 'woocommerce-product-gift-wrap' ),
            'id'        => 'product_gift_wrap_enabled',
            'type'      => 'checkbox',
        ),

This code shows what I was trying to do.

function parent_cat_enable() {
    global $post;
    if (all_cat_classes($post)) === 'parent-category'){
    $this->gift_wrap_enabled = true;
    }
    return $this->gift_wrap_enabled;
}

Any help would be greatly appreciated! Thanks.

New to java stuck on Switch statement

Hi I want to create a program by using switch statement where the user input for length should be within 1-100. If the user enters a value which is lees than 1 or greater than 100 then an error will be shown [System.out.println("Your number (" + Length + ") is not between 1-100. \nTry again.");]. The program I made is asking for an user input between 1-100 and its giving the output correct when I am entering the number 1 as number 1 is mentioned in case 1. But its not reading the condition that I have mentioned in case 1, when I am giving a different value to check whether the condition is working or not.

package com.company;
import java.util.Scanner;

/**
 * Created by MRIDULA on 27-12-2016.
 */
public class SwitchDemo {

    public static void main(String[] args) {

        Scanner length = new Scanner(System.in);
        System.out.println("Enter a number between 1-100 for length: ");

        int lamba;
        lamba = length.nextInt();

        switch (lamba) {

            case 1: while ((lamba> 100) || (lamba <= 1)) {

                System.out.println("Great, your number for length is between 1 and 100");
            break;}

                case 2: System.out.println("Your number for length is not between 1-100. \nTry again.");
                    break;

                default: System.out.println("Invalid number.\nTry again.");
            }
        }
    }

. Can someone tell me what needs to be done to get the desired result in the below mentioned program?

Is this error selection or conditional? (Java)

I have an error, on the third IF statement. It checks to see if the user entered at number within a range (1-6) and the letter is a-f. I cant test my search algorithm because there seems to be an error in that line. I can't work it out. What seems to be wrong? Is it the answer.charAt(1)?

boolean wronganswer = true;
while (wronganswer == true){

    answer = (String)JOptionPane.showInputDialog(null, new JLabel(sb.toString()), "Battleships", JOptionPane.INFORMATION_MESSAGE, pic, null, "");
    if(answer.length() == 2){
        if ((Character.isLetter(answer.charAt(0))) && (Character.isDigit(answer.charAt(1)))){
            if ((answer.charAt(1) >= 0) && (answer.charAt(1) <= 6)){
                for (int k = 0; k < rows.length; k++){
                    if(rows[k] == (""+answer.charAt(0))){
                        wronganswer=false;
                    }
                }
                JOptionPane.showMessageDialog(null,"No! That letter is not on the grid!");
            }
            else{
                JOptionPane.showMessageDialog(null,"No! That number is not on the grid!");
                System.out.println(answer.charAt(1));
            }
        }
        else{
            JOptionPane.showMessageDialog(null,"No! Enter a letter, THEN a number!");
        }
    }
    else{
        JOptionPane.showMessageDialog(null,"No! Enter ONE letter and ONE number!");
    }

}

[EDIT] Fixed an indentation error when pasting to stack overflow

Python: concat string if condition, else do nothing

I want to concat few strings together, and add the last one only if a boolean condition is True. Like this (a, b and c are strings):

something = a + b + (c if <condition>)

But Python does not like it. Is there a nice way to do it without the else option?

Thanks! :)

else statement is not recognized

Sorry, I look for information everywhere but didn't find anything new. I have a home work for my c# programming course, I entered the else statement into my code, but it says that it is an invalid expression term, I don't know what I made wrong, if you can Help me I would be very grateful, thank you.

mercredi 28 décembre 2016

Returning value with condition through a function using PHP

I am trying to return a value to a function with condition

for example,

function thisFunction($para){
  return ($para == true)? "Yes":"No";
}

is that the right way to return????

What if i need to return an array object? what is the possible solution to do it ?

if statements leading to unresolved identifier

According to Xcode, the "query" in the cloud kit perform function alerts me that "query" is an unresolved identifier. I know this issue revolves around the if statements because this code works if "query" is clearly defined by one record type. However, I do not understand why query is unresolved in this situation, when all potential queries are accounted for.

 if newindex.row == 5
    {
        let query = CKQuery(recordType: "mexican", predicate: predicate)
    }
    if newindex.row == 6
    {
        let query = CKQuery(recordType: "seafood", predicate: predicate)
    }
    else if newindex.row == 7
    {
        let query = CKQuery(recordType: "steakhouses", predicate: predicate)
    }


    publicDB.perform(query, inZoneWith: nil)

how can i use the i variable outside the for loop?

I want to use the value of 'i' in a certain point, like in the example below. What i have tried to do didnt work, what else can i do?

 int i =1;
 int r;


for(i=1;i<=100;i++){

num = reader.nextInt();

if (num == 55){
    r=i;
}
System.out.println(" 55 was typed in when i was equals to: "+r);

For Java, how can I make a variable be an image? [on hold]

I want my variable to be an image so that when something occurs such as an if statement being satisfied, that image will be displayed and hide all others. How do I do that?

Need to move rows in excel based off of contents in column but by listing what not to move in excel vba

I need to move rows based off of the contents from column 7. Now the thing is I need to list the things that are not to be moved over because they it's only 5 things ("YS,CO,CM,CS,SN") vs. a very long list that I do not even have a full list of all the possibilities.

I have thought that this could possibly be an if else statement or ifnot then statement but am unsure what the syntax would be.

Below I have what it would look like if I wanted to move the 5 items but I basically need the opposite.

Also I know the With .Range("$A$2:$O$" & Cells(Rows.Count, "A").End(xlUp).Row) part isn't correct so if someone happens to know how to make it go to the end of the page that would be a great help as well.

With Worksheets("YS,CO,CM,CS,SN")
    With .Range("$A$2:$O$" & Cells(Rows.Count, "A").End(xlUp).Row)
            .AutoFilter Field:=7, Criteria1:=Array("YS", "CO", "CM", "CS", "SN") _
            , Operator:=xlFilterValues
            .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) _
            .Copy Destination:=Worksheets("Others").Range("A2")
            .SpecialCells(xlCellTypeVisible).Delete
        End With
        .AutoFilterMode = False
    End With

How do I correctly use a bool with an if statement?

I have this method called "DoStuff()" and what it does it that it checks if the checkboxes are checked and if they are then do something.

    private void DoStuff()
    {
      if(Checkbox1.isChecked == true)
        {
          DoSomething();
        }

      if(Checkbox2.isChecked == true)
        {
          DoSomething();
        }

      if(Checkbox3.isChecked == true)
        {
          DoSomething();
        }

    }

How do I correctly set a bool so I dont have to do "== true" to every if statement?

Not getting complete output in R

I have three excel files, Book1, Book2, Book3, with me. Each one of them consists of 4 rows and 5 columns. And each cell contains a numeric value of an observation. Now I have a 3 tuple, (1, 2, 1) and I want to compare the numeric values of each cell of Book1 with 1st tuple (1) and of Book2 with 2nd tuple (2) and similarly Book3 with 3rd tuple (1). Now, whenever the corresponding cells of these excel files match with this tuple, I want to print 1 otherwise 0. That is, say my (1,2) cell in Book1 contains 1, in Book2 the cell (1,2) contains 2 and in (1,2) cell of Book3 we have 1, then I want to print 1 else 0.

So this is the program I wrote :

  library(openxlsx)

  Book1 = read.xlsx("D:/Python/Book1.xlsx" , colNames = FALSE)
  Book2 = read.xlsx("D:/Python/Book2.xlsx" , colNames = FALSE)
  Book3 = read.xlsx("D:/Python/Book3.xlsx" , colNames = FALSE)

  for (i in range(1,4)) {
     for (j in range(1,5)) {
        if(Book1[i,j]==1 & Book2[i,j]==2 & Book3[i,j]==1)
           print(1) 
        else
           print(0)

      }

   }

But the output I am getting is not what I expected.

1
0
0
1

Just these 4 numbers. I thought my loop would would give me a total of 20 values of 1's and 0's. But there seems to be some problem with the program which I can't detect. Can someone please help me with this?

Also, if instead of 4 rows and 5 columns, I have a very large number of rows and columns, say 10000 each, then will this format of the program work or some other methodology is required?

Android if-else equals not working

I have trouble with this simple code. The comparison with the strings do not seem to work, and I get a different result than hoped. I inserted a Toast for each cycle, to compare the result. What's wrong.

if (shared.equals("AZ") || shared.equals("") && shared1.equals("insieme") || shared1.equals("")) {
         visualizza = 3;
        Toast.makeText(getActivity(), visualizza + " " + shared + " " + shared1,
                Toast.LENGTH_SHORT).show();
    } else if (shared.equals("ZA") && shared1.equals("insieme")) {
        visualizza = 4;
        Toast.makeText(getActivity(), visualizza + " " + shared + " " + shared1,
                Toast.LENGTH_SHORT).show();
     } else if (shared.equals("AZ") && shared1.equals("default")) {
        visualizza = 1;
        Toast.makeText(getActivity(), visualizza + " " + shared + " " + shared1,
                Toast.LENGTH_SHORT).show();
     } else if (shared.equals("ZA") && shared1.equals("default")) {
        visualizza = 2;
        Toast.makeText(getActivity(), visualizza + " " + shared + " " + shared1,
                Toast.LENGTH_SHORT).show();
     }

Unexpected "=" in ifelse loops

I want to create a new column 'fgroup' based on the various combinations of values in three other columns: 'GVT', 'FOTH' and 'UNK', all three columns having either values 0 or 1. I have made this script using MUTATE.

sysrev$fclass <- mutate(ifelse(sysrev$GVT=1 & sysrev$FOTH=0 & sysrev$UNK=0, sysrev$fgroup=1),
                        ifelse(sysrev$GVT=1 & sysrev$FOTH=1 & sysrev$UNK=0, sysrev$fgroup=2),
                        ifelse(sysrev$GVT=0 & sysrev$FOTH=1, sysrev$fgroup=3),
                        ifelse(sysrev$GVT=0 & sysrev$FOTH=0 & sysrev$UNK=1, sysrev$fgroup=4))

However, it returns the error message:

Error: unexpected '=' in "                        ifelse(sysrev$GVT="

This is probably easy but I need some advice...

Autohotkey / pulovers macro creator inputbox loop error

First post here on stack overflow, I've been using the forums and lurking for a while but decided to sign up as my job now involves a lot more scripting.

So I'm using Pulover's Macro Creator to build an autohotkey script and I can't get my head around a problem with the InputBox command.

The purpose of the script is to error check user input, comparing the output variable to a set of 4 predetermined values. If the ouput variable is found to be invalid a MsgBox pops up to inform the user and then the script loops back around to the begginning so that they can try again.

The issue I'm having is that the script hangs on the InputBox command, but only after it has looped back to the start after an invalid string was detected by the if switch.

e.g. InputBox - user inputs invalid variable MsgBox appears Script restarts InputBox - user inputs VALID variable Script hangs

Here is my code: F8::

/*
This script asks for user input and keeps looping until the input matches the predefined valid strings.
*/

Loop
{

    InputBox, price_type, title, text, , , , , , , , RRP ; Get user input for "price_type" variable

    Sleep, 5

    StringUpper, price_type, price_type ; convert variable to uppercase to allow error checking

    Sleep, 5

    If price_type not in RRP,SALE,OFFERING,WAS ; check variable for invalid strings

        {
        MsgBox, 16, Invalid Input, Invalid Input message ; warn user that input is invalid
    }

Until, %price_type% in RRP,SALE,OFFERING,WAS ; infinite loop until variable matches valid input options
}

I have a suspicion the problem is to do with the way pulover's macro creator formats the ahk script but I'm all out of ideas!

Any help would be greatly appreciated.

Many thanks Doug

Segmentation fault using relational operators in if condidtion

The first if condition leads to a segmentation fault. I can't really comprehend why, since I use similar if clauses with relational operators elsewhere. Thanks for your help in advance.

int foo(char *str1,char **str2, char **str3)
{
  char *token1;
  char *token2;
  char *token = strtok(str1, "\"");
  int spaces = strcmp(token,"  ");
  int parenthesis = strcmp("{",token);
  if((name_a == NULL) || ((spaces != 0) && (parente != 0))) 
  {
    printf("ERR.\n");
    return 0;
  } 
  token = strtok(NULL, "\"");
  if(token == NULL)
  {  
    printf("2ERR\n");
    return 0;
  }
  token1= strtok(NULL, "\"");
  if(token1 == NULL || strcmp(token1," -> ") != 0)
  {
    printf("3ERR\n");
    return 0;
  }
  token2 = strtok(NULL, "\"");
  return 1;
  }

How to do conditional statements in pandas/python with null valves

How do I do condition replacements in pandas?

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])

In R - think this code is very easy to understand:

library(dplyr)
df = df %>% 
mutate(   #   mutate means create new column for non-r people
my_new_column = ifelse( is.na(the_2nd_column)==TRUE & is.na(the_3rd_column)==TRUE, ' abc', 'cuz')

how do I do this in pandas - probably dumb question with the syntax, but I have heard np.where is the equivalent of if else in R...

df['new_column'] = np.where(np.nan(....help here with a conditional....))

mardi 27 décembre 2016

VBA EXCEL: how to compare content of a cell against specific strings

'Initialising no of licenses to 0

dim transientLicense AS integer transientLicense=0 dim steadyLicense AS integer steadyLicense=0 dim staticLicense AS integer staticLicense=0

'checking conditions

if( (value.cell(AH) =("radial vibration" or "acceleration" or "acceleration2" or "velocity" or "velocity2")) && (value.cell(W)="yes") && (value.cell(D)="active") Then transientLicense++ else if( (value.cell(AH) =("radial vibration" or "acceleration" or "acceleration2" or "velocity" or "velocity2")) && (value.cell(W)="no") && (value.cell(D)="active") Then steadyLicense++ else if((value.cell(AH)=("axial vibration" or "temperature" or "pressure") && (value.cell(D)="active")) Then staticLicense++

how do i write this in proper vba syntax

How do I use if statements with checkboxes without clutter

I have this application with 13 checkboxes.
And i want to do if statements to check if a textbox is checked but its going to get really cluttered after checking 4 of them for example

if (checkBox1.IsChecked == true)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == true && checkBox2.isChecked = false)
    {
          DoSomething();          
    }

else if (checkBox1.IsChecked == false && checkBox2.isChecked = true)
    {
          DoSomething();          
    }

I bet you can see the pattern already.. I need to check every possible solution for 13 checkboxes, is there a way to do this more efficiently?

php - Foreach loop trough array with decimal numbers to reduce tokens. codeigniter

Been twisting my head on a foreach loop that decreses tokens. Attaching code that runs. What i try is to run trough the orders with same price (4 in total here, but after 3 are processed, i can not make it break. Also total tokens/coins add up to 4000 and should go up to 5000 leaving last order with xxxx coins left. Also the < > in the if statements are acting funny, probarly due it's a 8 digit decimal to play with.

The break should be the $user_amout initially and update the last order with remaining tokens to database.

$user_price =  '0.00002450';
$user_amount = '5000.00000000';

  if ($check_price == $user_price) {
  // We found a match, buy the amount of tokens
  echo "<br />We found Price a match<br />";
  $equalorder = $this->getEqual($type, $user_price);
  var_dump($equalorder);
  foreach ($equalorder as $equal) {
    if ($user_amount > $equal->amount){
      $to_reduce = $equal->amount;
    }
    $user_amount = bcsub($user_amount,$to_reduce,8);
    $order_check += $user_amount;
    //$user_amount -= $to_reduce;
    echo "<br> Coins to process from this order : ";
    echo $user_amount ;
    echo "<br>";
    if ($order_check == '5000.00000000') {
      break;
    }
  }  // End foreach loop
  echo "<br /><br /> Total coins processed : ";
  echo $order_check;
}

the result i get when running it with the var dump included.

    We found Price a match
array(4) { [0]=> object(stdClass)#29 (3) { ["id"]=> string(1) "1" ["price"]=> string(10) "0.00002450" ["amount"]=> string(13) "2500.00000000" } [1]=> object(stdClass)#28 (3) { ["id"]=> string(1) "2" ["price"]=> string(10) "0.00002450" ["amount"]=> string(13) "1000.00000000" } [2]=> object(stdClass)#27 (3) { ["id"]=> string(1) "4" ["price"]=> string(10) "0.00002450" ["amount"]=> string(13) "4000.00000000" } [3]=> object(stdClass)#26 (3) { ["id"]=> string(1) "9" ["price"]=> string(10) "0.00002450" ["amount"]=> string(14) "10000.00000000" } } 
Coins to process from this order : 2500.00000000

Coins to process from this order : 1500.00000000

Coins to process from this order : 500.00000000

Coins to process from this order : -500.00000000


Total coins processed : 4000

Thanks for any help.

Copy whole row across woorkbooks based on multiple citeria

piecing together bits of code i found and i have two options that both give me errors. I know the answer is obvious but i can't seem to find it...

Error always appears on the "IF" code line on debugger, usually on "_Global" mismatch or etc.

Search for a match in a different workbook based on 3 criteria. if all three are a match then copy the whole row to the next available row in the current workbook.

There could be zero matches or there could be many on a given run (that's why there is that "no wins this week"). also it would be nice when i run this that it writes over the saved results of last time. (i can deal with that later).

"wk1" is a forumla in a cell that give the week number based on =today()-14

my headers for columns on destination worksheet are on row 3. data to check in other workbook starts on row 2. Data to check is column A:AN, row2 to end ('000s).

Suggestion 1, lngLoop:

Sub WinsUpdate()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim wb1 As Workbook, wb2 As Workbook
Dim lngLoop As Long
    lngLoop = 1
Application.ScreenUpdating = False
Set wb1 = Workbooks("Weekly Sales Dashboard")
Set wb2 = Workbooks("Monday Sales Meeting Data")
Set ws1 = wb1.Sheets("Roll_12")
Set ws2 = wb2.Sheets("Sales Weekly Wins")
Set wk1 = ws2.Range("C2")
With Workbooks("Weekly Sales Dashboard").Worksheets("Roll_12")
    For lngLoop = 1 To Rows.Count
    If Cells(lngLoop, 5).Value = "USA - Chicago" And Cells(lngLoop, 9).Value = "Closed/Won" And Cells(lngLoop, 18).Value = wk1 Then
        .EntireRow.Copy Destination:=ws2.Range("A:A" & Rows.Count).End(xlUp).Offset(1)
        Else: ws2.Range("F1") = "No wins this week"
    End If
    Next lngLoop
End With
Application.ScreenUpdating = True
End Sub

Suggestion 2:

Sub WinsUpdate()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim wb1 As Workbook, wb2 As Workbook
Application.ScreenUpdating = False
Set wb1 = Workbooks("Weekly Sales Dashboard")
Set wb2 = Workbooks("Monday Sales Meeting Data")
Set ws1 = wb1.Sheets("Roll_12")
Set ws2 = wb2.Sheets("Sales Weekly Wins")
Set wk1 = ws2.Range("C2")
With Workbooks("Weekly Sales Dashboard").Worksheets("Roll_12")
    If Range("E:E").Value = "USA - Chicago" And Range("L:L").Value = "Closed/Won" And Range("R:R").Value = wk1 Then
        .EntireRow.Copy Destination:=ws2.Range("A:A" & Rows.Count).End(xlUp).Offset(1)
        Else: ws2.Range("F1") = "No wins this week"
    End If
End With
Application.ScreenUpdating = True
End Sub

my interpreter don't recognize December as the winter month (if/else)

I'm fairly new to Python. I'm using PyCharm for practice. When I typed "December" in month's input and the interpreter recognize December as the autumn month. Why is this happening? (Look at the bottom if you don't understand what I mean)

Winter = ['December', 'January', 'February']
Spring = ['March', 'April', 'May']
Summer = ['June', 'July', 'August']
Autumn = ['September', 'October', 'November']

month = input('What is the current month? ')

if month == Winter:
    print('%s is in the Winter' % month)

elif month == Spring:
    print('%s is in the Spring' % month)

elif month == Summer:
    print('%s is in the Summer' % month)

else:
    print('%s is in the Autumn' % month)

What is the current month? December
December is in the Autumn

Clojure: Compare an operator to list element (data)

I want to code a simple derivative solver. Therefore I need some code that is capable of checking which operator is used, but I just can't get it to work. I'm a newbie in clojure so I might overlook some important basic thing here .. :)

This is some test code:

(defn get-input []
'(* x y))

(println (get-input))
(println (first (get-input)))

(println 
    (if (= * (first (get-input)))  
        "Y"
        "N"))

This yields the following output:

(* x y)
*
N

As you can see, the first element of the input list is an asterisk, but the if special form yields false (and therefore "N" is printed). How can I modify the if to check if that first element of the list is indeed an asterisk?

Why is my rails 4.2 controller's if statement not working with a url parameter?

I have a standard pricing plan table on my website. When a visitor picks a plan they get a url with a plan id in it. I'm offering two types of services, blog maintenance and online store maintenance. I have the following if statement in my controller and it works if someone picks a blog plan but doesn't work for a store plan. It always wants to run the functions for the blog even if there is no blog plan parameter in the url.

if params[:user][:blogs][:bplan_id].present?
create_new_blog_customer
create_blog
elsif params[:user][:stores][:splan_id].present?
create_new_store_customer
create_store
end

I have also tried the following which works the same way (blog works but store doesn't).

if @selected_bplan_id.present?
create_new_blog_customer
create_blog
else
create_new_store_customer
create_store
end

The selected plan variable is setup like so:

def new
prepare_meta_tags title: "Create Your Account"
set_meta_tags noindex: true
@account = Account.new
@user = User.new
@blog = Blog.new
@store = Store.new
@selected_bplan_id = params[:bplan_id]
@selected_splan_id = params[:splan_id]
end

How to update the value of a field in a column with value from another field only in specific conditions (context)?

I have file where I want to update the values in the first field of a specific column (say 1 and 2) when there is a context (pipe i.e |) in the 5th field of that column.

I can use python but that is going to be a long script. I am looking for a solution using awk (pefereable) else others are fine too that are short. Also I want to embed this within python script.

Below are two columns from my data with fields within column separate by (:).

0/1:42,19:61:99:0|1:5185_T_TTCTATC:560,0,1648       0/1:38,34:72:99:0|1:5185_T_TTCTATC:1145,0,1311

0/0:124,0,0:124:99:0,120,1800,120,1800,1800    0/0:165,0,0:165:99:0,120,1800,120,1800,1800

0/0:152,0:152:99:.:.:0,120,1800    0/1:145,34:179:99:0|1:5398_A_G:973,0,6088

So, when the 5th field in that column has '|' we update first field with 5th field value.

Expected result:

0|1:42,19:61:99:0|1:5185_T_TTCTATC:560,0,1648       0|1:38,34:72:99:0|1:5185_T_TTCTATC:1145,0,1311

0/0:124,0,0:124:99:0,120,1800,120,1800,1800    0/0:165,0,0:165:99:0,120,1800,120,1800,1800

0/0:152,0:152:99:.:.:0,120,1800    0|1:145,34:179:99:0|1:5398_A_G:973,0,6088

Thanks,

Java Pattern with numbers

Hello i need to do the following /* 1234567 123456 12345 1234 123 12 1 */ i need it with a for loop and if statement please. that's the code in stars

for (int i = 0; i <= n; i++) {
        for (int j = n; j >= 0; j--) {
            if (i <= j) {
                System.out.print("*");
            }
        }
        System.out.println("");
    }

Bash - Check if array element starts with usr- [duplicate]

This question already has an answer here:

This is how my input looks like:

privatertid=[ "usr-11111", "usr-22222" ]

I am looping thru this treating it as an array and if the the string starts with usr-, I want to do more operations on it.

for i in $privatertid; do
  echo checking $i
  if [[ "$i" == usr-* ]]; then
    echo user:$i
  fi;
done

Control of the program never echoes user:usr-11111 or user:usr-22222.

Am i not comparing the "string starts with usr-" correctly?

create game over scene if button is not pressed in time (in swift)

My code is a streetlight that goes from red -> yellow -> green and times your reaction time when the light goes green. I want the user to switch view controllers to the game over view controller (automatically) if the user does not press the button within 3 seconds. I know how to segue the view controller so I don't need the code to that. I just need to know how to do a nested if loop within the update counter function. So that the user can either play the game again on go to the game over scene. If else options depending on weather the users reaction time was las than< 3 than seconds or greater than or equal to 3 seconds.

 var timer = Timer()
var scoreTimer = Timer()

var timerInt = 0
var scoreInt = 0


override func viewDidLoad() {
    super.viewDidLoad()
    scoreInt = 0
    labzel.text = String(scoreInt)
}

@IBAction func hitTheButton(_ sender: AnyObject) {


    if scoreInt == 0{
        timerInt = 3
        light.image = UIImage(named: "r.png")
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)

        startStop.isEnabled = false
        startStop.setTitle("Restart", for: [])


        scoreInt = 0
        labzel.text = String(scoreInt)


    } else {
        scoreTimer.invalidate()

    }

    if timerInt == 0 {
        scoreInt = 0
        startStop.setTitle("Restart", for: [])


    }}
// This is where the game is counted down from red to yellow to green.
func updateCounter(){

    timerInt -= 1
    if timerInt == 2{
        light.image = UIImage(named: "r.png")
    } else if timerInt == 1 {
        light.image = UIImage(named: "yellow.png")
    } else if timerInt == 0 {
        light.image = UIImage(named: "g.png")



            timer.invalidate()
            startStop.isEnabled = true
            scoreTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)


    }}
func updateScoreTime(){
    scoreInt += 1
    labzel.text = String(scoreInt)

}}

How to put if statement inside a lftp block

I am writing a bash script to download files from ftp server using lftp. I wanted to delete the files based on the second input argument.

!/bin/bash

cd $1

lftp -u found,e48RgK7s sftp://ftp.xxx.org << EOF
set xfer:clobber on
mget *.xml
if [ $2 = "prod"]; then
  echo "Production mode. Deleting files"
  mrm *.xml
else
  echo "Non-prod mode. Keeping files"
fi
EOF

However, if statement is not allowed in the lftp block before EOF.

Unknown command `if'.
Unknown command `then'.
Usage: rm [-r] [-f] files...
Unknown command `else'.

How do I embed if statement in such block?

for loop taking too long to produce/export output in Python

This question is a continuation of a previous question for loop taking too long to produce output that I asked earlier today. As advised to me in one comment, I used pandas for reading excel files in place of xlrd. Here is the program that I wrote -

   import pandas as pd
   import numpy as np

   no_of_columns = 10000

   Book1 = pd.read_excel("D:\Python\Book1.xlsx",header=None,name=range(no_of_columns))
   Book2 = pd.read_excel("D:\Python\Book2.xlsx",header=None,name=range(no_of_columns))
   Book3 = pd.read_excel("D:\Python\Book3.xlsx",header=None,name=range(no_of_columns))


   for i in range(1,11001):
      for j in range(0,10000):
         if Book1.iloc[i,j] == 100 and Book2.iloc[i,j] == 150 and Book3.iloc[i,j] == 150:
            print 1
         else:
            print 0

But this also didn't solved the problems that I am having. The program is still running (it has been 5 hours) and the text output that I am exporting in my directory is still of size 0 bytes. Again, is there anything wrong with the program? Why am I getting a file whose size has been the same since the beginning of the execution? I have ran such kind of large loops on R but each time I started to export my output in text or in excel format, I get a file in my directory whose size continues to increase as the loop progresses. So why this isn't happening here? What should I do here?

Make =IF Function Output Numbers For "Scoring": Google Sheets

I'm am exploring methods of giving scores to different datapoints within a dataset. These points come from a mix of numbers and text string attributes looking for certain characteristics, e.g. if Col. A contains more than X number of "|", then give it a 1. If not, it gets a 0 for that category. I also have some that give the point when the value is >X.

I have been trying to do this with =IF, for example, =IF([sheet] = [Text], "1","0").

I can get it to give me 1 or 0, but I am unable to get a point total with sum.

I have tried changing the formatting of the text to both "number", "plain text", and have left it as automatic, but I can't get it to sum. Thoughts? Is there maybe a better way to do this?

FWIW - I'm trying to score based on about 12 factors.

Best,

Alex

Nesting If/Else Statement in javascript

I've been trying to nest an if else statement inside a snippet of existing code I have that creates a summary section at the bottom of the page when a user clicks on a row from a table on the same page.

            //Register to selectionChanged event to hanlde events
        selectionChanged: function () {
            //Get all selected rows
            var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');

            $('#SelectedRowList').empty();
            if ($selectedRows.length > 0) {
                //Show selected rows
                $selectedRows.each(function () {
                    var record = $(this).data('record');
                    $('#SelectedRowList').append(
                        '<b>ISO Name</b>: ' + record.ISO_Name + '<br /><br />',
                        '<b>Abstract</b>: ' + record.Abstract + '<br /><br />',
                        '<b>Problem Description</b>: <pre>' + record.Problem_Description + '</pre><br /><br />'
                        );

                });
            } else {
                //No rows selected
                $('#SelectedRowList').append('No row selected! Select rows to see here...');
            }
        },

What I'm trying to accomplish is to nest an if statement that will run if a certain string is found within the Problem_Description field. What changes are <pre> tags, which I need in fields that contain the string "VEID", but not in fields that don't have this string.

As an example I've trying to simply nest an if statement where Problem_Description is so -

            //Register to selectionChanged event to hanlde events
        selectionChanged: function () {
            //Get all selected rows
            var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');

            $('#SelectedRowList').empty();
            if ($selectedRows.length > 0) {
                //Show selected rows
                $selectedRows.each(function () {
                    var record = $(this).data('record');
                    $('#SelectedRowList').append(
                        '<b>ISO Name</b>: ' + record.ISO_Name + '<br /><br />',
                        '<b>Abstract</b>: ' + record.Abstract + '<br /><br />',
                        **if ("CVIED" in record.Problem_Description);

                        {'<b>Problem Description</b>: <pre>' + record.Problem_Description + '</pre><br /><br />'}
                        else {<b>Problem Description</b>:' + record.Problem_Description + '<br /><br />}
                        );**

                });
            } else {
                //No rows selected
                $('#SelectedRowList').append('No row selected! Select rows to see here...');
            }
        },

I've tried creating two different statements all together which doesn't seems to work either, is there any I can accomplish this? Thank you.

*I've only ever programmed in python,so java script, and it variants are fairly new to me, so I apologize if my questions seems really simple.

IF statement not working in VBA

I am self-learning VBA and trying to write a little program does the following

1.asks users to enter a number between 10 to 20 in a textbox
2. When a button is clicked, the code will check the number entered in the textbox.If it is between 10 and 20, then a message will be displayed. If the number entered is not between 10 and 20 then the user will be invited to try a gain, and whatever was entered in the textbox will be erased.

Private Sub Command0_Click()
Me.Text3.SetFocus
inumber = Val(Text3.Text)
If Form_customer_test >= 10 & inumber <= 20 Then
MsgBox ("The number you entered is: ") & inumber
Else
Text3.Text = ""
MsgBox ("Please try again")
End If

End Sub

However, I don't think the else part of my codes is working. If I enter 5, it will display 5 instead of the message box. Could anyone please let me know if I have missed anything at all.

Thanks in advance. Happy Holidays.

Building an IF statement with an Array - Python [duplicate]

This question already has an answer here:

Pets = ["Dog", "Cat", "Hamster"]

I want to achieve this if statement:

if Pet == "Dog" or Pet == "Cat" or Pet == "Hamster":
    print "Correct!"

But my array has over 100+ items, so is there a quicker way to iterate over the array for an if statement like this instead of typing them all out? I know I can do:

for name in Pets:
   if Pet == name:
       print "Correct!"

But surely this is a lot slower as it's doing multiple if statements instead of just 1 longer one?

Thanks for looking/helping :)

How to loop an if statement [on hold]

I have an if statement which is used to control player turns. The functions within the if statement are click based, so the idea is that player 1 will click, then player 2, back to player 1 etc.

This is the code that I have so far

var player1turn=true;

if (player1turn) {
  recruitbuilderclickp1(cardsnames, allocatedcard, p1);
  mastclickp1(cardsnames, allocatedcard, p1);  
  player1turn = !player1turn;
  console.log(player1turn);
} else {
  recruitbuilderclickp2(cardsnames, allocatedcard, p2);
  mastclickp2(cardsnames, allocatedcard, p2);
  player1turn = !player1turn;
}

The problem which I am having is that once player 1 has had his turn, it is player 2's turn however this code isn't re-read and so nothing happens from that point on. How do I make it into a loop?

Stuck with readonly =true or false

I'm a little bit stuck so i hope sombody can help me out I have the code for read only that works fine but i want somthing a little bit diffrent Here is the code :

         If Me.dvg.Columns.Contains("edit") And _
            e.ColumnIndex >= 7 Then
            If Not IsNothing(Me.dvg.Rows(e.RowIndex).Cells("edit").Value) Then
                If Me.DataGridView_Booking.Rows(e.RowIndex).Cells("edit").Value.ToString <> "True" Then
                    e.CellStyle.ForeColor = Color.FromArgb(90, 90, 90)
                    Me.dvg.rows(e.RowIndex).Cells(e.ColumnIndex).ReadOnly = True
                End If

What i actually want = if edit contains value i need to be readonly. i have a few columns with months like jan(event), jan(date),Jan(cost) until dec(event) etc. at this point im stuck i want if jan(cost) is empty then i need to have diffrent cells on read only sombody got an idea how to do that ?

Thanks !

lundi 26 décembre 2016

for loop in Python taking too long for giving output

I have three excel files, Book1, Book2, Book3, with me. Each one of them consists of 11447 rows and 10335 columns. And each cell contains a numeric value of an observation. Now I have a 3 tuple, (100, 150, 150) and I want to compare the numeric values of each cell of Book1 with 1st tuple (100) and of Book2 with 2nd tuple (150) and similarly Book3 with 3rd tuple (150). Now whenever the corresponding cells of these excel files match with this tuple, I want to print 1 otherwise 0. That is, say my (10,200) cell in Book1 contains 100, in Book2 the cell (10,200) contains 150 and in (10,200) cell of Book3 we have 150, then I want to print 1 else 0.

So this is the program I wrote for this.

 import xlrd

 file_loc1 = "D:\Python\Book1.xlsx"
 file_loc2 = "D:\Python\Book2.xlsx"
 file_loc3 = "D:\Python\Book3.xlsx"

 workbook1 = xlrd.open_workbook(file_loc1)
 workbook2 = xlrd.open_workbook(file_loc2)
 workbook3 = xlrd.open_workbook(file_loc3)

sheet1 = workbook1.sheet_by_index(0)
sheet2 = workbook2.sheet_by_index(0)
sheet3 = workbook3.sheet_by_index(0)

for i in range(1,11447):
   for j in range(0,10334): 
      if sheet1.cell_value(i,j) == 100 and sheet2.cell_value(i,j) == 150 and sheet3.cell_value(i,j) == 150:
        print 1
     else:
        print 0

Firstly, I want to make sure if this program is correct or there is some issue with this? The range of loop is the one I required.

Secondly, I ran this program on my system and it has been around 10 hours and the program is still running. I am using 64-bit Python 2.7.13 on my 64-bit Windows 8.1 system. For executing, I am using Windows Powershell. I gave the following command for execution python script1.py > output1.txt as I also want an output in text. I got a text file generated in my Python directory named output1 but its size has been 0 bytes since the beginning of program. So, I am not even sure if I am getting any proper file or not. What should I do here? Is there any more efficient way to get such an output? Also, how long am I suppose to wait for this program/loop to finish up?

String length in if-statement (C++)

I want to check if a string is longer than 3 characters but I don't get the expected result. What I've tried so far:

if (str.length() > 3)
{
    cout << "It's longer than 3 characters";
}

declaring root of server with if statement

I have a project which i can't test it at the moment.In gulp file i have a task 'server' :

gulp.task('connect', function() {
connect.server({
root: ( 'build' ),
livereload: true,
 port: 5000,
 middleware: function(connect, opt) {
        return [
            proxy('/api', {
                target: 'http://localhost:3000',
                changeOrigin:true,
                ws: true    
            })
        ]
    }
});
});

and variable :

var ifProduction = gutil.env.production || false;

Can someone tell me if its possible to set an if statement for the root? Something like that:

root: ( ifProduction ? 'build' : 'temp')

Would that work?

how to do a if else statement on time intervals in swift 3

Right now my app has a timer that runs in seconds. I would like the code to work as this. If the time =< 10 then display image a else display image b.

if green {

            timer.invalidate()
            startStop.isEnabled = true
            scoreTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)

          I WOULD LIKE THE CODE FOR THE =<10 then display image a else display b. TO GO HERE

        }

How to read two files in a for-loop and update values in one files based on matching-values in another file?

I want to update a values in the column by reading two files simultaneously.

main_file has following data:

contig  pos GT  PGT_phase   PID PG_phase    PI
2   1657    ./. .   .   ./. .
2   1738    0/1 .   .   0|1 935
2   1764    0/1 .   .   1|0 935
2   1782    0/1 .   .   0|1 935
2   1850    0/0 .   .   0/0 .
2   1860    0/1 .   .   1|0 935
2   1863    0/1 .   .   0|1 935
2   2969    0/1 .   .   1|0 3352
2   2971    0/0 .   .   0/0 .
2   5207    0/1 0|1 5185    1|0 1311
2   5238    0/1 .   .   0|1 1311
2   5241    0/0 .   .   0/0 .
2   5258    0/1 .   .   1|0 1311
2   5260    0/0 .   .   0/0 .
2   5319    0/0 .   .   0/0 .
2   5398    0/1 0|1 5398    1|0 1311
2   5403    0/1 0|1 5398    1|0 1311
2   5426    0/1 0|1 5398    1|0 1311
2   5427    0/1 0|1 5398    0/1 .
2   5434    0/1 0|1 5398    1|0 1311
2   5454    0/1 0|1 5398    0/1 .
2   5457    0/0 .   .   0/0 .
2   5467    0/1 0|1 5467    0|1 1311
2   5480    0/1 0|1 5467    0|1 1311
2   5483    0/0 0|1 5482    0/0 .
2   6414    0/1 .   .   0|1 1667
2   6446    0/1 0|1 6446    0|1 1667
2   6448    0/1 0|1 6446    0|1 1667
2   6465    0/1 0|1 6446    0|1 1667
2   6636    0/1 .   .   1|0 1667
2   6740    0/1 .   6740    0|1 1667
2   6748    0/1 .    6740   0|1 .

The another match_file has following type of info:

**PI      PID**
1309    3617741,3617753,3617788,3618156,3618187,3618289
131     11793586
1310    
1311    5185,5398,5467,5576
1312    340692,340728
1313    18503498
1667    6740,12237,12298

What I am trying to do:

  • I want to create a new column(new_PI) with updated PI values.

How the updating works:

  • So, if there a PI value in the line of main_file, its simple: new_PI value = main_PI and then continue
  • If in main_file both main_PI and main_PID is ., new_PI = . and continue
  • But, if the PI value is '.' but PID value is some integer, now we look in the match_file for the PI value that contains that value in the list of PID. If a matching PID is found new_PI = PI_match_file and then continue

I have written the below code:

main_file = open("2ms01e_chr2_table.txt", 'r+')
match_file = open('updated_df_table.txt', 'r+')

main_header = main_file.readline()
match_header = match_file.readline()

main_data = main_file.read().rstrip('\n').split('\n')
match_data = match_file.read().rstrip('\n').split('\n')

file_update = open('PI_updates.txt', 'w')
file_update.write('contig   pos GT  PGT_phase   PID PG_phase    PI  new_PI\n')
file_update.close()

for line in main_data:
    main_column = line.split('\t')
    PID_main = main_column[4]
    PI_main = main_column[6]
    if PID_main == '.' and PI_main == '.':
        new_PI = '.'
        continue

    if PI_main != '.':
        new_PI = PI_main
        continue

    if PI_main == '.' and PID_main != '.':
        for line in match_data:
            match_column = line.split('\t')
            PI_match = match_column[0]
            PID_match = match_column[1].split(',')
            if PID_main in PID_match:
                new_PI = PI_match
                continue

    file_update = open('PI_updates.txt', 'a')
    file_update.write(line + '\t' + str(new_PI)+ '\n')
    file_update.close()

I am not getting any error but looks like I am not writing appropriate code to read the two files.

My output should be something like this:

contig  pos    GT    PGT       PID     PG      PI     new_PI
2      5426    0/1   0|1       5398   1|0   1311       1311 
2      5427    0/1   0|1       5398   0/1   .          1311
2      5434    0/1   0|1       5398   1|0   1311       1311
2      5454    0/1   0|1       5398   0/1   .          1311
2      5457    0/0   .          .     0/0   .          .
2      5467    0/1   0|1       5467   0|1   1311       1311
2      5480    0/1   0|1       5467   0|1   1311       1311
2      5483    0/0   0|1       5482   0/0   1667       1667
2      5518    1/1   1|1       5467   1/1   .          1311
2      5519    0/0   .         .      0/0   .          .
2      5547    1/1   1|1       5467   1/1   .          1311
2      5550    ./.   .         .      ./.   .          .
2      5559    1/1   1|1       5467   1/1   .          1311
2      5561    0/0   .         .      0/0   .          .
2      5576    0/1   0|1       5576   1|0   1311       1311
2      5599    0/1   0|1       5576   1|0   1311       1311
2      5602    0/0   .         .      0/0   .          .
2      5657    0/1   .         .      1|0   1311       1311
2      5723    0/1   .         .      1|0   1311       1311
2      6414    0/1   .         .      0|1   1667       1667
2      6446    0/1  0|1      6446     0|1   1667       1667
2      6448    0/1  0|1      6446     0|1   1667       1667
2      6465    0/1  0|1      6446     0|1   1667       1667
2      6636    0/1  .          .      1|0   1667       1667
2      6740    0/1  .        6740     0|1   1667       1667
2      6748    0/1  .        6740     0|1   .          1667

Thanks in advance !

Python - Nested IF loop

Like many here, I'm new to Python. I'm working on a snippet that asks the user to give their ID, then checks to see if the ID is exactly 6 digits in length. Then the code will ask the user to confirm their ID and if they mistyped, allows them to reset it. If the user confirms their entry was correct, then it asks for a location ID and follows the same path. If both IDs are confirmed, the user then can move on to the rest of the project.

This is something that will have to be input at the start of every use.

The issue I'm running in three sided.

1.) I can enter the empID 101290 and sometimes it tells me it's a valid entry while others it wont (but 101256 works regardless - both are 6 digits)

2.) Entering "1," to confirm the ID, the code moves to block 2 and asks for location ID but if the user enters "2" to say the Employee ID is wrong, it moves on anyway.

Any advice on what's in need of change here?

import time

print('What is your employee ID?') #user assigned ID
empID = input()
while empID != 0:
    print('Try again.')
    empID = input()

# employee ID is only 6 digits in length, no letters
if len(empID) != 6:
    print('Try again.')
elif len(empID) == 6:
    print('Thank you. Your ID is set to ' + empID + '.')
    time.sleep(0.5)
    print('Is this correct?'''
          '[1] Yes  [2] No ')
    yesNo = input()
    while True:
        yesNo == '1'
        print('Thank you. ID set.')
        break
# reset ID
    else:
        print('ID has been reset. Please enter your employee ID.')
        empID = input()
        break
    break

#Store Location ID
print('What is your Location ID?')
locID = input()
while locID != 0:
    print('Try again.')
    locID = input()

# store locations are 3-5 digits
# TODO: prepend any input with less than len 5 with 0
if len(locID) != 5:
    print('Try again.')
elif len(locID) == 5:
    print('Thank you. Your location is set to ' + locID + '.')
    time.sleep(.5)
    print('Is this correct?'''
          '[1] Yes  [2] No ')
    yesNo = input()
    while True:
        yesNo == '1'
        print('Thank you. Location ' + locID + 'set.')
        break
    else:
        print('Location ID has been reset. Please enter your location code.')
        empID = input()
        break
    break
break

next

Handle command-line switches in Ruby without if...else block

In a blog post about unconditional programming it recommends writing code that limits if statements.

How do I handle command-line switches without if statements?

For example using OptionParser I made a cat clone that will upcase the stream if the --upcase switch is set:

#!/usr/bin/env ruby

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Concatenate files or read from stdin\nUsage: argf_options_parser [options] [file ...]"

  opts.on("-u", "--upcase", "Upcase stream") do
    options[:upcase] = true
  end
end.parse!

if options[:upcase]
  puts ARGF.read.upcase
else
  puts ARGF.read
end

How would I handle that switch without an if..else block?

Also looking for general strategies for writing unconditional code.

Android If statement not being accessed for some reason

please I need your help i am building this application on Android, I ran into this problem where one String data is being retrieved from Firebase database and assigned to a String value, when I try to use (IF) statement to use inside condition, all I get is compiler checking the value condition and never enter the statement. I check the running application using Debugging mode, the value stored into the string is correct and if Statement has no problem in it.

I added part of the code where I have the problem

myRef.addValueEventListener(new ValueEventListener() {
        public static final String TAG = "Testtttttttt";

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " + value);
            if (value == "START") {
                textView.setText(value);


            }
        }

Why is 0.3-0.2 equalling 0.09999999999999998?

Why is that the if statement won't print out "false", however when I enter System.out.print("true"); in the else statement, it'll print out true? In what way are if statements designed in order to execute like that?

   int x, y;
    x = 5;
    y = 6;

    if( x == y && y == x ){
        System.out.println("false");
    }
    else
    {

    }

How to save the outcomes of a Loop (with if statement) in R?

Is it possible to save the outcome of a loop in a vector? My goal is to have a vector (or list) with the dates (of the vector"gifts") that are smaller than one specific date (date_3 in the code).

for (i in 1:21) {
if ((!is.na(gifts[i])) & (gifts[i] < Date_3)) {
  print(gifts[i])
}
}

"Gifts" represents a vector that contains a number of dates. Date_3 is a specific date

Can anyone help? Thanks

Repeat a second If condition using or

main_dict=
{1: {'Origin': '001', 'Destination': '002', 'Cost': '0100.00','Time': '04.00'}, 
 2: {'Origin': '002', 'Destination': '003', 'Cost': '0500.00', 'Time': '01.50'}, 
 3: {'Origin': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'}, 
 4: {'Origin': '002', 'Destination': '004', 'Cost': '0700.00', 'Time': '10.00'}, 
 5: {'Origin': '004', 'Destination': '006', 'Cost': '0550.00', 'Time': '06.75'}, 
 6: {'Origin': '004', 'Destination': '005', 'Cost': '0750.00', 'Time': '10.50'}, 
 7: {'Origin': '005', 'Destination': '006', 'Cost': '0460.00', 'Time': '08.00'}, 
 8: {'Origin': '002', 'Destination': '005', 'Cost': '1500.00', 'Time': '05.75'}}
count=9
first_list=[]                   
second_list=[]
for c in range(1,count):            
    first_list.append(main_dict[c]['Origin'])   #puts all origins in one list
    second_list.append(main_dict[c]['Destination'])#puts all destinations iin one list
locations=[]
locations.extend(first_list)
locations.extend(second_list)
locations=(list(set(locations)))#gets rid of any duplicates
locations.sort()
mat_nxn = [[None for x in range(len(locations))] for y in range(len(locations))] #in this section the main matrix is created 
for i in range(len(locations)):
    mat_nxn[0][i]=locations[i] #fills the first row with the locations
    mat_nxn[i][0]=locations[i] #fills the first column with the locations

for n in range(0,len(locations)-1):
    for i in range(0,len(locations)):
         if str(mat_nxn[0][n])==main_dict[n+1]['Origin'] or str(mat_nxn[i][0])==main_dict[i+1]['Destination'] :
            a=int(mat_nxn[0][n])
            b=int(mat_nxn[n][0])
            mat_nxn[b][a]=main_dict[n+1].values()

So what my code is supposed to do is arrange the dictionary's info in a NxN matrix, how it work is that the "Origin" and "Destination" are the "borders" of the martix enter image description here Then if let us say I can go from "Origin" to a "Destination" as stated in the dictionary I will add it to the matrix under an example would be, in the first dictionary I can go from "Origin 001" to "Destination 002" so I will place the values of the dictionary under X,Y(001,002) in the matrix My problem is in the last part of the code where I used the if condition with or inside two for loops

for n in range(0,len(locations)-1):
   for i in range(0,len(locations)):
     if str(mat_nxn[0][n])==main_dict[n+1]['Origin'] or str(mat_nxn[i][0])==main_dict[i+1]['Destination'] :

Now the problem is that if I have a duplicate "Origin" in my case it is 002 it will not check the rest "Destinations", only the first one, how can I make it check them all, did I use the or the wrong way? Would appreciate any help

SQL Server regex and if else in where clause

This is my code:

$db = new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={$server}; UID={$usr}; PWD={$pwd}; DATABASE={$dbname}";
$db->Open($dsn);
$sql = "SELECT o.CardCode, o.CardName, o.VatIDNum, o.AddID, o.Cellular, o.E_Mail, c.Address
            FROM ocrd o INNER JOIN crd1 c ON o.CardCode = c.CardCode
            WHERE o.Cellular = '$phone1' o.CardName LIKE N'%$lname%'";
$result = $db->execute($sql);

In the databese the o.Cellular column includes phone numbers that could be formatted with dashes/spaces/+ sign/braces so when I am checking WHERE o.Cellular = '$phone1' I need to reformat o.Cellular to only digits (the $phone1 already only digits).

The second problem is that if o.Cellular not equals $phone1, I want to check o.CardName LIKE N'%$lname%'.

So the current part of code doesn't works as I need.

Any help please...

Run following script before finish if statement

I try to run independent multiple if statement inside @IBAction func. But I would like to finish 1st if-statement first (i put a alert block to pause the process) then run 2nd if-statement and then run the rest script. My Code is look like this:

@IBAction func onDone(_ sender: Any) {
   if var1.count > 0 {
     let block: DTAlertViewButtonClickedBlock = {(alertView, buttonIndex, cancelButtonIndex) in
     //Do somethings
     }
     DTAlertView(block: block, title: "Do somethings?", cancelButtonTitle: "Cancel", positiveButtonTitle: "Let's do it!").show()
   }
   if var2.count > 0 {
     //Do another things
   }
   _ = navigationController?.popViewController(animated: true)
}

But Xcode seem to run 1st if-statement and 2nd if-statement in the popViewController in the same time doesn't wait me finish the Alert Block.

Any one face the same problem? What should I put in the code or does my code has something incorrect?

Combining Two 'if-statement' .second is depend on the first

second 'If' can come only after the first statement so there will not be run time error- due to the fact that "el_rule" can be sometimes nothing.. so i can't put both in same statement with AND. but after both 'if statement' i want same lines of code will run if one of the if statement will not happens(else)... is my only option is too just write it twice? like on following code? thanks for any help!

If el_rule.Length > 0 Then
                    If LCase(ActiveCell.Offset(0, el_rule.Item(0).Attributes.getNamedItem("column_number").Text).Value) = LCase(el_rule.Item(0).Attributes.getNamedItem("value").Text) Then
                     Set el = xDoc.SelectNodes("/Modes_of_auto_painting/Autopaint_lines_per_simulatorType/simulator[translate(@apiType, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='" & lookfor & "']/rule/formatting")

                 Else
                   Set el =.......   -code first time
               End If
else
                   Set el =.......    -code second time
               End If

"If statement" within for loop class name undefined

Each card has class names of "card player1card ________" or "card player2card _______" where the blank space is a random class name that is allocated from the cardnames array.

I want the code to check all cards, and for those which are player1card for them to have their class changed to "card player1card" and then an updated class from the cardnames array, and same for player2card.

All variables have been pre-defined.

I get the error "Uncaught TypeError: Cannot set property 'className' of undefined"

var cardsnames = ["recruitbuilder", "allwood", "cabin", "messhall", "mast", "captainsquarters", "schooner", "brig", "frigate", "shipballista", "ram", "crowsnest", "spoondrill", "reinforcements", "recruitgunman", "allgunpowder", "firebarrel", "fireship", "roundshot", "heavyshot", "swivelgun", "chainshot", "mortar", "barrage", "resupply", "smuggler", "blockade", "mutiny", "recruitmerchant", "allgold", "addwood", "addgunpowder", "addgold", "removewood", "removegunpowder", "removegold", "byzantinefire", "slaves", "mercenaries", "ironplating", "coercion", "ascension"];

var w;
var allocatedcard;
var card = document.getElementsByClassName("card");

for (w = 0; w < card.length; w++) {
    if (document.getElementsByClassName("card")[w].className.match('player1card')) {
        this.className = "card player1card";
        var allocatedcard = Math.floor(Math.random() * cardsnames.length);
        this.className += " " + cardsnames[allocatedcard];
        updateimages();             
    } else if (document.getElementsByClassName("card")[w].className.match('player2card')) {
        this.className = "card player2card";
        var allocatedcard = Math.floor(Math.random() * cardsnames.length);
        this.className += " " + cardsnames[allocatedcard];
        updateimages();     
    }
}