Search Results

Search found 13563 results on 543 pages for 'condition variable'.

Page 1/543 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Rails - How do I write this string condition as an array condition

    - by adam
    named_scope :correct, :include => :correction, :conditions => "checked_at IS NOT NULL AND corrections.id IS NULL" On a side note I have googled loads and looked through books but i cant seem to find a list of all the various types of conditions you can use and how they differ when implenting them as strings, arrays or hashes. Is there a list of the syntax anywhere?

    Read the article

  • Scientific evidence that supports using long variable names instead of abbreviations?

    - by Sebastian Dietz
    Is there any scientific evidence that the human brain can read and understand fully written variable names better/faster than abbreviated ones? Like PersistenceManager persistenceManager; in contrast to PersistenceManager pm; I have the impression that I get a better grasp of code that does not use abbreviations, even if the abbreviations would have been commonly used throughout the codebase. Can this individual feeling be backed up by any studies?

    Read the article

  • Class scope variable vs method scope variable

    - by Masud
    I know that variable scope is enclosed by a start of block { and an end of block }. If the same variable is declared within the block, then the compile error Variable already defined occurs. But take a look at following example. public class Test{ int x=0;// Class scope variable public void m(){ int x=9; //redeclaration of x is valid within the scope of same x. if(true){ int x=7; // but this redeclaration generates a compile time error. } } Here, x can be redeclared in a method, although it's already declared in the class. But in the if block, x can't be redeclared. Why is it that redeclaration of a class scope variable doesn't generate an error, but a method scope variable redeclaration generates an error?

    Read the article

  • How to pass results of bc to a variable

    - by shaolin
    I'm writing a script and I would like to pass the results from bc into a variable. I've declared 2 variables (var1 and var2) and have given them values. In my script I want to pass the results from bc into another variable say var3 so that I can work with var3 for other calculations. So far I have been able write the result to a file which is not what I'm looking for and also I've been able to echo the result in the terminal but I just want to pass the result to a variable at moment so that I can work with that variable. echo "scale=2;$var1/var2" | bc

    Read the article

  • Why do condition variables sometimes erroneously wake up?

    - by aspo
    I've known for eons that the way you use a condition variable is lock while not task_done wait on condition variable unlock Because sometimes condition variables will spontaneously wake. But I've never understood why that's the case. In the past I've read it's expensive to make a condition variable that doesn't have that behavior, but nothing more than that. So... why do you need to worry about falsely being woken up when waiting on a condition variable?

    Read the article

  • SQL SERVER – How to Set Variable and Use Variable in SQLCMD Mode

    - by Pinal Dave
    Here is the question which I received the other day on SQLAuthority Facebook page. Social media is a wonderful thing and I love the active conversation between blog readers and myself – actually I think social media adds lots of human factor to any conversation. Here is the question - “I am using sqlcmd in SSMS – I am not sure how to declare variable and pass it, for example I have a database and it has table, how can I make the table variable dynamic and pass different value everytime?” Fantastic question, and here is its very simple answer. First of all, enable sqlcmd mode in SQL Server Management Studio as described in following image. Now in query editor type following SQL. :SETVAR DatabaseName “AdventureWorks2012″ :SETVAR SchemaName “Person” :SETVAR TableName “EmailAddress“ USE $(DatabaseName); SELECT * FROM $(SchemaName).$(TableName); Note that I have set the value of the database, schema and table as a sqlcmd variable and I am executing the query using the same parameters. Well, that was it, sqlcmd is a very simple language to master and it also aids in doing various tasks easily. If you have any other sqlcmd tips, please leave a comment and I will publish it with due credit. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Server Management Studio, SQL Tips and Tricks, T SQL, Technology Tagged: sqlcmd

    Read the article

  • How to Pass a JS Variable to a PHP Variable

    - by dmullins
    Hello: I am working on a web application that currently provides a list of documents in a MySql database. Each document in the list has an onclick event that is suppose to open the specific document, however I am unable to do this. My list gets popluated using Ajax. Here is the code excerpt (JS): function stateChanged() { if (xmlhttp.readyState==4) { //All documents// document.getElementById("screenRef").innerHTML="<font id='maintxt'; name='title'; onclick='fileopen()'; color='#666666';>" + xmlhttp.responseText + "</font>"; } } } The onclick=fileopen event above triggers the next code excerpt, which downloads the file (JS): function stateChanged() { if (xmlhttp.readyState==4) { //Open file var elemIF = document.createElement("iframe"); elemIF.src = url; elemIF.style.display = "none"; document.body.appendChild(elemIF); } } } Lastly, the openfile onclick event triggers the following php code to find the file for downloading (php): $con = mysql_connect("localhost", "root", "password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Documents", $con); $query = mysql_query("SELECT name, type, size, content FROM upload WHERE name = NEED JS VARIABLE HERE"); $row = mysql_fetch_array($query); header ("Content-type: ". $row['type']); header ("Content-length: ". $row['size']); header ("Content-Disposition: attachement; filename=". $row['name']); echo $row['content']; This code works well, for downloading a file. If I omit the WHERE portion of the Sql query, the onclick event will download the first file. Somehow, I need to get the screenRef element text and change it into a variable that my php file can read. Does anyone know how to do this? Also, without any page refreshes. I really appreciate everyone's feedback and thank you in advance. DFM

    Read the article

  • MooTools/JavaScript variable scope

    - by 827
    I am trying to make each number displayed clickable. "1" should alert() 80, "2" should produce 60, etc. However, when the alert(adjust) is called, it only shows 0, not the correct numbers. However, if the commented out alert(adjust) is uncommented, it produces the correct number on page load, but not on clicking. I was wondering why the code inside addEvents cannot access the previously defined variable adjust. <html> <head> <script type="text/javascript" charset="utf-8" src="mootools.js"></script> <script type="text/javascript" charset="utf-8"> window.addEvent('domready', function() { var id_numbers = [1,2,3,4,5]; for(var i = 0; i<id_numbers.length; i++) { var adjust = (20 * (5 - id_numbers[i])); // alert(adjust); $('i_' + id_numbers[i]).addEvents({ 'click': function() { alert(adjust); } }); } }); </script> </head> <body> <div id="i_1">1</div> <div id="i_2">2</div> <div id="i_3">3</div> <div id="i_4">4</div> <div id="i_5">5</div> </body> </html> Thanks.

    Read the article

  • PHP variable in variable

    - by FFish
    I have set an array in my config file that I use global in my functions. This works fine, but now I want to pass the name of this array as a @param in my function. // in config file: $album_type_arr = array("appartamento", "villa"); global $album_type_arr; // pull in from db_config echo $album_type_arr[0]; function buildmenu($name) { $test = global $name . "_arr"; echo $test[0]; } buildmenu("album_type");

    Read the article

  • if ('constant' == $variable) vs. if ($variable == 'constant')

    - by Tom Auger
    Lately, I've been working a lot in PHP and specifically within the WordPress framework. I'm noticing a lot of code in the form of: if ( 1 == $options['postlink'] ) Where I would have expected to see: if ( $options['postlink'] == 1 ) Is this a convention found in certain languages / frameworks? Is there any reason the former approach is preferable to the latter (from a processing perspective, or a parsing perspective or even a human perspective?) Or is it merely a matter of taste? I have always thought it better when performing a test, that the variable item being tested against some constant is on the left. It seems to map better to the way we would ask the question in natural language: "if the cake is chocolate" rather than "if chocolate is the cake".

    Read the article

  • Checking for empty variable in PHPTAL condition

    - by kodziek
    In PHPTAL tal:condition can check is variable empty? Something like that: < tag tal:condition="var" >Some text< /tag > but the value of variable is like that: <?php $variable = ''; $Tpl->var = $variable; ?> And it's a problem 'cause PHPTAL that value '' interpreting like not empty value and condition return true. How fix it in PHPTAL side?

    Read the article

  • ASP.NET C# Session Variable

    - by SAMIR BHOGAYTA
    You can make changes in the web.config. You can give the location path i.e the pages to whom u want to apply the security. Ex. 1) In first case the page can be accessed by everyone. // Allow ALL users to visit the CreatingUserAccounts.aspx // location path="CreatingUserAccounts.aspx" system.web authorization allow users="*" / /authorization /system.web /location 2) in this case only admin can access the page // Allow ADMIN users to visit the hello.aspx location path="hello.aspx" system.web authorization allow roles="ADMIN' / deny users="*" / /authorization /system.web /location OR On the every page you need to check the authorization according to the page logic ex: On every page call this if (session[loggeduser] !=null) { DataSet dsUser=(DataSet)session[loggeduser]; if (dsUser !=null && dsUser.Tables.Count0 && dsUser.Tables[0] !=null && dsUser.Tables[0].Rows.Count0) { if (dsUser.Table[0].Rows[0]["UserType"]=="SuperAdmin") { //your page logic here } if (dsUser.Table[0].Rows[0]["UserType"]=="Admin") { //your page logic here } } }

    Read the article

  • Common Lisp condition system for transfer of control

    - by Ken
    I'll admit right up front that the following is a pretty terrible description of what I want to do. Apologies in advance. Please ask questions to help me explain. :-) I've written ETLs in other languages that consist of individual operations that look something like: // in class CountOperation IEnumerable<Row> Execute(IEnumerable<Row> rows) { var count = 0; foreach (var row in rows) { row["record number"] = count++; yield return row; } } Then you string a number of these operations together, and call The Dispatcher, which is responsible for calling Operations and pushing data between them. I'm trying to do something similar in Common Lisp, and I want to use the same basic structure, i.e., each operation is defined like a normal function that inputs a list and outputs a list, but lazily. I can define-condition a condition (have-value) to use for yield-like behavior, and I can run it in a single loop, and it works great. I'm defining the operations the same way, looping through the inputs: (defun count-records (rows) (loop for count from 0 for row in rows do (signal 'have-value :value `(:count ,count @,row)))) The trouble is if I want to string together several operations, and run them. My first attempt at writing a dispatcher for these looks something like: (let ((next-op ...)) ;; pick an op from the set of all ops (loop (handler-bind ((have-value (...))) ;; records output from operation (setq next-op ...) ;; pick a new next-op (call next-op))) But restarts have only dynamic extent: each operation will have the same restart names. The restart isn't a Lisp object I can store, to store the state of a function: it's something you call by name (symbol) inside the handler block, not a continuation you can store for later use. Is it possible to do something like I want here? Or am I better off just making each operation function explicitly look at its input queue, and explicitly place values on the output queue?

    Read the article

  • Rails Layout Rendering with controller condition

    - by Victor Martins
    I don't know what's the best way to doing this. On my application.html.erb I define a header div. My default controller ( root ) is a homepage controller. And I wish that if I'm at index of the homepage the header is rendering with some content, but all other controllers render another content inside that header. How can I make a condition in that header div to render different content based on the controller that's being rendered?

    Read the article

  • Rails - Find Condition of two model fields

    - by ChrisWesAllen
    I'm trying to find the results of a model where it queries as the result of two conditions. I have a search tag that looks for Model.find(:all, :conditions => "name LIKE params[search]") but I'd like for the search to find all records where "name LIKE params[search] or description LIKE params[search] . Is there any way to add an OR into a condition in rails? or should I make an if statement?

    Read the article

  • Elusive race condition in Java

    - by nasufara
    I am creating a graphing calculator. In an attempt to squeeze some more performance out of it, I added some multithreaded to the line calculator. Essentially what my current implementation does is construct a thread-safe Queue of X values, then start however many threads it needs, each one calculating a point on the line using the queue to get its values, and then ordering the points using a HashMap when the calculations are done. This implementation works great, and that's not where my race condition is (merely some background info). In examining the performance results from this, I found that the HashMap is a performance bottleneck, since I do that synchronously on one thread. So I figured that ordering each point as its calculated would work best. I tried a PriorityQueue, but that was slower than the HashMap. I ended up creating an algorithm that essentially works like this: I construct a list of X values to calculate, like in my current algorithm. I then copy that list of values into another class, unimaginatively and temporarily named BlockingList, which is responsible for ordering the points as they are calculated. BlockingList contains a put() method, which takes in two BigDecimals as parameters, the first the X value, the second the calculated Y value. put() will only accept a value if the X value is the next one on the list to be accepted in the list of X values, and will block until another thread gives it the next excepted value. For example, since that can be confusing, say I have two threads, Thread-1 and Thread-2. Thread-2 gets the X value 10.0 from the values queue, and Thread-1 gets 9.0. However, Thread-1 completes its calculations first, and calls put() before Thread-2 does. Because BlockingList is expecting to get 10.0 first, and not 9.0, it will block on Thread-1 until Thread-2 finishes and calls put(). Once Thread-2 gives BlockingList 10.0, it notify()s all waiting threads, and expects 9.0 next. This continues until BlockingList gets all of its expected values. (I apologise if that was hard to follow, if you need more clarification, just ask.) As expected by the question title, there is a race condition in here. If I run it without any System.out.printlns, it will sometimes lock because of conflicting wait() and notifyAll()s, but if I put a println in, it will run great. A small implementation of this is included below, and exhibits the same behavior: import java.math.BigDecimal; import java.util.concurrent.ConcurrentLinkedQueue; public class Example { public static void main(String[] args) throws InterruptedException { // Various scaling values, determined based on the graph size // in the real implementation BigDecimal xMax = new BigDecimal(10); BigDecimal xStep = new BigDecimal(0.05); // Construct the values list, from -10 to 10 final ConcurrentLinkedQueue<BigDecimal> values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal i = new BigDecimal(-10); i.compareTo(xMax) <= 0; i = i.add(xStep)) { values.add(i); } // Contains the calculated values final BlockingList list = new BlockingList(values); for (int i = 0; i < 4; i++) { new Thread() { public void run() { BigDecimal x; // Keep looping until there are no more values while ((x = values.poll()) != null) { PointPair pair = new PointPair(); pair.realX = x; try { list.put(pair); } catch (Exception ex) { ex.printStackTrace(); } } } }.start(); } } private static class PointPair { public BigDecimal realX; } private static class BlockingList { private final ConcurrentLinkedQueue<BigDecimal> _values; private final ConcurrentLinkedQueue<PointPair> _list = new ConcurrentLinkedQueue<PointPair>(); public BlockingList(ConcurrentLinkedQueue<BigDecimal> expectedValues) throws InterruptedException { // Copy the values into a new queue BigDecimal[] arr = expectedValues.toArray(new BigDecimal[0]); _values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal dec : arr) { _values.add(dec); } } public void put(PointPair item) throws InterruptedException { while (item.realX.compareTo(_values.peek()) != 0) { synchronized (this) { // Block until someone enters the next desired value wait(); } } _list.add(item); _values.poll(); synchronized (this) { notifyAll(); } } } } My question is can anybody help me find the threading error? Thanks!

    Read the article

  • What is the relaxation condition in graph theory

    - by windopal
    Hi, I'm trying to understand the main concepts of graph theory and the algorithms within it. Most algorithms seem to contain a "Relaxation Condition" I'm unsure about what this is. Could some one explain it to me please. An example of this is dijkstras algorithm, here is the pseudo-code. 1 function Dijkstra(Graph, source): 2 for each vertex v in Graph: // Initializations 3 dist[v] := infinity // Unknown distance function from source to v 4 previous[v] := undefined // Previous node in optimal path from source 5 dist[source] := 0 // Distance from source to source 6 Q := the set of all nodes in Graph // All nodes in the graph are unoptimized - thus are in Q 7 while Q is not empty: // The main loop 8 u := vertex in Q with smallest dist[] 9 if dist[u] = infinity: 10 break // all remaining vertices are inaccessible from source 11 remove u from Q 12 for each neighbor v of u: // where v has not yet been removed from Q. 13 alt := dist[u] + dist_between(u, v) 14 if alt < dist[v]: // Relax (u,v,a) 15 dist[v] := alt 16 previous[v] := u 17 return dist[] Thanks

    Read the article

  • SQL Server Process Queue Race Condition

    - by William Edmondson
    I have an order queue that is accessed by multiple order processors through a stored procedure. Each processor passes in a unique ID which is used to lock the next 20 orders for its own use. The stored procedure then returns these records to the order processor to be acted upon. There are cases where multiple processors are able to retrieve the same 'OrderTable' record at which point they try to simultaneously operate on it. This ultimately results in errors being thrown later in the process. My next course of action is to allow each processor grab all available orders and just round robin the processors but I was hoping to simply make this section of code thread safe and allow the processors to grab records whenever they like. So Explicitly - Any idea why I am experiencing this race condition and how I can solve the problem. BEGIN TRAN UPDATE OrderTable WITH ( ROWLOCK ) SET ProcessorID = @PROCID WHERE OrderID IN ( SELECT TOP ( 20 ) OrderID FROM OrderTable WITH ( ROWLOCK ) WHERE ProcessorID = 0) COMMIT TRAN SELECT OrderID, ProcessorID, etc... FROM OrderTable WHERE ProcessorID = @PROCID

    Read the article

  • Problem with writing if condition

    - by Himadri
    I have two decimal numbers. I want those number to be same upto 4 decimal points without rounding. If numbers are different I want 2nd number to be replaced by 1st. What if condition should I write? Eg, 1. num1 = 0.94618976 num2 = 0.94620239 If we round these numbers upto 4 decimal then we get 0.9462 same number, but I don't want to round these numbers. 2. num1 = 0.94620239 num2 = 0.94639125 The one way I found is take absolute difference of both numbers say diff and then check the value. My problem is of checking the range of diff. I am using delphi but you can answer in any language.Thank You.

    Read the article

  • Condition checking vs. Exception handling

    - by Aidas Bendoraitis
    When is exception handling more preferable than condition checking? There are many situations where I can choose using one or the other. For example, this is a summing function which uses a custom exception: # module mylibrary class WrongSummand(Exception): pass def sum_(a, b): """ returns the sum of two summands of the same type """ if type(a) != type(b): raise WrongSummand("given arguments are not of the same type") return a + b # module application using mylibrary from mylibrary import sum_, WrongSummand try: print sum_("A", 5) except WrongSummand: print "wrong arguments" And this is the same function, which avoids using exceptions # module mylibrary def sum_(a, b): """ returns the sum of two summands if they are both of the same type """ if type(a) == type(b): return a + b # module application using mylibrary from mylibrary import sum_ c = sum_("A", 5) if c is not None: print c else: print "wrong arguments" I think that using conditions is always more readable and manageable. Or am I wrong? What are the proper cases for defining APIs which raise exceptions and why?

    Read the article

  • Avoid IF statement after condition has been met

    - by greye
    I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible. I have an if condition to test the divisor value in order to avoid the div by zero, but I am wondering that there is a performance impact that evaluating this if will have for each run in subsequent loops, especially since I know it's of no use anymore. How should this be coded? in Python?

    Read the article

  • prevent race condition without using locks C++

    - by Hristo
    How do I prevent a race condition with locking or using mutexes/semaphors in C++? I'm dealing with a nested for loop in which I will be setting a value in an array: for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) for (int k = 0; k < o; ++k) array[k] += foo(...); More or less, I want to deal with this so that I can ensure different threads running at the same time don't write to array[k] at the same time. Any suggestions on how to approach this? Thanks, Hristo

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >