pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
5,722,203 | 0 | Keybords inputs in a WPF user control are not sent to the WinForms container <p>We have a WinForms application that we are progressively converting to WPF. At this point the application's main form is a Form (WinForm) that contains a vertical sidebar built in WPF. The sidebar is hosted in an ElementHost control.</p> <p>In the main form, KeyPreview is set to true and we override OnKeyDown() to process application wide keyboard shortcuts. When the sidebar has the focus, keyboard events are not sent to OnKeyDown.</p> <p>What is the correct way to fix this?</p> |
16,835,738 | 0 | <p>You can always animate the <code>contentOffset</code> property yourself and use <code>UIViewAnimationOptionBeginFromCurrentState</code> option. As soon as the second animation begins, the first will end, and by using current state option, the second animation will start from where the first left off. </p> |
21,717,089 | 0 | computing multiple fixed effects on large dataset <p>I'm trying to perform a fixed effects regression for two factor variables in a CSV dataset containing over 4000000 rows. These variables can respectively assume about 140000 and 50000 different integer values.</p> <p>I initially attempted to perform the regression using the biglm and ff packages for R as follows on a Linux machine with 8 Gb of memory; however, it seems that this requires too much memory because R complains about having to allocate a vector of a size greater than the maximum on my machine.</p> <pre><code>library(biglm) library(ff) d <- read.csv.ffdf(file='data.csv', header=TRUE) model = y~factor(a)+factor(b)-1 out <- biglm(model, data=d) </code></pre> <p>Some research online revealed that since factors are loaded into memory by ff, the latter will not significantly improve memory usage if many factor values are present.</p> <p>Is anyone aware of some other way to perform the aforementioned regression on a dataset of the magnitude I described without having to resort to a machine with significantly more memory?</p> |
10,837,994 | 0 | <p>The output is different for failures. For IsTrue, the message will be something like "Expected true but was false." For GreaterOrEqual, the message will be something like "Expected 1 or greater, but was -15." GreaterOrEqual provides more info in that you will see the actual value, which is more useful when debugging failures.</p> |
23,083,505 | 0 | <p>Same as @hsz answer but with one difference..</p> <pre><code>foreach ($test as $key=>$value) { // +1 because 1st array key is 0 ${'test' . ($key+1)} = $value; } </code></pre> <p>or with counter</p> <pre><code>$i = 1; foreach ($test as $value) { ${'test' . $i++} = $value; } </code></pre> <p>But it all depends on what you really need.. Once you have your values in 1 array you can use them a lot easier then creating such variables..</p> <p>.. For the SQL please check my edit</p> <pre><code>function rapport_detail_kosten($idKlant){ $this->db->from('Project'); $this->db->join('Kosten', 'Kosten.idProject = Project.idProject'); if ($idKlant > 0){ $this->db->where('idKlant', $idKlant); } $query = $this->db->get(); $project = array(); foreach($query->result() as $row){ $project[] = $row->idProject; } $sum = 0; $this->db->select('Kosten.idProject, SUM(Kosten.idProject) as sum'); $this->db->from('Kosten'); $this->db->where_in('Kosten.idProject',$project); $query = $this->db->get(); if($query->num_rows()>0){ return $query->result(); } return false; } </code></pre> |
1,235,336 | 0 | Jquery tab reload with a parameter <p>After some events in a tab, I would like to reload it. I need to send a parameter to the page that loads into the tab. </p> <p>The following reloads the page: $("#tabs").tabs( 'load' , 6);</p> <p>But, how can I send a parameter with it?</p> |
30,293,857 | 0 | <p>So I have found the "silver bullet" that seems to resolve a great number of challenges regarding auto layout of prototype cells. </p> <p>In the cellForRowAtIndexPath function I added the following line of code right before I return the cell:</p> <pre><code>lobj_NearbyLocationEntry!.layoutIfNeeded() </code></pre> <p>(lobj_NearbyLocationEntry is the name of my cell variable I am returning.)</p> <p>When I do this, the auto layout for my table works fine. On a side note, I found a defect in the code that uses the UITableViewController also. Once the data loads and it all looks good, if you scroll down and then scroll back up, you will see a couple of the cells are now not laid out correctly. Putting this line of code in that view controller's code also resolved that layout problem. </p> <p>I hope this helps many people who are sitting there trying to figure out why their app is not auto laying out a tableView cell correctly. :)</p> |
7,498,206 | 0 | Can a ClickOnce application return a value to the page that loaded it? <p>I have an online ClickOnce application that launches from a web page. After the application is closed, I would like the user to return to that page with some results passed from the application. Is this possible? </p> <p>Right now the only solution I have is for the application to upload the results to my server, and have javascript on the launching webpage to poll the server every 15 seconds as it waits for results.</p> |
17,835,952 | 0 | Returning only updated fields from database <p>I'm building stored procedure which will be used by my Web API application. Now, I have multiple databases and multiple stored procedures which returns me all data which is specified by API contract. What I want to do is to customize my SP's in the way that they are going to return me only updated rows. E.g. I have 10 columns in a table, and user changes 2 columns, stored procedure check which columns are affected and returns me only those and for all other columns it should return null. So far I was thinking to create new table which will store <code>ProductId</code> and <code>UpdatedFields</code> so when update SP is triggered, it will update Name and Category fields and store those column names in new table under <code>UpdatedFields</code> like comma separated strings (<code>Name</code>, <code>Category</code>...) and on retrieving member data SP will not return <code>Price</code> nor <code>Quantity</code> (those should be null) but just <code>Name</code> and <code>Category</code>.</p> <p>Any help is appreciated.</p> |
16,054,118 | 0 | <p>It might be easier if you think of the comma-expression list you present like this: </p> <pre><code>((a += 3, b = c * 2), d = a + b) </code></pre> <p>First the innermost comma-expression is evaluated:</p> <pre><code>a += 3, b = c * 2 </code></pre> <p>That expression will be evaluated in two steps:</p> <pre><code>a += 3 b = c * 2 </code></pre> <p>The result of <code>a += 3</code> will be thrown away by the compiler, <em>but the assignment still happens</em>, it's just that the returned result is thrown away. The result of the first comma expression is <code>b</code> (which will be <code>c * 2</code> (whatever that is)).</p> <p>The result of the first comma expression is then on the left-hand side of the next comma expression:</p> <pre><code>b = c * 2, d = a + b </code></pre> <p>Which will then be sequenced as</p> <pre><code>b = c * 2 d = a + b </code></pre> <p>The result of the expression <code>b = c * 2</code> is thrown away (but as it is still evaluated the assignment still happens), and the result of the complete expression is <code>d</code> (which is <code>a + b</code>).</p> <p>The result of the whole expression will be <code>d</code>.</p> |
24,081,707 | 0 | Google Spreadsheet: Count rows with not empty value <p>In a Google Spreadsheet: How can I count the rows of a given area that have a value? All hints about this I found up to now lead to formulas that do count the rows which have a not empty content (including formula), but a cell with =IF(1=2;"";"") // Shows an empty cell is counted as well.</p> <p>What is the solution to this simple task?</p> <p>Thank you in advance</p> |
10,810,407 | 0 | Already php sms function convert to C# success <p>i have already configured SMS gateway & some php code.Now my project is thatone convert it to Csharp with minor changes,</p> <p>probably i have to write new code.but so.. experienced guys from you i wanted to know is that possible ? Sample code below.</p> <pre><code>enter code here $username = "abcdsoft"; $password = "softsoft"; //GET parametrar //$source = $_GET['sourceaddr']; //$dest = $_GET['destinationaddr']; //$message_in = $_GET['message']; enter code here $source = $_GET['msisdn']; $dest = $_GET['shortcode']; $message_in = $_GET['msg']; </code></pre> <p>those are most top lines.below code i changed.(php to csharp)</p> <pre><code>enter code here string username ='abcdsoft'; string password = 'abcdabcd'; int source = ['sourceaddr']; int dest = ['shortcode']; string message_in = ['msg']; </code></pre> <p>Is this way is correct ?</p> |
8,385,604 | 0 | Lines with an applied DashStyle are wrongly drawn <p>Doing some GIS programming I stumbled over the following strange issue: When I apply a transformation matrix with fairly large transformation values to a Graphics object and then draw a line from point A to point B, it is drawn crooked as soon as I apply a DashStyle to the used Pen object.</p> <p>Here is some sample code:</p> <pre><code>protected override void OnPaint( PaintEventArgs e ) { base.OnPaint( e ); Graphics g = e.Graphics; g.Clear( Color.White ); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Matrix m = new System.Drawing.Drawing2D.Matrix(); m.Reset(); m.Translate( -1520106.88f, -6597594.5f, MatrixOrder.Append ); m.Scale( 0.393068463f, -0.393068463f, MatrixOrder.Append ); g.Transform = m; g.TranslateTransform( 0, 400 ); Pen p1 = new Pen( Color.Green, 8.0f ); Pen p2 = new Pen( Color.Magenta, 7.0f ); PointF[] roadLine = new PointF[2]; roadLine[0] = new PointF( 1520170.13f, 6596633.0f ); roadLine[1] = new PointF( 1521997.38f, 6596959.0f ); // Normal (solid line) g.DrawLines( p1, roadLine ); g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dashed g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.Dash; g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dashed g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.DashDot; g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dash-Dot-Dot g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.DashDotDot; g.DrawLines( p2, roadLine ); } </code></pre> <p>If you put this in a new Windows Forms app and run it, you'll see some solid lines and some dashed lines (with different dash styles). I would expect the dashed lines would completely overlay the respective solid line, but they don't.</p> <p>Note that both the green, solid lines and the dashed lines use the coordinates for point A and point B.</p> <p>Is this expected behaviour, or should I report this as a .NET bug?</p> <p>I tested with Visual Studio 2008 and .NET 2.0 and .NET 3.5.</p> |
38,718,459 | 0 | <p>you must not perform the substitutions yourself in a SQL query as this makes your code vulnerable to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injections</a>. </p> <p>The correct version is:</p> <pre><code>cr.execute( 'select distinct(value) from ir_translation ' 'where name = %s and src = %s and res_id = %S and lang = %s', ('product.bat3,name', res_bat[j][0].encode('utf-8'), res_bat[j][1], line2.partner_id.lang) ) </code></pre> <p>You may keep the first parameter in the query if you wish. </p> |
21,398,381 | 0 | <p>You're trying to assign an array of bytes (<code>byte[]</code>) to a single byte, hence the error.</p> <p>Try the following code:</p> <pre><code>byte[] imgarray = new byte[imglength]; </code></pre> |
22,802,834 | 0 | <p>For desktop app, please check your project properties "Security" setting, to make sure disable the ClickOnce security settings. Good luck!</p> |
13,378,535 | 0 | <pre><code><?php require './config.php'; require './facebook.php'; //connect to mysql database mysql_connect($db_host, $db_username, $db_password); mysql_select_db($db_name); mysql_query("SET NAMES utf8"); //Create facebook application instance. $facebook = new Facebook(array( 'appId' => $fb_app_id, 'secret' => $fb_secret )); $output = ''; $isHaveNext = false; if (isset($_POST['send_messages'])) { //default message/post $msg = array( 'message' => 'date: ' . date('Y-m-d') . ' time: ' . date('H:i') ); //construct the message/post by posted data if (isset($_POST['message'])) { $msg['message'] = $_POST['message']; } if (isset($_POST['url']) && $_POST['url'] != 'http://') { $msg['link'] = $_POST['url']; } if (isset($_POST['picture_url']) && $_POST['picture_url'] != '') { $msg['picture'] = $_POST['picture_url']; } // get offset $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0; // get total rows count $query = mysql_query("SELECT COUNT(1) FROM offline_access_users LIMIT 1"); $rows = mysql_fetch_array($query); $total = $rows[0]; //get users and try posting our message/post $result = mysql_query("SELECT * FROM offline_access_users LIMIT 50 OFFSET $offset"); if ($result) { while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $msg['access_token'] = $row['access_token']; try { $facebook->api('/me/feed', 'POST', $msg); $output .= "<p>Posting message on '" . $row['name'] . "' wall success</p>"; } catch (FacebookApiException $e) { $output .= "<p>Posting message on '" . $row['name'] . "' wall failed</p>"; } } } // next if ( $total > ($offset + 50) ) { $isHaveNext = true; $offset += 50; ?> <form action="" method="post"> <input type="hidden" name="message" value="<?php echo $_POST['message'] ?>"> <input type="hidden" name="url" value="<?php echo $_POST['url'] ?>"> <input type="hidden" name="picture_url" value="<?php echo $_POST['picture_url'] ?>"> <input type="hidden" name="offset" value="<?php echo $offset ?>"> <input type="submit" name="send_messages" value="Next"> </form> <?php echo $output; } } if ($isHaveNext) exit(1); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="et" lang="en"> <head> <title>Batch posting</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body { font-family:Verdana,"Lucida Grande",Lucida,sans-serif; font-size: 12px} </style> </head> <body> <h1>Batch posting</h1> <form method="post" action=""> <p>Link url: <br /><input type="text" value="http://" size="60" name="url" /></p> <p>Picture url: <br /><input type="text" value="" size="60" name="picture_url" /></p> <p>Message: <br /><textarea type="text" value="" cols="160" rows="6" name="message" />Message here</textarea></p> <p><input type="submit" value="Send message to users walls" name="send_messages" /></p> </form> <?php echo $output; ?> </body> </html> </code></pre> <p><strong>Bonus:</strong> Use <a href="http://www.php.net/manual/en/pdo.connections.php" rel="nofollow">PDO</a> instead of mysql_* functions.</p> |
28,574,861 | 0 | Convert string to date and merge data sets R <p>I have a column of data in the form of a string, and I need to change it to date because it is a time series.</p> <pre><code>200612010018 --> 2006-12-01 00:18 </code></pre> <p>I've tried unsucessfully,</p> <pre><code>strptime(200612010018,format ='%Y%M%D %H:%MM') </code></pre> <p>After doing this I need to append one data set to another one. Will I have any problems using rbind() if the column contains dates?</p> <p>Thanks</p> |
26,792,987 | 0 | <p><a href="http://dmauro.github.io/Keypress/" rel="nofollow">KEYPRESS</a> is focused on game input and supports any key as a modifier, among other features. It's also <a href="https://atmospherejs.com/keypress/keypress" rel="nofollow">pre-packaged for Meteor</a>.</p> |
36,517,321 | 0 | <p>This is a great use-case for custom directives. Here is an example of a custom directive that adds jQuery functionality to Vue: <a href="https://vuejs.org/examples/select2.html" rel="nofollow">https://vuejs.org/examples/select2.html</a></p> |
10,192,134 | 0 | Why am I getting index out of bounds error from database <p>I know what index out of bounds is all about. When I debug I see why as well. basically what is happening is I do a filter on my database to look for records that are potential/pending. I then gather a array of those numbers send them off to another server to check to see if those numbers have been upgraded to a sale. If it has been upgraded to a sale the server responds back with the new Sales Order ID and my old Pending Sales Order ID (SourceID). I then do a for loop on that list to filter it down that specific SourceID and update the SourceID to be the Sales Order ID and change a couple of other values. Problem is is that when I use that filter on the very first one it throws a index out of bounds error. I check the results returned by the filter and it says 0. Which i find kind of strange because I took the sales order number from the list so it should be there. So i dont know what the deal is. Here is the code in question that throws the error. And it doesn't do it all the time. Like I just ran the code this morning and it didn't throw the error. But last night it did before I went home.</p> <pre><code> filter.RowFilter = string.Format("Stage = '{0}'", Potential.PotentialSale); if (filter.Count > 0) { var Soids = new int[filter.Count]; Console.Write("Searching for Soids - ("); for (int i = 0; i < filter.Count; i++) { Console.Write(filter[i][1].ToString() + ","); Soids[i] = (int)filter[i][1]; } Console.WriteLine(")"); var pendingRecords = Server.GetSoldRecords(Soids); var updateRecords = new NameValueCollection(); for (int i = 0; i < pendingRecords.Length; i++) { filter.RowFilter = "Soid = " + pendingRecords[i][1]; filter[0].Row["Soid"] = pendingRecords[i][0]; filter[0].Row["SourceId"] = pendingRecords[i][1]; filter[0].Row["Stage"] = Potential.ClosedWon; var potentialXML = Potential.GetUpdatePotentialXML(filter[0].Row["Soid"].ToString(), filter[0].Row["Stage"].ToString()); updateRecords.Add(filter[0].Row["ZohoID"].ToString(), potentialXML); } </code></pre> <p>if i'm counting right line 17 is the error where the error is thrown. pendingRecords is a object[][] array. pendingRecords[i] is the individual records. pendingRecords[i][0] is the new Sales OrderID (SOID) and pendingRecords[i][1] is the old SOID (now the SourceID)</p> <p>Any help on this one? is it because i'm changing the SOID to the new SOID, and the filter auto updates itself? I just don't know</p> |
21,571,515 | 0 | <p>By passing the interface you are creating the opportunity to pass all the classes which implements the interface. But in case1 you can only pass the <code>MyClass</code> and its subclasses.</p> <p>For example think about the following case</p> <pre><code>public class YourClass implements MyInterface { public void foo() { doJob(); } } </code></pre> <p>Now in case2 you can pass both the instance of MyClass and YourClass. but in case1 you can't.</p> <blockquote> <p>Now, what is the importance of it?</p> </blockquote> <p>In OOP it is recommended to program to the interface instead of class. So if you think about good design there will be no case1. Only case2 will do the job for you.</p> |
34,449,869 | 1 | Unpacking "the rest" of the elements in list comprehension - python3to2 <p>In Python 3, I could use <code>for i, *items in tuple</code> to isolate the first time from the tuple and the rest into items, e.g.:</p> <pre><code>>>> x = [(2, '_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'), (1, '_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'), (3, '_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'), (4, '_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_')] >>> [items for n, *items in sorted(x)] [['_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'], ['_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'], ['_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'], ['_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_']] </code></pre> <p>I need to backport this to Python 2 and I can't use the <code>*</code> pointer to collect the rest of the items in the tuple. </p> <ul> <li><p>What is the equivalent in Python 2?</p></li> <li><p>Is it still possible to achieve the same using the list comprehension?</p></li> <li><p>What is the technical name for this <code>*</code> usage? Unpacking? Isolating? Pointers?</p></li> <li><p>Is there a <code>__future__</code> import that can be used such that I can use the same syntax in Python 2?</p></li> </ul> |
18,467,408 | 0 | <p>As written your formula will always return zero because the last two conditions are mutually exclusive - did you mean those last two to be <> rather than = (or did you refer to the wrong columns)?</p> <p>In any case I can see from the use of whole columns that you must be using <code>Excel 2007</code> or later (your current formula would give an error otherwise) in which case <code>COUNTIFS</code> will be much faster, i.e. assuming the last two conditions should be adjusted as I suggested try this version:</p> <p><code>=COUNTIFS(Sheet1!J:J,Sheet2!A2,Sheet1!G:G,"Windows XP",Sheet1!B:B,"Desktop",Sheet1!M:M,"<>Refresh >=Q2 2014",Sheet1!M:M,"<>Release 2013",Sheet1!M:M,"<>Release 2014",Sheet1!M:M,"<>N/A NVM",Sheet1!M:M,"<>No",Sheet1!M:M,"<>N/A")</code></p> <p>If you <strong>do</strong> need to use SUMPRODUCT then restrict the ranges rather than using whole columns</p> |
11,830,949 | 0 | <p>OpenLayers <a href="http://www.openlayers.org/" rel="nofollow">http://www.openlayers.org/</a> is the most featureful web-mapping client. It will happily read your data locally via standard GeoJSON files for vectors and geo-referenced images for rasters.</p> <p>You could even grab a bunch of tiles from something like an OpenStreetMap tile server and serve those locally for a pretty background.</p> |
5,850,596 | 0 | Conversion of long to decimal in c# <p>I have a value stored in a variable which is of type "long".</p> <pre><code>long fileSizeInBytes = FileUploadControl.FileContent.Length; Decimal fileSizeInMB = Convert.ToDecimal(fileSizeInBytes / (1024 * 1024)); </code></pre> <p>I want to convert the fileSizeInBytes to decimal number rounded up to 2 decimal places (like these: 1.74, 2.45, 3.51) But i'm not able to get the required result. I'm only getting single digit with no decimal places as result. Can some one help me with that ??.</p> <p>Thanks in anticipation</p> |
28,868,524 | 0 | <p>Integer or floats values other than 0 are treated as True:</p> <pre><code>In [8]: bool(int(1)) Out[8]: True In [9]: bool(int(0)) Out[9]: False In [10]: bool(int(-1)) Out[10]: True In [16]: bool(float(1.2e4)) Out[16]: True In [17]: bool(float(-1.4)) Out[17]: True In [20]: bool(0.0) Out[20]: False In [21]: bool(0.000001) Out[21]: True </code></pre> <p>Similarly, empty lists, sets, dicts, empty string, None, etc are treated as false:</p> <pre><code>In [11]: bool([]) Out[11]: False In [12]: bool({}) Out[12]: False In [13]: bool(set()) Out[13]: False In [14]: bool("") Out[14]: False In [19]: bool(None) Out[19]: False </code></pre> |
955,853 | 0 | <p>You could put a helper method in the view's codebehind, and then do something like:</p> <pre><code>Type modelType = this.Model.GetType(); if (modelType == typeof(NewsSummary)) this.RenderPartial("newspartial", this.Model as NewsSummary); else if (modelType == typeof(GigSummary)) this.RenderPartial("gigpartial", this.Model as GigSummary); </code></pre> |
101,836 | 0 | <p>You could try to get spanning-tree protocol information out of the smart switches; even unmanaged switches have to participate in this protocol (this doesn't apply to hubs, though).</p> |
16,851,657 | 0 | <pre><code>function functionTwo(b) { if(functionOne(b)) return true; else return false; } </code></pre> |
17,244,406 | 1 | Python : How to access file from different directory <p>I have the following project structure</p> <pre><code>SampleProject com python example source utils ConfigManager.py conf constants.cfg </code></pre> <p>How to access constants.cfg from ConfigManager.py. </p> <p>I have a limitation</p> <ol> <li>I can not give full path(absolute path) of constants.cfg because if I run in different PC it should work with out any modification</li> <li><p>Also if I represent something like below, I can access the file. But I don't want to give back slash every time</p> <pre><code>filename = ..\\..\\..\\..\\..\\..\\constants.cfg` </code></pre></li> </ol> <p>Currently I am doing something like this. But this works only when constants.cfg and ConfigManager.py are in same directory</p> <pre><code>currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) file = open(os.path.join(currentDir,'constants.cfg')) </code></pre> |
5,588,446 | 0 | <p>They won't be able to install and run the app (until they upgrade the OS on their device to that of the Deployment Target or above). But they might be able to buy and download the app using iTunes on their Mac or PC.</p> |
40,728,428 | 0 | <p>You can make a function like this:</p> <pre class="lang-python prettyprint-override"><code>def get_item(d, keys): current = d for k in keys: current = current[k] # You can add some error handling here return current </code></pre> <p>Example of usage: <a href="https://repl.it/E49o/1" rel="nofollow noreferrer">https://repl.it/E49o/1</a></p> <p>If you want to modify the value at the last index, you can do something like this. </p> <pre class="lang-python prettyprint-override"><code>def set_item(d, keys, new_value): current = d for k in keys[:-1]: # All the keys except the last one current = current[k] current[keys[-1]] = new_value </code></pre> |
3,659,507 | 0 | <p>Converting is not an option, since you don't know anything about what the user meant. For example, when I input the number '3', you can't determine if I meant 3 days or 3 months.</p> <p>Let me elaborate a bit: if I input '3' and select 'days', the time in seconds is: 60 * 60 * 24 * 3 = 259200 seconds. When displaying, you could divide it so that the output is '3 days' again. But what if I inputted '72' and selected 'hours'? You can't tell.</p> <p>Just store the users choice and you're fine.</p> |
7,190,464 | 0 | <p>The subtlety you miss is that the standard input and positional parameters are not the same thing.</p> <p>Standard input, which you can redirect with the '<', or even from another program with '|' is a sequence of bytes. A script can read stdin with, well, the <code>read</code> command.</p> <p>Positional parameters are numbered 1 to N and hold the value of each argument. The shell refers to them as $1 to ${42} (if you gave that many).</p> <p>Standard input and positional parameters are indepent of one another. You can have both, either, or none, depending how you call a program (and what that program expects):</p> <ol> <li>Both: <code>grep -E pattern < file</code></li> <li>Just stdin: <code>wc < file</code></li> <li>Just positional paramters: <code>echo Here are five positional parameters</code></li> <li>Neither: <code>ls</code></li> </ol> |
37,488,010 | 0 | <p>You don't need quotes around spaced entities when you use <code>fgrep</code>. <code>fgrep</code> takes each line literally already. It's only in the command line that you need quotes in order to disambiguate a string from extra command line arguments. Your file can just be:</p> <pre><code>content1 c o n t e n t 2 </code></pre> |
11,400,927 | 0 | <p>This is outside of the language specification and I think if this is a feature that you wish to have in the language another language would be of more use to you that has this kind of functionality in it. </p> <p>The only way I can think of implementing this is by doing some preprocessing tricks, which just seems like a bad idea. With this method you will not have if's in the code it self but some very unmaintainable preprocessing.</p> |
2,625,241 | 0 | Jquery Autocomplete Unable to Empty Input on Internet Explorer <p>I´ve got a Jquery autocomplete input like the following:</p> <pre><code>$("#cities").autocomplete(regionIDs, { minChars: 2, width: 310, autoFill: true, matchContains: "word", formatItem: function(row) { return row.city + ", " + "<span>" + row.country + "</span>"; }, formatMatch: function(row) { return row.city; }, formatResult: function(row) { return row.city + ", " + row.country; } }); </code></pre> <p>A listener for the input</p> <pre><code>$("#cities").result(function(event, data, formatted) { selectedCity = (data.regionID); }); </code></pre> <p>And the input: </p> <pre><code><input type="text" class="textbox" id="cities" name="q" autocomplete="off"> </code></pre> <p>The trouble is when I reload the page, Internet explorer displays last user Input in the text box. However, the variable has no value.</p> <p>I have tried with .reset() but no success.</p> <p>Any ideas why ?</p> |
16,028,715 | 0 | split a comma separated string in a pair of 2 using php <p>I have a string having 128 values in the form of :</p> <pre><code>1,4,5,6,0,0,1,0,0,5,6,...1,2,3. </code></pre> <p>I want to pair in the form of :</p> <pre><code>(1,4),(5,6),(7,8) </code></pre> <p>so that I can make a for loop for 64 data using PHP.</p> |
23,633,468 | 0 | Apply ISNULL like SQL in LINQ <p>I have the next LINQ where <b>o.Value</b> and <b>p.Value</b> are decimal types</p> <pre><code>from o in dbContext.Ammounts where o.Value > (from p in dbContext.Payments select p).Sum(p => p.Value)) </code></pre> <p>The inner LINQ <code>from p in dbContext.Payments select p).Sum(p => p.Value)</code> can be return a NULL value and I need to apply a <code>ISNULL(linq_sentence, 0)</code></p> <p>I try with this:</p> <pre><code>from o in dbContext.Ammounts where o.Value > ((from p in dbContext.Payments select p).Sum(p => p.Value)) ?? 0m) </code></pre> <p>But I get this message error:</p> <blockquote> <p>Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'</p> </blockquote> |
5,439,542 | 0 | animate div up and down <p>I am just making a panel, ( div ) that has cookie, and can be opened or closed. I would like though to animate the div open or closed on click.</p> <p>The code I have so far is:</p> <pre><code>var state; window.onload=function() { obj=document.getElementById('closeable'); state=(state==null)?'hide':state; obj.className=state; document.getElementById('setup').onclick=function() { obj.className=(obj.className=='show')?'hide':'show'; state=obj.className; setCookie(); return false; } } function setCookie() { exp=new Date(); plusMonth=exp.getTime()+(31*24*60*60*1000); exp.setTime(plusMonth); document.cookie='State='+state+';expires='+exp.toGMTString(); } function readCookie() { if(document.cookie) { state=document.cookie.split('State=')[1]; } } readCookie(); </code></pre> <p>Any help appreciated</p> |
39,925,370 | 0 | Lucida Console font underscores not showing in input <p>I am using the <code>font-family: "Lucida Console", Monaco, monospace</code> in my CSS. I am trying to use the same font as my terminal (or similar).</p> <p>The problem is that when used in an input element, the underscores are not shown.</p> <p>Here is an example here: <a href="https://jsfiddle.net/a69x99d9/" rel="nofollow">https://jsfiddle.net/a69x99d9/</a></p> <p>Try typing in the input and you should immediately see that the underscores are hidden.</p> <p>It seems that this might be caused because the underscore is displayed past the line-height of the element. Is this the case?</p> <p>How do I fix something like this?</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong> This problem seems to only happen on ubuntu. (and possibly mac). Tested on chromeos and windows, nothing happens.</p> |
18,701,116 | 0 | Cannot find library reference to libmysqlclient_r Angstrom <p>I downloaded the MySQL Connector / C++ code from dev.mysql.com. I also used opkg to download the libmysqlclient-r-dev package, which gave me libmysqlclient_r.so and .la in my /usr/lib directory.</p> <p>When I attempt to make the source code for the MySQL connector, I get the following error:</p> <pre><code>/usr/lib/gcc/arm-angstrom-linux-gnueabi/4.7.3/../../../../arm-angstrom-linux-gnueabi/bin/ld: cannot find -lmysqlclient_r collect2: error: ld returned 1 exit status make[2]: *** [driver/libmysqlcppconn.so.1.0.5] Error 1 make[1]: *** [driver/CMakeFiles/mysqlcppconn.dir/all] Error 2 make: *** [all] Error 2 </code></pre> <p>It tells me that the library is missing, eventhough it is present in /usr/lib? How does that work, and what should I do?</p> |
1,832,445 | 0 | <p>Just got a notification from PHPClasses, with one of the runner-ups of the monthly innovation award: <a href="http://www.phpclasses.org/browse/package/5721.html" rel="nofollow noreferrer">Text to Timestamp</a></p> <p>You could try that...</p> |
38,411,503 | 0 | <p>You could do:</p> <pre><code>def hour = Calendar.instance.HOUR_OF_DAY if(hour >= 8 && hour < 17) { // It's between 8am and 5pm } </code></pre> |
31,891,230 | 0 | <p>Try this working link at plnkr: <a href="http://plnkr.co/edit/OaQBWxlIfa2fVvanKKEl?p=preview" rel="nofollow">http://plnkr.co/edit/OaQBWxlIfa2fVvanKKEl?p=preview</a></p> <p>Hope it helps!!! HTML</p> <pre><code><div class="blockcontainer"> <div class="blockcenterbox"> <div class="blocktop">abc</div> </div> <div class="blockbottom"></div> </div> </code></pre> <p>CSS</p> <pre><code>.blockcontainer { width:200px; height:200px; background-color:#00CC66; overflow:hidden; } .blocktop { width:100px; background-color:#6699FF; height:50px; } .blockcenterbox { width: 100px; height: 50px; background-color: yellow; margin: 0 auto; } .blockbottom { width:25px; height:25px; background-color:black; margin: 0 auto; } </code></pre> |
33,866,122 | 0 | <p><a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v17/leanback/app/BrowseFragment.java#BrowseFragment.0mOnFocusSearchListener" rel="nofollow">BrowseFragment class</a> accesses search icon using title view's <code>getSearchAffordanceView()</code></p> <pre><code> private final BrowseFrameLayout.OnFocusSearchListener mOnFocusSearchListener = new BrowseFrameLayout.OnFocusSearchListener() { @Override public View onFocusSearch(View focused, int direction) { // If headers fragment is disabled, just return null. if (!mCanShowHeaders) return null; final View searchOrbView = mTitleView.getSearchAffordanceView(); . . . </code></pre> <p>Since <code>mTitleView</code> is <code>BrowseFragment</code>'s private member, you cannot get search icon reference directly. The only properties you can control for search affordance in the fragment title are: visibility and color. Visibility is controlled by the presence of a search listener.</p> |
3,939,880 | 0 | <p>Have you added <a href="http://msdn.microsoft.com/en-us/library/ez524kew%28VS.80%29.aspx" rel="nofollow">project reference</a>?</p> |
7,273,665 | 0 | <p>You're trying to set the <em>field names</em> as parameters - you can't do that. You can only specify <em>values</em> as parameters. So basically your first 14 <code>setString</code> calls should go away, and you should put those field names in the SQL:</p> <pre><code>String query = "INSERT INTO emp(epfno, fname, lname, sex, nid, address, " + "birthday, position, tpno, fathername, mothername, m_status, " + "comments, photo_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; st.setInt(1, emp.epfno); st.setString(2, emp.fname); st.setString(3, emp.lname); // etc </code></pre> |
34,067,879 | 0 | Avoiding DbSet objects count using ToList() <p>Using C# Entity Framework v6.1.1, I was trying to make a Count operation on a <code>DbSet</code>:</p> <pre><code>//Items is a List<Item> int count = db.MyObjects.Count(o => o.Items.FirstOrDefault(i => i.ItemID == 1) != default(Item)); </code></pre> <p>I did not use Contains, as there is a known EF issue on its use with Where Count etc.</p> <p>Now, the above line throws an NullReferenceException, telling me that object reference is not set to an instance of object.</p> <p>Changing it to:</p> <pre><code>//Items is a List<Item> int count = db.MyObjects.ToList().Count(o => o.Items.FirstOrDefault(i => i.ItemID == 1) != default(Item)); </code></pre> <p>Works as expected.</p> <p>Now, my assumption is that <code>DbSet</code> is working as a type of a proxy, loading lazily objects only when requested, something the <code>ToList()</code> forces it to.</p> <p>I am concerned though about the performance of all this. Is there a better way of making the count of a <code>DbSet</code>? Am I really enforced to do the <code>ToList()</code> call everywhere?</p> <p>I noticed that DbSet is <strong>not</strong> an <a href="https://msdn.microsoft.com/en-us/library/system.data.entity.dbset%28v=vs.113%29.aspx" rel="nofollow">IEnumerable</a>.</p> <p>UPDATE: I forgot to mention that I have Lazy Loading disabled, and that I am invoking this code without having applied Eager Loading to the <code>Items</code> collection, which probably explains a lot.</p> |
16,591,598 | 0 | <p>Assuming that your HTML resembles the following:</p> <pre><code><input name="demo" type="checkbox" checked value="1" /> <input name="demo" type="checkbox" value="2" /> <input name="demo" type="checkbox" checked value="3" /> </code></pre> <p>Then simply retrieve the elements of the relevant name, then iterate through the collection/nodeList and add the values to a declared 'total' variable:</p> <pre><code>var boxes = document.getElementsByName('demo'), total = 0; for (var i = 0, len = boxes.length; i < len; i++){ if (boxes[i].checked && boxes[i].type.toLowerCase() == 'checkbox') { total += parseInt(boxes[i].value, 10); } } console.log(total); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/YtArx/" rel="nofollow">JS Fiddle demo</a>.</p> <p>the above code is, I think, cross browser compatible; but if you're looking for a more up-to-date technique that simplifies the <code>for</code> loop (to omit the <code>if</code> checks), then you can use <code>document.querySelectorAll()</code> as the selector technique:</p> <pre><code>var boxes = document.querySelectorAll('input[name="demo"][type="checkbox"]:checked'), total = 0; for (var i = 0, len = boxes.length; i < len; i++){ total += parseInt(boxes[i].value, 10); } console.log(total); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/YtArx/1/" rel="nofollow">JS Fiddle demo</a>.</p> <p>References:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByName" rel="nofollow"><code>document.getElementsByName()</code></a>.</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll?redirectlocale=en-US&redirectslug=DOM%2FDocument.querySelectorAll" rel="nofollow"><code>document.querySelectorAll()</code></a>.</li> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase" rel="nofollow"><code>String.toLowerCase()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt" rel="nofollow"><code>parseInt()</code></a></li> </ul> |
12,832,100 | 0 | <p>Yes this can be easily done using Clojure (for backend) and ClojureScript OR JavaScript (for frontend).</p> <p>Basically the client js code will use websockets to connect to clojure server and on server you can have a state wrapped in an atom that is access by each client and each client is updated about the state through the connected websocket... something similar you do in a chat web application. </p> <p>For websocket you can use <a href="https://github.com/ztellman/aleph" rel="nofollow">Aleph</a>.</p> |
33,108,577 | 0 | <p>Here is an example that will help you get started:</p> <pre><code>const TCHAR szFilter[] = _T("CSV Files (*.csv)|*.csv|All Files (*.*)|*.*||"); CFileDialog dlg(FALSE, _T("csv"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this); if(dlg.DoModal() == IDOK) { CString sFilePath = dlg.GetPathName(); m_FilePathEditBox.SetWindowText(sFilePath); } </code></pre> |
902,770 | 0 | <p>Depending on the exact version of the IBM JDK you are using, there are various options for tracking "large allocations". The differences are mainly in the implementation, and the result is a logging Java stack trace when an allocation over a certain size is made (which should help you track down the culprit).</p> <p>"Sovereign" 1.4.2 SR4+: <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21236523" rel="nofollow noreferrer">http://www-01.ibm.com/support/docview.wss?uid=swg21236523</a></p> <p>"J9" 1.4.2 (if Java is running under -Xj9 option): You need to get hold of a JVMPI / JVMTI agent for the same purpose, I can't find a link for this one right now.</p> |
19,490,947 | 0 | Retrieving last monday but no data in result set <p>I am trying to retrieve last monday when given date is monday below is the code.</p> <pre><code>select Case when to_char(to_date('21/10/2013','dd/mm/yyyy'), 'DAY') = 'MONDAY' then to_date(next_day(to_date('21/10/2013','dd/mm/yyyy')-7,'Tuesday') - 1, 'dd/mm/yyyy') END from dual </code></pre> <p>Query is executing and result is one record but record is totally empty.</p> <p>I am confused why there is no data in the result set.</p> <p>Please help me in resolving this.</p> |
2,451,641 | 0 | <p>The most sargable option, short of using dynamic SQL, is to use an IF statement and two queries:</p> <pre><code>IF LEN(@Title) > 0 SELECT r.* FROM RECORDS r WHERE r.title LIKE '%'+ @Title +'%' ELSE SELECT r.* FROM RECORDS r </code></pre> <p>The SQL Server 2005+ dynamic SQL version would resemble:</p> <pre><code>DECLARE @SQL NVARCHAR(4000) SET @SQL = 'SELECT r.* FROM RECORDS r WHERE 1 = 1' --will be optimized out, easier to add clauses SET @SQL = @SQL + CASE LEN(@Title) WHEN 0 THEN '' ELSE ' AND r.name LIKE ''%''+ @Title +''%'' ' END BEGIN EXEC sp_executesql @SQL, N'@Title VARCHAR(#)', @Title END </code></pre> <p>Unlike <code>EXEC</code>, <code>sp_executesql</code> will cache the query plan. You can read more about it in <a href="http://www.sommarskog.se/dynamic_sql.html" rel="nofollow noreferrer">the Blessing & Curse of Dynamic SQL</a>.</p> |
22,719,135 | 0 | Objective C Regex Extract Data from Line Containing Text <p>I'm using objective c to create a program that will pull out data from a HTML file using regexes. The only lines that are important to the program contain the text <code>popupName</code> and I need to stip all HTML tags from it as well. Can this be done with one regex?</p> <p>So far I have been using <code>popupName</code> to find the line I am looking for and then deleting everything matching <code><[^>]*></code>.</p> <p>Could these two operations be combined into one?</p> <p>Here's example input:</p> <pre><code> <div> <div class="popupName"> Bob Smith</div> <div class="popupTitle"> <i></i> </div> <br /> <div class="popupTitle"></div> <div class="popupLink"><a href="mailto:"></a></div> </div> </code></pre> <p>From that I would like to extract only "Bob Smith". Except, I would have multiple occurrences of the line names like that.</p> |
29,327,287 | 0 | <p>I don't think <code>pivot</code> is useful here. Try this</p> <pre><code>WITH cte1 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data1 FROM yourtable WHERE col_id = 1), cte2 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data2 FROM yourtable WHERE col_id = 2), cte3 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data3 FROM yourtable WHERE col_id = 3) SELECT Row_number()OVER(ORDER BY a.rn) AS serial, Data1, Data2, Data3 FROM cte1 A FULL OUTER JOIN cte2 B ON a.RN = b.RN FULL OUTER JOIN cte3 C ON b.RN = C.RN </code></pre> |
40,777,459 | 0 | <p>Have you tried to look at this one?</p> <pre><code>Dim PathofYourFile As String = "c:\MyDirectory\MYFile.txt" Dim FileName As String = IO.Path.GetExtension(PathofYourFile) MsgBox(FileName) </code></pre> |
10,771,007 | 0 | <p>Make sure its in the right package, runs for me. I'm using this plugin</p> <p><a href="http://scala-ide.org/" rel="nofollow">http://scala-ide.org/</a></p> |
21,226,843 | 0 | <p>You want to use <a href="http://www.mathworks.com/help/signal/ref/findpeaks.html" rel="nofollow"><code>findpeaks</code></a></p> <pre><code>[pks,locs] = findpeaks(data) </code></pre> <p>You could find the local maxes that way, go left and right until it drops to a certain threshold or by a certain percentage (since the peaks have some girth), and then order them, and calculate the distances between as a subtraction between values.</p> |
34,358,645 | 0 | Wrapping in a form action into a curl php <p>I'm new to php development and i just heard of curl. i have this data i post in a form action</p> <pre><code><form id="new_member_sms" name="new_member_sms" method="post" action="http://myserver.com/app_api.php?view=send_sms&amp;&amp;user=username&amp;&amp;pass=password&amp;&amp;message=hello+this+message+is+dynamic+from+server&amp;&amp;sender_id=BlaySoft&amp;&amp;to=<?php echo $row_rs_sms['phone_no']; ?>&amp;&amp;key=4"> </form> </code></pre> <p>I want to know if there's a way i can wrap this post message <code>"http://myserver.com/app_api.php?view=send_sms&amp;&amp;user=username&amp;&amp;pass=password&amp;&amp;message=hello+this+message+is+dynamic+from+server&amp;&amp;sender_id=BlaySoft&amp;&amp;to=<?php echo $row_rs_sms['phone_no']; ?>&amp;&amp;key=4"</code> in a php curl and send it to the server</p> |
8,966,113 | 0 | <p>You can check the referrer of the Request object. But this is very easily spoofed, and should not be relied on.</p> |
5,483,771 | 0 | How can I chain together SELECT EXISTS() queries? <p>I have this simple query</p> <pre><code>SELECT EXISTS(SELECT a FROM A WHERE a = 'lorem ipsum'); </code></pre> <p>That will return a 0 or 1 if there exists a row in A that contains 'lorem ipsum'</p> <p>I would like to chain this behavior together. So I would get multiple rows, each with a 0 or 1 if that value exists.</p> <p>How would I go about doing this?</p> <p>Update:</p> <p>It's possible to do it like this but then I get a column for each result.</p> <pre><code>SELECT EXISTS(SELECT a FROM A WHERE a = 'lorem ipsum'), EXISTS(SELECT a FROM A WHERE a = 'dolor sit'); </code></pre> |
5,564,687 | 0 | PHP on IIS or Apache ( advantages and disadvantages) <p>What are the advantages and disadvantages of running php on IIS?</p> <p>or</p> <p>What are the advantages and disadvantages of running php on Apache?</p> |
27,794,955 | 0 | <p>Running into the same issue as you. I found the code here:</p> <p><a href="https://github.com/GoogleChrome/webrtc/tree/master/samples/web/content/apprtc" rel="nofollow">https://github.com/GoogleChrome/webrtc/tree/master/samples/web/content/apprtc</a></p> <p>Currently looking through the changes to see what could have broken it. Ill update this answer if I find something.</p> <p>UPDATE: Looks like they have made some breaking changes in this commit:</p> <p><a href="https://github.com/GoogleChrome/webrtc/commit/c36b88475fab8a3e4436a87a7ea84265b0e13a8a#diff-c3e41e94913c93dfe31babd4830c3065" rel="nofollow">https://github.com/GoogleChrome/webrtc/commit/c36b88475fab8a3e4436a87a7ea84265b0e13a8a#diff-c3e41e94913c93dfe31babd4830c3065</a></p> <p>They are moving from the GAE Channel api, to a websocket channel.</p> |
12,028,035 | 0 | <p>You can't change your IP like this. Your code obviously doesn't work, because you've just created a variable of type IPAddress and assigned some value to it. If you want a different IP address that you currently have assigned from your internet provider, you need to use a Proxy or TOR if you can't achieve a change of your IP by restarting your modem. However, it won't obviously allow you to use whatever IP you'd like.</p> |
7,932,352 | 0 | Right banner margin CSS <p>On the site: <a href="http://ukrainiansecret.com" rel="nofollow">ukrainiansecret.com</a></p> <p>I would like to get rid of that green right margin of the banner, and to have it exactly as the left side. Have tried to stretch the banner width but it didn't work out.</p> <p>Thanks</p> |
37,068,320 | 0 | <p>ConnectionHandler is not serializable because it contains references to Socket and ServerSocket, which are not serializable. You would have to write your own serialization and deserialization methods to make it serializable.</p> <p>However, it doesn't make sense to make it serializable anyway, since it doesn't have any serializable data in it to transmit over the network.</p> |
25,554,245 | 0 | How to check ping between client and server in php? <p>I have a problem, I need to check the connection between client server, i need to get the response time in ms between the client and a "x" server with php, how I can do that?</p> |
2,207,527 | 0 | Changing a label in Qt <p>I'm trying to make a simple program consisting of a button and a label. When the button is pressed, it should change the label text to whatever is in a QString variable inside the program. Here's my code so far:</p> <p>This is my widget.h file:</p> <pre><code>class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: Ui::WidgetClass *ui; QString test; private slots: void myclicked(); }; </code></pre> <p>And here's the implementation of the Widget class:</p> <pre><code>#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::WidgetClass) { ui->setupUi(this); test = "hello world"; connect(ui->pushButton, SIGNAL(clicked()), ui->label, SLOT(myclicked())); } Widget::~Widget() { delete ui; } void Widget::myclicked(){ ui->label->setText(test); } </code></pre> <p>It runs but when the button is clicked, nothing happens. What am I doing wrong?</p> <p>Edit: after i got it working, the text in the label was larger than the label itself, so the text got clipped. I fixed it by adding <code>ui->label->adjustSize()</code> to the definition of myclicked().</p> |
30,067,366 | 0 | <p>jQuery's <a href="http://api.jquery.com/val/" rel="nofollow"><code>.val()</code></a> method is both a getter and a setter.</p> <p>Try this:</p> <p><code>$('input[name="x"]').val($hello);</code></p> |
26,625,772 | 0 | How to Join a group facebook using facebook SDK in C# <p>I'm using facebook sdk 6.8.0 for deverloping an app in windows using C-sharp. I have a group id, how do i send a request to group's admin to join this group using FB sdk? Please!</p> |
37,210,341 | 0 | <p>From python's <a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow">docs</a>:</p> <p>iter(dictview)</p> <pre><code>Return an iterator over the keys, values or items (represented as tuples </code></pre> <p>of (key, value)) in the dictionary.</p> <pre><code>Keys and values are iterated over in an arbitrary order which is </code></pre> <p>non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. </p> <p>I would try with the order of inclusion since it seems you are not deleting values.</p> |
12,087,022 | 0 | <p>If the editor is in an iframe, you need to target the <code>top</code> window:</p> <pre><code>window.top.location = "http://"+url+""; </code></pre> <p>You should also make sure that the editor accept script tags (not all editors do).</p> |
31,528,821 | 0 | Worklight Java adapter invoke another adapter get I/O issue <p>I have a issue when I try to call adapter (HTTP/MYSQL) from a Java adapter.</p> <p>When I am using Postmen test it (added Authorization on the header) It's always get a IO issue: </p> <p><code>[I O: Invalid token on line 1, column 14]</code>.</p> <p>First, I guess it should be OAuth issue, I add <code>@OAuthSecurity(enabled=false)</code> at the class but not work.</p> <p>Would you please help me find out where the problem is.</p> <p>Code snippet:</p> <pre><code>DataAccessService service = WorklightBundles.getInstance() .getDataAccessService(); ProcedureQName name = new ProcedureQName("mysqlAdapter", "getMysqlAdapters"); String para = ""; // String para = "['a','b','c']"; InvocationResult mysql= service.invokeProcedure(name, para); JSONObject jsMysql = mysql.toJSON(); //String rst = jsMysql.get("key").toString(); </code></pre> <p>PS following code snippet is working when I test it on Postman:</p> <pre><code>HttpUriRequest request = api.getAdaptersAPI() .createJavascriptAdapterRequest("mysqlAdapter", "getMysqlAdapters"); try { HttpResponse response = api.getAdaptersAPI().executeAdapterRequest(request); JSONObject jsonObj =api.getAdaptersAPI().getResponseAsJSON(response); return jsonObj.toString(); } catch (MFPServerOAuthException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "error"; </code></pre> |
17,575,011 | 0 | <p>It's an ugly solution but you may try this ..</p> <pre><code>While DR.Read txtData.Text = txtData.Text & DR.Item("CostumerOrder") & Space(10) & DR.Item("OrderPrice") & vbCrLf Application.DoEvents() End While </code></pre> |
1,925,552 | 1 | Get Cygwin installation path in a Python script <p>I'm writing a cross-platform python script that needs to know if and where Cygwin is installed if the platform is NT. Right now I'm just using a naive check for the existence of the default install path 'C:\Cygwin'. I would like to be able to determine the installation path programmatically.</p> <p>The Windows registry doesn't appear to be an option since Cygwin no longer stores it's mount points in the registry. Because of this is it even possible to programmatically get a Cygwin installation path? </p> |
6,576,259 | 0 | <p>Or you can check first if key exists by using isset().</p> <pre><code>if ( isset($preset[$table]) ) </code></pre> <p>Return true if exists, otherwise return false.</p> |
38,190,485 | 0 | <p>Queries which are Unioned are independent of one another.<br> You want to join these tables.</p> <pre><code>select C2,C4 from D2.T2 a INNER JOIN D2.T3 b ON b.C3=a.C2; </code></pre> |
6,348,427 | 0 | Does HTML 5 application cache have any benefit for online apps? <p>Does the HTML 5 application (offline) cache have any benefit for online/connected apps? </p> <p>My page needs to be online to function and is loaded exclusively in a UIWebView as part of an iOS app. This page is loading some large dependencies and I was wondering if I could use the HTML 5 app cache to store these dependencies to avoid relying on the regular browser cache.</p> <p>So I guess my question is:</p> <p>When an HTML 5 page is online, does it use the offline cache if a dependency already exists in the HTML5 offline cache? </p> |
7,220,201 | 0 | Record Terminal output? <p>Im using a cool program in terminal but it's pre-compiled... Luckily all I need is the output of this system, but the way I need it is tricky... I need it to run normally but output the last line of text in the window to a text file. I jabs been looking around but people only make it so that I can log the whole thing, not just the last line.</p> <p>it is a compiled unix executable that can't be run with something like that because it needs to keep running and won't stop until stopped, and that didn't work</p> |
33,638,975 | 0 | Return blank cell only if referred cell is blank, but return aging if date is entered <p>I'm attempting an aging formula. I have one column with dates I've submitted info, but some rows in the column haven't been submitted. In another column I want to have an aging formula. If the "submitted date" cell is blank, I want the aging cell to be blank. If there is a date entered, I want it to show how many days it's been since it was submitted.</p> <p>I'm pretty new to excel formulas. I know how to create the aging, and I know how to make one cell blank if another is blank. But I do not know how to combine both formulas into one cell.</p> |
2,355,728 | 0 | JPQL Create new Object In Select Statement - avoid or embrace? <p>I've learnt recently that it is possible to create new objects in JPQL statements as follows:</p> <pre><code>select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr </code></pre> <p>Is this something to be avoided or rather to embrace? When is usage of this feature justified in the light of good practices?</p> |
6,103,593 | 0 | <p>First of all, you should always put <code>use strict;</code> at the top of your program. That will catch numerous errors early.</p> <p>The last line in your <code>foreach</code> loop is the one that dereferences <code>$thingy</code> correctly. But since you've put <code>@{$thingy}</code> on the left-hand side of the <code>.</code> (string concatenation) operator, the array is in scalar context, and arrays in scalar context evaluate to their size. Just say:</p> <pre><code>print "@{$thingy}\n"; </code></pre> <p>to get the elements of <code>@$thingy</code> separated by spaces, or in general</p> <pre><code>print join('|', @{$thingy}), "\n"; </code></pre> <p>if you want to use another separator, like the vertical bar character. You can also just say</p> <pre><code>print @{$thingy}, "\n"; </code></pre> <p>to print the elements with no separator at all.</p> |
32,205,707 | 0 | Filter data on the query or with Java stream? <p>I have a Play 2.3.x Java application connected to a MongoDB database via Morphia.</p> <p>I activated slow query profiling in MongoDB and saw that a query comes often. It looks like this :</p> <pre><code>"query": { "field1": null, "field2": true, "field3": "a061ee3f-c2be-477c-ad81-32f852b706b5", "$or": [ { "field4.VAL.VALUE_1": "EXPECTED_VALUE_1", "field4.VAL.VALUE_2": "EXPECTED_VALUE_2" } ] } </code></pre> <p>In its current state, there is no index so every time the query is executed the whole collection is scanned. I still have a few documents, but I anticipate the growth of the database.</p> <p>So I was wondering what was the best solution :</p> <ol> <li>Remove all the clauses above from the query, retrieve all results (paginated) and filter with Java <code>Stream API</code></li> <li>Keep the query as is and index the fields</li> </ol> <p>If you see another solution, feel free to suggest it :)</p> <p>Thanks.</p> |
36,595,396 | 0 | <p>check out how CardLayout works</p> <p><a href="https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html" rel="nofollow">https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html</a></p> <p>if you only want to switch between the windows:</p> <ol> <li>Add jPanel to your jFrame which will contain all jPanels you want to switch between (let's call it jPanelMain)</li> <li>Set CardLayout in jPanelMain</li> <li>Create jPanels you want to switch between with the stuff you need there</li> <li><p>Add Action Listener to the radio button, example</p> <pre><code>private void jButtonActionPerformed(java.awt.event.ActionEvent e) { jPanelMain.removeAll(); jPanelMain.repaint(); jPanelMain.revalidate(); jPanelMain.add(jPanel1); jPanelMain.repaint(); jPanelMain.revalidate(); } </code></pre></li> </ol> |
11,480,503 | 0 | How to add custom app icon on Android in Phonegap? <p>Do you know how to add a custom .png icon on Android in Phonegap? I changed the AndroidManifest.xml "android:icon="@drawable/ic_launcher" to a custom name but it's not working. In addition, my icons are all in the www/res/drawable folders with the correct sizes each png should be. I have no idea what the deal is. Any help would be greatly appreciated.</p> |
9,216,542 | 0 | How do I count the number of elements in each group? <p>How do I get a count of the elements within a particular group? So in the query below I want to know how many cancelled and active subscriptions each account has. What I am getting is either 0 or 1, depending on whether they have at least one cancelled or active subscription.</p> <pre><code>from a in Accounts let subs = ( from s in Subscriptions.Where(s=>s.AccountId == a.Id) group s by s.Status into bystatus select bystatus ) let csubs = subs.Count (s =>s.Key == "Cancelled") let asubs = subs.Count (s => s.Key == "Active") orderby a.Name select new { a.Name,a.AccountNumber, a.Status, ActiveSubscriptionCount = asubs, CancelledSubscriptionCount = csubs } </code></pre> |
6,119,557 | 0 | <p>Class level variables can't maintain their value on postback.</p> <p>But there are two ways you can maintain Data on the Page's PostBack: <code>ViewState and Session State</code>. But I would suggest in your Scenario to put it in the <code>ViewState</code>.</p> <pre><code>ViewState["theDataTable"] = theDataTable; Session["theDataTable"] = theDataTable; </code></pre> <p>And then you can access it on the page postback:</p> <pre><code>DataTable theDataTable = (DataTable)ViewState["theDataTable"]; DataTable theDataTable = (DataTable)Session["theDataTable"]; </code></pre> |
19,043,514 | 0 | <p>You've escaped the <code>}</code> for boost, but you need to escape the <code>\</code> escape char for the compiler as well.</p> <pre><code>boost::wregex rightbrace(L"\\}"); </code></pre> |
37,077,994 | 0 | <pre><code>angular .module('app', []) .controller('Ctrl', function() { this.tags = [ { name: 'bob' }, { name: 'rick' }, { name: 'dave' } ]; }) <body ng-controller="Ctrl as vm"> <ul> <li ng-repeat="obj in vm.tags" ng-class="{'active': vm.active == obj.name}"> <a ng-click="vm.active = obj.name">{{obj.name}}</a> </li> </ul> {{vm.active}} </body> </code></pre> <p><a href="https://plnkr.co/edit/wvKIUtJIb0AE1vpWDtv9?p=preview" rel="nofollow">https://plnkr.co/edit/wvKIUtJIb0AE1vpWDtv9?p=preview</a></p> |
25,662,942 | 0 | DocumentDb User Data Segregation <p>I'm testing out the recently released DocumentDb and can't find any documentation indicating best practice on how to perform user data segregation. </p> <p>I imagine the rough design would be:</p> <ul> <li>Authenticate the user and create new/obtain existing user id</li> <li>On document insert inject the user id into the document</li> <li>On read of document/collection of documents query where document user id = current user id</li> </ul> <p>I'm creating an AngularJs application and currently use an Azure Sql Database combined with Azure Mobile Services. </p> <p>Mobile services handles the user authentication and also the server side user data segregation by the use of data script javascript functions:</p> <p>e.g. </p> <pre><code>function insert(item, user, request) { item.userId = user.userId; request.execute(); } </code></pre> <p>Any suggestions on what would be the technique for secure user data segregation from AngularJS using DocumentDB?</p> |
11,674,164 | 0 | <p>From custom password validator you can return FaultCode that describe what's wrong:</p> <pre><code>throw new FaultException("Invalid user name or bad password.", new FaultCode("BadUserNameOrPassword")); throw new FaultException("Password expired.", new FaultCode("PasswordExpired")); throw new FaultException("Internal service error.", new FaultCode("InternalError")); </code></pre> |
40,516,789 | 0 | <p>In this case could be better a CreateCommand </p> <p>for do this you should bild raw query using join eg: </p> <pre><code>select * from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3) </code></pre> <p>or for delete </p> <pre><code>delete from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3) </code></pre> <p>then for Yii2</p> <pre><code>$sql = "delete from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3);" Yii::$app->db->createCommand($sql)->execute(); </code></pre> |
37,375,733 | 0 | <blockquote> <p>how vecor is initialised?</p> </blockquote> <p>It's default initialized implicitly (i.e. initialized by the default constructor). To be complete, it's default initialized at first, and then copy assigned in the body of constructor.</p> <p>The more effiient way is using <a href="http://en.cppreference.com/w/cpp/language/initializer_list" rel="nofollow">member initializer list</a>.</p> <pre><code>class Student : public Person { private: vector<int> testScores; public: Student(string firstname, string lastname, int id, const vector<int>& scores) :Person(firstname, lastname, id), testScores(scores) { } ... }; </code></pre> <p>It's copy initialized now (i.e. initialized by the copy constructor).</p> |
25,735,350 | 0 | <p>You can do this in this way.</p> <p>In HTML do like below.</p> <pre><code><ul> <li data-ng-repeat="record in records"> <input type="checkbox" ng-model="selected[record.Id]"> {{record.Id}} </li> </ul> </code></pre> <p>And in controller you have to add selected property.</p> <pre><code>function MyCtrl($scope) { $scope.records = [ { "Id": 1, }, { "Id": 2 }, { "Id": 3 } ]; $scope.selected = {}; $scope.ShowSelected = function() { return $scope.selected }; </code></pre> <p>When you read the selected property you will get the selected list.</p> <p><strong><a href="http://jsfiddle.net/e8Nj3/38/" rel="nofollow">Demo</a></strong></p> |
27,798,343 | 0 | <p><code>Base64</code> encoding takes 3 input bytes and converts them to 4 bytes. So if you have 100 Mb file that will end up to be 133 Mb in <code>Base64</code>. When you convert it to Java string (<code>UTF-16</code>) it size will be doubled. Not to mention that during conversion process at some point you will hold multiple copies in memory. No matter how you turn this it is hardly going to work. </p> <p>This is slightly more optimized code that uses <code>Base64OutputStream</code> and will need less memory than your code, but I would not hold my breath. My advice would be to improve that code further by skipping conversion to string, and using temporary file stream as output instead of <code>ByteArrayOutputStream</code>.</p> <pre><code>InputStream inputStream = null;//You can get an inputStream using any IO API inputStream = new FileInputStream(file.getAbsolutePath()); byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output64.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } output64.close(); attachedFile = output.toString(); </code></pre> |
36,031,822 | 0 | <p>You can use <strong>Project Dependencies</strong> to adjust build order:</p> <ol> <li>In Solution Explorer, select a project.</li> <li>On the <strong>Project</strong> menu, choose <strong>Project Dependencies</strong>.The <strong>Project Dependencies</strong> dialog box opens.</li> <li>On the <strong>Dependencies</strong> tab, select a project from the <strong>Project</strong> drop-down menu.</li> <li>In the <strong>Depends on</strong> field, select the check box of any other project that must build before this project does.</li> <li>Check-in the solution to TFS.</li> </ol> |
28,057,527 | 0 | <p>THIS is the right way to do it.</p> <p>One more thing to keep in mind is that you MUST set the FILE SIZE:</p> <pre><code>curl_easy_setopt(curlHandle, CURLOPT_INFILESIZE,(curl_off_t)putData.size); </code></pre> <p>Otherwise your server might throw an error stating that the request length wasn't specified.</p> <p>putData is an instance of the put_data structure.</p> |
Subsets and Splits