w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Performance Differences of Nested If Else Statements vs. ElseIf Statements
It depends on your code. The if statement is only accessed when a condition is met, otherwise it is ignored. the if elseif else block is the same but it is testing for many conditions and depending on which one is met a different action might have to be performed in order to get the results u want. My opinion is "It depends upon cases". If you want to execute everything in your code,then use elseif.. if you want to ignore something use if..

Categories : Dotnet

Nested For Each statements
I would suggest firstly that you read the two columns into an array. dim myarray() as variant myarray = range("A2:E" & lastrow).value2 Then loop through the column E values, looking for blanks: n = 2 cb_project = myarray(n,1) do while n <= lastrow 'copy row matching cb_project if myarray(n,5) = "" then cb_project = myarray(n+1,1) else 'copy row matching myarray(n,5) endif n=n+1 loop

Categories : Excel

Can if statements be nested in a while loop?
Check your code here you are missing else block: userInput = input.nextLine(); if ( !userInput.equalsIgnoreCase(endProgram) ) { System.out.printf("You entered the following: %s", userInput); } else This is the reason for the compilation error. You can fix this by either removing the else altogether or if you want to add something in it then do the following: userInput = input.nextLine(); if ( !userInput.equalsIgnoreCase(endProgram) ) { System.out.printf("You entered the following: %s", userInput); } else { // Do something } And to answer your questions, yes it's perfectly valid to nest if statements in a while loop.

Categories : Java

Nested If Statements in SSRS
Let's dissect your statement: =SUM( IIF(UCASE(TRIM(Fields!UOP.Value))="Y", IIF(UCASE(TRIM(Fields!HED.Value))="Y", IIF(UCASE(TRIM(Fields!FROMB.Value))="RED", IIF(UCASE(TRIM(Fields!TOB.Value))="BLUE", 1, 0), 0), 0) ) Your parentheses are unbalanced, and you are missing the false argument for the first IIF. Alternatively, you can invert your conditions and use SWITCH instead, which would be a bit easier to read: =SUM(Switch( _ UCASE(TRIM(Fields!UOP.Value))<>"Y", UOPFalseValue, _ UCASE(TRIM(Fields!HED.Value))<>"Y", 0, _ UCASE(TRIM(Fields!FROMB.Value))<>"RED", 0, _ UCASE(TRIM(Fields!TOB.Value))<>"BLUE", 0, _ True, 1)) Or, since it appears yo

Categories : Reporting Services

Ruby: nested if statements
I would do something like the following as it makes it clear that each case is mutually exclusive: def hours_occupied(date) if availability = get_work_hours(date) focus = "work" elsif availability = get_family_hours(date) focus = "family" elsif availability = get_friend_hours(date) focus = "friends" end end

Categories : Ruby

nested FOREACH statements
For fastest execution a UDF would be best. In pure Apache Pig it would be nice if you could do count on (group, lt, ln) before creating a relation with your schema. It woul be something like this (it is just a pseudo script, might need some debugging) Assuming load schema is (id, lt, ln) inpt = LOAD ....... as (id, lt : chararray, ln : chararray); grp1 = GROUP inpt BY (id, lt, ln); data1 = FOREACH grp FLATTEN(inpt), COUNT(data1) as cnt; data2 = GROUP data_wtih_count BY id; --data2: {group: chararray,data1: {(id, lt: chararray,ln: chararray, cnt : int)}} most_probable_pair = FOREACH data2 { ord = ORDER data1 BY cnt ASC; top = LIMIT ord 1; GENERATE group, top.(ln, lt); } Or you could flatten data2 and data1 and start with grp1.

Categories : Apache

Walking Through Nested For statements
The first one enumerates the range from zero to the value of entries_per_column as a variable named row For each row, there is an enumeration from zero to the value of width as a variable named column So this is creating a two dimensional matrix - should be pretty digestible. For each column in a row, the value in that space is assigned to the variable entry. If the entry does not exceed the maximum value of the matrix, then it is put inside the return list ret as a list. After this ret is given a newline character so that a new row can be created visually (when ret is printed out). So this program makes a list, ret, which contains a two dimensional matrix of values - a number of lists that are rows, each of which contain some single-valued lists called columns, which have entries insid

Categories : Python

Refactoring nested rescue statements
Probably this don't answer your question, but in this case I'd ask to o if it responds_to? the method I want to call, before calling it: method = [:foo, :bar, :baz].find { |m| o.respond_to?(m) } if method o.public_send(method) else warn "Object o responds not to basic methods!" end

Categories : Ruby

Nested jQuery IF statements not working
$('.member-type').val() will always return the value of the first .member-type radio button. Instead, you should filter the radio buttons to find the one that is checked, and get that radio button's value: var $types = $('.member-type'); var $amount = $('#Amount'); var pricing = { print: { Standard: 35, Youth: 35 }, digital: { Standard: 25, Youth: 10 }, printdigital: { Standard: 50, Youth: 30 } }; $(".highflight-type").change(function() { if ( ! this.checked ) return; $amount.val( pricing[ this.value ][ $types.filter(':checked').val() ] ); }); Here's the fiddle: http://jsfiddle.net/C8kZq/

Categories : Jquery

How/should I use nested for loops inside of if statements?
It is difficult to tell the precise situation here, but this is how it sounds to me: defaults is almost certainly meant to be an instance of NSUserDefaults. The bolded "for" in your instructions is not suggesting a for-loop; it's giving you a hint at the method you need to use. Take a look at the NSUserDefaults reference there and see if you can find a method that might be useful for looking up a BOOL value for a named key.

Categories : Objective C

Nested foreach statements to access
You have an extra } right before the second foreach. That one is closing the method, so the second foreach is out of the method definition and that is a syntax error.

