pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
37,322,582
0
<p>I used some deprecated event detection methods before and when I updated my code, my server did not clear the cache after flushing it 5 times.</p> <p>The code is fine, thus problem solved !</p>
39,620,324
0
<p>Add your forked Sylius repository like this in your composer.json</p> <pre><code>"repositories": [ { "type": "git", "url": "https://github.com/ylastapis/Sylius.git" }], </code></pre> <p>You can either require your master branch or create a custom branch (to merge your code pending that Sylius team accepts your merge, mine is called master-poc)</p> <p>In the require section, require YOUR branch, prefixed by "dev-". so master became dev-master, thus my branch master-poc is now dev-master-poc </p> <pre><code>"require": { "sylius/sylius": "dev-master-poc" }, </code></pre> <p>I also got a branch alias, Can't remember if it's still usefull</p> <pre><code> "extra": { "branch-alias": { "dev-master": "1.0-dev" } } </code></pre> <p>Some link to the doc: <a href="https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository" rel="nofollow">https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository</a></p>
24,642,324
0
<p>That's one of the downsides of having API's that returns <code>null</code>. The <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" rel="nofollow">Null Object</a> pattern could have been used here to simplify the API, relieving the clients from dealing with null values.</p> <p>".offset() returns an object containing the properties top and left"</p> <p>Therfore, you can do something like:</p> <pre><code>var menuOffset = menu.offset() || { top: 0, left: 0 }, menuTop = menuOffset.top + 100; $('.other').css('top', menuTop + 'px'); </code></pre>
11,747,206
0
<p>To use this code:</p> <pre><code>(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if([text isEqualToString:"\n"]) { NSString *modifiedString = [textView.text stringByAppendingString:@"\n\u2022"]; [textView setText:modifiedString]; return NO; } return YES; } </code></pre> <p>Your header file must look like this:</p> <pre><code>@interface MyViewController : UIViewController &lt;UITextViewDelegate&gt; { //instance variables in here } </code></pre>
8,716,830
0
<p>You can parse the parameters of the url with javascript easily, then check if that particular 'nofade' param exists (or any other) and fade your image if it does</p> <pre><code>$(function(){ // Grab our url parameters and split them into groups var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;'); // assign parameters to our object var params = {}; for(var i = 0; i &lt; hashes.length; i++){ var hash = hashes[i].split('='); params[hash[0]] = hash[1]; } // Now params contains your url parameters in an object if(typeof(params['nofade']) === 'undefined' || !params[nofade]){ // Perform image fade here } }) </code></pre>
30,349,049
0
<p>Use <code>int.TryParse</code> to parse the string to int. You also have some issues like sql injection and not using the <code>using</code>-statement. </p> <pre><code>private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e) { int id_furnizor; if(!int.TryParse(iD_FurnizorComboBox.Text, out id_furnizor)) { MessageBox.Show("id_furnizor is not a valid integer: " + iD_FurnizorComboBox.Text); return; } using(var connection=new OleDbConnection("Connection String")) { try { string query = @"select f.* from Furnizori f where id_furnizor = @id_furnizor;"; OleDbCommand command = new OleDbCommand(query, connection); command.Parameters.Add("@id_furnizor", OleDbType.Integer).Value = id_furnizor; connection.Open(); OleDbDataReader reader = command.ExecuteReader(); if (reader.Read()) { numeTextBox.Text = reader.GetString(reader.GetOrdinal("nume")); adresaTextBox.Text = reader.GetString(reader.GetOrdinal("adresa")); localitateTextBox.Text = reader.GetString(reader.GetOrdinal("localitate")); judetTextBox.Text = reader.GetString(reader.GetOrdinal("judet")); } } catch (Exception ex) { throw; // redundant but better than throw ex since it keeps the stacktrace } }// not necessary to close connection, done implicitly } </code></pre>
29,775,723
0
<p>I had a bit similar problem. Which was actually being raised due to the duplication of name attribute of the job listener; which should be unique.</p> <p>jobWasExecuted() method of listener gets called after the execute method of the job has finished its work. Roughly the Call hierarchy is like this</p> <ol> <li>Listener->jobToBeExecuted()</li> <li>Job->execute() </li> <li>Listener->jobWasExecuted()</li> </ol> <p>PS: Though a bit late but may be helpful to someone.:D</p>
26,189,656
0
How can I set an NSDate object to midnight? <p>I have an <code>NSDate</code> object and I want to set it to an arbitrary time (say, midnight) so that I can use the <code>timeIntervalSince1970</code> function to retrieve data consistently without worrying about the time <em>when</em> the object is created.</p> <p>I've tried using an <code>NSCalendar</code> and modifying its components by using some Objective-C methods, like this:</p> <pre class="lang-swift prettyprint-override"><code>let date: NSDate = NSDate() let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! let components: NSDateComponents = cal.components(NSCalendarUnit./* a unit of time */CalendarUnit, fromDate: date) let newDate: NSDate = cal.dateFromComponents(components) </code></pre> <p>The problem with the above method is that you can only set one unit of time (<code>/* a unit of time */</code>), so you could only have one of the following be accurate:</p> <ol> <li>Day</li> <li>Month</li> <li>Year</li> <li>Hours</li> <li>Minutes</li> <li>Seconds</li> </ol> <p>Is there a way to set hours, minutes, and seconds at the same time and retain the date (day/month/year)?</p>
6,376,252
0
<p>COALESCE() function could be your friend here.</p>
16,887,247
0
<p>The std::getline function you're using saves an input to a string (see: <a href="http://www.cplusplus.com/reference/string/string/getline/" rel="nofollow">http://www.cplusplus.com/reference/string/string/getline/</a>). If the argument you pass to the function was a string, it would get the whole line from your file, which is "0 50 100" and put it in your string.</p> <p>You could trying to save it to a string and then splitting it to three parts and converting to ints using atoi or std::stoi in C++11 (check <a href="http://stackoverflow.com/questions/7663709/convert-string-to-int-c">Convert string to int C++</a>) - this way it would be easier to handle possible errors. </p> <p>But there's an easier way to do it - assuming your numbers are split by spaces and pretty much everything is correct with them, the ">>" operator breaks on spaces. Try:</p> <pre><code>inFile &gt;&gt; inVal1; inFile &gt;&gt; inVal2; inFile &gt;&gt; inVal3; </code></pre> <p>Also, using cin.ignore() is not necessary when using the inFile buffer. Every stream has a different buffer associated with it (and cin != inFile) so you don't need to clear the cin buffer to read from your file.</p>
36,531,298
0
<p>This should work for you:</p> <pre><code>SELECT * FROM E WHERE EXISTS ( SELECT 1 FROM A JOIN B ON A.B_key = B.B_key JOIN C ON B.C_key = C.C_key JOIN D ON C.D_key = D.D_key WHERE D.E_key = E.E_key AND A.A_key = ? ) </code></pre>
18,673,345
0
<blockquote> <p>I am not sure how to tell regex "look for this in a new line, if it's there, capture the line. if it's not there, just stay on the current line.</p> </blockquote> <p>You could just match the new line as part of an expression repeated multiple times, e.g:</p> <pre><code>\d{3}(\n\d{3})* </code></pre> <p>Not sure of the specifics of exactly what you want to match but this is the best I could come up with without further info...</p>
14,557,076
0
<p>Just guessing at what you're trying to do here....</p> <pre><code>Set range1 = wbk1.Worksheets(1).Range("R3:R20") 'are range 2 and 3 on the same row? Set range2 = wbk2.worksheets(2).Range("N" &amp; .Rows.Count).End(xlup).Offset(1,0) Set range3 = wbk2.worksheets(2).Range("O" &amp; .Rows.Count).End(xlup).Offset(1,0) For Each c in g.keys For Each d in range1.Cells If c = d Then range2.Value = d range3.value = d.Offset(0,-16) 'What now? Once one match has been found, ' any later matches will write to the same cells... End If Next d Next c </code></pre>
29,308,065
0
MYSQL Query Count in time interval <p>My goal is to be able to graph the number of calls every X (5 minutes, or weekly or monthly) intervals and if there are no calls, indicate that as well. In the following example the interval is every 5 minutes. call_date and called_num are both fields in a mysql table. Call_interval and num_calls are what I am trying to extract with a MYSQL Query, and call_interval is <strong>NOT</strong> in my database table (does it need to be??). </p> <p>What should my MYSQL QUERY look like? </p> <p>Here is what I have, but I am unable to retrieve the time intervals and 0s in the result.</p> <pre><code>SELECT Count(*) AS num_calls FROM cdr WHERE DATE(call_date) = CURDATE() GROUP BY ( 12 * HOUR( call_date ) + FLOOR( MINUTE( call_date ) / 5 )) mysql table: call_date called_num 3/26/2015 8:31:27 AM 555-987-6543 3/26/2015 8:32:27 AM 555-987-6544 3/26/2015 8:34:27 AM 555-987-6545 3/26/2015 8:35:27 AM 555-987-6546 3/26/2015 8:36:27 AM 555-987-6547 3/26/2015 8:51:27 AM 555-987-6548 3/26/2015 8:55:27 AM 555-987-6549 ideal mysql result: call_interval num_calls 3/26/2015 8:30:00 AM 3 3/26/2015 8:35:00 AM 2 3/26/2015 8:40:00 AM 0 3/26/2015 8:45:00 AM 0 3/26/2015 8:50:00 AM 1 3/26/2015 8:55:00 AM 1 ..... and so on from 3/26/2015 00:00:00 AM to 3/26/2015 11:55:00 PM </code></pre> <p>Thank You.</p>
32,019,322
0
HOWTO create GoogleCredential by using Service Account JSON <p>I am using the Java SDK for <code>Android Publisher v2</code> and <code>Oauth2 v2</code>. Once I created the service account I was provided with a JSON of <code>Google Play Android Developer</code> service account with client id, email, private key etc. I have tried to look around and figure out how to create a Credential so that I use the AndoirdPublisher service to fetch info on my Android App's users subscriptions, entitlements etc and store this info on our backend servers.</p> <p>I am getting hard time trying to figure out how to go about this. None of the documentations I have seen so far help in creating <code>GoogleCredential</code> using the downloaded JSON. </p> <p>For example there is this <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">documentation</a> but it mentions only about P12 file and not the JSON. I want to avoid P12 if possible since I have multiple clients &amp; I would like to save this JSON in some sort of database &amp; then use it to create credential for each client.</p> <p>Just to clarify I am trying to create the GoogleCredential object as described here,</p> <pre><code>import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.sqladmin.SQLAdminScopes; // ... String emailAddress = "[email protected]"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(emailAddress) .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .build(); </code></pre> <p>But instead of setting the Service Account using P12 File like so <code>setServiceAccountPrivateKeyFromP12File()</code>, I want to use the JSON that carries the same info &amp; generated when I created the service account.</p>
14,396,233
0
<p>For smaller numbers (counts) you can use <code>stripchart</code> with <code>method="stack"</code> like this:</p> <pre><code>stripchart(c(rep(0.3,10),rep(0.5,70)), pch=19, method="stack", ylim=c(0,100)) </code></pre> <p>But stripchart does not work for 700 dots.</p> <hr> <p><em>Edit:</em></p> <p>The <code>dots()</code> function from the package <a href="http://cran.r-project.org/web/packages/TeachingDemos/index.html" rel="nofollow">TeachingDemos</a> is probably what you want:</p> <pre><code> require(TeachingDemos) dots(x) </code></pre>
28,436,502
0
Global data from eloquent in Laravel to be used for layout <p>I am using some variables in the layout which will load data from the eloquent. For this purpose I am using repository pattern which are injected into the controller through constructor. But obviously, I don't want to repeat this logic in every controller I make.</p> <p>What is the best approach to solve this? </p> <p>I have tried injecting the repositories into the BaseController constructor, but the baseController constructor is not getting called automatically. I need to call for parent::__construct() first which requires repositories parameters to be passed. Which I believe is not the correct way to do this.</p> <p>This is my BaseController. </p> <pre><code> class BaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ protected $repo; public function __construct(Repository $repo) { $this-&gt;repo = $repo; } protected function setupLayout() { if ( ! is_null($this-&gt;layout)) { $this-&gt;layout = View::make($this-&gt;layout); } $data = $this-&gt;repo-&gt;someMethod(); View::share('global_data',$data); } } </code></pre> <p>BaseController constructor is not called automatically to resolve the dependencies.</p> <p>What is the best approach to have global data from repositories to be used in the layout?</p>
30,324,059
0
Create a Function which returns -1 for empty matrix, 0 for scalar, 1 for vector, 2 for none of these <p>I am not allowed to use <code>isempty</code>, <code>isscalar</code>, or <code>isvector</code>.</p> <p><strong>My code is :</strong></p> <pre><code> function a = classify(x) b = sum(x(:)); c = sum(b); if c == 0 a = -1; elseif length(x) == 1 a = 0; elseif length(x) &gt; 1 a = 1; else a = 2; end </code></pre> <p>I am getting error with input :</p> <pre><code> 0 1 0 0 0 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0 0 1 0 1 0 1 0 1 0 0 1 1 1 1 0 1 0 0 0 0 1 </code></pre> <p>Output for above input is 1 </p> <p>My Auto grader is giving the following error:</p> <blockquote> <p>Feedback: Your function made an error for argument(s) <code>[0 1 0 0 0 1 1;1 0 0 1 1 0 0;1 1 0 0 1 1 1;0 1 1 1 1 1 0;0 1 0 1 0 1 0;1 0 0 1 1 1 1;0 1 0 0 0 0 1]</code> Your solution is <em>not</em> correct.</p> </blockquote>
35,407,772
0
HTML2Canvas does not display in new window <p>I have tried to display the contents of the body tag in HTML using the following code</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="jspdf.debug.js"&gt;&lt;/script&gt; &lt;script src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function demoFromHTML() { $('body').html2canvas(); var queue = html2canvas.Parse(); var canvas = html2canvas.Renderer(queue,{elements:{length:1}}); var img = canvas.toDataURL(); window.open(img); } &lt;/script&gt; &lt;/head&gt; &lt;body onload = "demoFromHTML();"&gt; &lt;div id="customers"&gt; &lt;table id="tab_customers" class="table table-striped" &gt; &lt;colgroup&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;/colgroup&gt; &lt;thead&gt; &lt;tr class='warning'&gt; &lt;th&gt;Country&lt;/th&gt; &lt;th&gt;Population&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Chinna&lt;/td&gt; &lt;td&gt;1,363,480,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;19.1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;India&lt;/td&gt; &lt;td&gt;1,241,900,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;17.4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;United States&lt;/td&gt; &lt;td&gt;317,746,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;4.44&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Indonesia&lt;/td&gt; &lt;td&gt;249,866,000&lt;/td&gt; &lt;td&gt;July 1, 2013&lt;/td&gt; &lt;td&gt;3.49&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Brazil&lt;/td&gt; &lt;td&gt;201,032,714&lt;/td&gt; &lt;td&gt;July 1, 2013&lt;/td&gt; &lt;td&gt;2.81&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I tried to add the following</p> <pre><code>&lt;script src="~/Js/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="~/Js/html2canvas.js"&gt;&lt;/script&gt; &lt;script src="~/Js/jquery.plugin.html2canvas.js"&gt;&lt;/script&gt; </code></pre> <p>I am not able to see any output . I need to export the contents of div to PDF by taking a screenshot using HTML2Canvas. Am I doing anything wrong in this code ? </p>
1,358,282
0
<p>As specified on MSDN, </p> <blockquote> <p>A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.</p> </blockquote> <p>As specified by Phil.Wheeler, this code does what you want:</p> <pre><code>List&lt;int[]&gt; name = new List&lt;int[]&gt;(){ new int[]{ 23, 21, 10 }, new int[]{ 45, 43, 50 }, new int[]{ 23, 21, 90 } }; string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(name); </code></pre> <p>Hope it will help</p>
37,994,259
0
<p>When a user makes a request using Goutte, a <code>Symfony\Component\DomCrawler</code> instance is returned. The Crawler object provides the <a href="http://symfony.com/doc/current/components/dom_crawler.html#links" rel="nofollow">Crawler::links()</a> utility method, providing all links within the given crawler object.</p> <p>The <code>Crawler::links()</code> method will return an array of links found within.</p> <pre><code>$links = $crawler-&gt;links(); foreach ($links as $link) { echo $link-&gt;getUri(); } </code></pre>
21,094,040
0
<p>This issue has been fixed in the latest version of scikit-image.</p>
19,461,888
0
<p>what command are you using to insert below? </p> <p>If you use the standard "o" keystroke while in Navigation mode, it should insert a new line immediately below whatever the cursor is on, and automatically place you into Insert mode, without inserting an extra "</p> <p>Similarly an uppercase "O" will insert a new line above whatever line the cursor is on, and place you in insert mode.</p>
32,120,721
0
<p>what I am doing right now: forget about <code>gtk.builder.connect_signals</code>.</p> <p>so after your code:</p> <pre><code>ui_builder = gtk.Builder() ui_builder.add_from_file('main.ui') self.win_main = builder.get_object('win_main') </code></pre> <p>I would have something similar to this:</p> <pre><code>list_of_handler_ids = [] import libxml2 doc = libxml2.parseFile('main.ui') ctxt = doc.xpathNewContext() signals = ctxt.xpathEval('//signal') for s in signals: handler = getattr(self, s.prop('handler')) signaller = getattr(self.win_main, s.parent.prop('id')) handler_id = signaller.connect(s.prop('name'), handler) list_of_handler_ids.append(handler_id) </code></pre> <p>which seems to sort of work after a first quick check.</p>
27,428,376
0
<p>I am 100% agree with nickL you have some formating issue in your query try to replace your search query by this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> $firstname=$_POST['firstname']; $surname=$_POST['surname']; $query = "SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'"; $q=mssql_query($sql);</code></pre> </div> </div> php is a case sensitive language your post variables name are wrong replace the code and try again, if not succeeded try echo $query and run it in query browser in sql server.</p> <p>hope this will fix the issue. </p>
35,590,776
0
Can I create and open an HTML file with VBA? <p>I have a function that generates the HTML, CSS, and JS that I want. All the code is stored in a string variable.</p> <p>How would I get VBA to create a .html file and open it in the default web browser?</p>
25,503,137
0
<p><code>btc_usd</code> and <code>btsx_btc</code> are promises, not numbers! You cannot simply multiply them - and you <a href="http://stackoverflow.com/q/14220321/1048572">can't make the asynchronous <code>getJSON</code> return a number</a>. Instead, use <a href="http://api.jquery.com/jQuery.when/" rel="nofollow"><code>jQuery.when</code></a> to wait for both values to arrive:</p> <pre><code>getValue = (url) -&gt; $.getJSON url .then (json) -&gt; json.last $(window).load -&gt; btsx_btc = getValue "http://data.bter.com/api/1/ticker/btsx_btc" btsx_btc.done (data) -&gt; $('#v_btsx_btc').html data btc_usd = getValue "http://data.bter.com/api/1/ticker/btc_usd" btc_usd.done (data) -&gt; $('#v_btc_usd').html data $.when btsx_btc, btc_usd .done (data1, data2) -&gt; $('#v_btsx_usd').html data1*data2 </code></pre>
32,066,015
0
<p>So basically you just want to remove all from the first list which appear in the second list and performance is important?</p> <p>I like <a href="http://stackoverflow.com/a/32013973/284240">Georges approach</a> most, it is the most efficient if the list is getting large. But <code>List.RemoveAll</code> is also more efficient:</p> <pre><code>dataList.RemoveAll(d =&gt; filterList.Any(x =&gt; x.ID == d.DataID)); </code></pre>
10,612,401
0
<pre><code>$('div.hide').hide(300,function() { // first hide all `.hide` $('#'+ id +'.hide').show(); // then show the element with id `#1` }); </code></pre> <p><em><strong>NOTE: DON'T USE ONLY NUMERIC ID. NOT PERMITTED. <a href="http://stackoverflow.com/questions/7987636/why-cant-i-have-a-numeric-value-as-the-id-of-an-element">READ THIS</a></em></strong></p>
39,221,893
0
PHP counting the letters in a word (HANGMAN) <p>I am trying to make a hangman game. I have a few words in an array and when one of them is picked I want to count how many letters are in that word so that it can then make that amount of spaces or dashes. Also I need an efficient way to put each letter of the word onto the screen. Each letter is to be invisible, so then when the letter is guessed it will be made visible.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hangman &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; Hangman &lt;h1&gt; &lt;?php session_start(); $maxAttempts = 6; $letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z'); ?&gt; &lt;form name="lettersubmit" method="post" action="Hangman.php" &gt; &lt;input name="letterguess" type= "text" value=""&gt; &lt;input name="submit" type="submit" value="Guess a Letter!"&gt;&lt;br&gt; &lt;p&gt; Guesses Remaining &lt;p&gt; &lt;input name="triesRemaining" type="text" value="&lt;?php print("$maxAttempts"); ?&gt;"&gt; &lt;/form&gt; &lt;?php $letterguess = $_POST["letterguess"]; if($letterguess= $word){ echo ("correct"); } if(!isset($_POST["submit"])){ $words = array ( "giants", "triangle", "particle", "birdhouse", "minimum", "flood", $word = $words[array_rand($words)]; ); } if(isset($_POST["submit"])){ $maxAttempts--; } $word = $words[array_rand($words)]; echo $words[array_rand($words)]; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
22,516,992
0
<p>To match a whole string that doesn't contain <code>101</code>:</p> <pre><code>^(?!.*101).*$ </code></pre> <p>Look-ahead are indeed an easy way to check a condition on a string through regex, but your regex will only match alphanumeric words that do not start with <code>101</code>.</p>
37,661,774
0
<p>Change your <code>baseurl: ""</code> in _config.yml to <code>baseurl: "/"</code>.</p> <p>The code in your head.html include is <code>&lt;link rel="stylesheet" href="{{ "css/main.css" | prepend: site.baseurl }}"&gt;</code></p> <p>Jekyll renders this code as <code>&lt;link rel="stylesheet" href="css/main.css"&gt;</code>. That code tries to find main.css relative to the page. </p> <p>Add the / and the code rendered will be <code>&lt;link rel="stylesheet" href="/css/main.css"&gt;</code>. This will try to find main.css relative to the site root.</p> <p>More info on relative paths - <a href="http://www.motive.co.nz/glossary/linking.php" rel="nofollow">http://www.motive.co.nz/glossary/linking.php</a></p>
21,673,866
0
<p>We managed to find a solution so I'm going to respond to myself just in case someone else has the same problem and is looking for a fix. </p> <p>We created a new page and started copying the code from the page across. We would publish the website after we added some code and tested that we could browse to the page, which we could. Eventually we had all the code in the new page and it was working fine. Problem solved! </p> <p>Out of interest we renamed the new page to the old one and tried to access the page and we got the same error again. On changing the name back it worked fine.</p> <p>TLDR version</p> <ol> <li>Create a new page with a different name, copy your code across.</li> <li>Try renaming the page.</li> </ol>
11,327,496
0
Web architecture with c++ backend in Linux best way ? <p>I have php front end that render the GUI ,<br> from there I like to use c++ engine in the backend that gets the users request with data xml structures this c++ engine is responsible to process the data and store it in the DB or files and return the response to the user<br> now , my front end is lighthttpd working great , in the back end I want to avoid to write the c/c++ daemon I like to use something that is well establish in the industry , which server shell I use to host my c++ back end code?<br> also what is the best way to establish connection between php and back end server ? sockets? Php sockets ?</p>
40,857,313
0
<p>The problem with:</p> <pre><code>BOOL r = [res isEqualToString:@"\x124Vx\xc3\xaa"]; </code></pre> <p>is with the <code>\x124</code> part. It seems you can only have hex values in the range <code>00</code> - <code>ff</code>. And note the removal of the <code>[ ]</code> around the string.</p> <p>If you don't want the <code>4</code> to be considered part of the <code>\x</code> hex number, you can do this:</p> <pre><code>BOOL r = [res isEqualToString:@"\x12""4Vx\xc3\xaa"]; </code></pre> <p>The two double-quote characters ensure the <code>\x</code> escape sequence stops where you need it to.</p> <p>To eliminate the new warning about a possible missing comma when using such a string in an <code>NSArray</code>, you will need to use the older syntax to create the array:</p> <pre><code>NSArray *answers = [NSArray arrayWithObjects: @"", @"#", @"\x12""4Vx\xc3\xaa", nil ]; </code></pre>
13,744,843
0
<p>Above solution gives NaN if any text box is empty. please try this it will give 0. </p> <p>var v1=0; var v2=0;</p> <pre><code>if(!isNaN(parseInt($('input[name=amounty]').val()))){ v1 = parseInt($('input[name=amounty]').val()); } if(!isNaN(parseInt($('input[name=quatity]').val()))){ v2 = parseInt($('input[name=quatity]').val()); } sum = v1 * v2; </code></pre>
31,610,124
0
One Button to update GridView <p>I want to update all rows of a GridView one time by clicking one button: aspx:</p> <pre><code>&lt;/asp:ObjectDataSource&gt; &lt;asp:ListBox ID="ListBoxRoles" runat="server" DataSourceID="ObjectDataSourceAllRoles" AutoPostBack="true" DataTextField="RoleName" DataValueField="RoleID" OnSelectedIndexChanged="ListBoxRoles_SelectedIndexChanged"&gt; &lt;/asp:ListBox&gt; &lt;asp:ObjectDataSource ID="ObjectDataSourceRolePermissions" runat="server" TypeName="RolePermission" SelectMethod="GetRolePermissionByRoleID" UpdateMethod="UpdateRolePermission"&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="ListBoxRoles" Name="RoleID" PropertyName="SelectedValue" Type="String" /&gt; &lt;/SelectParameters&gt; &lt;UpdateParameters&gt; &lt;asp:ControlParameter ControlID="ListBoxRoles" Name="RoleID" PropertyName="SelectedValue" Type="String" /&gt; &lt;/UpdateParameters&gt; &lt;/asp:ObjectDataSource&gt; &lt;asp:GridView ID="GridViewRolePermission" SkinID="GridViewSecurity" runat="server" style="width: 100%;" HeaderStyle-Height="50" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="ObjectDataSourceRolePermissions"&gt; &lt;Columns&gt; &lt;asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="PermissionName" SortExpression="PermissionName" /&gt; &lt;asp:TemplateField ItemStyle-HorizontalAlign="Center"&gt; &lt;ItemTemplate&gt; &lt;asp:CheckBox ID="CheckBoxRead" runat="server" Checked='&lt;%#Bind("Read") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField ItemStyle-HorizontalAlign="Center"&gt; &lt;ItemTemplate&gt; &lt;asp:CheckBox ID="CheckBoxUpdate" runat="server" Checked='&lt;%#Bind("Update") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/asp:GridView&gt; &lt;asp:Button runat="server" ID="ButtonUpdateRolePermissions" Text="Save" OnClick="ButtonUpdateRolePermissions_Click" /&gt; </code></pre> <p>I want to update all rows of the gridview once the ButtonUpdateRolePermissions clicked. I tried:</p> <pre><code> protected void ButtonupdateRolePermissions_Click(object sender, EventArgs e) { foreach(GridViewRow RolePermission in this.GridViewRolePermission.Rows) { this.ObjectDataSourceRolePermissions.Update(); } } </code></pre> <p>but the update method not take Update and Read fields into consideration.</p>
6,728,529
0
<p><a href="https://github.com/TurnWheel/jReject" rel="nofollow">jQuery Browser Rejection Plugin</a> can help you. it supports following browsers disable/enable options:</p> <pre><code> msie: false,msie5: true,msie6: true,msie7: false,msie8: false, // MSIE Flags (Global, 5-8) firefox: false,firefox1: false,firefox2: false,firefox3: false, // Firefox Flags (Global, 1-3) konqueror: false,konqueror1: false,konqueror2: false,konqueror3: false, // Konqueror Flags (Global, 1-3) chrome: false,chrome1: false,chrome2: false,chrome3: false,chrome4: false, // Chrome Flags (Global, 1-4) safari: false,safari2: false,safari3: false,safari4: false, // Safari Flags (Global, 1-4) opera: false,opera7: false,opera8: false,opera9: false,opera10: false, // Opera Flags (Global, 7-10) gecko: false,webkit: false,trident: false,khtml: false,presto: false, // Rendering Engines (Gecko, Webkit, Trident, KHTML, Presto) win: false,mac: false,linux : false,solaris : false,iphone: false, // Operating Systems (Win, Mac, Linux, Solaris, iPhone) unknown: false // Unknown covers everything else </code></pre>
19,712,488
0
<p>If you could make your <code>IFoo&lt;&gt;</code> interface <strong><em>covariant</em></strong> it would work, that is if you were allowed to change the declaration of it into:</p> <pre><code>public interface IFoo&lt;out T&gt; </code></pre> <p>(note the <code>out</code>). Because with covariance any <code>IFoo&lt;string&gt;</code> would also be an <code>IFoo&lt;object&gt;</code> because <code>string</code> is a reference type and derives from <code>object</code>.</p> <p><em><strong>But:</em></strong> A member of <code>IFoo&lt;&gt;</code>, the <code>Handle</code> method, uses the type parameter in a contravariant manner. So your interface cannot be declared covariant (<code>out</code>). (It could be declared contravariant (<code>in</code>) but that goes in the wrong direction for your example above.)</p> <p>Read up on covariance and contravariance in generics.</p> <p>The fundamental problem here is that your <code>StringFoo</code> handles only strings. Therefore it can never be used as an <code>IFoo&lt;object&gt;</code> because then you could pass for example a <code>Giraffe</code> instance (<code>Giraffe</code> derives from <code>object</code>, so a <code>Giraffe</code> is an <code>object</code>) into the <code>StringFoo</code>, and that is impossible when its <code>Handle</code> takes a <code>string</code>.</p>
6,625,413
0
<p>Use the attributes:</p> <pre><code>android:paddingTop android:paddingBottom android:paddingLeft android:paddingRight </code></pre> <p>This controls the amount of 'empty' space between the border of the button and the text.</p>
37,487,928
0
<p>Lots of ways to go about this! This is another Vanilla Javascript one, fill free to mix and match according to your actual specs.</p> <pre><code>var fruits = [{ fruit: "apple", selected: false }, { fruit: "pear", selected: false }, { fruit: "orange", selected: false }, { fruit: "pineaple", selected: false }, { fruit: "mango", selected: true }, { fruit: "peach", selected: false }, { fruit: "strawberry", selected: false }]; var selectedFruits = fruits.reduce((result, el) =&gt; { if(el.selected) { return Array(el).concat(result).slice(0, 3); } if (result.length &gt; 2) return result; result.push(el); return result; }, Array()); console.log(selectedFruits); </code></pre>
29,935,830
0
How do I destructuring-match syntax::ptr::P? <p>I have a function which tries to match an <code>syntax::ast::ExprBinary(syntax::ast::BinOp, syntax::ptr::P&lt;ast::Expr&gt;, syntax::ptr::P&lt;syntax::ast::Expr&gt;)</code>, but I cannot find the right syntax to match the <code>P</code> so I get the contained expression out of it. I see that I can use <code>Deref</code> to get at the <code>Expr</code>, but this is cumbersome.</p> <p>Is there a way to get rid of the <code>P</code> within the <code>match</code> (or <code>if let</code>) clause?</p>
32,910,458
1
Selecting only updated record in delta <p>Trying to compare 2 tables in the same db. Table 1 is the main historical table, table 2 is the temporary table with new data rcvd from server and used to update table 1. </p> <p>Need to output the items in table 1 that have a change in one of the fields on table 2. </p> <p>i.e. table 1(Services)</p> <pre> Service - folder- s2 - Real - s4 astatus - on - on - on - on </pre> <p>table 2(Services2)</p> <pre> Service - folder - s2 - Real - s4 astatus - on - on - off - on </pre> <p>So I need the output to indicate that Real in astatus table 1 is off (again table 2 is just the reference temp table with new data to update table 1) I have all the updates and remaining code done. But i'm stuck on this comparison part...</p> <p>my code is as follows:</p> <pre><code>cursor.execute("""Select inner.compare FROM (Select a.Real = aReal, b.Real = bReal FROM Services a JOIN Services2 b ON (lower(a.Service || a.Folder) = lower(b.Service || b.Folder)))inner.compare WHERE inner.astat != inner.bstat""") print inner.compare </code></pre>
8,702,630
0
<p>You would access the superglobal <a href="http://php.net/manual/reserved.variables.server.php" rel="nofollow"><code>$_SERVER</code></a> and its key <code>HTTP_HOST</code>:</p> <pre><code>echo 'Hello, and welcome to ' , $_SERVER['HTTP_HOST']; </code></pre>
28,118,598
0
How to change this jquery fiddle to have the first div open/active by default? <p>I found this fiddle (<a href="http://jsfiddle.net/m6aRW/109/" rel="nofollow">http://jsfiddle.net/m6aRW/109/</a>) that does exactly what I need it to do for me. However, how can I alter it so that #div1 is open on page load? Just using display:block keeps that div open even if you click the others.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(function ($) { $('.showSingle').click(function () { var itemid = '#div' + $(this).attr('target'); //id of the element to show/hide. //Show the element if nothing is shown. if ($('.active').length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); //Hide the element if it is shown. } else if (itemid == "#" + $('.active').attr('id')) { $('.active').slideUp(); $(itemid).removeClass('active'); //Otherwise, switch out the current element for the next one sequentially. } else { $('.active').slideUp(function () { $(this).removeClass('active'); if ($(".targetDiv:animated").length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); } }); } }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.targetDiv { display: none }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;a class="showSingle" target="1"&gt;Div 1&lt;/a&gt; &lt;a class="showSingle" target="2"&gt;Div 2&lt;/a&gt; &lt;a class="showSingle" target="3"&gt;Div 3&lt;/a&gt; &lt;a class="showSingle" target="4"&gt;Div 4&lt;/a&gt; &lt;div id="div1" class="targetDiv"&gt;Lorum Ipsum1&lt;/div&gt; &lt;div id="div2" class="targetDiv"&gt;Lorum Ipsum2&lt;/div&gt; &lt;div id="div3" class="targetDiv"&gt;Lorum Ipsum3&lt;/div&gt; &lt;div id="div4" class="targetDiv"&gt;Lorum Ipsum4&lt;/div&gt;</code></pre> </div> </div> </p>
26,824,566
0
how to prevent user response during delay before the AI response <p>I am having trouble with being able to keep activating buttons before my AI response in a Tic Tac Toe game. As you can see I added a delay response, but I am still able to do another turn even before my AI responds. Anyone knows how to disable the first player turn until the AI has made its turn?</p> <pre><code>@IBOutlet var userMessage: UILabel! struct Sender{ var tag = 1 } var plays = Dictionary&lt;Int,Int&gt;() var done = false var aiDeciding = false var sender: Sender = Sender() @IBAction func UIButtonClicked(sender:UIButton) { userMessage.hidden = true if plays[sender.tag] == nil &amp;&amp; !aiDeciding &amp;&amp; !done { setImageForSpot(sender.tag, player: 1) } checkForWin() func delay(delay:Double, closure:()-&gt;()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } delay(0.4) { self.aiTurn() } } </code></pre>
23,087,362
0
<p>The two <code>loaddata</code> are the same thing, but <code>syncdb</code> is a command that creates database tables loads the initial data for that app.</p> <p>You would use <code>loaddata</code> to load a fixture into a database and <code>syncdb</code> to set up your database for a new app.</p> <p><code>manage.py</code> is a wrapper around <code>django-admin.py</code> that adds your project to the path and sets up the DJANGO_SETTINGS_MODULE environment variable. Normally, you'll use <code>manage.py</code> once your project has been set up.</p>
28,810,175
0
<p>The values are posted to the controller, bot the problem is with controller parameter binding, because the names from the parameter and the drop down list is different. If you change the name of the controller parameter list from "SelectedIds" to drop down list name "FuncionarioId" it should work. So change this:</p> <pre><code>[HttpPost] public ActionResult EscolherFuncionarios(List&lt;int&gt; SelectedIds) { return View(); } </code></pre> <p>to this:</p> <pre><code> [HttpPost] public ActionResult Test(List&lt;int&gt; FuncionarioId) { return View(); } </code></pre>
18,856,303
0
TeamCity url to view report tab of latest build <p>Here is the url to a custom report tab of a specific build:</p> <p><code>http://teamcity/viewLog.html?buildId=1738&amp;buildTypeId=bt16&amp;tab=report_TODO_items</code></p> <p>What I cannot figure out is how to change that URL to always point to the latest build (finished or successful).</p> <p>There is help on how get artifact data here: <a href="http://confluence.jetbrains.com/display/TCD7/Patterns+For+Accessing+Build+Artifacts" rel="nofollow">http://confluence.jetbrains.com/display/TCD7/Patterns+For+Accessing+Build+Artifacts</a></p> <p>But <code>http://teamcity/bt16/.lastSuccessful/viewLog.html&amp;tab=report_TODO_items</code> doesn't work</p>
12,970,823
0
<p>Try to execute this first ,and check whether anyone from <code>other session</code> or <code>your session</code> put a lock on that table .If <code>you</code> have put a lock on that table,try to do <code>commit/rollback</code> .If <code>someone else</code> put a lock ,ask <code>him/her</code> or if you have rights <code>kill his session</code> .And then drop the table.</p> <pre><code> select session_id "sid",SERIAL# "Serial", substr(object_name,1,20) "Object", substr(os_user_name,1,10) "Terminal", substr(oracle_username,1,10) "Locker", nvl(lockwait,'active') "Wait", decode(locked_mode, 2, 'row share', 3, 'row exclusive', 4, 'share', 5, 'share row exclusive', 6, 'exclusive', 'unknown') "Lockmode", OBJECT_TYPE "Type" FROM SYS.V_$LOCKED_OBJECT A, SYS.ALL_OBJECTS B, SYS.V_$SESSION c WHERE A.OBJECT_ID = B.OBJECT_ID AND C.SID = A.SESSION_ID ORDER BY 1 ASC, 5 Desc </code></pre>
21,469,296
0
<pre><code>{foreach item="item" from=$root.page.news.item } {foreach from=$item.Tags item=tagitem key=kex} {if !$done.$tagitem} {$done.$tagitem = 1} {$tagitem} {/if} {/foreach} {/foreach} </code></pre> <p>I am not sure it works with all the versions.</p> <p>Maybe it would be a bit cleaner to call an <code>array_unique()</code> in the php.</p>
2,651,880
0
<p>Try changing &lt;%= to &lt;%# within your jQuery script. Check out <a href="http://leedumond.com/blog/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks/" rel="nofollow noreferrer">this article</a></p>
30,544,445
1
Scrapy pipeline html parsing <p>I have a spider with 3 items: url, title and category. </p> <p>They are loading fine in raw html but now I would like to convert title and category into plain text using html2test in a pipeline..</p> <p>Here is my incorrect pipeline code, could someone help debugging it.</p> <p>Thank you</p> <pre><code>import html2text import csv from tutorial import settings def write_to_csv(item): writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n') writer.writerow([item[key] for key in item.keys()]) class TutorialPipeline(object): def process_item(self, item, spider): h = html2text.HTML2Text() h.ignore_images = True h.handle(item['title']).strip() h.handle(item['category']).strip() write_to_csv(item) return item </code></pre> <p>Spider code</p> <pre><code>import scrapy from scrapy.http import Request from scrapy.contrib.spiders import CrawlSpider,Rule from scrapy.contrib.linkextractors import LinkExtractor from tutorial.items import TutorialItem class tuto(CrawlSpider): name = "tuto" allowed_domains = ['emedicine.medscape.com'] start_urls=["http://emedicine.medscape.com"] rules=( Rule( LinkExtractor(restrict_xpaths ='//div[@id="browsespecialties"]'),callback='follow_pages', follow=True), ) def follow_pages(self, response): for sel in response.xpath('//div[@class="maincolbox"]//a/@href').extract(): yield Request("http://emedicine.medscape.com/" + sel, callback = self.parse_item) def parse_item(self, response): item = TutorialItem() item['url'] = response.url item['background'] = response.xpath('//div[@class="refsection_content"]').extract() item['title'] = response.xpath('//h1').extract() yield item </code></pre>
7,515,672
0
Modal blocking dialog in Javascript <p>I'm developing Openlayers toolbar in Javascript with jQuery and jQuery UI.</p> <p>One feature that I want to implement is Adding points to the map.</p> <p>In openLayers you have to listen for event called 'sketchcomplete'.</p> <pre><code>layer.events.on({ 'sketchcomplete': onPointAdded }); </code></pre> <p>The problem is in onPointAdded callback. This callback should return true or false. True mean that the point should be added to the map and false means cancel adding this point to the map.</p> <p>Now the callback looks like this:</p> <pre><code>onPointAdded = function(feature) { var f = feature.feature; var result = false; $('#dialog-point-add').dialog({ modal : true, buttons : { 'Add point' : function() { result = true; $(this).dialog("close"); }, 'Cancel' : function() { result = false; $(this).dialog("close"); } } }); return result; }; </code></pre> <p>The problem is that this dialog doesn't block the executing code. I'm asking You How to handle this situation? I want to show dialog to the user with confirmation for adding the point.</p>
12,289,338
0
<p>First - you should be able to just use <a href="http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx" rel="nofollow"><code>File.ReadAllLines</code></a> instead of reading the text and splitting....</p> <p>You may need to trim the results. If there is extra whitespace on the lines, the condition may fail. Try using:</p> <pre><code>if (check[0].Trim() == "1") { </code></pre> <p>This will trim off any whitespace, which should cause your conditional to succeed.</p> <p>You can also put a breakpoint in, and inspect the values in the debugger. This will help you better diagnose the issue.</p>
7,732,753
0
<p>Make a shared assembly (.dll) We use that for our products and its working very well. We have like 4-5 WPF based shared assemblies. In Visual Studio we just used the "WPF Custom Control Library" instead of an App.xaml you have a Themes/Generic.xaml which will be loaded automatically if you add the reference to your main executable.</p>
21,121,561
0
<p>Here's a fairly simple algorithm to overlap two strings:</p> <pre><code>#include &lt;string&gt; std::string overlap(std::string first, std::string const &amp; second) { std::size_t pos = 0; for (std::size_t i = 1; i &lt; first.size(); ++i) { if (first.compare(first.size() - i, i, second, 0, i) == 0) { pos = i; } } first.append(second, pos, second.npos); return first; } </code></pre> <p>Usage:</p> <pre><code>std::string result = overlap("abcde", "defgh"); </code></pre> <p>And to overlap a whole range, use <code>std::accumulate</code>:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int main() { std::vector&lt;std::string&gt; strings = {"abc", "def", "fegh", "ghq"}; std::cout &lt;&lt; std::accumulate(strings.begin(), strings.end(), std::string(), overlap) &lt;&lt; std::endl; } </code></pre>
22,734,771
0
<p>It's because you set the <code>display:block</code> for your <code>a</code>, so the border will be around the box (which has <code>height</code> set to <code>46px</code>). Looks like you explicitly set <code>padding-bottom</code> to <code>0</code> and then it still should work (the bottom border should be close to the link text?) but not really, because you also set the <code>line-height</code> to be equal to the <code>height</code> (both are <code>46px</code>), so the text is centered vertically and give a space between the baseline and the border-bottom. </p> <p>To solve this problem, simply remove the line <code>display: block;</code> in your css for the <code>a</code> tag. You don't need that at all, removing will solve your problem:</p> <pre><code>#menu ul li a { text-decoration:none; color:#ccc; margin-right:5px; height:46px; line-height:46px; padding:0 5px 0 5px; font-size:20px; } </code></pre>
28,022,789
0
<p>So far by looking at the source of of pysqlite, I can say that it is not possible to share connection or cursor objects (see <code>pysqlite_check_thread</code> function usage) only. </p> <p><code>pysqlite_check_thread</code> function raises <code>ProgrammingError</code> exception with that message </p> <pre><code>SQLite objects created in a thread can only be used in that same thread. </code></pre> <p>Some function in your source code catches that exception and prints it.</p> <p>In order to find places in your source code that call connection methods in other threads, I would suggest to write call wrapper over connection object something like this:</p> <pre><code># script name: sqllitethread.py import inspect import sqlite3 import threading import thread from sqlite3 import ProgrammingError class CallWrapper(object): def __init__(self, obj): self.obj = obj self.main_thread_id = thread.get_ident() def __getattr__(self, name): if self.main_thread_id != thread.get_ident(): print "Thread %s requested `%s` attribute from %s" % (thread.get_ident(), name, self.obj) for frame in inspect.getouterframes(inspect.currentframe())[1:]: if frame[1].endswith('threading.py'): continue print "\t", "%s:%s" % (frame[1], frame[2]), frame[3], frame[4][0].strip() return getattr(self.obj, name) conn = CallWrapper(sqlite3.connect('example.db')) c = conn.cursor() def worker(): try: conn.execute('.tables') except ProgrammingError, e: print e t = threading.Thread(target=worker) t.start() t.join() </code></pre> <p>Output example:</p> <pre><code>Thread 140390877370112 requested `execute` attribute from &lt;sqlite3.Connection object at 0x7faf4e659858&gt; sqllitethread.py:30 worker conn.execute('.tables') SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140390912665408 and this is thread id 140390877370112 </code></pre>
4,486,858
0
<p>For simple enumeration, simply using fast enumeration (i.e. a <code>for…in…</code> loop) is the more idiomatic option. The block method might be marginally faster, but that doesn't matter much in most cases — few programs are CPU-bound, and even then it's rare that the loop itself rather than the computation inside will be a bottleneck.</p> <p>A simple loop also reads more clearly. Here's the boilerplate of the two versions:</p> <pre><code>for (id x in y){ } [y enumerateObjectsUsingBlock:^(id x, NSUInteger index, BOOL *stop){ }]; </code></pre> <p>Even if you add a variable to track the index, the simple loop is easier to read.</p> <p>So when you should use <code>enumerateObjectsUsingBlock:</code>? When you're storing a block to execute later or in multiple places. It's good for when you're actually using a block as a first-class function rather than an overwrought replacement for a loop body.</p>
6,055,087
0
Query expression to dot notation <p>hei, need some help to convert this linq query to dot notation:</p> <pre><code> var productions = from row in data group row by row.PRODUCTION_NAME into gr select new { Group = gr.Key, Jobs = from row in gr orderby row.SortFieldCard group row by row.JOB_NAME into job select new { job.Key, Cards = job } }; </code></pre>
4,201,502
0
<p>Here is a clearer view of why a clear is needed. <a href="http://www.quirksmode.org/css/clearing.html" rel="nofollow">http://www.quirksmode.org/css/clearing.html</a></p>
11,745,880
0
Accessing objects parent property in django profiles <p>I am using django profiles with having different types of profiles. </p> <p>My Profile Model of Company is similar to:</p> <pre><code>from django.db import models from django.contrib.auth.models import User from accounts.models import UserProfile from jobs.models import City from proj import settings from django.core.mail import send_mail class Company(UserProfile): name=models.CharField(max_length=50) short_description=models.CharField(max_length=255) tags=models.CharField(max_length=50) profile_url=models.URLField() company_established=models.DateField(null=True,blank=True) contact_person=models.CharField(max_length=100) phone=models.CharField(max_length=50) address=models.CharField(max_length=200) city=models.ForeignKey(City,default=True) def send_activation_email(self): self.set_activation_key(self.username) email_subject = 'Your '+settings.SITE_NAME+' account confirmation' email_body = """Hello, %s, and thanks for signing up for an example.com account!\n\nTo activate your account, click this link within 48 hours:\n\nhttp://"""+settings.SITE_URL+"/accounts/activate/%s""" % (self.username,self.activation_key) send_mail(email_subject, email_body, '[email protected]', [self.email]) </code></pre> <p>Here I am inheriting Company from UserProfile and in send activation email, I am trying to use properties and methods of parent classes user and userprofile. Its direct parent is userprofile while user has onetoone relation with userprofile. So I tried to call <code>self.activation_key</code> that is defined in userpofile and called self.username that is property of user class/table and getting error on self.username . </p> <p>So seems like I am calling self.username in wrong way,so how can I access self.username ? Any detail will be helpful and appreciated.</p>
23,904,128
0
<p>Follow the below link, I think it will help you to find the solution:</p> <p><a href="http://www.codeproject.com/Articles/631683/Standalone-NET-Framework-exe" rel="nofollow">http://www.codeproject.com/Articles/631683/Standalone-NET-Framework-exe</a></p> <p><a href="http://stackoverflow.com/questions/191251/how-to-install-wpf-application-to-a-pc-without-framework-3-5">How to install WPF application to a PC without Framework 3.5</a></p> <p><a href="http://stackoverflow.com/questions/3528126/installing-wpf-application-on-machine-without-net-framework-4">Installing WPF application on machine without .NET Framework 4</a></p>
12,399,958
0
<p>You are right, there's a limit (and a lot of work arounds techniques) in every processor architecture, but you will run into a lot of messy problems before you run out of numbers. Performance issues related to great amounts of data is a problem that you are likely to have.</p>
29,349,710
0
Can HTML <script defer> execute before <script async>? <p>I'm asking a question on a subject that has been well explored and there are many near-answers to what I am asking, but I haven't been able to find the exact answer to what is a simple question.</p> <p>I understand that defer scripts run in the order they appear on the page, but only after the DOM has been built, and I get that async scripts run as soon as is possible, and I know that neither one blocks the HTML parser.</p> <p>Here's the question: Is there a case in which a defer script can execute before all the async scripts have executed? Essentially, if the HTML parser has parsed the entire document and is ready to run the defer scripts BUT there are still some async scripts that have not loaded yet, will it wait for these async scripts to load (and execute), or will it run the defer scripts?</p> <p>Thanks!</p>
8,773,632
0
Calling javascript function to get offset of an element <p>I have a draggable div of which when you drop it, it gives you its left and top value and if it contains a specific class.</p> <p>Example:</p> <pre><code>$( "div" ).draggable({ cursor:'move', stop: function() { if ($(this).hasClass('cool')) { var state = "Class cool exists" } var b = $(this); var bl = b.offset().left; var bt = b.offset().top; console.log(" Left:" + bl + " Top:" + bt + " Class:" + state); }}); </code></pre> <p>and Fiddle: <a href="http://jsfiddle.net/sq4XZ/" rel="nofollow">http://jsfiddle.net/sq4XZ/</a></p> <p>Now this works just find but I want to call all those methods in a <strong>seperate function</strong> because in my actual script I have to call that function many times with button clicks, hovers and basically not just with you drop the div.</p> <p>So what i did was this:</p> <pre><code>function cool(){ if ($(this).hasClass('cool')) { var state = "Class cool exists" } var b = $(this); var bl = b.offset().left; var bt = b.offset().top; console.log(" Left:" + bl + " Top:" + bt + " Class:" + state); } $( "div" ).draggable({ cursor:'move', stop: function() { cool(); }}); </code></pre> <p>so that every time I need to get those values I would call cool() function. </p> <p>jsFiddle: <a href="http://jsfiddle.net/5bQ4d/" rel="nofollow">http://jsfiddle.net/5bQ4d/</a></p> <p>Now if you are a javascript guru you would should know by now that this shouldn't work because of $(this). If I replace $(this) with $('div') works just fine. But when I call cool() it doesn't know which $(this) is.</p> <p>In my actual page I have many of those divs so when I call cool() I have to pass the div id/name/class of which I am talking about. <strong>So, how can I pass the div name/id/class to the cool() function so that it knows that $(this) means the div I clicked/hovered/dropped from?</strong></p> <p>Thanks</p>
34,544,749
0
<p>For people who need this in <em>Swift</em></p> <pre><code>func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // to limit network activity, reload half a second after last key press. NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "reload", object: nil) self.performSelector("reload", withObject: nil, afterDelay: 0.5) } </code></pre> <p>EDIT: <strong>SWIFT 3</strong> Version</p> <pre><code>func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // to limit network activity, reload half a second after last key press. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.reload), object: nil) self.perform(#selector(self.reload), with: nil, afterDelay: 0.5) } func reload() { print("Doing things") } </code></pre>
33,790,526
0
How to place 3 d3.js charts in a row <p>I want to place 3 d3 charts in a row I tried doing it using bootstrap fro html but it does not help id there a better way to do this</p> <p>My current code</p> <pre><code>&lt;div class="row"&gt; &lt;div class="span4" id="chart_1"&gt;23&lt;/div&gt; &lt;div class="span4" id="chart_2"&gt;45&lt;/div&gt; &lt;div class="span4" id="chart_3"&gt;34&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Fiddle: <a href="https://jsfiddle.net/r2qepmk0/3/" rel="nofollow">https://jsfiddle.net/r2qepmk0/3/</a></p> <p>If I change bootstrap class to col-xs-4 which otherwise place divs in row but somehow the charts do not render. </p> <p>js fiddle with the col-xs-4 class <a href="https://jsfiddle.net/r2qepmk0/4/" rel="nofollow">https://jsfiddle.net/r2qepmk0/4/</a></p>
22,399,792
0
<p>The things that could have gone wrong are:</p> <ol> <li>The website is not responding</li> <li>The JSON is invalid</li> <li>There is some error in your code</li> </ol> <p>This code should tell your what is happening:</p> <pre><code>error_reporting(-1); // Turn on error reporting $url = "http://natomilcorp.com/api/get-users"; $jsonString = file_get_contents($url); if ( ! $jsonString) { die('Could not get data from: '.$url); } $obj = json_decode($jsonString); if ( ! $obj) { // See the following URL to figure out what the error is // Be sure to look at the comments, as there is a compatibility // function there // http://php.net/manual/en/function.json-last-error-msg.php die('Something is wrong with the JSON'); } echo $obj-&gt;"username"; </code></pre>
26,721,710
0
<p>On Windows you can use the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx" rel="nofollow">FindFirstFile</a> / <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx" rel="nofollow">FindNextFile</a> APIs to search for files in a path. There is no standard way to enumerate files in Visual C++ (or in C++ in general for that matter). But since your'e using Visual C++, there's a good chance you're programming for Windows so it makes sense to look at the Windows Platform API for a solution to your problem.</p> <pre><code> WIN32_FIND_DATA findFileData; HANDLE hFind; // find all files that start with a_ in a specific directory hFind = FindFirstFile("C:\\PATH\\TO\\DIRECTORY\\a_*", &amp;findFileData); if (hFind != INVALID_HANDLE_VALUE) { while(hFind != INVALID_HANDLE_VALUE) { if (findFileData.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) { /* current entry is a directory */ } else { /* file name is findFileData.cFileName */ } hFind = FindNextFile(hFind, &amp;findFileData); } FindClose(hFind); } </code></pre> <p>The example above is a simple way of enumerating through all files (and subdirectories) in a given path, that start with <code>a_</code>. If you need to look in sub-directories as well, then you should extend the method to recursively process each subdirectory, and change it so it will examine all files, and test for file name match on each file.</p>
11,080,746
0
Get an UIImage from URL to iPhone and iPhone retina <p>I'm trying to get an image from a URL to view it on an iPhone and an iPhone Retina. The problem is that iPhone is displayed correctly but Retina is blurred. The image has a size of 100x100 at 326dpi (size retina). </p> <p>I'm doing it correctly? </p> <pre><code> - (void)viewDidLoad { [super viewDidLoad]; double scaleFactor = [UIScreen mainScreen].scale; NSURL *imageURL = [NSURL URLWithString:@"http://s419999211.mialojamiento.es/img/bola.png"]; if (scaleFactor == 2){ // @2x NSLog(@"Estoy cargando la imágen retina"); NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; image = [UIImage imageWithData:imageData]; NSLog(@"Width: %f Height: %f",image.size.width,image.size.height); yourImageView = [[UIImageView alloc] initWithImage:image]; } else { // @1x NSLog(@"Estoy cargando la imágen normal"); NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; image = [UIImage imageWithData:imageData]; imagenScalada = [UIImage imageWithCGImage:[image CGImage] scale:1.0 orientation:UIImageOrientationUp]; NSLog(@"Width: %f Height: %f",imagenScalada.size.width,imagenScalada.size.height); yourImageView = [[UIImageView alloc] initWithImage:imagenScalada]; } [self.view addSubview:yourImageView]; } </code></pre> <p><img src="https://i.stack.imgur.com/fKDkr.png" alt="Image for normal screen"> <img src="https://i.stack.imgur.com/53vRL.png" alt="Imagen blurred"></p> <p>Thank you!</p> <p>iPhone Normal iPhone Retina</p>
26,132,204
0
<p>Back to my initial file, I managed to do some progress. Please find my file here: <a href="http://cjoint.com/14oc/DJbb2yqJ5XQ.htm" rel="nofollow">http://cjoint.com/14oc/DJbb2yqJ5XQ.htm</a></p> <p>I managed to be able to apply the PivotItem.Visible property on "(blank)" by adding this to the code:</p> <pre><code>mytable.ManualUpdate = True Dim pf As PivotField Set pf = ActiveSheet.PivotTables(1).PivotFields("date closed") pf.AutoSort xlManual, pf.SourceName </code></pre> <p>Now when it comes to compare the other dates with the max date, it does not work and I think it is because it compares a dd/mm/yyyy with a mm/dd/yyyy (I am not sure but please look at the printscreen): <a href="http://i62.tinypic.com/wv7o9l.jpg" rel="nofollow">http://i62.tinypic.com/wv7o9l.jpg</a></p> <p>Any help ? Thanks !</p> <p>Tweedi </p>
31,026,117
0
Fails to look up view in Express <p>This is the structure of my project. </p> <p>app <br> &nbsp; -controllers <br> &nbsp; &nbsp; &nbsp; index.server.controller.js <br> &nbsp; -models <br> &nbsp; -routes <br> &nbsp;&nbsp;&nbsp;&nbsp; index.server.routes.js <br> &nbsp;-views <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;index.ejs <br> config <br> &nbsp; -express.js <br></p> <p>I set the view directory in my express.js file:</p> <pre><code>app.set('views', '../app/views'); app.set('view engine', 'ejs'); </code></pre> <p>And this is in my controller file:</p> <pre><code>exports.render = function(req,res) { res.render('index' , { title: 'welcome to this page' }) }; </code></pre> <p>Whenever i open localhost i get </p> <p>Error: Failed to lookup view "index" in views directory "../app/views/"</p>
36,823,379
0
Why is core.js not loaded in Joomla 3? <p>I am migrating my own Joomla component from Joomla 2.5 to Joomla 3. Some of the buttons use javascript <code>Joomla.submitform()</code>, which was defined in \media\system\js\core.js, but somehow this file is not loaded any more now...</p> <p>I could simply add <code>JFactory::getDocument()-&gt;addScript( JURI::root().'media/system/js/core.js' )</code> to my component's code, but that seems the quick and dirty way to me.</p> <p>Could someone tell me what the nice and clean way is? Help is very much appreciated!</p>
29,653,579
0
<p>I think by XPath should work to get all items in a List object:</p> <pre><code>List&lt;WebElement&gt; parameters = driver.findElements( By.xpath(".//[local-name()='OBJECT']/[local-name()='PARAM']") ); </code></pre> <p>=== UPDATE ===</p> <blockquote> <p>Try using a CSS locator instead... it will probably be more reliable on IE8... or better yet: use a JavascriptExecutor and get the element using pure Javascript.</p> </blockquote>
760,329
0
Reimplementing the "ToneMatrix" audio toy <p>There is a really cool audio "toy" called <a href="http://lab.andre-michelle.com/tonematrix" rel="nofollow noreferrer">ToneMatrix</a>. I would like to reimplement it as a Java applet. I've tried using <a href="http://www.jfugue.org/" rel="nofollow noreferrer">JFugue</a>'s <code>player.play</code> with individual notes for sound and <code>Thread.sleep</code> for timing, but the results are horrible.</p> <p>JFugue stops responding after the 17th (yes, really, I counted) invocation of <code>player.play</code> and <code>Thread.sleep</code> is too irregular to deliver a good rhythm.</p> <p>What would you recommend instead? Basically, I'm looking for a simple way to generate single notes of sound on the fly. So a fraction of a second before the sound is due to play, I need to be able to look at the data and tell the audio library what notes to play. (Multiple notes in harmony are likely.)</p>
9,344,600
0
<p>Does your app have the permission <a href="http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE" rel="nofollow"><code>WRITE_EXTERNAL_STORAGE</code></a> specified in your manifest?</p>
23,395,550
0
<p>Without looking at any source code, I would guess that one way would be to convert a character to its' respective ASCII value, subtract 32 from it and convert the ASCII value back to a char.</p> <p><img src="https://i.stack.imgur.com/x1xKm.png" alt="enter image description here"></p>
6,060,971
0
prevent json_encode adding escape characters <p>Is there a solution to prevent json_encode adding escape characters? I am returning a json obj from an ajax request.</p> <p>Here is what I currently have:</p> <pre><code>foreach ($files as $file) { $inf = getimagesize( $file ); $farr[] = array ( "imgurl" =&gt; "/".str_replace( "\\" , "/" , str_replace( DOCROOT , "" , $file ) ) , "width" =&gt; $inf[0] , "height" =&gt; $inf[1] ); } $t = json_encode( $farr ); </code></pre> <p>which delivers:</p> <pre><code>[ {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/96\\\/full.png\",\"width\":580,\"height\":384}, {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/95\\\/full.png\",\"width\":580,\"height\":452}, {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/94\\\/full.png\",\"width\":580,\"height\":384} ] </code></pre> <p>but I need:</p> <pre><code>[ {imgurl:"/_assets/portfolio/96/full.png",width:580,height:384}, {imgurl:"/_assets/portfolio/95/full.png",width:580,height:452}, {imgurl:"/_assets/portfolio/94/full.png",width:580,height:384} ] </code></pre> <p>having the imgurl width and height indexes quoted is causing the rest of my javascript to break</p> <p>not having much luck so any tips very much welcome...</p>
8,497,161
0
<p>There are a whole lot of naming conventions advocated by Microsoft for .Net programming. You can read about these <a href="http://msdn.microsoft.com/en-us/library/ms229002.aspx">here</a>.</p> <p>As a rule of thumb, use PascalCase for public property, method and type name.</p> <p>For parameters and local variables, use camelCase.</p> <p>For private fields, choose one: some use camelCase, other prefix _camelCase with an _.</p> <p>A commonly seen convention is also to name constants with ALLCAPS.</p>
8,040,026
0
<p>I figured it out. I had to change this line in <code>drawRect:</code>:</p> <pre><code>otherPoint.x += dirtyRect.size.width; </code></pre> <p>to</p> <pre><code>otherPoint.x += (stringWidth + 20.0); </code></pre> <p>EDIT: You can change <code>20.0</code> depending on how much of a gap you want before the string repeats.</p>
40,143,772
0
docker - build fails when COPYing file to root <p>I'm getting a docker build error when I try to add a shell script to the root directory (/entrypoint.sh)</p> <p>Dockerfile:</p> <pre><code>FROM ubuntu:trusty COPY ./entrypoint.sh / ENTRYPOINT ["/entrypoint.sh"] </code></pre> <p>Output:</p> <pre><code>Sending build context to Docker daemon 3.072 kB Step 1 : FROM ubuntu:trusty ---&gt; 1e0c3dd64ccd Step 2 : COPY ./entrypoint.sh / stat /var/lib/docker/aufs/mnt/5570570a77deddea426b95bd0f706beff4b5195a2fba4a8f70dcac4671bca225/entrypoint.sh: no such file or directory </code></pre> <p>The file is present at the root of the build context, and when I change / to a subdirectory such as /opt/, it works. Any idea what could be going wrong?</p>
39,190,392
0
<p>There are libraries for testing like those in the <a href="https://docs.python.org/3/library/development.html" rel="nofollow">development-section</a> of the standard library. If you did not use such tools yet, you should start to do so - they help a lot with testing. (especially <code>unittest</code>).</p> <p>Normally Python runs programs in debug mode with <a href="https://docs.python.org/3/library/constants.html#__debug__" rel="nofollow"><code>__debug__</code></a> set to <code>True</code> (see <a href="https://docs.python.org/3/reference/simple_stmts.html#assert" rel="nofollow">docs on <code>assert</code></a>) - you can switch off debug mode by setting the command-line switches <code>-O</code> or <code>-OO</code> for optimization (see <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-O" rel="nofollow">docs</a>).</p> <p>There is something about using specifically assertions in the <a href="https://wiki.python.org/moin/UsingAssertionsEffectively" rel="nofollow">Python Wiki</a></p>
26,547,142
0
SQL not properly ended? <p>I know i don't have to use SQL but i have other code between declare begin and end . I just extracted this part and everything works except this . I get the following error:</p> <pre><code>Error report: ORA-06550: line 5, column 5: PL/SQL: ORA-00933: SQL command not properly ended ORA-06550: line 3, column 5: PL/SQL: SQL Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action: </code></pre> <p>This is the code:</p> <pre><code>DECLARE BEGIN UPDATE octombrie SET nr_imprumut = I.nr from (select book_date bd,count(book_date) nr from rental where to_char(book_date,'mm') like '10' group by book_date) I where data = I.bd; END; / </code></pre> <p>I don't get it what did i do wrong ?</p> <p>EDIT: book_date will give me a day from the month of october. In that day multiple books are rented, so i find out how many books i rented by counting the number of times the same date apears (the rented books are in the rental table). I then take this data and Update October table(i put the number of books aka 'nr' where the date in the october table matches the date in which the books where rented);</p>
38,596,953
0
IOS Swift- UITbar setting custom tabbar height leaves empty Space above it <p>I would like to know if there is a way to remove the empty space above the tab bar. I using below code in the custom class of UITabBarController. </p> <pre><code>override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var tabFrame = self.tabBar.frame tabFrame.size.height = 50 tabFrame.origin.y = self.view.frame.size.height - 40 self.tabBar.frame = tabFrame } </code></pre> <p>The resulting image looks like this. There is black empty space above the tab bar. Kindly let me know if i can remove the empty space. Thank you</p> <p><a href="https://i.stack.imgur.com/2PCkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2PCkR.png" alt="enter image description here"></a></p>
16,033,257
0
Check remote file existence on multiple Windows servers <p>I need to check a file status (existing? or last modified date) on multiple remote Windows servers (in LAN). The files are accessible via UNC path. The remote PCs need a user name and password. It's best to be some sort of script. </p> <p>I am not system admin, but asked to do this by my boss because each of these PCs are host of SQL Server and the file is a backup of database. I am a SQL Server database developer. I was trying to do it using T-SQL, but just found it not geared to do this (although maybe doable).</p>
1,695,409
0
<p>Make your imageview as big as the image, and put it inside a scrollview. Hide the scrollers if you want. No need for subclassing in this case.</p>
6,730,209
0
<p>You have to read <a href="http://docs.mono-android.net/Android.App.Activity.OnActivityResult%20%28int,%20Android.App.Result,%20Android.Content.Intent%29" rel="nofollow">data</a> parameter of <code>onActivityResult()</code>, in which you can get _id, displayName etc.. </p> <p>Try this code</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ADD_NEW_CONTACT) { if(resultCode == -1) { Uri contactData = data.getData(); Cursor cursor = managedQuery(contactData, null, null, null, null); if (cursor.moveToFirst()) { long newId = cursor.getLong(cursor.getColumnIndexOrThrow(Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME)); Log.i("New contact Added", "ID of newly added contact is : " + newId + " Name is : " + name); } Log.i("New contact Added : ", "Addedd new contact, Need to refress item list : DATA = " + data.toString()); } else { Log.i("New contact Added : ", "Canceled to adding new contacts : Not need to update database"); } } } </code></pre> <p>Happy coding.</p>
19,910,684
0
<p>Assuming "couldn't get it to work" means you didn't know how to loop the six PictureBox controls, try putting them into an array:</p> <pre><code>For Each pb As PictureBox In New PictureBox() {steen1, steen2, steen3, steen4, steen5, steen6} Select Case RandomNumber.Next(1, 7) Case 1 : pb.Image = Game.My.Resources.Een Case 2 : pb.Image = Game.My.Resources.Twee Case 3 : pb.Image = Game.My.Resources.Drie Case 4 : pb.Image = Game.My.Resources.Vier Case 5 : pb.Image = Game.My.Resources.Vijf Case 6 : pb.Image = Game.My.Resources.Zes End Select Next </code></pre> <p>This assumes you have six PictureBoxes named steen#, etc.</p> <p>Also note that I changed your Random range to 1 - 7. The max is one less, so in your code, you were never getting a number 6 for an image.</p>
18,009,578
0
<p>You can simply use <code>NSURLCredential</code>, it will save both username and password in the keychain.</p> <p>See my detailed answered on <a href="http://stackoverflow.com/a/17997943/249869">http://stackoverflow.com/a/17997943/249869</a>.</p>
9,278,749
0
<p>I assume that the box opens right as from the link you provided. You can add another class for the box to open left (say boxleft)</p> <pre><code>$('.content_area div').hide(); initwidth = $('.boxleft').width(); initHeight = $('.boxleft').height(); $(function() { $('.boxleft').bind('mouseenter', function() { $(this).children('.more').show(); $('.boxleft').not(this).stop(true, true).fadeTo('normal', 0.2); $(this).stop(true, true).animate({ width: '70', height: '70', left: '-=50' }, { queue: true, duration: 'fast' }).css('font-size', '1.2em'); }); $('.boxleft').bind('mouseleave', function() { $(this).children('.more').hide(); $('.boxleft').not(this).stop(true, true).fadeTo('normal', 1); $(this).stop(true, true).animate({ width: initwidth, height: initHeight, left: '+=50' }, { queue: true, duration: 'slow' }).css('font-size', '1em'); }); </code></pre> <p>As you can see i added the extra line left: '-=50' and left: '+=50' in the animate function.</p>
2,852,961
0
<p>It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:</p> <pre><code>foo(); bar(x, y); /* x must not be NULL */ baz(); </code></pre> <p>If I want to comment it out, I might try:</p> <pre><code>/* foo(); bar(x, y); /* x must not be NULL */ baz(); */ </code></pre> <p>Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the <code>*/</code> after the word "NULL" terminates the comment, making the <code>baz</code> call not commented out, and the <code>*/</code> after <code>baz</code> a syntax error. On the other hand:</p> <pre><code>#if 0 foo(); bar(x, y); /* x must not be NULL */ baz(); #endif </code></pre> <p>Works to comment out the entire thing. And the <code>#if 0</code>s will nest with each other, like so:</p> <pre><code>#if 0 pre_foo(); #if 0 foo(); bar(x, y); /* x must not be NULL */ baz(); #endif quux(); #endif </code></pre> <p>Although of course this can get a bit confusing and become a maintenance headache if not commented properly.</p>
28,602,783
0
ASP.NET mvc validation label on dropdownlist with integer value? <p>I'm working on an ASP.NET MVC 4 project and I have an issue with displaying the right validation label for an integer field. </p> <p>Here is my model properties:</p> <pre><code>[Required(ErrorMessage = "Please enter the title.")] public string Title { get; set; } [Required(ErrorMessage = "Please select a country.")] public int RegionId { get; set; } </code></pre> <p>Here is my cshtml:</p> <pre><code>@Html.TextBoxFor(m =&gt; m.article.Title, new { @placeholder = "Title", @autofocus = true }) @Html.ValidationMessageFor(m =&gt; m.article.Title) @(Html.Kendo().DropDownList() .Name("RegionControl") .DataTextField("Name") .DataValueField("RegionId") .OptionLabel("Select one...") .Events(e =&gt; e.Change("RegionChange").DataBound("RegionDataBound")) .BindTo(Model.regions) .Value(Model.article.RegionId.ToString()) @Html.ValidationMessageFor(m =&gt; m.article.RegionId) </code></pre> <p>My problem is that the validation message for Title is displaying fine <code>("Please enter the title.")</code>, BUT the validation for the dropdownlist is the default one <code>("The value 'NaN' is not valid for RegionId.")</code>.</p> <p>Why is the validation message for RegionId not displaying the message I set in the model <code>("Please select a country.")</code>? Is it due to the default value <code>(OptionLabel)</code>? How can I fix it?</p>
4,543,948
1
Python: type() gives blank result <p>What does it mean when I do</p> <pre><code>print type(foo) </code></pre> <p>and get absolutely nothing?</p> <p>foo is the response from an eBay REST search query, and it's supposed to be XML according to the eBay docs. When I</p> <pre><code>print foo </code></pre> <p>I get stuff -- a long string of values about ebay items all butted-up against one another.</p>
29,695,953
0
<p>Change:</p> <pre><code>from osv import fields, osv </code></pre> <p>to:</p> <pre><code>from openerp.osv import fields, osv </code></pre> <p>That should do it! :]</p>
35,264,429
0
<p>I was given a task to invoke the batch job one by one.Each job depends on another. First job result needs to execute the consequent job program. I was searching how to pass the data after job execution. I found that this ExecutionContextPromotionListener comes in handy.</p> <p>1) I have added a bean for "ExecutionContextPromotionListener" like below</p> <pre><code>@Bean public ExecutionContextPromotionListener promotionListener() { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); listener.setKeys( new String[] { "entityRef" } ); return listener; } </code></pre> <p>2) Then I attached one of the listener to my Steps</p> <pre><code>Step step = builder.faultTolerant() .skipPolicy( policy ) .listener( writer ) .listener( promotionListener() ) .listener( skiplistener ) .stream( skiplistener ) .build(); </code></pre> <p>3) I have added stepExecution as a reference in my Writer step implementation and populated in the Beforestep </p> <pre><code>@BeforeStep public void saveStepExecution( StepExecution stepExecution ) { this.stepExecution = stepExecution; } </code></pre> <p>4) in the end of my writer step, i populated the values in the stepexecution as the keys like below</p> <pre><code>lStepContext.put( "entityRef", lMap ); </code></pre> <p>5) After the job execution, I retrieved the values from the <code>lExecution.getExecutionContext()</code> and populated as job response.</p> <p>6) from the job response object, I will get the values and populate the required values in the rest of the jobs.</p> <p>The above code is for promoting the data from the steps to ExecutionContext using ExecutionContextPromotionListener. It can done for in any steps.</p>
4,033,061
0
<p>The problem is that a <code>RewriteCond</code> only applies to the rule immediately following it, so your second <code>RewriteRule</code> is always run. One solution <a href="http://my.galagzee.com/2009/02/11/mod_rewrite-one-rewritecond-to-many-rewriterules/" rel="nofollow">is to negate the test you are making, then have the next command skip the two commands you want to run</a>.</p> <pre><code>RewriteCond %{DOCUMENT_ROOT}assets/img$1/.$2.$4/$3.$4 !-f RewriteRule . - [S=2] RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.([^/]+)\.([a-z]{2,4})$ assets/img$1/.$2.$4/$3.$4 [NC,QSA] RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.([^/]+)\.([a-z]{2,4})$ assets/img/image.php?path=$1&amp;file=$2.$4&amp;key=$3 [NC,L,QSA] </code></pre>
26,117,059
0
<p>Here's a unicode aware implementation as a category on <code>NSString</code>:</p> <pre><code>@interface NSString (NRStringFormatting) - (NSString *)stringByFormattingAsCreditCardNumber; @end @implementation NSString (NRStringFormatting) - (NSString *)stringByFormattingAsCreditCardNumber { NSMutableString *result = [NSMutableString string]; __block NSInteger count = -1; [self enumerateSubstringsInRange:(NSRange){0, [self length]} options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { if ([substring rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound) return; count += 1; if (count == 4) { [result appendString:@" "]; count = 0; } [result appendString:substring]; }]; return result; } @end </code></pre> <p>Try it with this test string:</p> <pre><code>NSString *string = @"ab 132487 387 e e e "; NSLog(@"%@", [string stringByFormattingAsCreditCardNumber]); </code></pre> <p>The method works with non-BMP characters (i.e. emoji) and handles existing white space.</p>
21,578,803
0
<p>I have now managed to get it working. I have had to set the prefix for the plugins models to "media_" and then have the class names as "Media.Item" and call "$this->Item->find()" to get the containable behaviour to work.</p>