FAQ Database Discussion Community


If statement without condition

c,if-statement,conditional-statements
I would like to ask what is the behaviour of the C language on the following: int n = 0; . . // n in this block may change value to something else but a (positive) number . . if(n) { // do something } . . So what the...

Create rows of data conditionally

r,conditional-statements
A sample dataset: Price=c(6651, 7255, 25465, 35645, 2556, 3665) NumberPurchased=c(25, 30, 156, 250, 12, 16) Type=c("A", "A", "C", "C", "B", "B") Source=c("GSC", "MYL", "TTC", "ZAF", "CAN", "HLT") df1 <- data.frame(Price, NumberPurchased, Type, Source) I want to be able to create a new dataframe with two additional variables (ID, PurchaseDate) but...

Reverse engineer assembly code to c code

c,assembly,reverse-engineering,x86-64,conditional-statements
I think this is actually a pretty simple problem. I have to reverse engineer this assembly code to c code. I'll also provide what I think is going on so you can hopefully point to where I went wrong and I can learn from my mistakes now. .LFBO pushq %rbp...

AverageIf and Multiple data strings

excel-formula,excel-2010,conditional-statements
I'm involved with a youth football tournament on the referee side, with assessing/coaching the referees. I've just taken over doing the data entry for the referees assessment scores which we then use to determine who gets finals etc and am looking to extract more usable information from the data to...

Behavior not understood in C program that prints out initials

c,for-loop,conditional-statements,string.h
I have a simple C program that is supposed to accept a name given by a user and then print out the initials of the name in standard output. My implementation is as follows: #include <stdio.h> #include <cs50.h> #include <string.h> int main(int argc, string argv[]) { string name = GetString();...

Why does a single value work as a condition

python,conditional-statements
Obviously, in conditional statements you need to make sure a true or false value is returned to either execute or skip the block of code associated with the if statement. How does a single value serve as a true Boolean in python? I'm not sure if this is a universal...

How to write a fallback for css files not loaded, loading too long and blocked? [duplicate]

javascript,css,cdn,conditional-statements,fallback
This question already has an answer here: How to fallback to local stylesheet (not script) if CDN fails 10 answers I am trying to write a conditional statement for my css files, because I am hoping to host them on CDN. Anyhow, I need to write a fallback for...

How to .write() two items, a zero and an iterator in Python?

python,csv,formatting,conditional-statements,writing
I may have a simple formatting question here - I would like to do something like hrOut.write('0',i) in order to add/preface a zero to 'i' which is a timestamp, but I don't know the correct syntax. My code is below. Thank you all. hrIn = open('HrsInput.csv') hrOut = open('HrsOutput.csv', 'wt')...

Output breaks as input parameter increase in size

java,arrays,conditional-statements
I am writing a basic program that takes a parameter and then calculates the product of the odd numbers based on that parameter. It works if I pass anything from 1 up to 19 but at 20 my output is a negative number and at 35 it is 0?? I'm...

One liner conditional, multiple variables and check that all of them are not false?

python,if-statement,conditional,conditional-statements
How I can make a conditional in python that checks for this three keywords defined in the dictionary and that they are not False ? settings = { 'proxy_host': '127.0.0.1', 'proxy_port': 8080, 'proxy_protocol': 'socks', } I have tried with the sentence you can see below. But this is only checking...

How to get the correct text value from a button javafx

java,javafx,javafx-8,conditional-statements
I have been trying to use the name of a button in a conditional , checking if the string generated from .getText()is or is not equal to "New Project:" in the case below, but every time i try to run this code it always gives me a result of 'not...

Multiple ansible conditionals no longer work with version 1.9

conditional-statements,ansible
I have the following task file in one of my roles: - name: check for initalized fixtures stat: path={{ fixture_init_file }} register: fixture_init - name: copy fixtures copy: src={{ fixture_file }} dest={{ fixture_dest }} when: fixture_init.stat.exists == False - name: debug debug: var=fixture_init - name: db2 debug: var=database - name:...