Categories : C#

PHP - Avoiding nested if statements - cleaner way to code this
You don't need the empty checks at that point, move them to the validation functions. For example: function validate_email($str) { if(empty($str)) { return false; } $str = trim(strtolower($str)); if(!filter_var($str, FILTER_VALIDATE_EMAIL)) { return false; } else { return $str; } } $email = validate_email($_POST['email']); if($email) { // your code }

Categories : PHP

Using nested CASE statements in SQL Server 2008
You should create @table variable or even a physical permanent table with columns Sample1, Sample2, Sample3, Output - insert all your combinations and desired outputs in it and then just select Output from it based on your @Sample1, @Sample2,@Sample3 variables. This way with dozens of CASEs inside CASEs you are just going to get lost. Something like this: CREATE FUNCTION SampleFunction2 ( @Sample1 VARCHAR(50) , @Sample2 VARCHAR(50) = NULL , @Sample3 VARCHAR(50) = NULL ) RETURNS VARCHAR(255) AS BEGIN DECLARE @output VARCHAR(255) DECLARE @tempResults TABLE ( Sample1 VARCHAR(50) , Sample2 VARCHAR(50) , Sample3 VARCHAR(50) , [Output] VARCHAR(255) ) INSER

Categories : SQL

nested SQL statements but reusing out variable in the inner statement?
In order to do this when the table name is the same, you need to give aliases to the tables: SELECT surveyquestions.priority, surveyquestions.id, surveyquestions.question, surveyquestions.html FROM surveyquestions LEFT JOIN surveyanswers oa ON surveyquestions.id = oa.id AND oa.uuid = 22946252362612764 WHERE (surveyanswers.id IS null OR (SELECT datestamp FROM surveyanswers ia WHERE ia.id = oa.id ORDER BY datestamp DESC LIMIT 1) < DATE_SUB(NOW(),INTERVAL 1 HOUR)) AND surveyquestions.priority != 999 AND surveyquestions.brid = 'testprod2' ORDER BY surveyquestions.priority LIMIT 1; I used oa to denote "outer answers" and ia to denote "inner answers".

Categories : SQL

Is it possible to write nested conditional statements in Haskell?
Don't you have an incomplete (un-answered) branch in the X > 2 section? if x < 5 then 3 else if x < 10 then 10 // else, what answer here? The else in Haskell is mandatory. See: http://en.wikibooks.org/wiki/Haskell/Control_structures

Categories : Haskell

Rewriting nested if-statements in a more Pythonic fashion
Since you are comparing consecutive indexes, and assuming lst and seq are of the same type, you can use slicing: def sequence_in_list(seq, lst): m, n = len(lst), len(seq) for i in xrange(m): for j in xrange(n): if lst[i:i+3] == seq[j:j+3]: return lst[i+3] If the sequences are of different kind you should convert to a common type before doing the comparison(e.g. lst[i:i+3] == list(seq[j:j+3]) would work if seq is a string and lst is a list). Alternatively, if the sequences do not support slicing, you can use the built-in all to check for more conditions: def sequence_in_list(seq, lst): m, n = len(lst), len(seq) for i in xrange(m): for j in xrange(n): if all(lst[i+k] == seq[j+k] for k in range(3)): r

