Unnamed: 0
int64
65
6.03M
Id
int64
66
6.03M
Title
stringlengths
10
191
input
stringlengths
23
4.18k
output
stringclasses
10 values
Tag_Number
stringclasses
10 values
4,381,575
4,381,576
php symfony2 login_check captcha
<p>I have authentication and authorisation working fine in my php/symfony2 project. Now I am trying to add recaptcha on the user creation and login. I have it working on the user creation, but the login posts to login_check and ignores the captcha. How can I add the captcha validation on login? Thanks</p>
php
[2]
3,611,705
3,611,706
Transforming html file in java
<pre><code>public String transform_XML(String type, InputStream file){ TransformerFactory tf = TransformerFactory.newInstance(); String xslfile = "/StyleSheets/" + type + ".xsl"; Transformer t = tf.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslfile))).newTransformer(); Source source = new StreamSource(file); CharArrayWriter wr = new CharArrayWriter(); StreamResult result = new StreamResult(wr); t.transform(source, result); return wr.toString(); } </code></pre> <p>The above method takes an xsl and xml file as input and returns the transformed result as String. Classes from Package javax.xml.transform has been used to accomplish this.</p> <p>Now can i use the same package to transform an html file? (Since the package name has xml i seriously doubt it.) What should i do to transform an html file?</p>
java
[1]
4,156,216
4,156,217
Android Back button code never executed
<p>I have the following code in my Activity. I have Breakpoints set to all of these methods. When I press the Menu button, it enters onKeyDown and onKeyUp. When I press the back button, the app closes and phone goes back to home screen without passing any of my breakpoints.</p> <p>EDIT: This could should work according to most sources:</p> <pre><code>@Override public void onBackPressed() { SwitchToMenuState(); } </code></pre> <p>However, it doesn't. I have tried all permutations of the following code blocks, and neither of them ever get called:</p> <pre><code>@Override public void finish() { SwitchToMenuState(); } public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { SwitchToMenuState(); } return true; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { SwitchToMenuState(); } return true; } </code></pre> <p>I am using Android 2.3 and Processing, although it doesn't seem to be related to Processing at all. Eclipse tells me that I am overriding android.app.Activity.onBackPressed.</p>
android
[4]
266,855
266,856
java coding confusion about String args[] and String[] args
<p>I am new in programming with Java and I am confused about the following two statements:</p> <pre><code>public static void main(String args[]) </code></pre> <p>and</p> <pre><code>public static void main(String[] args) </code></pre> <p>Are they same? If not, how are they different from each other?</p>
java
[1]
3,899,113
3,899,114
Weird PHP problem
<p>I have the following code...</p> <pre><code>&lt;?php session_start(); require_once('myDB.php'); if (isset($_POST)) { foreach($GLOBALS['myDB']-&gt;getShops()as $i) { $tempLat = $i['latitude']; $templong = $i['longitude']; $distance = distance($_POST['latitude'],$_POST['longitude'],$tempLat,$templong); if($distance &lt;= 300) { echo "".$i['id']."|".$i['shopName']."|".$i['longitude']."|".$i['latitude']."|".$i['advert']."|"; } } } function distance($lat1, $lon1, $lat2, $lon2) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; return (($miles * 1.609344)*1000); } ?&gt; </code></pre> <hr> <p>Now when I get to see that page it gives me Error 324 (net::ERR_EMPTY_RESPONSE) and it says that the website may be temporarily down...If i try to open the page using firefox it opens a dialog for downloading the php file...</p> <p>What I would like to do is to have it print either the echoes (if distance is in fact bigger than 300 meters) or nothing at all but it should still be an empty html page...</p> <p>Can anyone see whats wrong with that???</p> <p>NOTE: The code works fine locally but not on my server..however every other page works as expected so the server is up and running...</p>
php
[2]
6,010,728
6,010,729
Define php function and use without ()
<p>Is it possible to define a function and use without ()?</p> <p>Like <code>require("a.php")</code> and <code>require "a.php"</code>. </p> <pre><code>function getNameById($id){}; /*and use it like*/ $id = getNameById "1"; </code></pre> <p>Thanks.</p>
php
[2]
5,612,401
5,612,402
indirect path for download files
<p>i need to create a download section on my website , but as i concern , i want my users can only download files with indirect links , to prevent them from sharing my files on my server </p> <p>such as : </p> <p><a href="http://mysite.com/download/12.zip" rel="nofollow">http://mysite.com/download/12.zip</a></p> <p>to </p> <p><a href="http://mysite.com/download/12" rel="nofollow">http://mysite.com/download/12</a></p> <p>is there a way in php to do so ?</p>
php
[2]
2,958,857
2,958,858
Improving Newton's Method Recursion
<p>I have solved a previous problem and now I am stuck with this one. It is asking for an improvement of the previous solution which I posted below, but can't quite understand what the problem is asking. (Also, can't really figure out how to solve it.) Please help thanks.</p> <p>Problem: Elena complains that the recursive newton function in Project 2 includes an extra argument for the estimate. The function’s users should not have to provide this value, which is always the same, when they call this function. Modify the definition of the function so that it uses a keyword parameter with the appropriate default value for this argument, and call the function without a second argument to demonstrate that it solves this problem.</p> <p>Here is my code:</p> <pre><code>def newtonSquare(x, estimate): if abs(x-estimate ** 2) &lt;= 0.000001: return estimate else: return newtonSquare(x, (estimate + x / estimate) / 2) def main(): num = int(raw_input('Enter a positive number &gt;&gt; ')) print newtonSquare(num, 1.0) main() </code></pre>
python
[7]
3,562,639
3,562,640
Why are myarray instanceof Array and myarray.constructor === Array both false when myarray is in a frame?
<p>So the following code alerts false twice:</p> <pre><code>window.onload = function(){ alert(window.myframe.myarray instanceof Array); alert(window.myframe.myarray.constructor === Array); } </code></pre> <p>When there's an iframe in the page named "myframe" that has contains an array called "myarray". If the array is moved into the main page (as opposed to the iframe), then the code alerts true twice as expected. Does anyone know why this is?</p>
javascript
[3]
587,275
587,276
How to store values in NSUserDefaults like as a Database
<p>I need to create an application using NSUserDefaults.</p> <p>In my first view i will enter the password. In second view i will enter the confirm password. Then validation will be come. after then if password will be match in both views, then success window will be open. After then some views will come. I need that password should be save in NSUserDefaults for future use.</p> <p>if i will close my application after validation, then if i will build and run again my application now the password validation window should not be open.</p> <p>Only one view simply will ask the password, if the current password is equal to before terminate application's password, then the application's success view will be open. Now here the validation should be compare with current password with NSUserDefaults's value[i.e old password, which is stored before terminate my application].</p> <p>It is possible to using NSUserDefaults?</p> <p>If anybody knows the any idea please help me..</p> <p>Thanks.</p>
iphone
[8]
5,559,447
5,559,448
Does Droid RAZR/Droid RAZR MAXX update have Wifi Direct?
<p>Just a quick question I was hoping somebody with either the Razr or Razr MAXX could answer if after updating to ICS if the ability to toggle WiFi Direct was added. Considering this phone and am developing an app using this feature. Thanks! </p>
android
[4]
2,540,039
2,540,040
Format money for display: "x" -> "x.00"?
<p>I am storing money in MySQL with float format but <code>.00</code> are removed since they don't have much meaning but I want to show them to user in a correct money format using PHP.</p> <p>I wrote a function which checks whether the money field has any <code>.</code> period otherwise add <code>.00</code>.</p> <p>But personally I didn't like this function so I am looking for a built-in function which can do the same job:</p> <pre><code>function formatMoney($price){ if (strpos($price,".") &gt; -1) return $price; else return $price . ".00"; } </code></pre> <p><strong>Edit:</strong> For the people who somehow reached my question should know that <code>money_format</code> doesn't work on Windows Machines as it is explained here below taken from the PHP Manual:</p> <blockquote> <p>The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.</p> </blockquote> <p>So you should use <code>number_format</code> in place of it. You can see my answer on how I solved this problem.</p>
php
[2]
623,955
623,956
Gridview populates on second time clicking the button
<p>I have an updatepanel. Inside that i have some controls for selecting search criteria. For search button onclientclick iam calling javascript functon for validation and in onclick iam calling the mathod to populate the gridview. On clicking search first time it is not loading the grid and clicking the second time it populates.</p>
asp.net
[9]
859,684
859,685
Hide/show checkboxes by class according to dropdown selectedIndex
<p>I have a dropdown list with a few options and a group of checkboxes that should be available only if the user selects some particular options while filling the form.</p> <p>Then, there's a group of checkboxes (4 checkboxes), 3 of which have class="extrasB" and that should be available for selection <strong>only</strong> if user has chosen the last 2 options in the select (5,6). </p> <p>Each selected checkbox of the above adds an extra cost (it's value) to the total cost of the form (field scost). Let's say that the user selects option 5, selects some checkboxes and then decides he want's option 3 (no checkboxes). This should automatically un-select the already checked checkboxes and change the value of scost. <strong>How do I do this?</strong></p> <p>Here's a <a href="http://jsfiddle.net/HbpRn/12/" rel="nofollow">jsfiddle</a> with all of the above in working order.</p>
jquery
[5]
5,399,450
5,399,451
Conflict with jscrollPane and animate
<p>I am using jscollPane on a div that is displayed via the jquery animate function.</p> <p>The animate function seems to be causing a conflict with the jscrollpane script and thus the scrollbars do not show. </p> <p>Here is an example page to demonstrate: <a href="http://mikesewell.net/dev/scrollpane/" rel="nofollow">http://mikesewell.net/dev/scrollpane/</a></p> <p>The div #text is hidden using display: none; it is shown using this function:</p> <pre><code>$(".bio-button").hover(function() { $(this).next("#text").animate({opacity: "show"}, "slow"); } </code></pre> <p>If I dont' hide #text jscrollPane works fine, but if using this function to animate stops the scrollbars from showing.</p> <p>Any suggestions would be greatly, greatly appreciated. Thanks!!</p>
jquery
[5]
4,271,823
4,271,824
Unindent does not match any outer indentation level?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/492387/indentationerror-unindent-does-not-match-any-outer-indentation-level">IndentationError: unindent does not match any outer indentation level</a> </p> </blockquote> <p>I have the following python code.</p> <pre><code>import sys ins = open( sys.argv[1], "r" ) array = [] for line in ins: s = line.split() array.append( s[0] ) # &lt;-- Error here print array ins.close() </code></pre> <p>The python interpreter complains </p> <pre><code> File "sort.py", line 7 array.append( s[0] ) ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>Why so? And how to correct this error?</p>
python
[7]
3,821,282
3,821,283
Declare by including its header, not by explicit declaration
<p>What does this piece of advice mean? It's from <em>The C++ Programming Language, Special Edition</em>.</p> <blockquote> <p>Declare standard library facilities by including its header, not by explicit declaration; §16.1.2.</p> </blockquote> <p>Here's an extract from §16.1.2 that I believe is relevant:</p> <blockquote> <p>For a standard library facility to be used its header must be included. Writing out the relevant declarations yourself is <em>not</em> a standards-conforming alternative. The reason is that some implementations optimize compilation based on standard header inclusion and others provide optimized implementations of standard library facilities triggered by the headers. In general, implementers use standard headers in ways programmers cannot predict and shouldn’t have to know about.</p> </blockquote>
c++
[6]
2,339,690
2,339,691
why java.lang.IllegalStateException: no transaction pending and how to solve
<p>I developed one android application.Its working fine for our device and and most of the devices.But some of the users sent error report.</p> <pre><code>java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:200) at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274) at java.util.concurrent.FutureTask.setException(FutureTask.java:125) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) at java.lang.Thread.run(Thread.java:1019) Caused by: java.lang.IllegalStateException: no transaction pending at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:610) at com.footy.fixture.FixtureActivity$ProgressTask.doInBackground(FixtureActivity.java:1) at android.os.AsyncTask$2.call(AsyncTask.java:185) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) </code></pre> <p>Why this happends for some devices.Which type of error is this?...How can I solve this</p>
android
[4]
1,600,366
1,600,367
Why should I convert a string to upper case when comparing?
<p>I constantly read about it being a good practise to convert a string to upper case (I think Hanselman mentioned this on his blog a long time ago), when that string is to be compared against another (which should also be converted to upper case).</p> <p>What is the benefit of this? Why should I do this (or are there any cases when I shouldn't)?</p> <p>Thanks</p>
c#
[0]
4,281,216
4,281,217
What is a jQuery Object?
<p>JavaScript kind of redefines what an Array means because an array is an object with a .length property and methods like .slice() and .join().</p> <p>jQuery defines a jQuery object as "Array like", because it has a length property but it doesn't have certain array methods like join().</p> <p>If I were to define the jQuery object as an object, and forget about mentioning anything to do with an array, how would I define it? What properties does it have besides length?</p> <p>I guess all the methods are what you see in the documentation, far exceeding the number of methods that are in an array.</p>
jquery
[5]
1,573,659
1,573,660
set method and incrementing
<p>When setting new section I need to keep track of the counters. for example if m1 is Brass and I use setSection(Strings); I want it to Brass-- and Strings++ But I'm not sure how to do it with if statments and im not sure if getSection()toString() would get me the original section or not</p> <pre><code>/**This function sets a musician's Orchestra Section. @param section is a SymphonySection indicating the musician's Orchestra Section.*/ public void setSection(SymphonySection section) { this.section = section; if (getSection().toString().equals( "Strings" )){ Strings--; } else if (getSection().toString().equals( "Brass" )){ Brass--; } else if (getSection().toString().equals( "Conductor" )){ Conductor--; } else if (getSection().toString().equals( "Percussion" )){ Percussion--; } else if (getSection().toString().equals( "WoodWinds" )){ WoodWinds--; } if (section.toString().equals( "Strings" )){ Strings++; } else if (section.toString().equals( "Brass" )){ Brass ++; } else if (section.toString().equals( "Conductor" )){ Conductor ++; } else if (section.toString().equals( "Percussion" )){ Percussion ++; } else if (section.toString().equals( "WoodWinds" )){ WoodWinds ++; } } </code></pre>
java
[1]
3,056,819
3,056,820
Why won't this create a link?
<p>I am trying to make a link with PHP and I am not sure what is wrong with this code.</p> <pre><code>$product_list .= "\n\r " . 'Ticket Download: ' . ": " . &lt;a href=$single_link["url"]&gt;($single_link['name'])&lt;/a&gt; . "\n\r"; </code></pre> <p>I know the issue is with the link (meaning between the opening and closing html tags). What am I doing wrong?</p> <p>Edit: I have tried using the code you have all provided, and I still can't get it to work. I am not sure why.</p>
php
[2]
485,944
485,945
For loop to search for word in string
<p>I can't seem to find the syntax needed for the for loop in this method. I am looking to iterate through the words in the string <code>suit</code>.</p> <p>EDIT: one thing to note is that cardArray is a ArrayList.</p> <pre><code>public String getSuit(int card){ String suit = cardArray.get(card); for (String word : suit){ if (word.contains("SPADES")){ suit = "SPADES"; } } return suit; } </code></pre>
java
[1]
1,496,554
1,496,555
How to write a jquery function that can return 3 possible options
<p>I have a basic points counter widget that I am working on. I had an earlier question that got answered to help me get moving. But I have a final question. Basically, I have a function that is going to return true or false, but I need a third option.</p> <p>the logic is:</p> <ul> <li>if input char count is in range, user gets points</li> <li>if user edits and count stays in range no new points</li> <li>if user edits and count goes out of range after it was in range, then user looses points</li> </ul> <p>I think I hve this right, just not sure how to complete the function.</p> <p><a href="http://jsfiddle.net/jNtJA/8/" rel="nofollow">http://jsfiddle.net/jNtJA/8/</a></p> <pre><code> var check = false; function titleInc() { var length = $('#title').val().length; if (length &gt;= 5 &amp;&amp; length &lt;= 10 &amp;&amp; !check) { check = true; return true; } else if (check &amp;&amp; length &lt; 5 &amp;&amp; length &gt; 10) { // Set the function to return DECREMENT } else { return false; } $('#title').blur(function () { var current = parseInt($('#end_val').val(), 10); if (titleInc()) { $('#end_val').val(current + 12); } else if( ){ // THERE NEEDS TO BE A WAY TO DECREMENT } }); }); </code></pre>
jquery
[5]
3,524,423
3,524,424
How do I stretch a UI Element to fill the vertical space on a view?
<p>I have a layout that contains three rows or segments in my Android view.</p> <p>The first layout region has a fixed height based upon the content of the region with a:layout_height="wrap_content".</p> <p>The next segment will contain a ListView with it's built in scrolling capability, I would like this to take up the available screen real-estate.</p> <p>The final segment will always have a fixed height based upon an absolute value or a:layout_height="32dp". I would like this thrid segment "docked" to the bottom of the view.</p> <p>For reference the following XAML accomplishes what I want</p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="auto" /&gt; &lt;RowDefinition Height="*" /&gt; &lt;RowDefinition Height="32" /&gt; &lt;/Grid.RowDefinisions&gt; &lt;/Grid&gt; </code></pre> <p>Is this possible via android layout XML? And if so how can this be done.</p>
android
[4]
5,430,578
5,430,579
how to find daily visitors of website using php
<p>i want to know that how to find approximate visitors and daily earning of website using php.</p> <pre><code>$value=$alexa.".".$random_number; </code></pre> <p>my current algorithm is using alexa and one random number .</p> <p>so any idea what could be best algorithm and possible factors that effect it.</p>
php
[2]
3,236,352
3,236,353
JavaScript beginner: How to restart a loop
<p>Once the user guesses the right number I need to ask if the user would like to play again. As it is the loop will just repeat itself but what I need is the prompt box to ask if you would like to play again. If the user replies yes the loop will initiate again until the answer is guessed</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;/HEAD&gt; &lt;BODY &lt;FORM NAME="testform"&gt; &lt;BR&gt; &lt;BR&gt; &lt;BR&gt; &lt;/FORM&gt; &lt;INPUT id="attempts" TYPE="text" NAME="inputbox" VALUE="" /&gt; &lt;INPUT id="zero" TYPE="button" NAME="resetbox" VALUE="Reset " onclick="reset()" /&gt; &lt;SCRIPT type="text/javascript"&gt; varattempts = 0; x = Math.round((Math.random()*19))+1; var tip; tip=prompt("Do you want to play a game?") while(tip.charAt(0).toLowerCase() == "y") { var Guess; document.getElementById('attempts').value = 0; do { Guess = prompt("Pick a number between 1 and 20","") if (Guess === null) break; document.getElementById('attempts').value = parseInt(document.getElementById('attempts').value)+1 } while (Guess!=x); if (Guess == x) { alert("You guessed right!") } } function reset() { varattempts=0; document.getElementById('attempts').value = 'Attempts: 0'; } &lt;/SCRIPT&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
javascript
[3]
5,275,634
5,275,635
how to see current version of iphone SDK in MAC system?
<p>anyone can help?</p>
iphone
[8]
2,612,272
2,612,273
Read files from a Folder present in project
<p>I have a C# project (Windows Console Application). I have created a folder named <strong>Data</strong> inside project. There are two text files inside folder Data.</p> <p>How can I read the text files from "Data" folder. I tried below things.</p> <pre><code>string[] files = File.ReadAllLines(@"Data\Names.txt") </code></pre> <p>It is thowing error that file not found.</p> <p>I have checked some Stackoverflow answers posted before and none of then are working for me.</p> <p>How can I proceed? Thanks!</p>
c#
[0]
3,748,187
3,748,188
android 4.0 - How to get bottom menu button using theme black?
<p>I am trying to create an android app that has the following:</p> <ul> <li>Theme set to @android:style/Theme.Black</li> <li>Bottom options menu button on all activities except for one.</li> </ul> <p>I am trying to remove the bottom menu button from the activity that I do not want it to appear on by returning false in the OnCreateOptionsMenu method. This doesn't work... </p> <p>So if I compile my app to target sdk version 14 the menu is gone from every activity...</p> <p>How can I achieve this?</p>
android
[4]
3,908,906
3,908,907
Dynamically naming the file name ( Excel File ) in C#
<p>I want to name the file dynamically in C#.</p> <p>i.e) Name of the File will be picked from Database. When i generate the Excel File and save in a working folder, the file name should be picked from the variable !!</p> <p>i am searching online to find the solution !!</p>
c#
[0]
5,108,362
5,108,363
class initialization in java
<p>Why does java allow this </p> <pre><code>public class A { private int i; public A(int i){ } } </code></pre> <p>but not this</p> <pre><code>public class A { private final int i; public A(int i){ // compile - time error } } </code></pre> <p>What is the difference push the item to the stack when it is <strong>final</strong> ? Why doesn't it understand that A(i) is different than final int i ?</p>
java
[1]
4,595,007
4,595,008
Remove line from end of file with PHP
<p>How would I remove a line from the end of a string with PHP? Thanks.</p>
php
[2]
457,583
457,584
Write Content To New Window with JQuery
<p>I have a web page with a DIV element in it. When a user clicks "print", I want to print the contents of that div. Please note, I only want to print the contents of the DIV, not the entire page. To attempt this, I decided I would open a new window using JavaScript. I was then going to write the contents of the DIV into the new window. My question is, is this possible with JQuery? If so, how? Currently, I'm trying the following:</p> <pre><code>function printClick() { var w = window.open(); var html = $("#divToPrintID").html(); // how do I write the html to the new window with JQuery? } </code></pre>
jquery
[5]
5,589,537
5,589,538
Loop doesn't stop when flag is set?
<p>I am developing a program in which I need to stop a loop when a flag is true. This is a short example of that I want:</p> <pre><code>var aux = true; for(i=0; i &lt; limit &amp;&amp; aux; i++) { ... if (condition) aux = false; } </code></pre> <p>When the condition should end the loop. But this is not true. What is the problem?</p> <p>EDIT:</p> <p>The code is as follows:</p> <pre><code>aux = true; for(j=posX+1; j &lt;= limitXTop &amp;&amp; aux; j++) if(j != limiteXSuperior) { if(map.getXY(j,posY)[0] == 2) { aux = false; } else // Change ... } ... </code></pre> <p>I print a message to check if the execution enter in the IF and it enter.</p>
javascript
[3]
1,736,374
1,736,375
PHP calculations in an array (recursive?)
<p>I'm trying to write a function that calculates the grand total price of each order, when given the price of the product and a credit that this user has. The credit should be deducted and if anything remains it should be deducted from the next order.</p> <p>The function should return the final price of each order and the credits that remain foreach each account in <strong>one single array</strong> with the customer IDs as keys. Any negative numbers (credit or order prices) should all be set to 0.</p> <p>'<code>abc</code>' and '<code>def</code>' are customer IDs. This sample code should explain things much better. <strong>Do I need a recursive function for this?</strong></p> <p>Input: </p> <pre><code>//should return: order 1 = 375, order 2 = 90, remaining credit = 0; $order['abc'][1] = 500; $order['abc'][2] = 90; $credit['abc'] = 125; //should return: order 1: 0, order 2: 0, remaining credit = 125 $order['def'][1] = 100; $order['def'][2] = 75; $credits['def'] = 300; </code></pre> <p>The return should be one single array, as such:</p> <pre><code>$set['abc'][1] = 375; $set['abc'][2] = 90; $set['abc']['credit_remaining'] = 0; $set['def'][1] = 0; $set['def'][2] = 0; $set['def']['credit_remaining'] = 125; </code></pre>
php
[2]
2,187,453
2,187,454
guidance for copying contents from .jrn file to .text and delete content in every 1 hour
<p>I need to develop an application to copy the contents of .jrn file as soon as it is generated in ATM.The generated file name(.jrn) will be saved on the basis of date,What i wanted is,my application should copy the content of .jrn file to one text file lets say "xy.txt" and all of these contents should be deleted in every one hour.I am planning to develop this in .NET platform.Can any one suggest me how can i do it or the steps involved in it?</p>
c#
[0]
4,603,381
4,603,382
Sending Sms through Android Emulator
<p>I have created an android application. Now i want to send sms through it to a real mobile number..Can somebody please help me with it.The information provided on the internet is to send message between two emulators. But i want to send sms on a real mobile number..Please help me out with it</p>
android
[4]
5,444,367
5,444,368
editText in android
<p>I am making an application and I have added an EditText in my layout.</p> <p>What I'm trying to achieve is that when EditText is selected should open a dialog box, with some general text and an <code>OK</code> button. Which method can I use to accomplish this?</p>
android
[4]
395,409
395,410
How to call An activity class from nonactivityclass (class without extends anything) in android?
<p>I want call an activity class from a normal java class(without extends anything) for every some time interval to refresh the Ui, Is it possible to call an activity from normal java class. We can call the activity from another activity using intent and startactivity. But am not sure about calling the activity from class.</p> <p>For example</p> <pre><code> class example extends Activity { } class example2 extends Activity { // we can call like Intent intent = new Intent(this.example2,example.class); startActivity(intent); } class test { // How can i call example or example2 from here. } </code></pre> <p>Thanks,</p> <p>Lakshmanan </p>
android
[4]
944,931
944,932
jquery code explanation
<p>I have this code and I need an explanation on what it does:</p> <pre><code>function delaymethod(settings) { settings.timeout = settings.timeout || 2000; var start = new Date(); var id = parent.setInterval(function () { if (settings.condition()) { parent.clearInterval(id); if (settings.success) { settings.success(); } } var now = new Date(); if (now - start &gt; settings.timeout) { parent.clearInterval(id); if (settings.fail) { settings.fail(); } else if (settings.success) { settings.success(); } } }, 200); } </code></pre>
javascript
[3]
3,463,674
3,463,675
Javascript Array Sum
<p>How I can sum up the values filled in unitprice array using javascript Here is my html.</p> <pre><code> &lt;td&gt; &lt;input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"&gt; &lt;/td&gt; </code></pre>
javascript
[3]
4,315,438
4,315,439
java one elment list
<p>What is the most efficient (performant) way to create a list with just one element? </p>
java
[1]
3,714,126
3,714,127
dynamically changing application's language in android
<p>Ok, so I have an app and <strong>remote service</strong> running. every 5 hours for example, the service makes a <strong>request to a server</strong>, get some xml data, parse it and then fill a database with it.</p> <p>When language tag is detected while parsing I get the URL attribute, download a language file from same server and store it in database too.</p> <p>So now I want my application language to change with that new language after it has been downloaded.</p> <p>I have a default language in assets which its been used when app is installed for the first time. but after that I need my language to be properly updated when new language is downloaded. </p> <p>I use hashmap for setting the language for my UI<br> example: </p> <pre><code>title.setText(Utils.langhashmap.get("screenCaption1"); </code></pre> <p>I can create hashmap with the new language but I need somehow to refresh my screens with the new data.</p> <p>I tried using broadcast receiver (registering it in every activity screen) and in his onReceive() updating some textviews but its not properly working on a tablet. It's got to be another way .. much better than that.</p>
android
[4]
727,833
727,834
Convert the first letter to Capital letter but ONLY for UPPERCASE strings - PHP
<p>Anyone could help me doing this?</p> <p>For example I have a string of</p> <pre><code>SOME of the STRINGS are in CAPITAL Letters </code></pre> <p>What I want exactly for the output is</p> <pre><code>Some of the Strings are in Capital Letters </code></pre> <p>Only those in UPPERCASE will be turn their first letter to capital and leave the rest as lower case.</p> <p>How can I achieve this using PHP?</p> <p>Thanks in advance.</p>
php
[2]
3,559,669
3,559,670
java : get values from table and apply formula
<p>in the bellow code, I try to calcul the formula:</p> <p>y=val1+val2+val4/all values </p> <p>val is a string get from a table.</p> <p>my aim is , for a row 0, get all values from each column "values" then calcul the formule.</p> <p>after that do the same for each row. but my code doesn't print me the expected behaviour for the first step. </p> <p>thanks,</p> <pre><code>&gt; String[] values = { x1,x2,x3,x4}; &gt; &gt; String val = null ; &gt; for (int i = 0; i &lt; values .length; i++) &gt; { &gt; val = table.getValue(0, table.getColumnValue(x[i])); &gt; &gt; } &gt; &gt; //my fomula y = value[x[0]]+value[x[1]]+value[x[3]]/values[0..3] &gt; &gt; int Num = Integer.parseInt(value[x[0]])+Integer.parseInt(value[x[1]])+Integer.parseInt(value[x[3]]); &gt; int Denum = Integer.parseInt(val ); &gt; &gt; y=Num/Denum ; </code></pre>
java
[1]
5,712,994
5,712,995
What's the most reliable way to check a javascript is null?
<p>What is the mos reliable way if I want to check if the variable is null or is not present?. </p> <p>There are diferent examples:</p> <pre><code>if (null == yourvar) if (typeof yourvar != 'undefined') if (undefined != yourvar) </code></pre>
javascript
[3]
3,858,612
3,858,613
Not allow texting android?
<p>If user select the text messaging app, it have to populate "you are not allowed to use this app" in android phone. How this can be able to achieve in android? help me plz.. thanks in advance.</p>
android
[4]
2,887,954
2,887,955
-[FGalleryViewController loadView] in FGalleryViewController.o
<p>ld: warning: ignoring file /Users/macfd1/Desktop/CoreGraphics.framework/CoreGraphics, missing required architecture i386 in file <code>/Users/macfd1/Desktop/CoreGraphics.framework/CoreGraphics (2 slices)</code></p> <p>Undefined symbols for architecture i386:</p> <pre><code> "_CGRectZero", referenced from: -[FGalleryViewController loadView] in FGalleryViewController.o -[FGalleryViewController buildViews] in FGalleryViewController.o -[FGalleryViewController buildThumbsViewPhotos] in FGalleryViewController.o -[FGalleryPhotoView initWithFrame:target:action:] in FGalleryPhotoView.o -[FGalleryViewController loadView] in FGalleryViewController.o -[FGalleryViewController buildViews] in FGalleryViewController.o -[FGalleryViewController buildThumbsViewPhotos] in FGalleryViewController.o -[FGalleryPhotoView initWithFrame:target:action:] in FGalleryPhotoView.o </code></pre> <p>ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)</p>
iphone
[8]
4,017,490
4,017,491
ProcessRequest invoked 3 times per request
<p>For some reason I'm experiencing that ProcessRequest is invoked 3 times per browser request in my HttpHandler. I'm using this to fetch documents from a database, and send them to the client. It's setup so every request to www.site.dk/documents/* is processed by this HttpHandler.</p> <p>Any help would be appreciated.</p> <p>Best regards.</p>
asp.net
[9]
273,117
273,118
Error while posting a request via soap client
<p>I have implemented arzoo Flight API in my php web site. I have used soap client to send the request. while browsing I got the following error</p> <pre><code>HERE IS A FAULT : SoapFault exception: [HTTP] Error Fetching http headers in /home/wwwkomet/public_html/demo1/dom_avail.php:71 Stack trace: #0 [internal function]: SoapClient-&gt;__doRequest('__call('getAvailability', Array) #2 {main} </code></pre> <p>This is my code</p> <pre><code>$location_URL = "http://59.162.33.102/ArzooWS/services/DOMFlightAvailability"; $action_URL ="http://com.arzoo.flight.avail"; $client = new SoapClient('http://59.162.33.102/ArzooWS/services/DOMFlightAvailability?wsdl', array( 'soap_version' =&gt; SOAP_1_1, 'location' =&gt; $location_URL, 'uri' =&gt; $action_URL, 'style' =&gt; SOAP_RPC, 'use' =&gt; SOAP_ENCODED, 'trace' =&gt; 1, )); try { $result = $client-&gt;__call('getAvailability',array($req_int)); $response= htmlentities($result); } </code></pre> <p>What is the reason to this? How to overcome this error? </p> <p>Thanks in advance </p>
php
[2]
1,022,305
1,022,306
"Assigning the return value of new by reference is deprecated" error
<p>The problem is:</p> <blockquote> <p>Deprecated: Assigning the return value of new by reference is deprecated in C:\wamp\www\FlashChat_v607\chat\inc\common.php on line 155</p> <p>Notice: Undefined variable: step in C:\wamp\www\FlashChat_v607\chat\inc\common.php on line 94</p> </blockquote> <p>This is the link where you can find the code: <a href="http://www5.zippyshare.com/v/3592861/file.html" rel="nofollow">http://www5.zippyshare.com/v/3592861/file.html</a></p>
php
[2]
5,010,572
5,010,573
How to call a controller action in external php file in our project in Yii framework?
<p>I have a ipn.php file in my project folder, and here i want to call a action of controller.</p>
php
[2]
4,073,414
4,073,415
Is it possible to write constructor assignment operator only mentioning specially -copied members?
<p>Let's say I have class with N members. Most member are copyable. Only one member needs manual copying code. </p> <p>Is there method to write copy assignment operator in such a way that I write code only for nonstandard member, and letting compiler generate copying code for all/other members ?</p>
c++
[6]
922,174
922,175
Basic Java Questions
<p>Hi guys Could you please be kind enough to answer one ore more of these questions? Thanks so much!</p> <p>Q1. Lets say I initialize an array of "Class A" objects", Can I Also put Class B objects(a subclass of Class A) in the same array. Or do I have to upcast the reference type of Object B to become a class A reference type?</p> <p>Q2.Can I redefine public methods to be private in a subclass? </p> <p>Q3.So I understand that if I want to access my superclass' private instance variables I need to use its accessor methods. This is slightly irritating because it doesn't comply with biological inheritance. Why is this the case? Why cant we just treat the private instance variables or private methods of its superclass like it were its own instance variables (what biological inheritance promises)? </p> <p>Thanks so much! Regards John.</p>
java
[1]
839,677
839,678
how do i get string like "aaa-23" from "aaa-23-34" in jquery?
<p>For example-1 : I have string like "aaa-23-34" and I want string from this is "aaa-23"</p> <p>For example-2 : <code>var str = "aaa-44-34-12"</code></p> <p>output should be <code>"aaa-44-34"</code></p> <p>That means I want string before the last hyphen.</p>
javascript
[3]
1,518,108
1,518,109
Get IP from computer name in intranet C# Windows application
<p>I'm trying to get an IP address from computer name in same network... Something like CMD command "nbtstat -a COMPNAME" in C# windows application</p>
c#
[0]
3,295,884
3,295,885
"Append if doesn't exists" in jQuery
<p>I'm trying to write a helper function for jQuery that creates an element if it doesn't already exist. So far I have:</p> <pre><code>function setup(element, parent){ if($(parent).child(element).length == 0){ $(parent).append('&lt;div class="'+element+'"&gt;&lt;/div&gt;'); } } </code></pre> <p>but I'm wondering if this isn't a solved problem. Is it?</p> <p>(The reason I want this is so I can pull in JSON content and put it in the right place. If the right place exists, I'll just update the content. If it doesn't exist, I'll create it.)</p>
jquery
[5]
2,264,304
2,264,305
Force popup window ratio on resize
<p>I know there maybe ugly hacks to achieve this, which is why I am asking this. Basically I have a video chat window, so I want to allow resizing of window, but I would like to force the ratio (so that it is maintained). I guess I can run a javascript which refreshes every X seconds and resizes the window. </p> <p>Any good ideas? I don't mind if the hacks work on certain browsers and not on others. As many as possible.</p>
javascript
[3]
3,021,926
3,021,927
Perfect square and perfect cube
<p>Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..</p>
c++
[6]
5,382,488
5,382,489
Android: backup package data w/o root
<p>I have seen apps which can backup/restore package data from another app without root-ruser permissions. My google-fu seems to be out of wack on this one. How can I do this as well?</p>
android
[4]
4,796,302
4,796,303
How to upload preview image before upload through JavaScript
<p>I want to preview an image before uploading it to the server. I have written a little bit code for it, but it is only being previewed in Internet Explorer, not in other browsers like Safari, Chrome, Firefox, due to some type of security reasons. Is there any solution to preview the image in these browsers?</p> <pre><code> &lt;body&gt; &lt;form name="Upload" enctype="multipart/form-data" method="post"&gt; Filename: &lt;INPUT type="file" id="submit"&gt; &lt;INPUT type="button" id="send" value="Upload"&gt; &lt;/form&gt; &lt;div id="div" align="center" style="height: 200px;width: 500px;border-style: ridge;border-color: red"&gt; &lt;/div&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; var img_id=0 var image = new Array() document.getElementById('send').onclick=function() { img_id++ var id="imgid"+img_id image = document.getElementById('submit').value; document.getElementById('div').innerHTML="&lt;img id='"+id+"' src='"+image+"' width=500px height=200px&gt;" } &lt;/script&gt; &lt;/html&gt; </code></pre>
javascript
[3]
3,933,255
3,933,256
JQuery mouseenter fire more than once on overlapping divs
<p>I am using JQuery mouseenter event to show a div inside another div. When the mouse enters DIV A I show a smaller DIV B inside it. The problem is that when I put my mouse over DIV B, JQuery runs the mouseenter event again. I want to show DIV B (inner one) and when the mouse goes over it, not to fire the mouseenter event again. Although technically, my mouse is still hovering DIV A. So on other words, Mouseout over DIV B causes JQuery to run mouseenter on DIV A again, that what I understand.</p> <p><img src="http://i.stack.imgur.com/diq3g.png" alt="enter image description here"></p> <p>Code:</p> <pre><code>$(document).on("mouseenter", ".si", function (e) { settingsIcon(e,1); }); $() $(document).on("mouseout", ".si", function (e) { settingsIcon(e,0); }); function settingsIcon(e, action) { if (action === 1) // show { $(".settings_icon").remove(); var id = parseInt(e.target.id.replace("dvci_", ""), 10); $("#dvc_" + id).prepend("&lt;div class='settings_icon' &gt;&lt;img class='settings_icon_image' src='settings.png' style='width:59px; height:57px' /&gt;&lt;/div&gt;"); var icon = $("#dvc_" + id + " .settings_icon"); icon.css({ "left": ($("#dvci_" + id).width() / 2) - 30, "top": parseInt($("#dvci_" + id).css("margin-top").replace("px", ""), 10) + ($("#dvci_" + id).height() / 2) - 30 }); $(".settings_icon img").show("scale", {}, 400); } else { // hide $(".settings_icon").remove(); } } </code></pre> <p><strong>jsfiddle</strong>: <a href="http://jsfiddle.net/tLUrd/" rel="nofollow">http://jsfiddle.net/tLUrd/</a></p>
jquery
[5]
5,803,363
5,803,364
Why is typeid not constant like sizeof
<p>Why is typeid(someType) not constant like sizeof(someType) ?</p> <p>This question came up because recently i tried something like:</p> <pre><code>template &lt;class T&gt; class Foo { BOOST_STATIC_ASSERT(typeid(T)==typeid(Bar) || typeid(T)==typeid(FooBar)); }; </code></pre> <p>And i am curious why the compiler knows the size of types (sizeof) at compile time, but not the type itself (typeid)</p>
c++
[6]
4,819,843
4,819,844
recursive boolean evaluation
<p>Suppose I have something like:</p> <pre><code>[(True, False, False), True] = True </code></pre> <p>or</p> <pre><code>(False, [True, True, False], False) = False </code></pre> <p>that could be infinitely deep and tuples were evaluated as ORs and lists ANDs</p> <p>How could this function be written in python?</p>
python
[7]
5,291,474
5,291,475
What does jquery $ actually return?
<p>I have read the JQuery documentation, and while much attention is devoted to what you should <em>pass</em> the function, I don't see any information on what it actually <em>returns</em>.</p> <p>In particular, does it always return an array, even if only one element is found? Does it return null when nothing is found? Where is this documented?</p> <p>I understand that jquery methods can be applied to the return value, but what if I want to just use the return value directly?</p>
jquery
[5]
4,265,778
4,265,779
How to tell what value types are initialized to by the CLR
<p>This pertains to C# &amp; the .NET Framework specifically.</p> <p>It's best practice not to initialize the following types in the .NET framework because the CLR initializes them for you:</p> <p>int, bool, etc.</p> <p>and same for setting an object to null (I believe).</p> <p>For example you do not need to do this and in fact it's a performance hit (drops in the bucket or not):</p> <pre><code>int Myvar = 0; </code></pre> <p>Just need <code>int Myvar;</code> and that's it. the CLR will initialize it to int.</p> <p>I obviously just "know" from programming that int is set to 0 by default and bool to false.</p> <p>And also setting an object to null because the CLR does it for you. But how can you tell what those primitive types are set to. I tried opening up Reflector to take a look at int32 and bool but could not figure out how they are initialized by default.</p> <p>I looked on msdn and I don't see it there either. Maybe I'm just missing it.</p>
c#
[0]
5,356,165
5,356,166
subprocess module: using the call method with tempfile objects
<p>I have created temporary named files, with the tempfile libraries NamedTemporaryFile method. I have written to them flushed the buffers, and I have not closed them (or else they might go away)</p> <p>I am trying to use the subprocess module to call some shell commands using these generated files.</p> <p>subprocess.call('cat %s' % f.name) always fails saying that the named temporary file does not exist.</p> <p>os.path.exists(f.name) always returns true. I can run the cat command on the file directly from the shell.</p> <p>Is there some reason the subprocess module will not work with temporary files?</p> <p>Is there any way to make it work?</p> <p>Thanks in advance.</p>
python
[7]
4,663,999
4,664,000
How can I make an array of arrays of custom objects in Javascript?
<p>So, I have a friendly neighborhood object constructor, like so;</p> <pre><code>function Clip(a, b) { this.track = a this.slot = b this.path = "live_set tracks " + a + " clip_slots " + b + " clip " clip = new LiveAPI(this.patcher, this.path) this.length = clip.get("length") } </code></pre> <p>What I'd like to do is </p> <ol> <li>Add an an arbitrary number of them to an array</li> <li>When the length of the array hits 8, add that array to a new "super"array and start a new array. </li> </ol> <p>In other words, the superarray should allow me to access the objects' properties and methods by, for instance, <code>clip[0][0].length - clip[0][7].length</code>, <code>clip[1][0].length - clip[1][7].length</code>, etc.</p>
javascript
[3]
5,574,368
5,574,369
Cross-thread operation not valid in C#?
<p>I am creating a background worker thread and Loading data in it and showing in UI. I know the problem is while showing the data in UI(because it is a UI thread) But i get the data from server in form of blocks . Suppose for the first time receive 10 records then i have to update the Ui and then call the next records. </p> <p>How to resolve this Issue ? Thanks.</p>
c#
[0]
932,025
932,026
(String) or .toString()?
<p>Actually, this question has no big meaning, I guess.</p> <p>The situation is: I have a method with an "Object o" parameter.</p> <p>In this method, I exactly know there is a string in "o" which is not null. There is no need to check, or do something else. I have to treat it exactly like a <code>String</code> object.</p> <p>Just curious - what is cheaper - cast it to <code>String</code>, or use <code>Object.toString()</code>? Or is it same by time-/cpu-/mem- price?</p> <p>Update: The method accepts "Object" because it's the implementation of an interface. There is no way to change the parameter type.</p> <p>And it can't be null at all. I just wanted to say that I do not need to check it for null or emptyness. In my case, there is always a nonempty string.</p>
java
[1]
5,827,034
5,827,035
What is the most elegant way to change a key of an array by preserve the order
<p>I have a big associative array with over 1 000 items and I want to rename one key but the order must be preserved.</p> <p>I don't wont to iterate over the complete array and copy it into a new.</p>
php
[2]
4,544,767
4,544,768
Meaning of 'this' inside jQuery code
<p>I am reading an excellent book about jQuery (Apress Pro jQuery) and I am a little confused about the use of 'this'. For example I am reading the following code :</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { var isResult = $('img').is(function(index) { return this.getAttribute("src") == "rose.png"; }); console.log("Result: " + isResult); }); &lt;/script&gt; </code></pre> <p>I am wondering at which object in this case 'this' refers to. Thank you.</p>
jquery
[5]
2,084,032
2,084,033
Collection was modified; enumeration operation may not execute
<p>I have this code that removes a player if the player is not alive, but I figured the problem is to do with the <code>foreach</code> loop. I've seen solutions involving making new lists, but I cannot see how I can apply it to my code. Can anyone please shed some light?</p> <pre><code>private Dictionary&lt;int, Player&gt; numPlayers = new Dictionary&lt;int, Player&gt;(); private void CheckPlayers() { foreach (Player player in numPlayers.Values) { if (!player.isAlive) { canvas.Children.Remove(player.hand); numPlayers.Remove(player.id); // breaks here } } } </code></pre>
c#
[0]
3,000,888
3,000,889
Pass Listview selection from one class to another and change button text
<p>I have a class with a <code>ListView</code>. Once the user makes a selection I want to pass that selection to the button on the previous class. This is what I have so far:</p> <pre><code>public class SetupNewCourse extends Activity { String[] tees; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setup_new_course); final Button b = (Button) findViewById(R.id.button1); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(SetupNewCourse.this, selectTee.class); startActivity(i); // following code is the hang up I know its in the wrong place selectTee buttonText = new selectTee(); buttonText.returnTeeSelection(); b.setText((CharSequence) buttonText); }; }); } } </code></pre> <p>Following is my <code>ListView</code> class</p> <pre><code>public class selectTee extends ListActivity { String[] tees_list; String selectedText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tees_list = getResources().getStringArray(R.array.tees_array); setListAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.list_view, tees_list)); final ListView teelist = getListView(); teelist.setChoiceMode(1); teelist.setTextFilterEnabled(false); teelist.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; teeAdapter, View arg1, int selectedInt, long selectedLong) { selectedText = (String) (teelist.getItemAtPosition(selectedInt)); Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show(); System.out.println(selectedText); finish(); } }); } public String returnTeeSelection() { return selectedText; } } </code></pre> <p>Any help would be appreciated.<br> Thanks in advance.</p>
android
[4]
2,321,478
2,321,479
Weather Forecast Web Service
<p>I want to understand more how to get third party web services working, after looking through tutorials I have managed to get a QuoteOfTheDay(); web service working. But I do not know where to start with this one:</p> <p><a href="http://www.restfulwebservices.net/wcf/WeatherForecastService.svc?wsdl" rel="nofollow">http://www.restfulwebservices.net/wcf/WeatherForecastService.svc?wsdl</a></p> <p>Any tips in the right direction would be great.</p> <p>Thanks.</p>
asp.net
[9]
1,495,689
1,495,690
Pseudo-classical vs. "The JavaScript way"
<p>Just finished reading Crockford's "<strong><a href="http://oreilly.com/catalog/9780596517748/">JavaScript: The Good Parts</a></strong>" and I have a question concerning his stance on the psuedo-classical vs. prototypal approaches. Actually I'm not really interested in his stance; I just want to understand his argument so I can establish a stance of my own.</p> <p>In the book, Crockford seems to infer that constructor functions and "all that jazz" shouldn't be used in JavaScript, he mentions how the 'new' keyword is badly implemented - i.e. non-Constructor functions can be called with the 'new' keyword and vice versa (potentially causing problems).</p> <p>I thought I understood where he was coming from but I guess I don't.</p> <p>When I need to create a new module I would normally start of like this:</p> <pre><code>function MyModule(something) { this.something = something || {}; } </code></pre> <p>And then I would add some methods to its prototype:</p> <pre><code>MyModule.prototype = { setSomething : function(){}, getSomething : function(){}, doSomething : function(){} } </code></pre> <p>I like this model; it means I can create a new instance whenever I need one and it has its own properties and methods:</p> <pre><code>var foo = new MyModule({option1: 'bar'}); // Foo is an object; I can do anything to it; all methods of the "class" // are available to this instance. </code></pre> <p><strong>My question is</strong>: How do I achieve the above using an approach more suited to JavaScript? In other words, if "JavaScript" were a person, what would she suggest?</p> <p>Also: What does Crockford mean when he says a particular design pattern "is more expressive" then another?</p>
javascript
[3]
1,979,502
1,979,503
First Adapter image is incorrect
<p>For some reason, my first image displays correctly, then gets overwrriten with another user's image. Any ideas:</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; ViewHolder holder; if( convertView == null ){ vi = inflater.inflate(R.layout.feed_item, null); holder=new ViewHolder(); holder.userImage = (ImageView) vi.findViewById(R.id.feed_userimage); vi.setTag(holder); } else { holder=(ViewHolder)vi.getTag(); } if(user.has("image") &amp;&amp; user.getString("image") != null &amp;&amp; !user.getString("image").equals("null")) { holder.userImage.setTag(user.getString("image")); imageLoader.DisplayImage(user.getString("image"), act, holder.userImage,USER_IMAGE_SIZE); } else { holder.userImage.setImageDrawable(null); } </code></pre>
android
[4]
3,837,515
3,837,516
Add an OnClick handler with jQuery only once - even if called again
<p>If I assign a handler to the OnClick event of an element twice, the handler will be executed twice. But I want to change this so even if I assign it twice, the handler will only execute one time.</p> <p>Nonsensical example to demonstrate issue:</p> <pre><code>$('.button').click( function(){ alert('here'); }); $('.button').click( function(){ alert('here'); }); </code></pre> <p>So I've added the handler twice. Now when I click an element with that class, I'd get two alert boxes.</p> <p>The question is, how do I restrict it so I would only get one alert box?</p>
jquery
[5]
3,656,222
3,656,223
Is there a quicker way of writing this simple jQuery command?
<p>I would prefer to use .slideToggle and 3 lines of code but not sure how to get the script to 'refresh' itself after it's slid open and return to it's orginal state when it's slid back up (it doesn't slide back up when I use 3 lines and a .slideToggle). Sorry for the bad technical explanation. </p> <pre><code>$('#showHide').hide(); $('a#slickShow').click(function() { $('#showHide').show(400); $('.archiveText2 a').replaceWith('&lt;a id="slickShow" href="#"&gt;View less Blog Entries&lt;span class="archiveLink2"&gt;{&lt;/span&gt;&lt;/a&gt;'); $('a#slickShow').click(function() { $('#showHide').hide(400); $('.archiveText2 a').replaceWith('&lt;a id="slickShow" href="#"&gt;View more Blog Entries&lt;span class="archiveLink2"&gt;}&lt;/span&gt;&lt;/a&gt;'); </code></pre> <p><strong>This is the code that eventually got it working</strong></p> <pre><code>$('#showHide').hide(); $('#slickShow').click(function(){ $('#showHide').slideToggle(400, function() { if ($('#showHide').is(':visible')){ $('.archiveText2 a').html('View less Blog Entries&lt;span class="archiveLink2"&gt;{&lt;/span&gt;'); } else{ $('.archiveText2 a').html('View more Blog Entries&lt;span class="archiveLink2"&gt;}&lt;/span&gt;'); } }); return false; }); </code></pre>
jquery
[5]
2,037,775
2,037,776
Class Assignment Problems
<p>Why is PyDev giving me this error: "Class variable undefined" when I try to implement a simple class for an inversion counting algorithm? Here's my code:</p> <pre><code>from collections import deque Class inversionCount: def __init__(self, n): self.n = n def inversionMergeSort(m, n): print m if len(m) &lt;= 1: n = 0 return (m, n) half = len(m)/2 left = m[0:half] right = m[half:] left = mergeSort(left) right = mergeSort(right) return inversionSort(left, right) def inversionSort(left, right, n): leftQueue = deque(i for i in left) rightQueue = deque(j for j in right) orderedList = [] while len(leftQueue) &gt; 0 or len(rightQueue) &gt; 0: if len(leftQueue) &gt; 0 and len(rightQueue) &gt; 0: if leftQueue[0] &lt; rightQueue[0]: orderedList.append(leftQueue[0]) leftQueue.popleft() else: orderedList.append(rightQueue[0]) if len(leftQueue) &gt; 1: self.n += len(leftQueue) rightQueue.popleft() elif len(leftQueue) &gt; 0: orderedList.append(leftQueue[0]) leftQueue.popleft() elif len(rightQueue) &gt; 0: orderedList.append(rightQueue[0]) rightQueue.popleft() return (orderedList, n) </code></pre> <p>yet PyDev is failing to recognize that inversionCount is indeed a class. Any thoughts? </p>
python
[7]
4,484,396
4,484,397
application crash after low memory warnings
<p>my iphone application crash after raising 4 warnings of low memory, instruments is showing no memory leaks but in memory allocation live Bytes goes up to 4.7mb and Over all Bytes goes upto 79.0 MB and application crash at this point</p> <p>any help will be highly appreciated </p> <pre><code>for (int i = 0; i&lt;3; i++) { UIImage *rendered_image; UIGraphicsBeginImageContextWithOptions(sub_view.bounds.size, NO, 0.0); [appdelegate.arrimages removeAllObjects]; [appdelegate.arranimations removeAllObjects]; NSString *oldgroup = [[NSString alloc] init]; NSString *currentgroup = [[NSString alloc] init]; for(int i=0; i&lt;[sub_view.data count]; i++) { oldgroup = (i&gt;0) ? [sub_view.group objectAtIndex:(i-1)] : [sub_view.group objectAtIndex:i]; currentgroup = [sub_view.group objectAtIndex:i]; /* IF DIFFERENT GROUP NAME RECEIVED 1-GET NEW INSTANCE OF IMAGE 2-SAVE PREVIOUS IN ARRAY */ if (![oldgroup isEqualToString:currentgroup]) { rendered_image = UIGraphicsGetImageFromCurrentImageContext(); [self SaveImagesOfAnimation:[self compressImageDownToPhoneScreenSize:rendered_image]]; [appdelegate.arranimations addObject:[sub_view.anim objectAtIndex:i]]; UIGraphicsEndImageContext(); UIGraphicsBeginImageContextWithOptions(sub_view.bounds.size, NO, 0.0); } id element = [sub_view.data objectAtIndex:i]; color = [sub_view.fillColor objectAtIndex:i]; [color setFill]; [element fill]; [[UIColor blackColor] setStroke]; [element stroke]; } rendered_image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self SaveImagesOfAnimation:[self compressImageDownToPhoneScreenSize:rendered_image]]; } </code></pre>
iphone
[8]
1,111,152
1,111,153
asp.net stored procedure problem
<p>Why this code don't work,when i want run this code vwd 2008 express show me this error message:Invalid object name 'answers'.</p> <p>this is my ascx.cs code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using System.Data.SqlClient; using System.Configuration; public partial class odgl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { string connectionString = @"SANATIZEDSTRING!!!!"; using (SqlConnection cn = new SqlConnection(connectionString)) { using (SqlCommand dohvati = new SqlCommand("dbo.get_answers",cn)) { dohvati.CommandType = CommandType.StoredProcedure; SqlParameter izracun = new SqlParameter("@count", SqlDbType.Int); izracun.Direction = ParameterDirection.Output; dohvati.Parameters.Add(izracun); cn.Open(); dohvati.ExecuteNonQuery(); int count = Int32.Parse(dohvati.Parameters["@count"].Value.ToString()); Response.Write(count.ToString()); cn.Close(); } } } } </code></pre> <p>and this is my stored procedure :</p> <pre><code>set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[get_answers] @ukupno int output as select @count= (SELECT COUNT(*) FROM answers) go </code></pre>
asp.net
[9]
1,388,820
1,388,821
List is a raw type. References to generic type List<E> should be parameterized
<p>bellow is my syntax </p> <pre><code>List synchronizedpubliesdList = Collections.synchronizedList(publiesdList); </code></pre> <p>I am facing syntax error as "List is a raw type. References to generic type <code>List&lt;E&gt;</code> should be parameterized". Please suggest the solution.</p>
java
[1]
523,455
523,456
Handling Dangling pointer/reference in case of operator overloading
<p>Is it safe to write our own copy constructor always during operator overloading ?</p> <pre><code>Complex Complex::operator+(const Complex&amp; other) { Complex local ; local.result_real = real + other.real; local.result_imaginary = imag + other.imag; return local ; } </code></pre> <p>Most of the times i have seen the above format , instead of returning it as reference .</p> <p>Can we take thumb rule like 1- Always pass the function parameter by reference . 2- Always return the object by reference .</p> <p>Is there any special case in operator overloading where we have to return the object by value only ?</p>
c++
[6]
3,638,803
3,638,804
validation for integer and float values in php
<p>Im checking for validation for both integer and float. preg('/^[0-9]+(.[0-9]+)?$/',$str) This works fine 12,12.05 But not for .12</p> <p>Any suggestions?</p> <p>Thanks in advance, kumar.</p>
php
[2]
1,448,821
1,448,822
If I'm making a queue with a fixed size, is array or arraylist the way to go?
<p>I'm making a top-bottom queue. Do I use array or arraylist?</p>
java
[1]
4,535,663
4,535,664
jQuery, Twitter bootstrap: How do I generate alerts(and text) on based on actions?
<p>Here is my html for alerts</p> <pre><code>&lt;div id="feature" class="feature"&gt; &lt;div id="alerts"&gt; &lt;/div&gt; # other html data &lt;/div&gt; </code></pre> <p>Here is my <code>Ajax</code> call</p> <pre><code> // send the data to the server using .ajax() or .post() $.ajax({ type: 'POST', url: 'addVideo', data: { video_title: title, playlist_name: playlist, url: id, success: notify('success', 'saved!') error: notify('failure', 'not saved!') }, </code></pre> <p>Here is how <code>notify</code> function looks</p> <pre><code>function notify(notify_type, msg) { var alerts = $('#alerts'); alerts.append('&lt;a class="close" data-dismiss="alert" href="#"&gt;×&lt;/a&gt;'); if (notify_type == 'success') { alerts.addClass('alert alerts-success').fadeIn('fast'); } if (notify_type == 'failure') { alerts.addClass('alert alerts-error').fadeIn('fast'); } } </code></pre> <p>I am using reference from here - <a href="http://twitter.github.com/bootstrap/components.html#alerts" rel="nofollow">http://twitter.github.com/bootstrap/components.html#alerts</a> When I debug on Firebug, I see <strong>No elements were found with the selector: "#alerts"</strong> Although I can see the div tag in view-source, what must be wrong?</p> <p><strong>Needed</strong> - Based on response I would like to insert appropriate alert in text automatically</p> <p>I am learning jQuery and I am sure this has error, but not able to understand where this is failing</p>
jquery
[5]
1,963,116
1,963,117
getting error when click on the Image button?
<p>in my application i have vidoes there with image when i click on any video it is showing this message.</p> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. </p> <p>i place the enbaleEven validation="true" both in webconfig in that particular page. even though it is giving same error </p>
asp.net
[9]
3,691,773
3,691,774
Java date counting
<p>I need to calculate the number of days passed between 2 dates using java.util.Date, java.util.Calendar and java.text.SimpleDateFormat. I'm breaking my brain, how could I accomplish that?</p>
java
[1]
4,203,792
4,203,793
what is the default access modifier for controls created on .aspx page. Private or something else?
<p>What is the default access modifier for controls created on .aspx page. Private or something else?</p>
asp.net
[9]
3,458,942
3,458,943
Splitting String in case of a new line
<p>I have a method in java which returns the updated lines of a flat file as a "String". I am receiving the String as a bunch of lines, what i want to do is to separate the String line by line. How can i do that in java????? </p>
java
[1]
4,314,463
4,314,464
Restart application on preference changed
<p>I need to restart the application from <code>PreferenceActivity</code> on preference changed. I tried:</p> <pre><code>@Override public void onSharedPreferenceChanged(SharedPreferences pref, String key) { System.exit(2); } </code></pre> <p>but after restart settings are not saved. Any ideas of how to restart the app with preferences are saved?<br> Thanks in advance</p>
android
[4]
4,456,707
4,456,708
C# How can I read all jpeg files in a directory using a Filestream so the files aren't locked?
<p>How can I read all jpeg files in a directory using a Filestream so the files aren't locked? My current code is below, there is no mention of Filestream as I can't get it to work. Many thanks for any help.</p> <pre><code> public Form1() { InitializeComponent(); images = new List&lt;Image&gt;(); // add images DirectoryInfo di = new DirectoryInfo(@"\\server\files\"); FileInfo[] finfos = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly); foreach (FileInfo fi in finfos) images.Add(Image.FromFile(fi.FullName)); } private void buttonNext_Click(object sender, EventArgs e) { index++; if (index &lt; 0 || index &gt;= images.Count) index = 0; pictureBox1.Image = images[index]; int count = index + 1; labelCount.Text = "Showing " + count.ToString() + " of " + images.Count; } </code></pre>
c#
[0]
3,128,352
3,128,353
Comparing Android versions from a developer's perspective
<p>Where can I find a tabular comparison of the different features available in each Android OS version that are available to the developer. </p> <p>I have an idea for an app in mind and I'd like to know what the earliest version of Android OS I can set my project against.</p>
android
[4]
3,184,461
3,184,462
Multi-column ComboBox
<p>Can somebody please recommend a good multi-column combobox control for use in a Web Form? I'm quite disappointed to not find any multi-column support on the DevExpress ASPxComboBox control, unless I'm missing something.</p>
asp.net
[9]
4,931,709
4,931,710
How Can i Make Dynamic a JtabbedPane?
<p>as i said in title i wanna do dynamic jtabbedpane .. for example ;</p> <pre><code>JTabbedPane tabbedPane = new JTabbedPane(); ImageIcon icon = createImageIcon("images/middle.gif"); JComponent panel1 = makeTextPanel("Panel #1"); tabbedPane.addTab("Tab 1", icon, panel1,"Does nothing"); </code></pre> <p>i can dynamically adding tabs to tabbedpane container.But problem is how can i design panels that i want to add tabbedpane.Its too hard to make from code behind.I can only add a label thats it :) Is there any way to Design my panel then add it Jtabbedpane from code behind ? .. </p>
java
[1]
1,011,178
1,011,179
Get Value of Div after append function
<p>All, I'm using the following code:</p> <pre><code>$(document).on('change','.found_other_vendor',function(){ if(checked){ alert("it was checked"); if($("#other_liked_vendors").val()!=""){ alert("second_one"); $.post(ajaxurl, { clicked_id: clicked_id, action: action }, function(results){ $("#other_liked_vendors").append(", " + results); }); $("#other_liked_vendors") }else{ alert("first_one"); $.post(ajaxurl, { clicked_id: clicked_id, action: action }, function(results){ $("#other_liked_vendors").html(results); }); } } } </code></pre> <p>For some reason it always says that my first if statement for:</p> <pre><code>if($("#other_liked_vendors").val()!="") </code></pre> <p>Is always coming up false even after I've put data in my div with the html. Any idea why it isn't recognize a value in my div even after I put data in it? </p> <p>Thanks!</p>
jquery
[5]
4,793,882
4,793,883
How to Develop Automation FW in C# with Visual Studio Test Pro 2010?
<p>How to Develop Automation FW in C# with Visual Studio Test Pro 2010? Need guidelines.</p> <p>Thanks, ~Amol</p>
c#
[0]
2,186,428
2,186,429
Problem comparing arrays of Strings with nested loops
<p>This is the problem I am trying to solve: I have two arrays of Strings ("matches" and "visibleObjects"). I would like to search through all the words in the array "matches" to see if there is at least one word from the array "visibleObjects". If this condition is satisfied, I'd like to search through the words in "matches" again this time looking for at least a word from the array "actionWords". This is what I have, where "testDir" is just a debug string that gets printed:</p> <pre><code>protected void Action(){ boolean actionWord = false; String target = null; testDir = "first stage"; firstLoop: for(String word : matches) { testDir += " " + word; for(String hint : visibleObjects) { testDir += " " + hint; if(word.equals(hint)) { target = word; //found a matching word testDir = "Hint found"; break firstLoop; } } } if(target != null) { testDir = "stage two"; secondLoop: for(String word : matches) { for(String action : actionWords) { if(word.equals(action)) { actionWord = true; //found one word from the actionWords array testDir = "Acion OK"; break secondLoop; } } } } if(actionWord){ testDir = target; performAction(target); } } </code></pre> <p>All I get printed is the first word from the array matches and all the words from the array visibleObject once, so it doesnt get past the second loop....</p> <p>Is this code right? Can anyone spot the bug?</p> <p>Thanks for your help!</p>
java
[1]