Can I combine error exception and a conditional in a single line?

python,error-handling,conditional-statements
If for example, my code does something like this: try: for n in graph[x]: #... #... if event == 0: #do something except IndexError: #do the same thing My if block and my error exception block have the same exact code; so instead of having redundant lines, I want to...

R filtering logic

r,filter,logic,conditional-statements
Need some insight on how to fix this filtering logic. test.session <- c("A","A","A","B","B","B") test.start_flag <- c("1","0","0","1","0","0") test.url <- c("in_list","in_field","out","not_in_list","in_field","out") test.code_map <- 'tbd' test.manual_map <- c("1","1","0","0","0","0") test.df <- data.frame(test.session, test.start_flag, test.url, test.code_map, test.manual_map) I want to generate the test.code_map to match the test.manual_map vector. I have the first four lines coded,...

Convert string to variable in PHP

php,string,if-statement,conditional-statements
I have a variable $allrule = '(1 == 2) && (2 == 2)'; when i check if($allrule), it returns true because $allrule is treated as string. So i want to convert $allrule as condition of if statement. how can we do it.

Find folder named with lowest number in a directory , conditional statement on the command line

windows,batch-file,command-line,conditional-statements,xcopy
I'm new to conditional statements with the command lein, I'd like to write a batch file for a server running Windows Server 2003 to do a similar task as this, but for the statement to find the lowest numbered folder (including subdirectories) and copy that to an external drive attached...

subtract list of lists from list of lists with conditional arguments

python,for-loop,conditional-statements,nested-lists,subtraction
I have sort of a tricky problem that I'm having a hard time wrapping my head around. I have two lists of lists: firstList = [[0, 9], [0, 4], [0]] secondList = [[18], [19, 7], [20]] I would like to subtract the value(s) in firstList from the values in secondList...

Multiple ifs in Smalltalk

refactoring,conditional-statements,smalltalk,pharo
I'm really new to smalltalk and still trying to figure out the basic stuff. Below is a simple program I wrote. It is supposed to print "a" if the number can be divided by 5, "b" if it can be divided by 3, and "ab" if it can be divided...

Conditionally include script for browsers

javascript,jquery,javascript-events,reference,conditional-statements
I have such kind of script code setTimeout(function () { $('.grayscale .inactive img').each(function () { $(this).wrap('<div style="display:inline-block;width:' + this.width + 'px;height:' + this.height + 'px;">').clone().addClass('gotcolors').css({ 'position': 'absolute', 'opacity': 0 }).insertBefore(this); this.src = grayscale(this.src); }).animate({opacity: 1}, 500); $(".grayscale li").hover(function () { $(this).find('.gotcolors').stop().animate({opacity: 1}, 200); }, function () {...

SAS statistic parameters of specific variables from data with conditions

variables,statistics,sas,conditional-statements,proc
I have a variable I created based on a certain data. now in this new data I need to calculate different statistic parameters, but with conditions for example: *median of this new var only for obs that their birth country is not Italy. *mean of a different var only when...

Assoc array to object no longer fails on false

php,mysqli,conditional-statements
I wrote some code to pull data from a database, and then return the results as an associative array, however I switched the return value to an object (which works), but it is no longer failing at the following condition when no results exist. if($myobject = MyClass::GetRecords("something")) { // this...

A value returned from a conditional selection algorithm that I didn't provide?

conditional-statements,modelica,openmodelica
In Modelica, I constructed a simple mapping (a pair of case structures) to reduced a table of MxN values into a table of 5x5 values. But when I simulate with an input that is at the boundary (row = M or column = N) the mapping returns "0" when it...

What does this if assignment/statement mean in C++

c++,if-statement,condition,variable-assignment,conditional-statements
Our professor gave us this code. It assigns a value to a char[] depending on the value of the first index in the array. He said it was an if statement but I've never seen one like this. I'm new to c++ temp.byte[0] = byte[0] == '0' ? '1' :...

Conditional statement not working as expected

linux,shell,conditional-statements,konsole
I am using Konsole on kubuntu 14.04. I want to take arguments to this shell-script, and pass it to a command. The code is basically an infinite loop, and I want one of the arguments to the inner command to be increased once every 3 iterations of the loop. Ignoring...

Trying to add conditional script for a wordpress page, but not working. Help please?

javascript,wordpress,conditional-statements
I am trying to include some JS to just one single page of a Wordpress based website. Basically, what I've done is in the header.php of the theme, I've put the following: <?php if( is_page('17')) { ?> <!--Start of Zopim Live Chat Script--> <script type="text/javascript"> window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s= d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set. _.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");...

else if statement not working

java,if-statement,conditional-statements
I am new to Java and really kind of teaching myself. I am practising with the else and if statement. I have written the below very basic program for grading a score but i cannot get all of the else if statements to work properly, it invokes the first two...

How to conditionally check the state of an openstack instance

cloud,state,conditional-statements,ansible,openstack
I am trying to conditionally check the state of an openstack cloud instance in my playbook. The playbook itself takes the name of a cloud instance as a parameter and then deletes it by setting the state to absent using nova compute. What I want to do is check if...

run an IF statement once

javascript,jquery,html,asp.net,conditional-statements
I have an age value which I'm using as a condition to enter an IF statement. The IF statement populates random values in to a field (this is a childs math game). After the fields are populated the user can enter their answers and then check them using a 'Check...

How to use Oozie action with input path depending on flag

conditional-statements,oozie
I have an oozie action that has a defined input path. In case this path does not exist I want to set the input to some default path. Is there a way to have the path depending on a condition? I know I can replicate the action for each possible...

What is the use of = sign (single) in a condition?

javascript,if-statement,conditional-statements,assignment-operator
I had read in some articles that in some languages, like in JavaScript, assignment operators can be used in conditional statements. I want to know what is the logic behind that operation? As far as I know, only comparison operators are allowed in condition checking statements.

SQL - Conditional Join

mysql,sql,conditional-statements
I'm looking to do an SQL join on some data. In a nutshell, I have a table (e.g. items_tbl) where users submit items for other users to bid on e.g. itemUID, Details, Price, usernameOfSeller And in another table (e.g. bid_tbl), I collect the bids itemUID, usernameOfSeller, usernameofBuyer, offerPrice What I...

Is there a way to combine several different conditionals with a shared statement?

c,syntax,logic,structure,conditional-statements
Is there a way to combine several different conditionals with a shared statement? For example: int a; ... if (a == 1){ foo; ... return K1; } else if (a == 2){ foo; ... return K2; } ... else if (a == i){ foo; ... return Ki; } Is there...

SQL Several Count

mysql,sql,if-statement,count,conditional-statements
First sorry if my english is bad, it's not my native language. I have two tables (A and B) with the following columns: A: PRENUMERO (ID), DATA, ARMAZEM, TIPO and B: Autoreg (ID), PRENUMERO, PRODUTO I want a result like: *CountA, CountB, CountC, DATE * CountA is when PRODUTO is...

Occurences of a value, based on corresponding value across columns

count,google-spreadsheet,spreadsheet,conditional-statements
I currently have a table in a layout similar to this: Quality | Fruit1 | Fruit2 | Fruit3 ---------------------------------- Sweet | Apple | Orange | Pear Firm | Pear | Apple | Watermelon Sweet | Orange | Pear | Melon Soft | Banana | Orange | Strawberry Firm | Apple...

confuse create print out when create some condition in Sqlite3 with python

python,database,sqlite3,conditional-statements,string-split
I created a test database with the table name and in it there are two columns with names Words and Sentences and I want to do a search in databases (sqlite3) whether the data or the word is there or not, if there is then the system will output /...

SQL Conditional sum and grouping

sql,grouping,sybase,conditional-statements
I have a query that's trying to sum up a patient's length of stay at a hospital. Here is an example of the data | Patient | Admission_ID | Admission_Event_ID | Admission_Event_Type | Start Date | End Date | Duration | Linked_Admission | | P0001 | ADM0001 | AE1 |...

Combine `if` inside another `if` statement

ruby-on-rails,ruby,conditional-statements
I have the following if statement: if( @items.name.present? && @items.value.present?) I would like to add a check for @items.price.blank? if @items_table[:check_price] to this if statement. So my final if statement would check for all three conditions using && if my model had [:check_price]; otherwise it will only check for the...

Optimising conditional code for Wordpress

wordpress,templates,conditional-statements
There are two types of pages I am interested in for Wordpress: pages and posts. At the top of my posts template, I have some code as following to display varying banner ads: <?php if ( ! is_single() && ! is_search() && ! is_category() && ! is_tag() && my_wp_is_mobile() )...

Conditionally rendering component sections in React JSX

javascript,reactjs,conditional-statements,conditional-operator,react-jsx
According to MDN "You can also do more than one single operation per case, separating them with a comma." The example below works: var stop = false, age = 23; age > 18 ? ( alert("1"), alert("2") ) : ( stop = true, alert("Sorry, you are much too young!") );...

Trying to use wildcards in bash conditional statement/case mixed with exact alpha char and failing

bash,wildcard,conditional-statements,alpha
Essentially, I'm testing a variable to ensure it's contents matches a specific time format: 4 digits, am/pm/AM/PM, no spaces (i.e. 1204pm). I've gotten this much to work: tm0=1204pm; [[ $tm0 == [0-2###aApP]* ]] && echo PASS or tm0=1203pm; case $tm0 in [0-2###apAP]*) echo PASS; esac But when I try to...

Add class based on a condiiton in angularjs?

javascript,angularjs,conditional-statements
I want to add classes based on a condition in angularJs, I am following below method and it is working fine, Is there any best practice? <div ng-if="client.status != 2" class="list-primary"> <span class="pull-right amount">{{client.receivables|number:2}}</span> <div class="name">{{client.name}}</div> </div> <div ng-if="client.status == 2" class="list-primary text-muted"> <span class="pull-right amount">{{client.receivables|number:2}}</span> <div...

How to check/compare whether four variables are same or different using conditional statement in C# or C++

c#,linq,sorting,visual-c++,conditional-statements
I have 4 variables having values as a=50;b=100;c=500;d=1000; If all the values are the same then count =1,else if any two values are same then count = 3,if any three values are same then count = 2. I can easily find out if all values are the same but in...

jQuery conditional: if div has a particular ID, add class to another div

jquery,css,conditional-statements
I am trying to get a jQuery conditional to apply a class to this particular element – – when another element contains a particular ID. Here's what I have so far: <script type="text/javascript"> $(document).ready(function() { if( $('.container-fluid').hasId('europe') === true ) { $('controlBar_playerVideo1').addClass('darkcontrols'); } }); </script> Here's the live site: http://fsa.space/...

Extremely puzzling behavior when evaluating a tuple object that holds multiple DataFrames

python,if-statement,pandas,tuples,conditional-statements
I have some statements where I invoke a function that I defined myself: sim_extracted_dfs = extract_dataframes(sim_queue_total_df_sim) print (sim_extracted_dfs is tuple) where extract_dataframes() is a function that accepts a large DataFrame as an argument and processes that DataFrame to return me a tuple consisting of 4 smaller DataFrames, as this is...

Javascript: Incorporating random( ) start

javascript,arrays,conditional-statements,khan-academy
Please help with this program. It's a challenge on Khan Academy to make it rain using arrays, loops, and conditions. I'm supposed to: Add more drops to the arrays. Make it so that the drops start back at the top once they've reached the bottom, using a conditional. Make an...

Excel - ASSIGNING PRIORITY

excel,excel-formula,conditional-statements
Logically, I have a hierarchal set of strings that looks like this: Priority 1 = "SAME" <---Most important Priority 2 = "DIFFERENT" Priority 3 = "CLASSICAL" Priority 4 = "DROPPED" <---Least important If I have 5 contiguous Excel cells, with any combination of 1 of the above strings in each...

Readability in nested conditional statements

python,conditional-statements,code-readability
I'm currently writing a program in Python to model projective geometry, and the congruence function for a projective point is looking rather nasty. (for anyone interested, two projective points are congruent if they both lie on a single line passing through the origin.) class Point(object): def __init__(self, a, b, c):...

Handling NSError with error.code

ios,error-handling,conditional-statements,nserror
I am trying to handle specific NSErrors with UIAlertView but none of the codes in the if statements are called when the webview didFailLoadWithError is called. Below is my condition statement: - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { loadFailedBool = YES; NSLog(@"Error code %ld", (long)[error code]); if ([error code] != -999)...

Why if statement to test for correct notation in Deg Min Sec ignoring condition?

python-2.7,if-statement,while-loop,conditional-statements
I have a script with multiple functions, one of them taking the bearing for a direction distance traverse in ArcMAP, and tests to make sure the input follows the standard guidelines for Degrees Minutes Seconds. It checks for the North South and East West just fine, but when it gets...

Using echo within conditional statement

php,html,conditional-statements
I'm using a conditional statement to check what language the page is on. It's fine when I just need to output HTML, but the particular line I need to translate already has an echo statement in it and I am unsure how to echo the whole statement. The line: <div...

SSIS Conditional Split - No value return

ssis,conditional-statements,isnull,ssis-2012
I am using SSIS 2012 My statement: Select BOSP from MyTable Result is not NULL, it returns nothing as seen below. Problem now is in SSIS if the result is NOTHING like above I need to do something using the Conditional Split, but if there is data then I need...

JavaScript short circuit evaluation error?

javascript,conditional-statements,conditional-operator,typeof,short-circuiting
The two below snippets of JS code have had me confused, in my eyes both should work the same, due to short circuit evaluation. But for some reason snippet '1' causes the error (on the third line): Cannot read property 'match' of undefined Array 'a' holds 3 character values user...

Java scanner adding variable conditions

java,java.util.scanner,conditional-statements
I'd like to ask how do i exactly condition what my program does if my user types in a character or a string if i want him to type an integer instead? I tried to do it how i showed here in quotes and also tried with "equals". The second...

How to load a script only in IE

javascript,internet-explorer,conditional-statements
I need a particular script to be triggered in Internet Explorer browsers Only! I've tried this: <!--[if IE]> <script></script> <![endif]--> Unfortunately this actually stops the script from being loaded. EDIT: For everyone asking why I need this: IE makes scrolling extremely jumpy when using some animations. In order to address...

Empty block and blocks with ; only in if statement

java,if-statement,syntax,conditional-statements
I've been testing myself with a test in Java SE 7 Programmer 1 study guide. There is this question about if statements. It asks which option won't compile: > a) if(true) ; > b) if(true) {} > c)if(true) {;} > d)if(true) {;;} > e)if (true) ;{}; > f) all of...

What is the best way to invalid an expression for debugging?

php,conditional-statements
Consider: if ($expression1) { // code block 1 } else { // code block 2 } To debug code block 1, I can prefix TRUE || to $expression1 to get it to evaluate to TRUE: if (TRUE || $expression1) { // code block 1 } else { // code block...

Rails - If / Else in view returning both branches

ruby-on-rails,if-statement,model-view-controller,conditional-statements,has-many-through
I've an 'if / else' running in my view, based on the current URL of the page, and currently the view is displaying what is should were the 'if' both true and false. It's a little tricky to explain, and I've no idea why this is happening - any explanations...

Multiple if conditions for ad code

php,wordpress,conditional-statements
I'm trying to set multiple conditions to display my ad code, but don't know how to combine the statements. Here is the first chunk, which ensures that the ad code doesn't show up on mobile devices: <?php if (function_exists('wpmd_is_notdevice') && wpmd_is_notdevice()) :?> MY AD CODE <?php else : ?> <?php...

Trouble with a loop statement in R

r,if-statement,for-loop,conditional-statements
I am having trouble writing the proper R code to perform a looped, if else, conditional test. I am trying to solve for x (must be a whole number), such that F_c = 5 (see below). Both z and w are a series of known values, with z representing abundance...

Unix Shell Scripting - Verifying that a copy succeeded

shell,unix,if-statement,scripting,conditional-statements
I would like to write a script that verifies if a copy succeeded or not. Here's what I have: #!/bin/sh cp home/testing/present.txt home/testing/future.txt echo "Copy Code: $? - Successful" if [ $? != 0 ]; then echo "Copy Code: $? - Unsuccessful" fi The "if" statement is not being initialized....

Can I put an if/unless clause on the next line in Ruby?

ruby,conditional-statements
In Perl, I often find myself using the following pattern: croak "incompatible object given: $object" unless $object->isa('ExampleObject') and $object->can('foo'); I tried to translate this into Ruby like this: raise ArgumentError, "incompatible object given: #{object.inspect}" unless object.is_a?(ExampleObject) and object.respond_to?(:foo) But that does not work because Ruby interprets unless as the start...

Shiny - How can I render two objects that are both based on the same reactive data frame?

r,function,shiny,conditional-statements
I am creating an app in Shiny. One of the things I need it to do is display a boxplot that summarizes a data frame that is subsetted based on inputs from the user. Here is some of the code I use to subset the data frame here: Due to...

'OR' Is Not Working When Checking If Something 'IS NOT' Or '!=' In a String?

python,if-statement,boolean,conditional-statements
Looked around for an answer, but couldn't find anything. Here's my code: def translate(string, c = 0): for char in string: if char != 'u' or char != 'i': print string[c] c += 1 translate("this is fun") If I try this, the whole if statement gets canceled out and it...

Finding numeric element patterns using conditionals R

r,pattern-matching,conditional-statements
I have x x <- c(2, 28, 1, 31, 1, 10, 2, 1, 17, 4, 2, 5, 19, 6) I want to find those numbers which oscillates three or more times between being the same or more than 7 followed by a 2 or 1 and convert x into 0s...

How to find average of Excel column A if B(i) is TRUE and B(i-1) is FALSE?

excel,average,conditional-statements
I know the title is confusing but it was no easy task to summarize the problem in one sentence so bear with me. I have two columns in Excel, column A contains real numbers, column B contains Boolean values of either TRUE or FALSE. I want to get the average...

Excel - Conditional Formatting using time arguments

excel,date,formatting,formula,conditional-statements
Looking to change the fill of a cell based upon the amount of time between the current date (TODAY), an entered value detailing when something was done historically and a set period from that historical date of either 6months or 1year. E.g. I have a date of 12/04/2015 entered as...

Python Reduce conditional expression

python,conditional-statements
I have 9 variables a,b,c,d,e,f,g,h,i and I loop them inside 9 for loop from 0 to 9. But the range may vary. I want all sequences of them abcdefghi, such that there is no repeated number. Right now I have this, below: for a in range(0, 9): for b in...

Possible Vectorization using If Statements in MATLAB

matlab,if-statement,vector,vectorization,conditional-statements
Suppose I have the following column vectors as res1 = -0.81 res2 = 0.61 0.1 -0.4 -0.91 0.62 0.2 -0.56 0.63 -0.72 and I have two fixed constant D = 0.5. Now suppose an element of res1 is called X and an element of res2 is called Y. I have...

Match multiple strings using re.search within an if condition

regex,python-2.7,conditional-statements
I am writing a program to create a list from a spreadsheet based on a position value in another cell. So my code looks like for j in xrange(1,13): for sheet in wb.sheets(): for i in xrange(1,12*15): team=sheet.cell(i,0) position=sheet.cell(i,2) games=sheet.cell(i,23) if re.match(owner[j], str(team.value)) and (not re.findall('Defense' or 'K,' or 'KFG'...