Categories : Python

Cleaner code: Re-factor multiple nested if statements
Possibly encapsulate the functionality you need for each boolean condition into a method and use the method instead of specifying condition1, condition2, condition3 etc. private boolean isRed() { //do some stuff } private boolean isBlue() { //do some other stuff } private boolean isGreen() { //do some more stuff } ... if(isRed() && isBlue() && isGreen()) { //do some more stuff }

Categories : C#

Nested (Condition) ? true:false statements in JavaScript
Generally speaking using binary operations should be faster than conditional statements with branching because of branch prediction, caching, yada yada yada. But your code is fine. I like the && || but it's just a preference and not based on anything empirical. var data = {a: 1, b: 2, c: 3}; var result = data.x || data.y && "y" || data.z && "z" || data.w && "w" || null; I didn't feel like typing .hasOwnProperty. EDIT After actually looking at your code var paintMode = data.regions || data.vpcs || data.zones || data.subnets || data.clusters || null; if(paintNode) { for(var i=0; i<paintMode.length; i++) paintGroups(paintMode[i]); }

Categories : Javascript

My nested IF statements wont proceed in Excel 2010?
From what I can see, G13 contains the value you are trying to use to determine one of 'Low Cost', 'Budget', 'Standard', 'Premium' or 'Exclusive'. The first IFchecks whether this value is larger than the value in sheet TimeSummary. If reads: if value is larger or equal to reference in TimeSummary, it's a low cost value. Somehow, it doesn't sound right. I suggest you use: =IF(G13<=TimeSummary!B21,"Low Cost",IF(G13<=TimeSummary!B20,"Budget",IF(G13<=TimeSummary!B17,"Standard",IF(G13<=TimeSummary!B23,"Premium","Exclusive")))) It would also have been simpler with a vlookup, if the reference values were one after the other and not seemingly scattered about as your formula suggests.

Categories : Excel

Optimizing MySQL query with nested select statements?
This is an equivalent query using joins. It depends what indexes are defined on the tables how this will perform. If your Perl interface has the notion of prepared statements, you may be able to save some time by preparing once and executing with 9000 different binds. You could also possibly save time by building one query with a big acd.content_url_id In ($content_path_id1, $content_path_id2, ...) clause Select an.uuid From alf_node an Inner Join alf_node_properties anp On an.id = anp.node_id Inner Join alf_content_data acd On anp.long_value = acd.id Where acd.content_url_id = $content_path_id

Categories : Mysql

Please explain the nested switch-case statements in the following C program and the corresponding output
The switch statement is just a jump into the middle of a for loop (at case label 2). Then the code executes the for loop. Pretty much equivalent to: #include <stdio.h> int main() { int i=5; goto label_2; for ( i=0; i<10; i++ ) { printf("A i=%d ",i); label_2: printf("B i*i=%d ",i*i); }; label_3: printf("done"); return 0; } That's all there is to it.

Categories : C

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS nested case statements
As the error said, you cannot select more than one column into a value. When doing a select statement: SELECT A, B, C ... Each expression A, B, C, represents a column of data to be returned. That column is composed of values that have a data type like integer or double or varchar. So when you do: SELECT A, B, (SELECT C, D FROM ...) ... You are saying "I want a column of As, a column of Bs, and a column of ..." Oops. You just broke SQL because it doesn't know how to put multiple values in a single cell like that. (Well, some SQL variants do know how to do that, but it is not always so simple.) What you probably want is: SELECT A, B, (SELECT C FROM ...), (SELECT D FROM ...) etc. So, that means something like this: declare @workdays int SELECT creationDateTime , closedDa

Categories : Sql Server

Multiple If-Else Statements VS. Switch Statements within While Loop for C Language
No, that code is not possible to write with a switch. The values for case must be constant, and integer. You can have case 4611: but not `case a > 360". So, unless you want hundreds of case statements (you don't) the code is not easily translatable to use a switch. UPDATE One way to make it (in my opinion) more elegant is to order the ranges, and reduce repeat by relying on the lower bound already having been checked in all else ifs: while(1) { const float A = get_angle(); if (A > 1 && A <= 180) { put_speed (600, 200); } else if (A <= 360) { put_speed(600, 100); } else if (A <= 540) { put_speed(100, 600); } else if (A <= 700) { put_speed(200, 600); } else {

Categories : C

DRY With Different Try Statements and Identical Catch Statements
You could pass an Action into a function that handles the exceptions: private void HandleErrorsFor(Action action) { try { action(); } catch (Exception ex) { //repeated exception handling... { } //... public void DoSomething() { HandleErrorsFor(() => { //try block #1 }); HandleErrorsFor(() => { //try block #2 }); } It's a bit easier to read and avoids the repeated code.

Categories : C#

Struts 1.1 nested and in combination
Use <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> and the code will look like <c:choose> <c:when test="${element.method1 == true}"> <c:choose> <c:when test="${element.method2 == true}"> <span style="color:green;"><c:out value="${element.prop1}/></span> </c:when> <c:otherwise> <span style="color:red;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose> </c:when> <c:otherwise> <span style="color:black;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose>

Categories : Java

Nesting "and" statements with "or" statements
Enclose the compound statements in extra brackets to explain to the compiler how to order the logical statments... Try this: If (cell.Value) = "FTV1" _ Or (cell.Value) = "FTV2" _ Or (cell.Value) = "FTV3" _ Or (cell.Value) = "FTV4" _ Or (cell.Value) = "FTV5" _ Or (cell.Value) = "ISTCR" _ Or (cell.Value) = "CAST" _ Or (cell.Value) = "Rig" _ Or ((cell.Value) > 50000 And (cell.Value) < 52000) _ Or ((cell.Value) > 55000 And (cell.Value) < 56000) Then

Categories : Excel

emulated prepared statements vs real prepared statements
You are correct, real prepared statements must be supported by the server. A real prepared means querying the database in two steps. The fist step consists in sending a query template, that the server can pre-compile. The database engine also prepares in advance the execution plan (mostly, what indexes will be used to serve the actual query). The second step is giving actual values to the placeholders and run the actual query with these parameters. This typically allows faster execution of several similar queries, because 1. the query has already been pre-compiled (the execution plan is already computed) and 2. only the parameters values are sent subsequently. A emulated query is just a syntactic sugar, that only allows easier sending (not faster execution) of several, successive, simi

Categories : Mysql

How can I bind data from nested List<> objects to nested ListView controls?
You can bind the datasource of your inner list view to a property of the items bound to your outer listview. However, to do that the inner listview as to be in the itemtemplate of the outer listview. See the code below and note the DataSource='<%# Eval("Labels_color") %>' attribute for the inner list view. <asp:ListView ID="ListView_Orp_Results" runat="server" ItemPlaceholderID="itemPlaceholder"> <LayoutTemplate> <div id="outer_result_container"> <div id="itemPlaceholder" /> </div> </LayoutTemplate> <ItemTemplate> <div id="result_photo">...</div> <div id="result_category">...</div> <div id="result_detector">...</div> <div id="inner_result_container" runat="server"

Categories : Asp Net

JQuery selector for finding a nested span within a nested class is not working
I don't see any problem with your code at the moment, let's reformat it a bit: var tabs = $('.collapse').not('.in'); console.log("tabs.length: " + tabs.length); tabs.each(function () { var $this = $(this), thisErrors = $this.find('.field-validation-error'), thisId = '#' + $this.attr('id'); console.log("current tab ID: " + thisId); console.log("number of errors: " + thisErrors.length); if (thisErrors.length) { $(thisId).collapse('show'); } }); Or working fiddle: http://jsfiddle.net/Rq8y7/ Does it work now? And what's the debug message in console after you run above code?

Categories : Jquery

Parsing a flattly-written nested text template into a usable nested data structure for N levels
Replaces each ">" with a tab. Output is pretty much exactly as your brute force output. (file.txt is your template file as above) test = open("file.txt", "r") for line in test: print line.replace(">", " ") #print line

Categories : Python

How Can I Convert Nested YAML to nested Arrays and OpenStructs in Ruby
There is the solution (https://github.com/jsuchal/hashugar) i often use. opts = Hashugar.new({:a => 1, 'b' => {:c => 2, :d => [3, 4, {:e => 5}]}}) But you also need to do: opts.b.d.last.e I do not understand how do you want to name array's getters. As Arup Rakshit sayed: give us yaml example and expected output or behavior.

Categories : Ruby

Avoiding nested each loops when handling nested JSON data
JSON is "just" javascript object literals. You can skip the jQuery call, and just reference the objects and arrays directly after you parse it. obj.custom_sql_rule[0].something_else[0]; of course, your JSON is a bit oddly-formed. If at all possible, don't arbitrarily mix objects {} and arrays [] . Use the latter when you have lists of identical objects or primitive data, and the former when you have named properties. And once you have a valid javascript object, you can just iterate through its properties. for(var sqlProp in jsonObj) { if(jsonObj[sqlProp].error) { errorsContainer.append("<div>" + jsonObj[sqlProp].error + "</div>"); } }

Categories : Javascript

nested json with jQuery: create List of nested item
Your problem is that institut is an array containing a single object, so you can reference that single object using institut[0]. This will work: $.each(data.fakultaeten, function (key, value) { var mother = "<li id='first'>" + value.name + "<ul>"; $.each(value.institut[0], function (key1, value1) { alert(key1); }); }); Here is a working example

Categories : Jquery

MySQL - Reference main query in nested select (need to be nested)
This cannot work. SELECT clause is always evaluated at the end of the execution chain, @teamg_id variable will always be 0 in the nested subquery. Try this query, it is not tested (I can't see your data, playing whith sample data always helps), but probably it gives desired results. I commented out some parts and add one join condition. /* SET @teamg_id := 0; */ SELECT /* @teamg_id := player.team_id, */ player.team_id AS player_team, event.local_team_id AS local_team, event.visitor_team_id AS visitor_team, action.unique_id AS action_id, action.player_id AS player_id, player.name AS player_name, playerindex.rank AS player_pos, playerindex.ses_var_nest AS ses_var_nest FROM er_players player

Categories : Mysql

How to insert nested lists (or nested block elements) into RichTextBlock?
Ok Ill start with silverlight. There was a TreeView Control in silverlight that would have exactly solved your problem. Link to tree view example But since we already know that winRt is a subset of API's these controls have been removed for metro app. More over microsofts design policy regarding the Type Of scenario you are mentioning has changed to : Semantic Zoom For Metro Apps So i advise if your app requirement is like that Either go with the richtextbox or use Grids with Rows and columns Which ever suits your coding best. One more way is to use third party library for tree structure . Syncfusion tree control Syncfusion has a tree control you can try out in the Demo. Even there are more third party tool but none are free not even he above one. Please Let me know if any more co

Categories : HTML

Idiomatic Emberjs for nested routes but non-nested templates
You could define the parent template to just display the outlet and have an index route which will get displayed inside that. Then for the nested resource you can do the same thing. <script type="text/x-handlebars" data-template-name="user"> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="user/index"> <h2>user/index</h2> </script> <script type="text/x-handlebars" data-template-name="posts"> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="posts/index"> <h2>posts/index</h2> </script> That way it won't be a master/detail. The router would be: App.Router.map(function() { this.resource('user', function() { this.resource('posts', function() { }); });

Categories : Ember Js

nested attributes, passing current_user.id to nested model
'current_user' is a devise helper method. it can be accessed in controllers n views directly. if i m not wrong, only the new answer should have the current_user.id Old answers should not be updated. u can do this as f.fields_for :answers, @question.answers.build do |a| a.hidden_field :user_id, :value => current_user.id a.submit

Categories : Ruby On Rails

PHP - Find nested array1 in nested array2
If I understand correctly what you are trying to achieve, you could do it like this (see comments in code): /* Process one needle (look into haystack and modify it accordingly) */ function processNeedle(&$haystack, $needle) { $needleKeys = array_keys($needle); $needleValues = array_values($needle); $needleLen = count($needle); $haystackLen = count($haystack); /* Find indexes where a match begins */ $matches = array(); for ($i = 0; $i < ($haystackLen - $needleLen + 1); $i++) { $match = true; for ($j = 0; $j < $needleLen; $j++) { if ($haystack[$i + $j]["v1"] != $needleKeys[$j]) { $match = false; break; } } if ($match) { $matches[] = $i;

Categories : PHP

Nested ajax with nested rendered attribute in JSF
It is most likely what your ManagedBean is not in ViewScoped or SessionScoped. When you post back to the bean, you are loosing rendered states. I suggest to change for the ViewScoped one. Not related : You should remove the action attribute from the h:form since JSF override it.

Categories : JSF

how to remove nested entry in a nested map using dot notation
You could write your own method to do this, although you'd be likely to have to resort to a fair amount of casting. You'd probably just split on dots, then keep calling get (and remembering the result for the next step) until you got to the last part, at which point you'd call remove instead... remembering to check for a null return from get at every step. I don't know of anything built into a third party library to do this - which isn't to say it's nowhere, of course.

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.