qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
275,544
<p>I know in a lot of asynchronous communication, the packet begins starts with a start bit.</p> <p>But a start bit is just a 1 or 0. How do you differentiate a start bit from the end bit from the last packet?</p> <p>Ex. If I choose my start bit to be 0 and my end bit to be 1. and I receive 0 (data stream A) 1 0 (data stream B) 1, what's there to stop me from assuming there is a data stream C which contains the same contents of "(data stream A) 1 0 (data stream B)" ?</p> <p>Isn't it more convenient to have a start BYTE and then check the data stream for that combination of bits? That will reduce the possibility of a confusing between the start/end bit.</p>
[ { "answer_id": 275554, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "ABC A = 65 = 0x41 = 0100 0001\nB = 66 = 0x42 = 0100 0010\nC = 67 = 0x43 = 0100 0011\n 0 1 1 Data: ....1111 0010000011 111 0010000101 0010000111 11111....\n (quiet) ^ A $ ^ B $ ^ C $ (quiet)\n 1 0 ^ 1 $" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
275,550
<p>I know how to include files that are in folders further down the heirachy but I have trouble finding my way back up. I decided to go with the set_include_path to default all further includes relative to a path 2 levels up but don't have the slightest clue how to write it out.</p> <p>Is there a guide somewhere that details path referencing for PHP?</p>
[ { "answer_id": 275556, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "set_include_path('/path/to/files');\n /home/files index.php\ntest/\n test.php\ntest2/\n test2.php\n\n// /home/files/index.php\ninclude('test/test.php');\n\n// /home/files/test/test.php\ninclude('../test2/test2.php');\n /home/files/test/test.php // expected\n/home/test2/test2.php // maybe not expected\n /home/files/test2/test.php set_include_path() <?php\n// location: /home/files/index.php\n set_include_path('../'); // our include path is now /home/\n\n include('files/test/test.php'); // try to include /home/files/test/test.php\n include('test2/test2.php'); // try to include /home/test2/test2.php\n include('../test3.php'); // try to include /test3.php\n?>\n" }, { "answer_id": 275647, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "$base = dirname( __FILE__ ); # Path to directory containing this file\ninclude( \"{$base}/includes/Common.php\" ); # Kick off some magic\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24416/" ]
275,562
<p>I'm writing a simple time tracking program to manage my own projects. I'm a big fan of keeping reporting code in the database, so I've been attempting to create a few sprocs that generate the invoices and timesheets etc.</p> <p>I have a table that contains Clock Actions, IE "Punch In", and "Punch Out". It also contains the user that did this action, the project associated with the action, and the current date/time.</p> <p>I can select from this table to get clock in's for a specific time/project/and user, but I want to aggregate it down so that each clock in and out is converted from 2 rows to a single row containing total time.</p> <p>For example, here is a sample output:</p> <pre><code>ClockActionID ActionType DateTime -------------------- ---------- ----------------------- 17 1 2008-11-08 18:33:56.000 18 2 2008-11-08 18:33:59.587 19 1 2008-11-08 18:34:01.023 20 2 2008-11-08 18:34:02.037 21 1 2008-11-08 18:45:06.317 22 2 2008-11-08 18:46:14.597 23 1 2008-11-08 18:46:16.283 24 2 2008-11-08 18:46:17.173 25 1 2008-11-08 18:50:37.830 26 2 2008-11-08 18:50:39.737 27 1 2008-11-08 18:50:40.547 (11 row(s) affected) </code></pre> <p>Where ActionType 1 is "ClockIn" and ActionType 2 is "ClockOut". I also pruned out the User, Project, and Description columns for brevity.</p> <p>I need to generate, in pure SQL, a result set like:</p> <pre><code>Description | Total Time </code></pre> <p>For each ClockIn / ClockOut Pair.</p> <p>I figure this will actually be fairly simple, I'm just not quite sure which way to approach it.</p> <p>EDIT: The user will be able to clock into multiple projects simultaneously, though by first narrowing down the result set to a single project, this shouldn't make any difference to the logic here.</p>
[ { "answer_id": 275615, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 2, "selected": true, "text": "DECLARE @clock TABLE (ClockActionID INT PRIMARY KEY IDENTITY, ActionType INT, ActionDateTime DATETIME)\n\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:00:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:01:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:02:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:03:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:04:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:05:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:06:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:07:00')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (1,'20080101 00:08:12')\nINSERT INTO @clock (ActionType, ActionDateTime) VALUES (2,'20080101 00:09:00')\n\n-- Get the range\nSELECT ActionDateTime CheckIn, \n (SELECT TOP 1 ActionDateTime \n FROM @clock C2 \n WHERE C2.ActionDateTime > C.ActionDateTime) CheckOut \nFROM @clock C\nWHERE ActionType = 1\n\n-- Get the duration\nSELECT DATEDIFF(second, ActionDateTime, \n (SELECT TOP 1 ActionDateTime \n FROM @clock C2 \n WHERE C2.ActionDateTime > C.ActionDateTime)\n ) / 60.0 Duration_Minutes\nFROM @clock C\nWHERE ActionType = 1\n CheckIn CheckOut\n2008-01-01 00:00:00.000 2008-01-01 00:01:00.000\n2008-01-01 00:02:00.000 2008-01-01 00:03:00.000\n2008-01-01 00:04:00.000 2008-01-01 00:05:00.000\n2008-01-01 00:06:00.000 2008-01-01 00:07:00.000\n2008-01-01 00:08:12.000 2008-01-01 00:09:00.000\n\nDuration_Minutes\n1.000000\n1.000000\n1.000000\n1.000000\n0.800000\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
275,569
<p>This is kind of a brainteaser question, since the code works perfectly fine as-is, it just irritates my aesthetic sense ever so slightly. I'm turning to Stack Overflow because my own brain is failing me right now.</p> <p>Here's a snippet of code that looks up an address using the Google Maps JS API and places a marker on a map. However, sometimes the initial lookup fails, so I want to repeat the process with a different address.</p> <pre><code>geocoder.getLatLng(item.mapstring, function(point) { if (!point) { geocoder.getLatLng(item.backup_mapstring, function(point) { if (!point) return; map.setCenter(point, 13); map.setZoom(7); map.addOverlay(new GMarker(point)); }) return; } map.setCenter(point, 13); map.setZoom(7); map.addOverlay(new GMarker(point)); }) </code></pre> <p>(The second parameter to <code>getLatLng</code> is a callback function.)</p> <p>Of course you can see that the three lines that center and zoom the map and add the marker are duplicated, once in the primary callback and once in the "fallback callback" (ha ha). Can you find a way to express the whole thing without any redundancy? You earn bonus points, and my adulation, if your solution works for an arbitrary number of backup map strings.</p>
[ { "answer_id": 275582, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 1, "selected": false, "text": "function place_point(mapstrings,idx)\n{\n if(idx>=mapstrings.length) return;\n geocoder.getLatLng(mapstrings[idx],\n function(point)\n {\n if(!point)\n {\n place_point(mapstrings,idx+1);\n return;\n }\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n });\n}\n" }, { "answer_id": 275590, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 2, "selected": false, "text": "geocoder.getLatLng(item.mapstring, function(point) {\n if (!point) {\n geocoder.getLatLng(item.backup_mapstring, function(point) {\n if (point) {\n setPoint(point);\n }\n })\n return;\n }\n\n function setPoint(point) {\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n }\n\n setPoint(point);\n});\n" }, { "answer_id": 275601, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "function Y(le, a) {\n return function (f) {\n return f(f);\n }(function (f) {\n return le(function (x) {\n return f(f)(x);\n }, a);\n });\n}\n point mapstrings geocoder.getLatLng(pop(mapstrings), Y(\n function(getLatLongCallback, point)\n {\n if (!point)\n {\n if (length(mapstrings) > 0)\n geocoder.getLatLng(pop(mapstrings), getLatLongCallback);\n return;\n }\n\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n });\n" }, { "answer_id": 275678, "author": "tway", "author_id": 35890, "author_profile": "https://Stackoverflow.com/users/35890", "pm_score": 5, "selected": true, "text": "mapstrings = ['mapstring1', 'mapstring2', 'mapstring3'];\n\ngeocoder.getLatLng(mapstrings.shift(), function lambda(point) {\n if(point) {\n // success\n map.setCenter(point, 13);\n map.setZoom(7);\n map.addOverlay(new GMarker(point));\n }\n else if(mapstrings.length > 0) {\n // Previous mapstring failed... try next mapstring\n geocoder.getLatLng(mapstrings.shift(), lambda);\n }\n else {\n // Take special action if no mapstring succeeds?\n }\n})\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56817/" ]
275,571
<p>I want to write a simple utility to upload images to various free image hosting websites like TinyPic or Imageshack via a right-click context menu for the file.</p> <p>How can I do this using .NET? I've seen some linux scripts that use cURL to post images to these website but I'm not sure how I could create the post request, complete with an image in C#?</p> <p>Can someone point me in the right direction?</p> <hr> <p>EDIT:</p> <p>I've found a pretty good resource. Cropper, a free screenshot tool written in .net, has a lot of open-source plugins. One of them is a SendToTinyPic.. complete with source. Link here:<br> <a href="http://www.codeplex.com/cropperplugins" rel="nofollow noreferrer">http://www.codeplex.com/cropperplugins</a></p>
[ { "answer_id": 275586, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 2, "selected": false, "text": "// http://www.flickr.com/services/api/misc.api_keys.html\nstring flickrApiKey = \"<api key>\";\nstring flickrApiSharedSecret = \"<shared secret>\";\nstring flickrAuthenticationToken = \"<authentication token>\";\n\nFlickr flickr = new Flickr( flickrApiKey, flickrApiSharedSecret );\n\nflickr.AuthToken = flickrAuthenticationToken; \n\nforeach ( FileInfo image in new FileInfo[] { \n new FileInfo( @\"C:\\image1.jpg\" ), \n new FileInfo( @\"C:\\image2.jpg\" ) } )\n{\n string photoId = flickr.UploadPicture(\n image.FullName, image.Name, image.Name, \"tag1, tag2\" );\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,577
<p>If I have a char which holds a hex value such has 0x53, (S), how can I display this as "S"?</p> <p>Code:</p> <pre><code>char test = 0x53; cout &lt;&lt; test &lt;&lt; endl; </code></pre> <p>Thanks!</p>
[ { "answer_id": 275646, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "test = 0x53; // hex\ntest = 'S'; // literal constant\ntest = 83; // decimal\ntest = 0123; // octal\n" }, { "answer_id": 275669, "author": "gagneet", "author_id": 35416, "author_profile": "https://Stackoverflow.com/users/35416", "pm_score": 1, "selected": false, "text": "using namespace std;\n\nint main() {\n char test = 0x53;\n std::cout << test << std::endl;\n return 0;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
275,593
<p>I'm having trouble converting my Cocoa project from a manually-synched interface model to a bindings model so that I don't have to worry about interface glue code.</p> <p>I followed the CocoaDevCentral <a href="http://cocoadevcentral.com/articles/000080.php" rel="nofollow noreferrer">Cocoa Bindings tutorial</a> to make sure that I had covered all the bases, but things aren't working correctly. I have a master-detail interface, but I'm having trouble even getting the master portion of the interface to work correctly. No data is showing up in the master column, even though I've set up the bindings model similar to how it is shown in the tutorial. I've made sure all my controllers and objects have <code>-(id)key</code> and <code>-(void)setKey:(id)key</code> methods so that they're bindings-compliant, I've created a ControllerAlias object in my nib, connected it to my controller, created an NSArrayController that binds to one of the NSMutableArrays from the class that ControllerAlias connects to, made sure to set the type of objects that are contained within the array, and then I've bound a table column to the NSArrayController.</p> <p>I'm getting no errors whatsoever in the Console, and setting <code>NSBindingDebugLogLevel</code> to 1 doesn't produce any errors either, that would help me figure out what the problem is.</p> <p>The only other thing I could think of to make sure that things are working correctly is to check that the NSMutableArray that connects to the NSArrayController actually has something in it, and it does.</p> <p>Any suggestions? What other typical pitfalls are there with Cocoa bindings that I should check?</p>
[ { "answer_id": 275616, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "NSMutableArray" }, { "answer_id": 275666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "theArray = [[NSMutableArray alloc] init];\n[theArray addObject:newThing];\n theArray = [[NSMutableArray alloc] init];\nNSMutableArray *bindingsCompliantArray = [self mutableArrayValueForKey:@\"things\"];\n[bindingsCompliantArray addObject:newThing];\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,625
<pre><code>var pattern = /^0+$/; </code></pre> <p>My guess is this:</p> <p>"Take a look at both the beginning and the end of the string, and if there's a pattern of one or more zeros at the beginning and the end, then return that pattern."</p> <p>I'm sure that's wrong, though, because when I run the expression with this string:</p> <pre><code>var string = "0000009000000"; </code></pre> <p>It comes up <code>null</code>.</p> <p>So what's it really saying? And while I'm asking, what/how does JavaScript consider the beginning, middle and end of a string? </p> <p><strong>UPDATE #1:</strong> Thanks for the responses! I think I understand this now. My confusion stemmed from the fact that I'm visualizing the string as having a beginning, a middle and an end. Like this:</p> <p>[beginning][middle][end]</p> <p>In other words, for the given string above, the following expressions work as I expect them to:</p> <p><code>/^0+/;</code> returns "000000" (a pattern of one or more zeros at the beginning of the string)</p> <p>and</p> <p><code>/0+$/</code>; returns "000000" (a pattern of one or more zeros at the end of the string)</p> <p><strong>UPDATE #2:</strong> I up-voted all the responses to this point, because they're all helpful, and I compiled the answers into one great big one:</p> <p>Given the following JavaScript code:</p> <pre><code>var string = "0000009000000"; var regExp = /^0+$/; alert(regExp.exec(string)); </code></pre> <p>It reads, in part, like this: </p> <p>"If the exact character(s) followed by the ^ modifier and preceded by the $ modifier in the regular expression are not SIMULTANEOUSLY sitting in the first position(s) of the string AND the last position(s) of the string (i.e., they are not the only character(s) in the string), then return <code>null</code>. Else, return the character(s)."</p> <p>In other words, let's say the given string is six zeros "000000". This results in a match because the exact same group of "0" characters are sitting in BOTH the first positions (<strong>1st 2nd 3rd</strong> 4th 5th 6th) AND the last positions (1st 2nd 3rd <strong>4th 5th 6th</strong>) of the string.</p> <p>However, in the original given string, there are six zeros, followed by a nine, followed by six zeros ("0000009000000"). Now, the six zeros in the first positions of the string (1st, 2nd, 3rd, 4th, 5th, 6th) are NOT the exact same six zeros sitting in the last positions of the string (8th, 9th, 10th, 11th, 12th, 13th). Hence, a <code>null</code> is returned.</p>
[ { "answer_id": 275636, "author": "Nate Parsons", "author_id": 34910, "author_profile": "https://Stackoverflow.com/users/34910", "pm_score": 2, "selected": false, "text": "var pattern = /^0+.*0+$/\n" }, { "answer_id": 275638, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "/^0+[0-9]+0$/\n /regex/m\n" }, { "answer_id": 275677, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "/(^0+|0+$)/\n" }, { "answer_id": 275859, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 1, "selected": false, "text": "000000 900000 /0+/ /^0+$/ true /^(0+)$/" }, { "answer_id": 279397, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 1, "selected": false, "text": "/^0+$/" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,630
<p>I'm trying to automate some stuff in MS Excel. When I try to set the Calculation property I get the following error message: 'Unable to set the Calculation property of the Application class'</p> <p>I believe this property should be settable.</p> <p>Any advice appreciated!</p>
[ { "answer_id": 275635, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 1, "selected": false, "text": " Application.Calculation = xlCalculationManual\n" }, { "answer_id": 275743, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 4, "selected": true, "text": "import win32com\n\n# Create new Excel instance\nxl = win32com.client.DispatchEx(\"Excel.Application\") \n\n# Open blank workbook\nxl.Workbooks.Add()\n\n# Set property\nxl.Calculation = win32com.client.constants.xlCalculationManual\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,631
<p>There are <code>&lt;meta&gt;</code> tags and other things you can place in the <code>&lt;head&gt;</code> of your HTML document. What <code>&lt;meta&gt;</code> tags etc. and best practices do you make use of in your HTML document to make it more accessible, searchable, optimized etc.</p>
[ { "answer_id": 275665, "author": "andyk", "author_id": 26721, "author_profile": "https://Stackoverflow.com/users/26721", "pm_score": 5, "selected": true, "text": "Content-type description keywords media=\"\" <script> <head>" }, { "answer_id": 275673, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<base> <head> ." }, { "answer_id": 275752, "author": "Raithlin", "author_id": 6528, "author_profile": "https://Stackoverflow.com/users/6528", "pm_score": 1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n <title>...</title>\n <meta name=\"Description\" ...>\n <meta name=\"Keywords\" ...>\n <meta name=\"Copyright\" ...>\n <meta name=\"Author\" ...>\n <meta name=\"Language\" ...>\n <style type=\"text/css\" ...>\n" }, { "answer_id": 275805, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 2, "selected": false, "text": "<head> <title> <title> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Reports Blah Blah</title>\n<meta name=\"ROBOTS\" content=\"NOINDEX, NOFOLLOW\" />\n<meta http-equiv=\"content-type\" content=\"application/xhtml+xml; charset=UTF-8\" />\n...\n</head>\n" }, { "answer_id": 275815, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 0, "selected": false, "text": "meta X-UA-Compatible" }, { "answer_id": 275838, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<meta name=\"DC.abstract\" content=\"Document abstract\" />\n<meta name=\"DC.audience\" content=\"Target audience\" />\n" }, { "answer_id": 275896, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 3, "selected": false, "text": "Stack Overflow - HTML head best practices\n <script src=\"\"> </body> <link rel=\"start\" href=\"/\" title=\"Home\" />\n <link rel=\"\">" }, { "answer_id": 1482139, "author": "kangax", "author_id": 130652, "author_profile": "https://Stackoverflow.com/users/130652", "pm_score": 3, "selected": false, "text": "<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\">\n" }, { "answer_id": 8762672, "author": "Milche Patern", "author_id": 845310, "author_profile": "https://Stackoverflow.com/users/845310", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <!-- declare all page rendering and programmatic related tags -->\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n <!-- Care about IE ? -->\n <meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\">\n <!-- globalise scripting and styling content language -->\n <meta name=\"Content-Type-Script\" content=\"text/javascript\" />\n <meta name=\"Content-Type-Style\" content=\"text/css\" />\n <!-- title tag is MANDATORY -->\n <title>Short and relevant, about 64 characters/spaces</title>\n <!-- declare all CACHE controll -->\n <meta name=\"ROBOTS\" content=\"NOINDEX, NOFOLLOW\" />\n <meta name=\"revisit-after\" content=\"7 days\" />\n\n <!-- declare all content description tags -->\n <meta http-equiv=\"PICS-Label\" content='(PICS-1.1 \"http://www.gcf.org/v2.5\" labels on \"1994.11.05T08:15-0500\" until \"1995.12.31T23:59-0000\" for \"http://w3.org/PICS/Overview.html\" ratings (suds 0.5 density 0 color/hue 1))'>\n <!-- language specific keywords -->\n <meta name=\"keywords\" lang=\"en-us\" content=\"vacation, Greece, sunshine\" />\n <!-- For french example -->\n <meta name=\"keywords\" lang=\"fr\" content=\"vacances, Grèce, soleil\" />\n <meta name=\"description\" content=\"about 255 characters/spaces WORDS relevant to the content of the actual page\" />\n <meta name=\"Abstract\" content=\"about 96 characters/spaces PARAGRAPH describing the actual page content within your site\" />\n\n <!-- declare all situationnal and external relativity related tags -->\n <link rel=\"DC.identifier\" type=\"text/plain\" href=\"http://www.ietf.org/rfc/rfc1866.txt\" />\n <link rel=\"start\" href=\"/\" title=\"Home\" />\n <link rel=\"prev\" href=\"../\" title=\"Parent section\" />\n\n <!-- declare all page rendering cascading style sheets in order of incidence -->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"globaly-used.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"specificly-used.css\" />\n <!-- declare all page rendering specific cascading style i.e. IE only, hacks etc -->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"more-specificly-used.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"i-love-ie.css\" />\n\n <!-- not relevent to subject, declare all javascripts AFTER css linking -->\n\n</head>\n<body>\n</body>\n</html>\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21406/" ]
275,683
<p>Using <a href="http://imdbpy.sourceforge.net" rel="noreferrer">IMDbPy</a> it is painfully easy to access movies from the IMDB site:</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) </code></pre> <p>However I see no way to get the picture or thumbnail of the movie cover. Suggestions?</p>
[ { "answer_id": 275774, "author": "Tim Kersten", "author_id": 33514, "author_profile": "https://Stackoverflow.com/users/33514", "pm_score": 4, "selected": true, "text": "import imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\nprint \"title: %s year: %s\" % (movie['title'], movie['year'])\nprint \"Cover url: %s\" % movie['cover url']\n from BeautifulSoup import BeautifulSoup\nimport imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\npage = urllib2.urlopen(access.get_imdbURL(movie))\nsoup = BeautifulSoup(page)\ncover_div = soup.find(attrs={\"class\" : \"photo\"})\ncover_url = (photo_div.find('img'))['src']\nprint \"Cover url: %s\" % cover_url\n" }, { "answer_id": 275826, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 2, "selected": false, "text": "import urllib\nfrom imdb import IMDb\n\nia = IMDb(#yourParameters)\nmovie = ia.get_movie(#theMovieID)\n\nif 'cover url' in movie:\n urlObj = urllib.urlopen(movie['cover url'])\n imageData = urlObj.read()\n urlObj.close()\n # now you can save imageData in a file (open it in binary mode).\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
275,689
<p>There's a part in my apps that displays the file path loaded by the user through OpenFileDialog. It's taking up too much space to display the whole path, but I don't want to display only the filename as it might be ambiguous. So I would prefer to show the file path relative to the assembly/exe directory.</p> <p>For example, the assembly resides at <code>C:\Program Files\Dummy Folder\MyProgram</code> and the file at <code>C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat</code> then I would like it to show <code>.\Data\datafile1.dat</code>. If the file is in <code>C:\Program Files\Dummy Folder\datafile1.dat</code>, then I would want <code>..\datafile1.dat</code>. But if the file is at the root directory or 1 directory below root, then display the full path. </p> <p>What solution would you recommend? Regex?</p> <p>Basically I want to display useful file path info without taking too much screen space.</p> <p>EDIT: Just to clarify a little bit more. The purpose of this solution is to help user or myself knowing which file did I loaded last and roughly from which directory was it from. I'm using a readonly textbox to display the path. Most of the time, the file path is much longer than the display space of the textbox. The path is supposed to be informative but not important enough as to take up more screen space.</p> <p>Alex Brault comment was good, so is Jonathan Leffler. The Win32 function provided by DavidK only help with part of the problem, not the whole of it, but thanks anyway. As for James Newton-King solution, I'll give it a try later when I'm free.</p>
[ { "answer_id": 275691, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 2, "selected": false, "text": "RelPath = AbsPath.Replace(ApplicationPath, \".\")\n" }, { "answer_id": 275740, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 5, "selected": false, "text": "PathRelativePathTo()" }, { "answer_id": 275744, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "RefDir = D:\\Abc\\Def\\Ghi\nAbsName = D:\\Abc\\Default\\Karma\\Crucible\n LCP = D:\\Abc\n(RefDir - LCP) = Def\\Ghi\n(Absname - LCP) = Default\\Karma\\Crucible\nRelPath = ..\\..\\Default\\Karma\\Crucible\n" }, { "answer_id": 275749, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Creates a relative path from one file\n/// or folder to another.\n/// </summary>\n/// <param name=\"fromDirectory\">\n/// Contains the directory that defines the\n/// start of the relative path.\n/// </param>\n/// <param name=\"toPath\">\n/// Contains the path that defines the\n/// endpoint of the relative path.\n/// </param>\n/// <returns>\n/// The relative path from the start\n/// directory to the end path.\n/// </returns>\n/// <exception cref=\"ArgumentNullException\"></exception>\npublic static string MakeRelative(string fromDirectory, string toPath)\n{\n if (fromDirectory == null)\n throw new ArgumentNullException(\"fromDirectory\");\n\n if (toPath == null)\n throw new ArgumentNullException(\"toPath\");\n\n bool isRooted = (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath));\n\n if (isRooted)\n {\n bool isDifferentRoot = (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0);\n\n if (isDifferentRoot)\n return toPath;\n }\n\n List<string> relativePath = new List<string>();\n string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);\n\n string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);\n\n int length = Math.Min(fromDirectories.Length, toDirectories.Length);\n\n int lastCommonRoot = -1;\n\n // find common root\n for (int x = 0; x < length; x++)\n {\n if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)\n break;\n\n lastCommonRoot = x;\n }\n\n if (lastCommonRoot == -1)\n return toPath;\n\n // add relative folders in from path\n for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)\n {\n if (fromDirectories[x].Length > 0)\n relativePath.Add(\"..\");\n }\n\n // add to folders to path\n for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)\n {\n relativePath.Add(toDirectories[x]);\n }\n\n // create relative path\n string[] relativeParts = new string[relativePath.Count];\n relativePath.CopyTo(relativeParts, 0);\n\n string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);\n\n return newPath;\n}\n" }, { "answer_id": 337156, "author": "CestLaGalere", "author_id": 6684, "author_profile": "https://Stackoverflow.com/users/6684", "pm_score": 1, "selected": false, "text": "Private Function AddEllipsisPath(ByVal text As String, ByVal colIndex As Integer, ByVal grid As DataGridView) As String\n 'Get the size with the column's width \n Dim colWidth As Integer = grid.Columns(colIndex).Width\n\n 'Calculate the dimensions of the text with the current font\n Dim textSize As SizeF = MeasureString(text, grid.Font)\n\n Dim rawText As String = text\n Dim FileNameLen As Integer = text.Length - text.LastIndexOf(\"\\\")\n Dim ReplaceWith As String = \"\\...\"\n\n Do While textSize.Width > colWidth\n ' Trim to make room for the ellipsis\n Dim LastFolder As Integer = rawText.LastIndexOf(\"\\\", rawText.Length - FileNameLen - 1)\n\n If LastFolder < 0 Then\n Exit Do\n End If\n\n rawText = rawText.Substring(0, LastFolder) + ReplaceWith + rawText.Substring(rawText.Length - FileNameLen)\n\n If ReplaceWith.Length > 0 Then\n FileNameLen += 4\n ReplaceWith = \"\"\n End If\n textSize = MeasureString(rawText, grid.Font)\n Loop\n\n Return rawText\nEnd Function\n\nPrivate Function MeasureString(ByVal text As String, ByVal fontInfo As Font) As SizeF\n Dim size As SizeF\n Dim emSize As Single = fontInfo.Size\n If emSize = 0 Then emSize = 12\n\n Dim stringFont As New Font(fontInfo.Name, emSize)\n\n Dim bmp As New Bitmap(1000, 100)\n Dim g As Graphics = Graphics.FromImage(bmp)\n\n size = g.MeasureString(text, stringFont)\n g.Dispose()\n Return size\nEnd Function\n" }, { "answer_id": 340454, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "Path.GetRelativePath /// <summary>\n/// Creates a relative path from one file or folder to another.\n/// </summary>\n/// <param name=\"fromPath\">Contains the directory that defines the start of the relative path.</param>\n/// <param name=\"toPath\">Contains the path that defines the endpoint of the relative path.</param>\n/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>\n/// <exception cref=\"ArgumentNullException\"></exception>\n/// <exception cref=\"UriFormatException\"></exception>\n/// <exception cref=\"InvalidOperationException\"></exception>\npublic static String MakeRelativePath(String fromPath, String toPath)\n{\n if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(\"fromPath\");\n if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException(\"toPath\");\n\n Uri fromUri = new Uri(fromPath);\n Uri toUri = new Uri(toPath);\n\n if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.\n\n Uri relativeUri = fromUri.MakeRelativeUri(toUri);\n String relativePath = Uri.UnescapeDataString(relativeUri.ToString());\n\n if (toUri.Scheme.Equals(\"file\", StringComparison.InvariantCultureIgnoreCase))\n {\n relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);\n }\n\n return relativePath;\n}\n" }, { "answer_id": 485516, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 6, "selected": false, "text": "public static string GetRelativePath(string fromPath, string toPath)\n{\n int fromAttr = GetPathAttribute(fromPath);\n int toAttr = GetPathAttribute(toPath);\n\n StringBuilder path = new StringBuilder(260); // MAX_PATH\n if(PathRelativePathTo(\n path,\n fromPath,\n fromAttr,\n toPath,\n toAttr) == 0)\n {\n throw new ArgumentException(\"Paths must have a common prefix\");\n }\n return path.ToString();\n}\n\nprivate static int GetPathAttribute(string path)\n{\n DirectoryInfo di = new DirectoryInfo(path);\n if (di.Exists)\n {\n return FILE_ATTRIBUTE_DIRECTORY;\n }\n\n FileInfo fi = new FileInfo(path);\n if(fi.Exists)\n {\n return FILE_ATTRIBUTE_NORMAL;\n }\n\n throw new FileNotFoundException();\n}\n\nprivate const int FILE_ATTRIBUTE_DIRECTORY = 0x10;\nprivate const int FILE_ATTRIBUTE_NORMAL = 0x80;\n\n[DllImport(\"shlwapi.dll\", SetLastError = true)]\nprivate static extern int PathRelativePathTo(StringBuilder pszPath, \n string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);\n" }, { "answer_id": 1599260, "author": "AMissico", "author_id": 163921, "author_profile": "https://Stackoverflow.com/users/163921", "pm_score": 2, "selected": false, "text": "CommonPath RelativePath Namespace IO.Path\n\n Public NotInheritable Class RelativePath\n\n Private Declare Function PathRelativePathTo Lib \"shlwapi\" Alias \"PathRelativePathToA\" ( _\n ByVal pszPath As String, _\n ByVal pszFrom As String, _\n ByVal dwAttrFrom As Integer, _\n ByVal pszTo As String, _\n ByVal dwAttrTo As Integer) As Integer\n\n Private Declare Function PathCanonicalize Lib \"shlwapi\" Alias \"PathCanonicalizeA\" ( _\n ByVal pszBuf As String, _\n ByVal pszPath As String) As Integer\n\n Private Const FILE_ATTRIBUTE_DIRECTORY As Short = &H10S\n\n Private Const MAX_PATH As Short = 260\n\n Private _path As String\n Private _isDirectory As Boolean\n\n#Region \" Constructors \"\n\n Public Sub New()\n\n End Sub\n\n Public Sub New(ByVal path As String)\n _path = path\n End Sub\n\n Public Sub New(ByVal path As String, ByVal isDirectory As Boolean)\n _path = path\n _isDirectory = isDirectory\n End Sub\n\n#End Region\n\n Private Shared Function StripNulls(ByVal value As String) As String\n StripNulls = value\n If (InStr(value, vbNullChar) > 0) Then\n StripNulls = Left(value, InStr(value, vbNullChar) - 1)\n End If\n End Function\n\n Private Shared Function TrimCurrentDirectory(ByVal path As String) As String\n TrimCurrentDirectory = path\n If Len(path) >= 2 And Left(path, 2) = \".\\\" Then\n TrimCurrentDirectory = Mid(path, 3)\n End If\n End Function\n\n ''' <summary>\n ''' 3. conforming to general principles: conforming to accepted principles or standard practice\n ''' </summary>\n Public Shared Function Canonicalize(ByVal path As String) As String\n Dim sPath As String\n\n sPath = New String(Chr(0), MAX_PATH)\n\n If PathCanonicalize(sPath, path) = 0 Then\n Canonicalize = vbNullString\n Else\n Canonicalize = StripNulls(sPath)\n End If\n\n End Function\n\n ''' <summary>\n ''' Returns the most common path between two paths.\n ''' </summary>\n ''' <remarks>\n ''' <para>returns the path that is common between two paths</para>\n ''' <para>c:\\FolderA\\FolderB\\FolderC</para>\n ''' c:\\FolderA\\FolderD\\FolderE\\File.Ext\n ''' \n ''' results in:\n ''' c:\\FolderA\\\n ''' </remarks>\n Public Shared Function CommonPath(ByVal path1 As String, ByVal path2 As String) As String\n 'returns the path that is common between two paths\n '\n ' c:\\FolderA\\FolderB\\FolderC\n ' c:\\FolderA\\FolderD\\FolderE\\File.Ext\n '\n ' results in:\n ' c:\\FolderA\\\n\n Dim sResult As String = String.Empty\n Dim iPos1, iPos2 As Integer\n path1 = Canonicalize(path1)\n path2 = Canonicalize(path2)\n Do\n If Left(path1, iPos1) = Left(path2, iPos2) Then\n sResult = Left(path1, iPos1)\n End If\n iPos1 = InStr(iPos1 + 1, path1, \"\\\")\n iPos2 = InStr(iPos2 + 1, path1, \"\\\")\n Loop While Left(path1, iPos1) = Left(path2, iPos2)\n\n Return sResult\n\n End Function\n\n Public Function CommonPath(ByVal path As String) As String\n Return CommonPath(_path, path)\n End Function\n\n Public Shared Function RelativePathTo(ByVal source As String, ByVal isSourceDirectory As Boolean, ByVal target As String, ByVal isTargetDirectory As Boolean) As String\n 'DEVLIB\n ' 05/23/05 1:47PM - Fixed call to PathRelativePathTo, iTargetAttribute is now passed to dwAttrTo instead of IsTargetDirectory.\n ' For Visual Basic 6.0, the fix does not change testing results,\n ' because when the Boolean IsTargetDirectory is converted to the Long dwAttrTo it happens to contain FILE_ATTRIBUTE_DIRECTORY,\n '\n Dim sRelativePath As String\n Dim iSourceAttribute, iTargetAttribute As Integer\n\n sRelativePath = New String(Chr(0), MAX_PATH)\n source = Canonicalize(source)\n target = Canonicalize(target)\n\n If isSourceDirectory Then\n iSourceAttribute = FILE_ATTRIBUTE_DIRECTORY\n End If\n\n If isTargetDirectory Then\n iTargetAttribute = FILE_ATTRIBUTE_DIRECTORY\n End If\n\n If PathRelativePathTo(sRelativePath, source, iSourceAttribute, target, iTargetAttribute) = 0 Then\n RelativePathTo = vbNullString\n Else\n RelativePathTo = TrimCurrentDirectory(StripNulls(sRelativePath))\n End If\n\n End Function\n\n Public Function RelativePath(ByVal target As String) As String\n Return RelativePathTo(_path, _isDirectory, target, False)\n End Function\n\n End Class\n\nEnd Namespace\n" }, { "answer_id": 5891810, "author": "Cameron Stone", "author_id": 642311, "author_profile": "https://Stackoverflow.com/users/642311", "pm_score": 1, "selected": false, "text": "public static string MakeRelativePath(string fromPath, string toPath)\n{\n // use Path.GetFullPath to canonicalise the paths (deal with multiple directory seperators, etc)\n return Path.GetFullPath(toPath).Substring(Path.GetFullPath(fromPath).Length + 1);\n}\n" }, { "answer_id": 19817301, "author": "Szybki", "author_id": 2572796, "author_profile": "https://Stackoverflow.com/users/2572796", "pm_score": 1, "selected": false, "text": " public static string GetRelativePath(string BasePath, string AbsolutePath)\n {\n char Separator = Path.DirectorySeparatorChar;\n if (string.IsNullOrWhiteSpace(BasePath)) BasePath = Directory.GetCurrentDirectory();\n var ReturnPath = \"\";\n var CommonPart = \"\";\n var BasePathFolders = BasePath.Split(Separator);\n var AbsolutePathFolders = AbsolutePath.Split(Separator);\n var i = 0;\n while (i < BasePathFolders.Length & i < AbsolutePathFolders.Length)\n {\n if (BasePathFolders[i].ToLower() == AbsolutePathFolders[i].ToLower())\n {\n CommonPart += BasePathFolders[i] + Separator;\n }\n else\n {\n break;\n }\n i += 1;\n }\n if (CommonPart.Length > 0)\n {\n var parents = BasePath.Substring(CommonPart.Length - 1).Split(Separator);\n foreach (var ParentDir in parents)\n {\n if (!string.IsNullOrEmpty(ParentDir))\n ReturnPath += \"..\" + Separator;\n }\n }\n ReturnPath += AbsolutePath.Substring(CommonPart.Length);\n return ReturnPath;\n }\n" }, { "answer_id": 29119169, "author": "Maxence", "author_id": 200443, "author_profile": "https://Stackoverflow.com/users/200443", "pm_score": 2, "selected": false, "text": "public static class StringExtensions\n{\n /// <summary>\n /// Creates a relative path from one file or folder to another.\n /// </summary>\n /// <param name=\"absPath\">Absolute path.</param>\n /// <param name=\"relTo\">Directory that defines the start of the relative path.</param> \n /// <returns>The relative path from the start directory to the end path.</returns>\n public static string MakeRelativePath(this string absPath, string relTo)\n {\n string[] absParts = absPath.Split(Path.DirectorySeparatorChar);\n string[] relParts = relTo.Split(Path.DirectorySeparatorChar);\n\n // Get the shortest of the two paths\n int len = absParts.Length < relParts.Length\n ? absParts.Length : relParts.Length;\n\n // Use to determine where in the loop we exited\n int lastCommonRoot = -1;\n int index;\n\n // Find common root\n for (index = 0; index < len; index++)\n {\n if (absParts[index].Equals(relParts[index], StringComparison.OrdinalIgnoreCase))\n lastCommonRoot = index;\n else \n break;\n }\n\n // If we didn't find a common prefix then throw\n if (lastCommonRoot == -1)\n throw new ArgumentException(\"The path of the two files doesn't have any common base.\");\n\n // Build up the relative path\n var relativePath = new StringBuilder();\n\n // Add on the ..\n for (index = lastCommonRoot + 1; index < relParts.Length; index++)\n {\n relativePath.Append(\"..\");\n relativePath.Append(Path.DirectorySeparatorChar);\n }\n\n // Add on the folders\n for (index = lastCommonRoot + 1; index < absParts.Length - 1; index++)\n {\n relativePath.Append(absParts[index]);\n relativePath.Append(Path.DirectorySeparatorChar);\n }\n relativePath.Append(absParts[absParts.Length - 1]);\n\n return relativePath.ToString();\n }\n}\n" }, { "answer_id": 32113484, "author": "Muhammad Rehan Saeed", "author_id": 1212017, "author_profile": "https://Stackoverflow.com/users/1212017", "pm_score": 6, "selected": false, "text": "var relativePath = Path.GetRelativePath(\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\",\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\");\n relativePath Data\\datafile1.dat / Uri.UriSchemeFile \"FILE\" /// <summary>\n/// Creates a relative path from one file or folder to another.\n/// </summary>\n/// <param name=\"fromPath\">Contains the directory that defines the start of the relative path.</param>\n/// <param name=\"toPath\">Contains the path that defines the endpoint of the relative path.</param>\n/// <returns>The relative path from the start directory to the end path.</returns>\n/// <exception cref=\"ArgumentNullException\"><paramref name=\"fromPath\"/> or <paramref name=\"toPath\"/> is <c>null</c>.</exception>\n/// <exception cref=\"UriFormatException\"></exception>\n/// <exception cref=\"InvalidOperationException\"></exception>\npublic static string GetRelativePath(string fromPath, string toPath)\n{\n if (string.IsNullOrEmpty(fromPath))\n {\n throw new ArgumentNullException(\"fromPath\");\n }\n\n if (string.IsNullOrEmpty(toPath))\n {\n throw new ArgumentNullException(\"toPath\");\n }\n\n Uri fromUri = new Uri(AppendDirectorySeparatorChar(fromPath));\n Uri toUri = new Uri(AppendDirectorySeparatorChar(toPath));\n\n if (fromUri.Scheme != toUri.Scheme)\n {\n return toPath;\n }\n\n Uri relativeUri = fromUri.MakeRelativeUri(toUri);\n string relativePath = Uri.UnescapeDataString(relativeUri.ToString());\n\n if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))\n {\n relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);\n }\n\n return relativePath;\n}\n\nprivate static string AppendDirectorySeparatorChar(string path)\n{\n // Append a slash only if the path is a directory and does not have a slash.\n if (!Path.HasExtension(path) &&\n !path.EndsWith(Path.DirectorySeparatorChar.ToString()))\n {\n return path + Path.DirectorySeparatorChar;\n }\n\n return path;\n}\n var relativePath = PathExtended.GetRelativePath(\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\",\n @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\");\n\npublic static class PathExtended\n{\n private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;\n private const int FILE_ATTRIBUTE_NORMAL = 0x80;\n private const int MaximumPath = 260;\n\n public static string GetRelativePath(string fromPath, string toPath)\n {\n var fromAttribute = GetPathAttribute(fromPath);\n var toAttribute = GetPathAttribute(toPath);\n\n var stringBuilder = new StringBuilder(MaximumPath);\n if (PathRelativePathTo(\n stringBuilder,\n fromPath,\n fromAttribute,\n toPath,\n toAttribute) == 0)\n {\n throw new ArgumentException(\"Paths must have a common prefix.\");\n }\n\n return stringBuilder.ToString();\n }\n\n private static int GetPathAttribute(string path)\n {\n var directory = new DirectoryInfo(path);\n if (directory.Exists)\n {\n return FILE_ATTRIBUTE_DIRECTORY;\n }\n\n var file = new FileInfo(path);\n if (file.Exists)\n {\n return FILE_ATTRIBUTE_NORMAL;\n }\n\n throw new FileNotFoundException(\n \"A file or directory with the specified path was not found.\",\n path);\n }\n\n [DllImport(\"shlwapi.dll\", SetLastError = true)]\n private static extern int PathRelativePathTo(\n StringBuilder pszPath,\n string pszFrom,\n int dwAttrFrom,\n string pszTo,\n int dwAttrTo);\n}\n" }, { "answer_id": 33079341, "author": "user626528", "author_id": 626528, "author_profile": "https://Stackoverflow.com/users/626528", "pm_score": 0, "selected": false, "text": " public static string ToRelativePath(string filePath, string refPath)\n {\n var pathNormalized = Path.GetFullPath(filePath);\n\n var refNormalized = Path.GetFullPath(refPath);\n refNormalized = refNormalized.TrimEnd('\\\\', '/');\n\n if (!pathNormalized.StartsWith(refNormalized))\n throw new ArgumentException();\n var res = pathNormalized.Substring(refNormalized.Length + 1);\n return res;\n }\n" }, { "answer_id": 41189926, "author": "excanoe", "author_id": 474967, "author_profile": "https://Stackoverflow.com/users/474967", "pm_score": 0, "selected": false, "text": "private string rel(string path) {\n string[] cwd = new Regex(@\"[\\\\]\").Split(Directory.GetCurrentDirectory());\n string[] fp = new Regex(@\"[\\\\]\").Split(path);\n\n int common = 0;\n\n for (int n = 0; n < fp.Length; n++) {\n if (n < cwd.Length && n < fp.Length && cwd[n] == fp[n]) {\n common++;\n }\n }\n\n if (common > 0) {\n List<string> rp = new List<string>();\n\n for (int n = 0; n < (cwd.Length - common); n++) {\n rp.Add(\"..\");\n }\n\n for (int n = common; n < fp.Length; n++) {\n rp.Add(fp[n]);\n }\n\n return String.Join(\"/\", rp.ToArray());\n } else {\n return String.Join(\"/\", fp);\n }\n}\n" }, { "answer_id": 45590737, "author": "Alexey Makarenya", "author_id": 2043898, "author_profile": "https://Stackoverflow.com/users/2043898", "pm_score": 0, "selected": false, "text": "public static string MakeRelativePath(string fromPath, string toPath, string sep = \"/\")\n{\n var fromParts = fromPath.Split(new[] { '/', '\\\\'},\n StringSplitOptions.RemoveEmptyEntries);\n var toParts = toPath.Split(new[] { '/', '\\\\'},\n StringSplitOptions.RemoveEmptyEntries);\n\n var matchedParts = fromParts\n .Zip(toParts, (x, y) => string.Compare(x, y, true) == 0)\n .TakeWhile(x => x).Count();\n\n return string.Join(\"\", Enumerable.Range(0, fromParts.Length - matchedParts)\n .Select(x => \"..\" + sep)) +\n string.Join(sep, toParts.Skip(matchedParts));\n} \n" }, { "answer_id": 47233440, "author": "Spongman", "author_id": 204555, "author_profile": "https://Stackoverflow.com/users/204555", "pm_score": 0, "selected": false, "text": "public static string RelativePathTo(this System.IO.DirectoryInfo @this, string to)\n{\n var rgFrom = @this.FullName.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);\n var rgTo = to.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);\n var cSame = rgFrom.TakeWhile((p, i) => i < rgTo.Length && string.Equals(p, rgTo[i])).Count();\n\n return Path.Combine(\n Enumerable.Range(0, rgFrom.Length - cSame)\n .Select(_ => \"..\")\n .Concat(rgTo.Skip(cSame))\n .ToArray()\n );\n}\n" }, { "answer_id": 47340368, "author": "Sergey Orlov", "author_id": 1588592, "author_profile": "https://Stackoverflow.com/users/1588592", "pm_score": 0, "selected": false, "text": "private String GetRelativePath(Int32 level, String directory, out String errorMessage) {\n if (level < 0 || level > 5) {\n errorMessage = \"Find some more smart input data\";\n return String.Empty;\n }\n // ==========================\n while (level != 0) {\n directory = Path.GetDirectoryName(directory);\n level -= 1;\n }\n // ==========================\n errorMessage = String.Empty;\n return directory;\n }\n [Test]\n public void RelativeDirectoryPathTest() {\n var relativePath =\n GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);\n Console.WriteLine(relativePath);\n if (String.IsNullOrEmpty(errorMessage) == false) {\n Console.WriteLine(errorMessage);\n Assert.Fail(\"Can not find relative path\");\n }\n }\n" }, { "answer_id": 48756531, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 4, "selected": false, "text": "Path.GetRelativePath() var relativeTo = @\"C:\\Program Files\\Dummy Folder\\MyProgram\";\n var path = @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\";\n\n string relativePath = System.IO.Path.GetRelativePath(relativeTo, path);\n\n System.Console.WriteLine(relativePath);\n // output --> Data\\datafile1.dat \n" }, { "answer_id": 51181785, "author": "Anton Krouglov", "author_id": 2746150, "author_profile": "https://Stackoverflow.com/users/2746150", "pm_score": 3, "selected": false, "text": "Path.GetRelativePath // Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\n//Adapted from https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Path.cs#L697\n// by Anton Krouglov\n\nusing System.Runtime.CompilerServices;\nusing System.Diagnostics;\nusing System.Text;\nusing Xunit;\n\nnamespace System.IO {\n // Provides methods for processing file system strings in a cross-platform manner.\n // Most of the methods don't do a complete parsing (such as examining a UNC hostname), \n // but they will handle most string operations.\n public static class PathNetCore {\n\n /// <summary>\n /// Create a relative path from one path to another. Paths will be resolved before calculating the difference.\n /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix).\n /// </summary>\n /// <param name=\"relativeTo\">The source path the output should be relative to. This path is always considered to be a directory.</param>\n /// <param name=\"path\">The destination path.</param>\n /// <returns>The relative path or <paramref name=\"path\"/> if the paths don't share the same root.</returns>\n /// <exception cref=\"ArgumentNullException\">Thrown if <paramref name=\"relativeTo\"/> or <paramref name=\"path\"/> is <c>null</c> or an empty string.</exception>\n public static string GetRelativePath(string relativeTo, string path) {\n return GetRelativePath(relativeTo, path, StringComparison);\n }\n\n private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) {\n if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo));\n if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));\n Debug.Assert(comparisonType == StringComparison.Ordinal ||\n comparisonType == StringComparison.OrdinalIgnoreCase);\n\n relativeTo = Path.GetFullPath(relativeTo);\n path = Path.GetFullPath(path);\n\n // Need to check if the roots are different- if they are we need to return the \"to\" path.\n if (!PathInternalNetCore.AreRootsEqual(relativeTo, path, comparisonType))\n return path;\n\n int commonLength = PathInternalNetCore.GetCommonPathLength(relativeTo, path,\n ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);\n\n // If there is nothing in common they can't share the same root, return the \"to\" path as is.\n if (commonLength == 0)\n return path;\n\n // Trailing separators aren't significant for comparison\n int relativeToLength = relativeTo.Length;\n if (PathInternalNetCore.EndsInDirectorySeparator(relativeTo))\n relativeToLength--;\n\n bool pathEndsInSeparator = PathInternalNetCore.EndsInDirectorySeparator(path);\n int pathLength = path.Length;\n if (pathEndsInSeparator)\n pathLength--;\n\n // If we have effectively the same path, return \".\"\n if (relativeToLength == pathLength && commonLength >= relativeToLength) return \".\";\n\n // We have the same root, we need to calculate the difference now using the\n // common Length and Segment count past the length.\n //\n // Some examples:\n //\n // C:\\Foo C:\\Bar L3, S1 -> ..\\Bar\n // C:\\Foo C:\\Foo\\Bar L6, S0 -> Bar\n // C:\\Foo\\Bar C:\\Bar\\Bar L3, S2 -> ..\\..\\Bar\\Bar\n // C:\\Foo\\Foo C:\\Foo\\Bar L7, S1 -> ..\\Bar\n\n StringBuilder\n sb = new StringBuilder(); //StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length));\n\n // Add parent segments for segments past the common on the \"from\" path\n if (commonLength < relativeToLength) {\n sb.Append(\"..\");\n\n for (int i = commonLength + 1; i < relativeToLength; i++) {\n if (PathInternalNetCore.IsDirectorySeparator(relativeTo[i])) {\n sb.Append(DirectorySeparatorChar);\n sb.Append(\"..\");\n }\n }\n }\n else if (PathInternalNetCore.IsDirectorySeparator(path[commonLength])) {\n // No parent segments and we need to eat the initial separator\n // (C:\\Foo C:\\Foo\\Bar case)\n commonLength++;\n }\n\n // Now add the rest of the \"to\" path, adding back the trailing separator\n int differenceLength = pathLength - commonLength;\n if (pathEndsInSeparator)\n differenceLength++;\n\n if (differenceLength > 0) {\n if (sb.Length > 0) {\n sb.Append(DirectorySeparatorChar);\n }\n\n sb.Append(path, commonLength, differenceLength);\n }\n\n return sb.ToString(); //StringBuilderCache.GetStringAndRelease(sb);\n }\n\n // Public static readonly variant of the separators. The Path implementation itself is using\n // internal const variant of the separators for better performance.\n public static readonly char DirectorySeparatorChar = PathInternalNetCore.DirectorySeparatorChar;\n public static readonly char AltDirectorySeparatorChar = PathInternalNetCore.AltDirectorySeparatorChar;\n public static readonly char VolumeSeparatorChar = PathInternalNetCore.VolumeSeparatorChar;\n public static readonly char PathSeparator = PathInternalNetCore.PathSeparator;\n\n /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary>\n internal static StringComparison StringComparison => StringComparison.OrdinalIgnoreCase;\n }\n\n /// <summary>Contains internal path helpers that are shared between many projects.</summary>\n internal static class PathInternalNetCore {\n internal const char DirectorySeparatorChar = '\\\\';\n internal const char AltDirectorySeparatorChar = '/';\n internal const char VolumeSeparatorChar = ':';\n internal const char PathSeparator = ';';\n\n internal const string ExtendedDevicePathPrefix = @\"\\\\?\\\";\n internal const string UncPathPrefix = @\"\\\\\";\n internal const string UncDevicePrefixToInsert = @\"?\\UNC\\\";\n internal const string UncExtendedPathPrefix = @\"\\\\?\\UNC\\\";\n internal const string DevicePathPrefix = @\"\\\\.\\\";\n\n //internal const int MaxShortPath = 260;\n\n // \\\\?\\, \\\\.\\, \\??\\\n internal const int DevicePrefixLength = 4;\n\n /// <summary>\n /// Returns true if the two paths have the same root\n /// </summary>\n internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) {\n int firstRootLength = GetRootLength(first);\n int secondRootLength = GetRootLength(second);\n\n return firstRootLength == secondRootLength\n && string.Compare(\n strA: first,\n indexA: 0,\n strB: second,\n indexB: 0,\n length: firstRootLength,\n comparisonType: comparisonType) == 0;\n }\n\n /// <summary>\n /// Gets the length of the root of the path (drive, share, etc.).\n /// </summary>\n internal static int GetRootLength(string path) {\n int i = 0;\n int volumeSeparatorLength = 2; // Length to the colon \"C:\"\n int uncRootLength = 2; // Length to the start of the server name \"\\\\\"\n\n bool extendedSyntax = path.StartsWith(ExtendedDevicePathPrefix);\n bool extendedUncSyntax = path.StartsWith(UncExtendedPathPrefix);\n if (extendedSyntax) {\n // Shift the position we look for the root from to account for the extended prefix\n if (extendedUncSyntax) {\n // \"\\\\\" -> \"\\\\?\\UNC\\\"\n uncRootLength = UncExtendedPathPrefix.Length;\n }\n else {\n // \"C:\" -> \"\\\\?\\C:\"\n volumeSeparatorLength += ExtendedDevicePathPrefix.Length;\n }\n }\n\n if ((!extendedSyntax || extendedUncSyntax) && path.Length > 0 && IsDirectorySeparator(path[0])) {\n // UNC or simple rooted path (e.g. \"\\foo\", NOT \"\\\\?\\C:\\foo\")\n\n i = 1; // Drive rooted (\\foo) is one character\n if (extendedUncSyntax || (path.Length > 1 && IsDirectorySeparator(path[1]))) {\n // UNC (\\\\?\\UNC\\ or \\\\), scan past the next two directory separators at most\n // (e.g. to \\\\?\\UNC\\Server\\Share or \\\\Server\\Share\\)\n i = uncRootLength;\n int n = 2; // Maximum separators to skip\n while (i < path.Length && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;\n }\n }\n else if (path.Length >= volumeSeparatorLength &&\n path[volumeSeparatorLength - 1] == PathNetCore.VolumeSeparatorChar) {\n // Path is at least longer than where we expect a colon, and has a colon (\\\\?\\A:, A:)\n // If the colon is followed by a directory separator, move past it\n i = volumeSeparatorLength;\n if (path.Length >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;\n }\n\n return i;\n }\n\n /// <summary>\n /// True if the given character is a directory separator.\n /// </summary>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n internal static bool IsDirectorySeparator(char c) {\n return c == PathNetCore.DirectorySeparatorChar || c == PathNetCore.AltDirectorySeparatorChar;\n }\n\n /// <summary>\n /// Get the common path length from the start of the string.\n /// </summary>\n internal static int GetCommonPathLength(string first, string second, bool ignoreCase) {\n int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);\n\n // If nothing matches\n if (commonChars == 0)\n return commonChars;\n\n // Or we're a full string and equal length or match to a separator\n if (commonChars == first.Length\n && (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))\n return commonChars;\n\n if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))\n return commonChars;\n\n // It's possible we matched somewhere in the middle of a segment e.g. C:\\Foodie and C:\\Foobar.\n while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))\n commonChars--;\n\n return commonChars;\n }\n\n /// <summary>\n /// Gets the count of common characters from the left optionally ignoring case\n /// </summary>\n internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) {\n if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0;\n\n int commonChars = 0;\n\n fixed (char* f = first)\n fixed (char* s = second) {\n char* l = f;\n char* r = s;\n char* leftEnd = l + first.Length;\n char* rightEnd = r + second.Length;\n\n while (l != leftEnd && r != rightEnd\n && (*l == *r || (ignoreCase &&\n char.ToUpperInvariant((*l)) == char.ToUpperInvariant((*r))))) {\n commonChars++;\n l++;\n r++;\n }\n }\n\n return commonChars;\n }\n\n /// <summary>\n /// Returns true if the path ends in a directory separator.\n /// </summary>\n internal static bool EndsInDirectorySeparator(string path)\n => path.Length > 0 && IsDirectorySeparator(path[path.Length - 1]);\n }\n\n /// <summary> Tests for PathNetCore.GetRelativePath </summary>\n public static class GetRelativePathTests {\n [Theory]\n [InlineData(@\"C:\\\", @\"C:\\\", @\".\")]\n [InlineData(@\"C:\\a\", @\"C:\\a\\\", @\".\")]\n [InlineData(@\"C:\\A\", @\"C:\\a\\\", @\".\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\a\", @\".\")]\n [InlineData(@\"C:\\\", @\"C:\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\", @\"..\\b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\\\", @\"..\\b\\\")]\n [InlineData(@\"C:\\a\\b\", @\"C:\\a\", @\"..\")]\n [InlineData(@\"C:\\a\\b\", @\"C:\\a\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\\", @\"C:\\a\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\\", @\"C:\\a\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\b\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\b\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\", @\"C:\\a\\\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\b\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\b\\\", @\"..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\b\\c\\\", @\"C:\\a\\\", @\"..\\..\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\b\", @\"..\\b\")]\n [InlineData(@\"C:\\a\", @\"C:\\a\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\A\\b\", @\"b\")]\n [InlineData(@\"C:\\a\", @\"C:\\b\\c\", @\"..\\b\\c\")]\n [InlineData(@\"C:\\a\\\", @\"C:\\a\\b\", @\"b\")]\n [InlineData(@\"C:\\\", @\"D:\\\", @\"D:\\\")]\n [InlineData(@\"C:\\\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\\", @\"D:\\b\\\", @\"D:\\b\\\")]\n [InlineData(@\"C:\\a\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\a\\\", @\"D:\\b\", @\"D:\\b\")]\n [InlineData(@\"C:\\ab\", @\"C:\\a\", @\"..\\a\")]\n [InlineData(@\"C:\\a\", @\"C:\\ab\", @\"..\\ab\")]\n [InlineData(@\"C:\\\", @\"\\\\LOCALHOST\\Share\\b\", @\"\\\\LOCALHOST\\Share\\b\")]\n [InlineData(@\"\\\\LOCALHOST\\Share\\a\", @\"\\\\LOCALHOST\\Share\\b\", @\"..\\b\")]\n //[PlatformSpecific(TestPlatforms.Windows)] // Tests Windows-specific paths\n public static void GetRelativePath_Windows(string relativeTo, string path, string expected) {\n string result = PathNetCore.GetRelativePath(relativeTo, path);\n Assert.Equal(expected, result);\n\n // Check that we get the equivalent path when the result is combined with the sources\n Assert.Equal(\n Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar),\n Path.GetFullPath(Path.Combine(Path.GetFullPath(relativeTo), result))\n .TrimEnd(Path.DirectorySeparatorChar),\n ignoreCase: true,\n ignoreLineEndingDifferences: false,\n ignoreWhiteSpaceDifferences: false);\n }\n }\n}\n" }, { "answer_id": 58657062, "author": "Dragos Durlut", "author_id": 249895, "author_profile": "https://Stackoverflow.com/users/249895", "pm_score": 0, "selected": false, "text": "ASP.NET Core 2 bin\\Debug\\netcoreapp2.2 using Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Configuration;\npublic class RenderingService : IRenderingService\n{\n\n private readonly IHostingEnvironment _hostingEnvironment;\n public RenderingService(IHostingEnvironment hostingEnvironment)\n {\n _hostingEnvironment = hostingEnvironment;\n }\n\n public string RelativeAssemblyDirectory()\n {\n var contentRootPath = _hostingEnvironment.ContentRootPath;\n string executingAssemblyDirectoryAbsolutePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n string executingAssemblyDirectoryRelativePath = System.IO.Path.GetRelativePath(contentRootPath, executingAssemblyDirectoryAbsolutePath);\n return executingAssemblyDirectoryRelativePath;\n }\n}\n" }, { "answer_id": 73768911, "author": "Chris Schaller", "author_id": 1690217, "author_profile": "https://Stackoverflow.com/users/1690217", "pm_score": 0, "selected": false, "text": "System.IO.Path.GetRelativePath public static partial class PathUtilities\n{\n /// <summary>\n /// Rebases file with <paramref name=\"path\"/> to the folder specified by <paramref name=\"relativeTo\"/>.\n /// </summary>\n /// <param name=\"path\">Full file path (absolute)</param>\n /// <param name=\"relativeTo\">Full base directory path (absolute) the result should be relative to. This path is always considered to be a directory.</param>\n /// <returns>Relative path to file with respect to <paramref name=\"relativeTo\"/></returns>\n /// <remarks>Paths are resolved by calling the <seealso cref=\"System.IO.Path.GetFullPath(string)\"/> method before calculating the difference. This will resolve relative path fragments:\n /// <code>\n /// \"c:\\test\\..\\test2\" => \"c:\\test2\"\n /// </code>\n /// These path framents are expected to be created by concatenating a root folder with a relative path such as this:\n /// <code>\n /// var baseFolder = @\"c:\\test\\\";\n /// var virtualPath = @\"..\\test2\";\n /// var fullPath = System.IO.Path.Combine(baseFolder, virtualPath);\n /// </code>\n /// The default file path for the current executing environment will be used for the base resolution for this operation, which may not be appropriate if the input paths are fully relative or relative to different\n /// respective base paths. For this reason we should attempt to resolve absolute input paths <i>before</i> passing through as arguments to this method.\n /// </remarks>\n static public string GetRelativePath(string relativeTo, string path)\n {\n String pathSep = \"\\\\\";\n String itemPath = Path.GetFullPath(path);\n String baseDirPath = Path.GetFullPath(relativeTo); // If folder contains upper folder references, they get resolved here. \"c:\\test\\..\\test2\" => \"c:\\test2\"\n bool isDirectory = path.EndsWith(pathSep);\n\n String[] p1 = Regex.Split(itemPath, \"[\\\\\\\\/]\").Where(x => x.Length != 0).ToArray();\n String[] p2 = Regex.Split(relativeTo, \"[\\\\\\\\/]\").Where(x => x.Length != 0).ToArray();\n int i = 0;\n\n for (; i < p1.Length && i < p2.Length; i++)\n if (String.Compare(p1[i], p2[i], true) != 0) // Case insensitive match\n break;\n\n if (i == 0) // Cannot make relative path, for example if resides on different drive\n return itemPath;\n\n String r = String.Join(pathSep, Enumerable.Repeat(\"..\", p2.Length - i).Concat(p1.Skip(i).Take(p1.Length - i)));\n if (String.IsNullOrEmpty(r)) return \".\";\n else if (isDirectory && p1.Length >= p2.Length) // only append on forward traversal, to match .Net Standard Implementation of System.IO.Path.GetRelativePath\n r += pathSep;\n\n return r;\n }\n}\n string itemPath = @\"C:\\Program Files\\Dummy Folder\\MyProgram\\Data\\datafile1.dat\";\nstring baseDirectory = @\"C:\\Program Files\\Dummy Folder\\MyProgram\";\nstring result = PathUtilities.GetRelativePath(baseDirectory, itemPath);\nConsole.WriteLine(result);\n Data\\datafile1.dat\n string itemPath = @\"C:\\Program Files\\Dummy Folder\\datafile1.dat\";\n string baseDirectory = @\"C:\\Program Files\\Dummy Folder\\MyProgram\";\n string result = PathUtilities.GetRelativePath(baseDirectory, itemPath);\n Console.WriteLine(\"Before Check: '{0}'\", result);\n if (result.StartsWith(\"..\\\\\"))\n result = itemPath;\n Console.WriteLine(\"After Check: '{0}'\", result);\n Before Check: '..\\datafile1.dat'\n After Check: 'C:\\Program Files\\Dummy Folder\\datafile1.dat'\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
275,701
<p>I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed to stop after the view was loaded. Can I define methods within views? If not, why, and what workarounds would you suggest?</p> <p><strong>Note</strong>: The method has to do with formatting output strings.</p>
[ { "answer_id": 275729, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 0, "selected": false, "text": "if (!function_exists('myfunc'))\n{\n function myfunc() {}\n}\n while(ob_end_flush()){}\nerror_reporting(E_ALL);\nini_set('display_errors', 1);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
275,707
<p>Create a file called Valid[File].txt and stick some text in it. Start powershell and go to the directory.<br> <PRE> gc Valid[File].txt </PRE> should display the value in the file. It returns blank. If you use tab auto-completion it escapes the name: <PRE> gc 'Valid<code>[File</code>].txt' </PRE> but still returns nothing.</p> <p>How do I reference files with brackets in their names?</p>
[ { "answer_id": 275719, "author": "Brian Adams", "author_id": 32992, "author_profile": "https://Stackoverflow.com/users/32992", "pm_score": 4, "selected": true, "text": "-literalpath" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32992/" ]
275,711
<p>Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)</p> <pre><code>static String intToString(int num, int digits) { StringBuffer s = new StringBuffer(digits); int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; for (int i = 0; i &lt; zeroes; i++) { s.append(0); } return s.append(num).toString(); } </code></pre>
[ { "answer_id": 275715, "author": "begray", "author_id": 12123, "author_profile": "https://Stackoverflow.com/users/12123", "pm_score": 12, "selected": true, "text": "String formatted = String.format(\"%03d\", num);\n" }, { "answer_id": 275716, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 7, "selected": false, "text": "String.format String format = String.format(\"%0%d\", digits);\nString result = String.format(format, num);\nreturn result;\n %% --> %\n0 --> 0\n%d --> <value of digits>\nd --> d\n %05d String.format" }, { "answer_id": 275799, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 5, "selected": false, "text": "static String intToString(int num, int digits) {\n assert digits > 0 : \"Invalid number of digits\";\n\n // create variable length array of zeros\n char[] zeros = new char[digits];\n Arrays.fill(zeros, '0');\n // format number as String\n DecimalFormat df = new DecimalFormat(String.valueOf(zeros));\n\n return df.format(num);\n}\n" }, { "answer_id": 3758787, "author": "Madhu Subramanian", "author_id": 453694, "author_profile": "https://Stackoverflow.com/users/453694", "pm_score": -1, "selected": false, "text": " int iTest = 2;\n StringBuffer sTest = new StringBuffer(\"000000\"); //if the string size is 6\n sTest.append(String.valueOf(iTest));\n System.out.println(sTest.substring(sTest.length()-6, sTest.length()));\n" }, { "answer_id": 5427138, "author": "Torin Rudeen", "author_id": 675942, "author_profile": "https://Stackoverflow.com/users/675942", "pm_score": 3, "selected": false, "text": "public static String intToString(int num, int digits) {\n String output = Integer.toString(num);\n while (output.length() < digits) output = \"0\" + output;\n return output;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
275,717
<p>I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:</p> <pre> 1) read a byte from the serial port 2) store each char into tagBuffer as they are read 3) run a query using tagBuffer to see what type of tag it is (book or shelf tag) 4) depending on the type of tag, output a series of bytes corresponding to the type of tag </pre> <p>Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.</p> <p>The lines are the two lines at the very bottom: <code></p> <pre><code> sprintf(buf,"%s!\n", tagBuffer); WriteFile(hSerial,buf,strlen(buf), &amp;dwBytesWritten,&amp;ovWrite); </code></pre> <p></code></p> <p>If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().</p> <p>I thought sprintf and WriteFile are I/O functions and would have no effect on variables. I'm stuck and I need help to fix this.</p> <p><code></p> <pre><code>//keep polling as long as stop character '-' is not read while(szRxChar != '-') { // Check if a read is outstanding if (HasOverlappedIoCompleted(&amp;ovRead)) { // Issue a serial port read if (!ReadFile(hSerial,&amp;szRxChar,1, &amp;dwBytesRead,&amp;ovRead)) { DWORD dwErr = GetLastError(); if (dwErr!=ERROR_IO_PENDING) return dwErr; } } // resets tagBuffer in case tagBuffer is out of sync time_t t_time = time(0); char buf[50]; if (HasOverlappedIoCompleted(&amp;ovWrite)) { i=0; } // Wait 5 seconds for serial input if (!(HasOverlappedIoCompleted(&amp;ovRead))) { WaitForSingleObject(hReadEvent,RESET_TIME); } // Check if serial input has arrived if (GetOverlappedResult(hSerial,&amp;ovRead, &amp;dwBytesRead,FALSE)) { // Wait for the write GetOverlappedResult(hSerial,&amp;ovWrite, &amp;dwBytesWritten,TRUE); if( strlen(tagBuffer) &gt;= PACKET_LENGTH ) { i = 0; } //load tagBuffer with byte stream tagBuffer[i] = szRxChar; i++; tagBuffer[i] = 0; //char arrays are \0 terminated //run query with tagBuffer sprintf(query,"select type from rfid where rfidnum=\""); strcat(query, tagBuffer); strcat(query, "\""); mysql_real_query(&amp;mysql,query,(unsigned int)strlen(query)); //process result and send back to handheld res = mysql_use_result(&amp;mysql); while(row = mysql_fetch_row(res)) { printf("result of query is %s\n",row[0]); string str = ""; str = string(row[0]); if( str == "book" ) { WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR), &amp;dwBytesWritten,&amp;ovWrite); } else if ( str == "shelf" ) { WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR), &amp;dwBytesWritten,&amp;ovWrite); } else //this else doesn't work { WriteFile(hSerial,NOK,strlen(NOK), &amp;dwBytesWritten,&amp;ovWrite); } } mysql_free_result(res); // Display a response to input //printf("query is %s!\n", query); //printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer)); //without these, tagBuffer only holds the last character sprintf(buf,"%s!\n", tagBuffer); WriteFile(hSerial,buf,strlen(buf), &amp;dwBytesWritten,&amp;ovWrite); } } </code></pre> <p></code></p> <p>With those two lines, my output looks like this: s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001</p> <p>Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.</p> <p>Any help at all will be greatly appreciated. Thanks.</p>
[ { "answer_id": 275725, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "buf tagBuffer" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
275,736
<p>I use the dark-blue2 color theme but it seems ugly under console. So I want to use no color theme under terminal, what can I do then?</p>
[ { "answer_id": 275755, "author": "Samuel Tardieu", "author_id": 22890, "author_profile": "https://Stackoverflow.com/users/22890", "pm_score": 2, "selected": true, "text": "TERM=xterm-mono emacs -nw\n" }, { "answer_id": 276586, "author": "quodlibetor", "author_id": 25616, "author_profile": "https://Stackoverflow.com/users/25616", "pm_score": 4, "selected": false, "text": "window-system something nil (if window-system\n (progn\n (load \"color-theme\")\n (color-theme-darkblue2)))\n (load \"color-theme\")\n(if window-system\n (color-theme-darkblue2)\n (some-term-theme)))\n" }, { "answer_id": 25536380, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "(when window-system\n (load-theme '<myThemeName>))\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34924/" ]
275,737
<pre><code>DECLARE @p_date DATETIME SET @p_date = CONVERT( DATETIME, '14 AUG 2008 10:45:30',?) SELECT * FROM table1 WHERE column_datetime = @p_date </code></pre> <p>I need to compare date time like:</p> <pre><code>@p_date=14 AUG 2008 10:45:30 column_datetime=14 AUG 2008 10:45:30 </code></pre> <p>How can I do this?</p>
[ { "answer_id": 275776, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "DECLARE @end datetime\nSET @end = DATEADD(ss,1,@p_date)\n WHERE column_datetime >= @p_date AND column_datetime < @end\n DATEADD" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,756
<p>I was looking at the <a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html" rel="noreferrer">Python documentation</a> and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. </p> <p>Apart from the fact that some include <em>stderr</em> while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well.</p>
[ { "answer_id": 275817, "author": "J S", "author_id": 25676, "author_profile": "https://Stackoverflow.com/users/25676", "pm_score": 4, "selected": false, "text": "subprocess" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
275,761
<p>I have a textbox and a link button. When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.</p> <p>How can I do it?</p> <hr /> <p>When I click the submit button for the textbox below, the message box must show <em>Lorem ipsum</em>. Because &quot;Lorem ipsum&quot; is selected in the area.</p> <hr /> <p>If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.</p> <p>Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.</p> <p>How is it to be done?</p>
[ { "answer_id": 275797, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "function getTextFieldSelection(textField) {\n return textField.value.substring(textField.selectionStart, textField.selectionEnd);\n}\n alert(getTextFieldSelection(document.getElementsByTagName(\"textarea\")[0]));\n HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {\n var ss = this.selectionStart;\n var se = this.selectionEnd;\n if (typeof ss === \"number\" && typeof se === \"number\") {\n return this.value.substring(this.selectionStart, this.selectionEnd);\n }\n return \"\";\n};\n alert(document.getElementsByTagName(\"textarea\")[0].getSelection());\nalert(document.getElementsByTagName(\"input\")[0].getSelection());\n" }, { "answer_id": 275825, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": true, "text": "function ShowSelection()\n{\n var textComponent = document.getElementById('Editor');\n var selectedText;\n\n if (textComponent.selectionStart !== undefined)\n { // Standards-compliant version\n var startPos = textComponent.selectionStart;\n var endPos = textComponent.selectionEnd;\n selectedText = textComponent.value.substring(startPos, endPos);\n }\n else if (document.selection !== undefined)\n { // Internet Explorer version\n textComponent.focus();\n var sel = document.selection.createRange();\n selectedText = sel.text;\n }\n\n alert(\"You selected: \" + selectedText);\n}\n document.onkeydown = function (e) { ShowSelection(); }\n li input" }, { "answer_id": 22434042, "author": "prat3ik-patel", "author_id": 3340034, "author_profile": "https://Stackoverflow.com/users/3340034", "pm_score": 2, "selected": false, "text": "function disp() {\n var text = document.getElementById(\"text\");\n var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);\n alert(t);\n} <TEXTAREA id=\"text\">Hello, How are You?</TEXTAREA><BR>\n<INPUT type=\"button\" onclick=\"disp()\" value=\"Select text and click here\" />" }, { "answer_id": 24025245, "author": "fishjd", "author_id": 321747, "author_profile": "https://Stackoverflow.com/users/321747", "pm_score": 1, "selected": false, "text": "<!doctype html>\n<html>\n\n<head>\n <meta charset=\"UTF-8\">\n <title>jquery-textrange</title>\n <script src=\"http://code.jquery.com/jquery-latest.min.js\"></script>\n <script src=\"jquery-textrange.js\"></script>\n\n <script>\n /* Run on document load */\n $(document).ready(function() {\n /* Run on any change of 'textarea' **/\n $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {\n\n /* The magic is on this line **/\n var range = $(this).textrange();\n\n /* Stuff into selectedId. I wanted to\n store this is a input field so it\n can be submitted in a form. */\n $('#selectedId').val(range.text);\n });\n });\n </script>\n</head>\n\n<body>\n The smallest example possible using\n <a href=\"https://github.com/dwieeb/jquery-textrange\">\n jquery-textrange\n </a><br/>\n <textarea id=\"textareaId\">Some random content.</textarea><br/>\n <input type=\"text\" id=\"selectedId\"></input>\n\n</body>\n\n</html>\n" }, { "answer_id": 32397146, "author": "Dan Dascalescu", "author_id": 1269037, "author_profile": "https://Stackoverflow.com/users/1269037", "pm_score": 4, "selected": false, "text": "document.querySelector('textarea').addEventListener('mouseup', function () {\n window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)\n // window.getSelection().toString();\n}); <textarea>\n Select some text\n</textarea>\n<a href=\"#\" onclick=alert(mySelection);>Click here to display the selected text</a> keyup window.mySelection window.getSelection().toString()" }, { "answer_id": 61967743, "author": "Optimaz ID", "author_id": 5719038, "author_profile": "https://Stackoverflow.com/users/5719038", "pm_score": 0, "selected": false, "text": "// jQuery\nvar textarea = $('#post-content');\nvar selectionStart = textarea.prop('selectionStart');\nvar selectionEnd = textarea.prop('selectionEnd');\nvar selection = (textarea.val()).substring(selectionStart, selectionEnd);\n\n// JavaScript\nvar textarea = document.getElementById(\"post-content\");\nvar selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439507/" ]
275,771
<p>I need to get the values in the registers with GCC.</p> <p>Something similar to this:</p> <pre> EAX=00000002 EBX=00000001 ECX=00000005 EDX=BFFC94C0 ESI=8184C544 EDI=00000000 EBP=0063FF78 ESP=0063FE3C CF=0 SF=0 ZF=0 OF=0 </pre> <p>Getting the 32-bit registers is easy enough, but I'm not sure what the simplest way to get the flags is.</p> <p>In the examples for this book: <a href="http://kipirvine.com/asm/" rel="nofollow noreferrer">http://kipirvine.com/asm/</a></p> <p>They do it by getting the whole EFLAGS register and shifting for the bit in question. I also thought of doing it using Jcc's and CMOVcc's. </p> <p>Any other suggestions on how to do it? Some test cases to verify would also be useful.</p>
[ { "answer_id": 275837, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": true, "text": " PUSHFD\n POP EAX \n , eax now contains the EFLAG data\n" }, { "answer_id": 6405090, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 1, "selected": false, "text": "pushfd pushfq jc jnc jo jno #include <stdio.h>\n#include <stdint.h>\n\n#define HIGH32(x) ((uint32_t)(((uint64_t)x)>>32))\n#define LOW32(x) ((uint32_t)(((uint64_t)x)& 0xFFFFFFFF))\n\nint main(int argc, char** argv)\n{\n uint32_t eax32, ebx32, ecx32, edx32;\n uint64_t rax64, rbx64, rcx64, rdx64;\n\n asm (\n \"movl %%eax, %[a1] ;\"\n \"movl %%ebx, %[b1] ;\"\n \"movl %%ecx, %[c1] ;\"\n \"movl %%edx, %[d1] ;\"\n\n \"movq %%rax, %[a2] ;\"\n \"movq %%rbx, %[b2] ;\"\n \"movq %%rcx, %[c2] ;\"\n \"movq %%rdx, %[d2] ;\"\n :\n [a1] \"=m\" (eax32), [b1] \"=m\" (ebx32), [c1] \"=m\" (ecx32), [d1] \"=m\" (edx32), \n [a2] \"=m\" (rax64), [b2] \"=m\" (rbx64), [c2] \"=m\" (rcx64), [d2] \"=m\" (rdx64)\n );\n\n printf(\"eax=%08x\\n\", eax32);\n printf(\"ebx=%08x\\n\", ebx32);\n printf(\"ecx=%08x\\n\", ecx32);\n printf(\"edx=%08x\\n\", edx32);\n\n printf(\"rax=%08x%08x\\n\", HIGH32(rax64), LOW32(rax64));\n printf(\"bax=%08x%08x\\n\", HIGH32(rbx64), LOW32(rbx64));\n printf(\"cax=%08x%08x\\n\", HIGH32(rcx64), LOW32(rcx64));\n printf(\"dax=%08x%08x\\n\", HIGH32(rdx64), LOW32(rdx64));\n\n uint64_t flags;\n\n asm (\n \"pushfq ;\"\n \"pop %[f1] ;\"\n :\n [f1] \"=m\" (flags)\n );\n\n printf(\"flags=%08x%08x\", HIGH32(flags), LOW32(flags));\n\n if(flags & (1 << 0)) // Carry\n printf(\" (C1\"); \n else\n printf(\" (C0\");\n\n if(flags & (1 << 2)) // Parity\n printf(\" P1\");\n else\n printf(\" P0\");\n\n if(flags & (1 << 4)) // Adjust\n printf(\" A1\");\n else\n printf(\" A0\");\n\n if(flags & (1 << 6)) // Zero\n printf(\" Z1\");\n else\n printf(\" Z0\");\n\n if(flags & (1 << 7)) // Sign\n printf(\" S1\");\n else\n printf(\" S0\");\n\n if(flags & (1 << 11)) // Overflow\n printf(\" O1)\\n\");\n else\n printf(\" O0)\\n\");\n\n return 0;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30626/" ]
275,778
<p>How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change. Thanks </p>
[ { "answer_id": 275785, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 3, "selected": true, "text": "public class RoadPanel extends JPanel {\n\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n // your drawing code here\n }\n}\n" }, { "answer_id": 275999, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 1, "selected": false, "text": "paintComponent() protected void paintComponent(Graphics g){\n super.paintComponent(g);\n if (drawRoad) {\n drawRoadMethod(g);\n }\n drawTheRest(g);\n}\n" }, { "answer_id": 276067, "author": "Ben Page", "author_id": 29924, "author_profile": "https://Stackoverflow.com/users/29924", "pm_score": 2, "selected": false, "text": "// Field that stores the image so it is always accessible\nprivate Image roadImage = null;\n// ...\n// ...\n// Override paintComponent Method\npublic void paintComponent(Graphics g){\n\n if (roadImage == null) {\n // Create the road image if it doesn't exist\n roadImage = createImage(width, height);\n // draw the roads to the image\n Graphics roadG = roadImage.getGraphics();\n // Use roadG like you would any other graphics\n // object to draw the roads to an image\n } else {\n // If the buffer image exists, you just need to draw it.\n // Draw the road buffer image\n g.drawImage(roadImage, 0, 0, null);\n }\n // Draw everything else ...\n // g.draw...\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4885/" ]
275,781
<p>Can anyone explain the difference between <code>Server.MapPath(".")</code>, <code>Server.MapPath("~")</code>, <code>Server.MapPath(@"\")</code> and <code>Server.MapPath("/")</code>?</p>
[ { "answer_id": 275791, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 11, "selected": true, "text": "Server.MapPath(\".\") Server.MapPath(\"..\") Server.MapPath(\"~\") Server.MapPath(\"/\") http://www.example.com/ C:\\Inetpub\\wwwroot\n D:\\WebApps\\shop\n Server.MapPath() http://www.example.com/shop/products/GetProduct.aspx?id=2342\n Server.MapPath(\".\") D:\\WebApps\\shop\\products Server.MapPath(\"..\") D:\\WebApps\\shop Server.MapPath(\"~\") D:\\WebApps\\shop Server.MapPath(\"/\") C:\\Inetpub\\wwwroot Server.MapPath(\"/shop\") D:\\WebApps\\shop / \\ MapPath() MapPath() @ Server.MapPath(null) Server.MapPath(\"\")" }, { "answer_id": 17616488, "author": "dav_i", "author_id": 1185053, "author_profile": "https://Stackoverflow.com/users/1185053", "pm_score": 5, "selected": false, "text": "MapPath(string virtualPath) public string MapPath(string virtualPath)\n{\n return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));\n}\n MapPath(VirtualPath virtualPath) MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) //...\nif (virtualPath == null)\n{\n virtualPath = VirtualPath.Create(\".\");\n}\n//...\n MapPath(null) MapPath(\"\") MapPath(\".\")" }, { "answer_id": 48148734, "author": "Vaibhav_Welcomes_You", "author_id": 7845508, "author_profile": "https://Stackoverflow.com/users/7845508", "pm_score": 2, "selected": false, "text": "Server.MapPath(\".\") aspx D:\\WebApplications\\Collage\\Departments Server.MapPath(\"..\") D:\\WebApplications\\Collage Server.MapPath(\"~\") D:\\WebApplications\\Collage Server.MapPath(\"/\") C:\\Inetpub\\wwwroot" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
275,795
<p>E.g.</p> <p>What's best out of these:</p> <pre><code>std::string f() {} </code></pre> <p>or </p> <pre><code>const std::string&amp; f() {} </code></pre>
[ { "answer_id": 275811, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 5, "selected": false, "text": "operator<< std::ostream & operator<<(std::ostream &out, const object &obj)\n{\n out << obj.data();\n return out;\n}\n operator= // move constructor\nobject(object && obj)\n{}\n object factory()\n{\n object obj;\n return std::move(obj);\n}\n std::move()" }, { "answer_id": 275819, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "return return string\nfoobar()\n{\n string result;\n // fill in \"result\"\n return result;\n}\n shared_ptr" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,810
<p>Is anyone using Castle MonoRail and ELMAH with success?</p> <p>We are using a number of Resuces to present users with friendly error messages, but if we do this the exceptions never get as far as ELMAH as the MonoRail rescue intercepts them.</p> <p>Ideally we want the user to see the rescue, but for the exception to be logged in ELMAH.</p> <p>Any ideas/pointers?</p> <p>Cheers,</p> <p>Jay.</p>
[ { "answer_id": 620066, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 3, "selected": true, "text": "public class ElmahExceptionHandler : AbstractExceptionHandler {\n public override void Process(IRailsEngineContext context) {\n ErrorSignal.FromCurrentContext().Raise(context.LastException);\n }\n}\n <monorail>\n <extensions>\n <extension type=\"Castle.MonoRail.Framework.Extensions.ExceptionChaining.ExceptionChainingExtension, Castle.MonoRail.Framework\"/>\n </extensions>\n <exception>\n <exceptionHandler type=\"MyNamespace.ElmahExceptionHandler, MyAssembly\"/>\n </exception>\n...\n</monorail>\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8542/" ]
275,824
<p>I am getting an 'Access to the path is denied" error message when running in debug mode. I have tried granting permissions to {MACHINENAME}\ASPNET and to NETWORK SERVICE but this hasn't made any difference. I have also tried &lt; impersonate = true /> using an admin account, this also made no difference. So how do I establish exactly which account is being used?</p>
[ { "answer_id": 275830, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 5, "selected": true, "text": " Dim User = System.Security.Principal.WindowsIdentity.GetCurrent.User\n Dim UserName = User.Translate(GetType(System.Security.Principal.NTAccount)).Value\n" }, { "answer_id": 275843, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "Response.Write(\"Windows Account which runs ASP.NET is: \" \n + Environment.Username);\n Response.Write(\"Windows Account which runs ASP.NET is: \" _\n & Environment.Username)\n Environment.UserName Page.User" }, { "answer_id": 1095515, "author": "Adam", "author_id": 33503, "author_profile": "https://Stackoverflow.com/users/33503", "pm_score": 4, "selected": false, "text": "var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;\nvar userName = user.Translate(typeof (System.Security.Principal.NTAccount));\n" }, { "answer_id": 15383216, "author": "manju", "author_id": 2165011, "author_profile": "https://Stackoverflow.com/users/2165011", "pm_score": -1, "selected": false, "text": "strint t=System.Web.Security.Membership.GetUser().UserName.ToString();\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
275,836
<p>I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?</p>
[ { "answer_id": 275876, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 7, "selected": true, "text": "public void RenderRainbowText(string Text, PictureBox pb)\n{\n // PictureBox needs an image to draw on\n pb.Image = new Bitmap(pb.Width, pb.Height);\n using (Graphics g = Graphics.FromImage(pb.Image))\n {\n // create all-white background for drawing\n SolidBrush brush = new SolidBrush(Color.White);\n g.FillRectangle(brush, 0, 0,\n pb.Image.Width, pb.Image.Height);\n // draw comma-delimited elements in multiple colors\n string[] chunks = Text.Split(',');\n brush = new SolidBrush(Color.Black);\n SolidBrush[] brushes = new SolidBrush[] { \n new SolidBrush(Color.Red),\n new SolidBrush(Color.Green),\n new SolidBrush(Color.Blue),\n new SolidBrush(Color.Purple) };\n float x = 0;\n for (int i = 0; i < chunks.Length; i++)\n {\n // draw text in whatever color\n g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);\n // measure text and advance x\n x += (g.MeasureString(chunks[i], pb.Font)).Width;\n // draw the comma back in, in black\n if (i < (chunks.Length - 1))\n {\n g.DrawString(\",\", pb.Font, brush, x, 0);\n x += (g.MeasureString(\",\", pb.Font)).Width;\n }\n }\n }\n}\n" }, { "answer_id": 420796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "lable.Text = \"This color is Red\" lable.Text = \"<span style='Color:Blue'>\" + \" The color is \" +\"</span>\" + \"<span style='Color:Red'>\"Red\"</span>\"\n" }, { "answer_id": 33027593, "author": "harry4516", "author_id": 3304035, "author_profile": "https://Stackoverflow.com/users/3304035", "pm_score": 2, "selected": false, "text": "private void rtb_AppendText(Font selfont, Color color, Color bcolor, \n string text, RichTextBox box)\n {\n // append the text to the RichTextBox control\n int start = box.TextLength;\n box.AppendText(text);\n int end = box.TextLength;\n\n // select the new text\n box.Select(start, end - start);\n // set the attributes of the new text\n box.SelectionColor = color;\n box.SelectionFont = selfont;\n box.SelectionBackColor = bcolor;\n // unselect\n box.Select(end, 0);\n\n // only required for multi line text to scroll to the end\n box.ScrollToCaret();\n }\n myRtb.Text = \"\";\nrtb_AppendText(new Font(\"Courier New\", (float)10), \n Color.Red, SystemColors.Control, \" my red text\", myRtb);\nrtb_AppendText(new Font(\"Courier New\", (float)10), \n Color.Blue, SystemColors.Control, \" followed by blue\", myRtb);\n" }, { "answer_id": 48922765, "author": "Padmaja Vudatha", "author_id": 6318527, "author_profile": "https://Stackoverflow.com/users/6318527", "pm_score": -1, "selected": false, "text": " labelId.Text = \"Successfully sent to\" + \"<a style='color:Blue'> \" + name + \"</a>\"; \n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8207/" ]
275,842
<p>Frequently, I've dug into apropos and docs looking for something like the following only to give up to get back to the task at hand:</p> <p>(repeat-last-command)</p> <p>do the last C- or M- command I just executed (to be rebound to a fn key)</p> <p>or sometimes the related: </p> <p>(describe-last-function)</p> <p>what keystroke did I just mistakenly issue, the effect of which I'd like to add to my bag of tricks. describe-key is close, but requires knowing what I typed. </p> <p>Am I simply asking too much from my trusty sidekick?</p>
[ { "answer_id": 275861, "author": "Emerick Rogul", "author_id": 33837, "author_profile": "https://Stackoverflow.com/users/33837", "pm_score": 7, "selected": false, "text": "repeat.el repeat.el" }, { "answer_id": 275862, "author": "echox", "author_id": 35915, "author_profile": "https://Stackoverflow.com/users/35915", "pm_score": 4, "selected": false, "text": "repeat" }, { "answer_id": 275875, "author": "cms", "author_id": 28532, "author_profile": "https://Stackoverflow.com/users/28532", "pm_score": 7, "selected": true, "text": "last-command (describe-function last-command) describe-last-function (defun describe-last-function() \n (interactive) \n (describe-function last-command))\n .emacs command-history" }, { "answer_id": 276557, "author": "quodlibetor", "author_id": 25616, "author_profile": "https://Stackoverflow.com/users/25616", "pm_score": 5, "selected": false, "text": "M-x view-lossage M-x command-history C-h w" }, { "answer_id": 624710, "author": "ashawley", "author_id": 73449, "author_profile": "https://Stackoverflow.com/users/73449", "pm_score": 6, "selected": false, "text": "repeat repeat-complex-command" }, { "answer_id": 1732831, "author": "Murali VP", "author_id": 179189, "author_profile": "https://Stackoverflow.com/users/179189", "pm_score": 3, "selected": false, "text": "C-x M-ESC runs the command repeat-complex-command\n which is an interactive compiled Lisp function in `simple.el'.\nIt is bound to <again>, <redo>, C-x M-:, C-x M-ESC.\n(repeat-complex-command ARG)\n\nEdit and re-evaluate last complex command, or ARGth from last.\nA complex command is one which used the minibuffer.\nThe command is placed in the minibuffer as a Lisp form for editing.\nThe result is executed, repeating the command as changed.\nIf the command has been changed or is not the most recent previous command\nit is added to the front of the command history.\nYou can use the minibuffer history commands M-n and M-p\nto get different commands to edit and resubmit.\n" }, { "answer_id": 8105886, "author": "sabof", "author_id": 735243, "author_profile": "https://Stackoverflow.com/users/735243", "pm_score": 2, "selected": false, "text": "(global-set-key \"\\C-r\" #'(lambda () (interactive)\n (eval (car command-history))))\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35911/" ]
275,853
<p>I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway.)</p> <p>The majority of the places where this goes wrong is a simple iteration of a std::vector, often this used to be an array in the past and has been changed to a std::vector later. So these loops generally look like this:</p> <pre><code>for (int i = 0; i &lt; someVector.size(); ++i) { /* do stuff */ } </code></pre> <p>Because this pattern is used so often, the amount of compiler warning spam about this comparison between signed and unsigned type tends to hide more useful warnings. Note that we definitely do not have vectors with more then INT_MAX elements, and note that until now we used two ways to fix compiler warning:</p> <pre><code>for (unsigned i = 0; i &lt; someVector.size(); ++i) { /*do stuff*/ } </code></pre> <p>This usually works but might silently break if the loop contains any code like 'if (i-1 >= 0) ...', etc.</p> <pre><code>for (int i = 0; i &lt; static_cast&lt;int&gt;(someVector.size()); ++i) { /*do stuff*/ } </code></pre> <p>This change does not have any side effects, but it does make the loop a lot less readable. (And it's more typing.)</p> <p>So I came up with the following idea:</p> <pre><code>template &lt;typename T&gt; struct vector : public std::vector&lt;T&gt; { typedef std::vector&lt;T&gt; base; int size() const { return base::size(); } int max_size() const { return base::max_size(); } int capacity() const { return base::capacity(); } vector() : base() {} vector(int n) : base(n) {} vector(int n, const T&amp; t) : base(n, t) {} vector(const base&amp; other) : base(other) {} }; template &lt;typename Key, typename Data&gt; struct map : public std::map&lt;Key, Data&gt; { typedef std::map&lt;Key, Data&gt; base; typedef typename base::key_compare key_compare; int size() const { return base::size(); } int max_size() const { return base::max_size(); } int erase(const Key&amp; k) { return base::erase(k); } int count(const Key&amp; k) { return base::count(k); } map() : base() {} map(const key_compare&amp; comp) : base(comp) {} template &lt;class InputIterator&gt; map(InputIterator f, InputIterator l) : base(f, l) {} template &lt;class InputIterator&gt; map(InputIterator f, InputIterator l, const key_compare&amp; comp) : base(f, l, comp) {} map(const base&amp; other) : base(other) {} }; // TODO: similar code for other container types </code></pre> <p>What you see is basically the STL classes with the methods which return size_type overridden to return just 'int'. The constructors are needed because these aren't inherited.</p> <p><strong>What would you think of this as a developer, if you'd see a solution like this in an existing codebase?</strong></p> <p>Would you think 'whaa, they're redefining the STL, what a huge WTF!', or would you think this is a nice simple solution to prevent bugs and increase readability. Or maybe you'd rather see we had spent (half) a day or so on changing all these loops to use std::vector&lt;>::iterator?</p> <p>(In particular if this solution was combined with banning the use of unsigned types for anything but raw data (e.g. unsigned char) and bit masks.)</p>
[ { "answer_id": 275873, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "'int' for(std::vector<int>::size_type i = 0; i < someVector.size(); i++) {\n /* ... */\n}\n for(std::vector<int>::size_type i = someVector.size() - 1; \n i != (std::vector<int>::size_type) -1; i--) {\n /* ... */\n}\n for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) {\n /* ... */\n}\n 'int' 23.1 p5 Container Requirements T::size_type T Container std::size_t i T::size_type std::size_t i (std::size_t)-1 someVector.size() == 0" }, { "answer_id": 275889, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": false, "text": "using size_t int vector<T>::size_type" }, { "answer_id": 275897, "author": "Lodle", "author_id": 23339, "author_profile": "https://Stackoverflow.com/users/23339", "pm_score": 0, "selected": false, "text": "vector.size() size_t int size_t" }, { "answer_id": 275951, "author": "Tim Weiler", "author_id": 33703, "author_profile": "https://Stackoverflow.com/users/33703", "pm_score": 2, "selected": false, "text": "for (auto i = someVector.begin();\n i != someVector.end();\n ++i)\n" }, { "answer_id": 18369772, "author": "Adrian McCarthy", "author_id": 1386054, "author_profile": "https://Stackoverflow.com/users/1386054", "pm_score": 2, "selected": false, "text": "for (auto it = begin(v); it != end(v); ++it) { ... }\nfor (const auto &x : v) { ... }\nstd::for_each(v.begin(), v.end(), ...);\n for (std::vector<T>::size_type i = 0; i < v.size(); ++i) { ... }\n std::size_t std::size_t std::vector<T>::size_type size_type std::size_t for (std::size_t i = v.size(); i-- > 0; ) { ... }\n std::size_t std::vector<T>::size_type std::size_t int #include <cassert>\n#include <cstddef>\n#include <limits>\n\ntemplate <typename ContainerType>\nconstexpr int size_as_int(const ContainerType &c) {\n const auto size = c.size(); // if no auto, use `typename ContainerType::size_type`\n assert(size <= static_cast<std::size_t>(std::numeric_limits<int>::max()));\n return static_cast<int>(size);\n}\n for (int i = 0; i < size_as_int(v); ++i) { ... }\n for (int i = size_as_int(v) - 1; i >= 0; --i) { ... }\n size_as_int" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
275,855
<p>I have a custom attribute which can be assigned to a class, <code>[FooAttribute]</code>. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have:</p> <pre><code>[FooAttribute] public class Bar { } </code></pre> <p>In the code for FooAttribute, how can I determine it was Bar class that added me? I'm not specifically looking for the Bar type, I just want to set a friendly name using reflection. e.g.</p> <pre><code>[FooAttribute(Name="MyFriendlyNameForThisClass")] public class Bar { } public class FooAttribute() { public FooAttribute() { // How do I get the target types name? (as a default) } } </code></pre>
[ { "answer_id": 275921, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "[DisplayName] [Foo(\"Some name\", typeof(Bar)]\n DisplayNameAttribute DisplayName" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
275,868
<p>How would I go about having a CMake buildsystem, which scans for source files now using <a href="http://www.cmake.org/cmake/help/cmake2.6docs.html#command:aux_source_directory" rel="noreferrer">AUX_SOURCE_DIRECTORY</a>, scan for header files too in the same directory, preferably using a similar command?</p> <p>I didn't find an easy way to do this in the documentation yet, so I now have a crappy bash script to post-process my (CodeBlocks) project file...</p>
[ { "answer_id": 309455, "author": "David", "author_id": 28275, "author_profile": "https://Stackoverflow.com/users/28275", "pm_score": 5, "selected": true, "text": "set(dir my_search_dir)\nfile (GLOB headers \"${dir}/*.h\")\nmessage(\"My headers: \" ${headers})\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
275,871
<p>Suppose I have code like this:</p> <pre><code>template&lt;class T, T initial_t&gt; class Bar { // something } </code></pre> <p>And then try to use it like this:</p> <pre><code>Bar&lt;Foo*, NULL&gt; foo_and_bar_whatever_it_means_; </code></pre> <p>GCC bails out with error (on the above line):</p> <blockquote> <p>could not convert template argument '0' to 'Foo*'</p> </blockquote> <p>I found this thread: <a href="http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html" rel="nofollow noreferrer">http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html</a>, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.</p>
[ { "answer_id": 275884, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "Bar<Foo*, (Foo*)NULL> foo_and_bar_whatever_it_means_;\n" }, { "answer_id": 277934, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "Bar<Foo, NULL> template <typename T, int dummy> class Bar; /* Declared but not defined */\ntemplate <typename T> class Bar <T,NULL> { /* Specialization */ };\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
275,878
<p>My client gets a <code>sec_error_unknown_issuer</code> error message when visiting <a href="https://mediant.ipmail.nl" rel="noreferrer">https://mediant.ipmail.nl</a> with Firefox. I can't reproduce the error myself. I installed FF on a Vista and a XP machine and had no problems. FF on Ubuntu also works fine.</p> <p>Does anyone get the same error and does anyone have some clues for me so I can tell my ISP to change some settings? The certificate is a so called wild-card SSL certificate that works for all subdomains (*.ipmail.nl). Was I wrong to pick the cheapest one?</p>
[ { "answer_id": 1026287, "author": "user126810", "author_id": 126810, "author_profile": "https://Stackoverflow.com/users/126810", "pm_score": 5, "selected": false, "text": "SSLCertificateChainFile /etc/ssl/crt/yourSERVERNAME.ca-bundle\n" }, { "answer_id": 14721055, "author": "vadipp", "author_id": 501399, "author_profile": "https://Stackoverflow.com/users/501399", "pm_score": 1, "selected": false, "text": "SSLCertificateChainFile" }, { "answer_id": 20267134, "author": "Cc65", "author_id": 2497291, "author_profile": "https://Stackoverflow.com/users/2497291", "pm_score": 3, "selected": false, "text": "$ cat www.example.com.crt bundle.crt > www.example.com.chained.crt\n server {\n listen 443 ssl;\n server_name www.example.com;\n ssl_certificate www.example.com.chained.crt;\n ssl_certificate_key www.example.com.key;\n ...\n}\n" }, { "answer_id": 23670019, "author": "Steven Lizarazo", "author_id": 589132, "author_profile": "https://Stackoverflow.com/users/589132", "pm_score": 1, "selected": false, "text": "SSLCertificateChainFile /path/COMODORSADomainValidationSecureServerCA.crt\n" }, { "answer_id": 24231709, "author": "lito", "author_id": 999525, "author_profile": "https://Stackoverflow.com/users/999525", "pm_score": 1, "selected": false, "text": "var privateKey = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');\nvar certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');\n\nfiles = [\"COMODORSADomainValidationSecureServerCA.crt\",\n \"COMODORSAAddTrustCA.crt\",\n \"AddTrustExternalCARoot.crt\"\n ];\n\nca = (function() {\n var _i, _len, _results;\n\n _results = [];\n for (_i = 0, _len = files.length; _i < _len; _i++) {\n file = files[_i];\n _results.push(fs.readFileSync(\"helpers/sslcert/\" + file));\n }\n return _results;\n})();\n\nvar credentials = {ca:ca, key: privateKey, cert: certificate};\n\n// process.env.PORT : Heroku Config environment\nvar port = process.env.PORT || 4000;\n\nvar app = express();\nvar server = http.createServer(app).listen(port, function() {\n console.log('Express HTTP server listening on port ' + server.address().port);\n});\nhttps.createServer(credentials, app).listen(3000, function() {\n console.log('Express HTTPS server listening on port ' + server.address().port);\n});\n\n// redirect all http requests to https\napp.use(function(req, res, next) {\n if(!req.secure) {\n return res.redirect(['https://mydomain.com', req.url].join(''));\n }\n next();\n});\n sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000\nsudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000\n ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep \"^ \"\ndepth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root\nverify error:num=19:self signed certificate in certificate chain\nverify return:0\n 0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com\n i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA\n 1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA\n i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority\n 2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority\n i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n 3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root\n Protocol : TLSv1.1\n Cipher : AES256-SHA\n Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD\n Session-ID-ctx:\n Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94\n Key-Arg : None\n PSK identity: None\n PSK identity hint: None\n SRP username: None\n TLS session ticket lifetime hint: 300 (seconds)\n TLS session ticket:\n 0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac |.6..MLG....p...\n 0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9 ..J&..........S.\n 0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79 .I.HD&.......s.y\n 0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32 .yj........R...2\n 0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce ........(.......\n 0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c .+.s...........L\n 0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e P\"`.....B.V..{..\n 0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f ..J......4...{./\n 0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da .3..H...i....R..\n 0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e .....=......N...\n Start Time: 140...549\n Timeout : 300 (sec)\n Verify return code: 19 (self signed certificate in certificate chain)\n" }, { "answer_id": 28257078, "author": "chmoder", "author_id": 3064462, "author_profile": "https://Stackoverflow.com/users/3064462", "pm_score": 1, "selected": false, "text": "cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt > YOURDOMAIN.ca-bundle" }, { "answer_id": 57954298, "author": "Meloman", "author_id": 2282880, "author_profile": "https://Stackoverflow.com/users/2282880", "pm_score": 0, "selected": false, "text": "SSLCACertificateFile /your/path/to/ssl_ca_certs.pem\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21238/" ]
275,885
<p>Although a DataTable is a memory hog, wouldn't a DataTable be the best choice to implement and IdentityMap if the set of objects is very large since retrieval time is O(1)?</p> <p><strong>Update</strong></p> <p>If I decide to use IDictionary, do I sacrifice speed when retrieving my objects?</p>
[ { "answer_id": 275915, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "Dictionary<,> SortedList<,> SortedDictionary<,> Dictionary<,> Collection<T> Dictionary<,> SortedList<,>" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19799/" ]
275,888
<p>Use HttpWebRequest to download web pages without key sensitive issues</p>
[ { "answer_id": 275905, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "WebClient using (WebClient wc = new WebClient())\n {\n string page1 = wc.DownloadString(\"http://en.wikipedia.org/wiki/Algeria\");\n\n string page2 = wc.DownloadString(\"http://en.wikipedia.org/wiki/%27Abadilah\");\n }\n" }, { "answer_id": 275938, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": "%27" }, { "answer_id": 1964299, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 1, "selected": false, "text": "client.Headers.Add(\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35917/" ]
275,891
<p>I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:</p> <pre><code>&lt;div id=&quot;menu&quot;&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;menuItem&quot;&gt;&lt;a href=#&gt;Bla&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.menuItem{ display:inline; height:30px; width:100px; background-color:#000; } </code></pre> <p>Javascript:</p> <pre><code>$('.menuItem').hover( function(){ $(this).css('background-color', '#F00'); }, function(){ $(this).css('background-color', '#000'); }); </code></pre> <p><strong>EDIT:</strong> I forgot to say that I had reasons not to want to use the css way.</p> <p>And I indeed forgot to check if the DOM was loaded.</p>
[ { "answer_id": 275912, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 7, "selected": true, "text": "$(function() {\n $('.menuItem').hover( function(){\n $(this).css('background-color', '#F00');\n },\n function(){\n $(this).css('background-color', '#000');\n });\n});\n" }, { "answer_id": 275919, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": false, "text": "<div> <div id=\"menu\">\n <a class=\"menuItem\" href=#>Bla</a>\n <a class=\"menuItem\" href=#>Bla</a>\n <a class=\"menuItem\" href=#>Bla</a>\n</div>\n .menuItem{\n height:30px;\n width:100px;\n background-color:#000;\n}\n.menuItem:hover {\n background-color:#F00;\n}\n" }, { "answer_id": 275932, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n <head>\n <title>jQuery Test</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\" />\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\" src=\"test.js\"></script>\n </head>\n <body>\n <div id=\"menu\">\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n <div class=\"menuItem\"><a href=#>Bla</a></div>\n </div>\n </body>\n</html>\n .menuItem\n{\n\n display: inline;\n height: 30px;\n width: 100px;\n background-color: #000;\n\n}\n $( function(){\n\n $('.menuItem').hover( function(){\n\n $(this).css('background-color', '#F00');\n\n },\n function(){\n\n $(this).css('background-color', '#000');\n\n });\n\n});\n" }, { "answer_id": 275936, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 5, "selected": false, "text": ".menuItem\n{\n display: inline;\n background-color: #000;\n\n /* width and height should not work on inline elements */\n /* if this works, your browser is doing the rendering */\n /* in quirks mode which will not be compatible with */\n /* other browsers - but this will not work on touch mobile devices like android */\n\n}\n.menuItem a:hover \n{\n background-color:#F00;\n}\n" }, { "answer_id": 275947, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 1, "selected": false, "text": "display: block ; .menuItem $(...).addClass(\"myclass\") $(...).removeClass(\"myclass\")" }, { "answer_id": 276025, "author": "Justin Lucente", "author_id": 35773, "author_profile": "https://Stackoverflow.com/users/35773", "pm_score": 3, "selected": false, "text": " <ul id=\"menu\">\n <li><a href=\"#\">Bla</a></li>\n <li><a href=\"#\">Bla</a></li>\n <li><a href=\"#\">Bla</a></li>\n </ul>\n #menu {\n margin: 0;\n}\n#menu li {\n float: left;\n list-style: none;\n margin: 0;\n}\n#menu li a {\n display: block;\n line-height:30px;\n width:100px;\n background-color:#000;\n}\n#menu li a:hover {\n background-color:#F00;\n}\n" }, { "answer_id": 276521, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 2, "selected": false, "text": "$(\".menuItem\").hover(function(){\n this.style.backgroundColor = \"#F00\";\n}, function() {\n this.style.backgroundColor = \"#000\";\n});\n" }, { "answer_id": 5018641, "author": "Greg", "author_id": 619965, "author_profile": "https://Stackoverflow.com/users/619965", "pm_score": 1, "selected": false, "text": "function changeAttr(attrName,changeThis,toThis){\n var mysheet=document.styleSheets[1], targetrule;\n var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;\n\n for (i=0; i<myrules.length; i++){\n if(myrules[i].selectorText.toLowerCase()==\".daymark:hover\"){ //find \"a:hover\" rule\n targetrule=myrules[i];\n break;\n }\n }\n switch(changeThis)\n {\n case \"height\":\n targetrule.style.height=toThis+\"px\";\n break;\n case \"width\":\n targetrule.style.width=toThis+\"px\";\n break;\n }\n\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35197/" ]
275,920
<p>I have been trying to set up my Beta 1 MVC app on IIS 6 and cannot get it to run correctly. I have added a Wildcard mapping to the .net isapi DLL as suggested in other blog posts but get the following error when I access the root of the website:</p> <pre><code>The incoming request does not match any route. .. [HttpException (0x80004005): The incoming request does not match any route.] System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +147 System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +36 System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4 HCD.Intranet.Web.Default.Page_Load(Object sender, EventArgs e) +81 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 </code></pre> <p>I am using the Default.aspx page supplied in the MVC template application that rewrites access to the root of the website properly.</p> <pre><code>public partial class Default : Page { public void Page_Load(object sender, System.EventArgs e) { HttpContext.Current.RewritePath(Request.ApplicationPath); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); } } </code></pre> <p>If I try and access a route within the application, such as /Project, I get the standard IIS 404 error page, not the .net error page.</p> <p>I tried adding the following line to my Web.config httpHandlers section:</p> <pre><code>&lt;add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; </code></pre> <p>This gave me a different error - the .net 404 error page.</p> <p>I added the following to my Global.asax, which did nothing:</p> <pre><code>protected void Application_BeginRequest(object sender, EventArgs e) { if (Context.Request.FilePath.Equals("/")) Context.RewritePath("Default.aspx"); } </code></pre> <p>I am using the following route configuration (uses the restful routing supplied by the MvcContrib project):</p> <pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); SimplyRestfulRouteHandler.BuildRoutes(routes); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre> <p>Any suggestions would be grealy received as I've exhausted all options for the time I have right now.</p> <p>Many thanks.</p>
[ { "answer_id": 275928, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 1, "selected": false, "text": "routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\nSimplyRestfulRouteHandler.BuildRoutes(routes);\n\nroutes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{id}\",\n new { controller = \"Home\", action = \"Index\", id = \"\" }\n);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31412/" ]
275,926
<p>We are developing a WCF based system. In the process we are trying to lock some data from being modified by more than one users. So we decided to have a data structure that will contain the necessary information for the locking logic to execute (by for example storing the ID of the locked objects)</p> <p>The problem we are having is persisting that data between sessions. Is there anyway we can avoid executing expensive database calls? I am not sure how can we do that in WCF since it can only persist data (in memory) during an open session.</p>
[ { "answer_id": 430569, "author": "Matt Davis", "author_id": 51170, "author_profile": "https://Stackoverflow.com/users/51170", "pm_score": 2, "selected": false, "text": "[ServiceContract]\npublic interface IMyService\n{\n [OperationContract]\n void Start(IPAddress address);\n}\n\n[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]\npublic class MyService : IMyService\n{\n private static readonly List<IPAddress> _addresses = new List<IPAddress>();\n public void Start(IPAddress address)\n {\n lock(((ICollection)_addresses).SyncRoot)\n {\n if (!_addresses.Contains(address)\n {\n // Open the connection here and then store the address.\n _addresses.Add(address);\n }\n }\n }\n}\n [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]\npublic class MyService : IMyService\n{ ... }\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28212/" ]
275,931
<p>I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element &mdash; ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?</p>
[ { "answer_id": 275953, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 4, "selected": false, "text": "jQuery.fn.flash = function( color, duration )\n{\n\n var current = this.css( 'color' );\n\n this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );\n this.animate( { color: current }, duration / 2 );\n\n}\n $( '#importantElement' ).flash( '255,0,0', 1000 );\n" }, { "answer_id": 1145719, "author": "curthipster", "author_id": 139262, "author_profile": "https://Stackoverflow.com/users/139262", "pm_score": 7, "selected": false, "text": "$(\"div\").stop().css(\"background-color\", \"#FFFF9C\")\n .animate({ backgroundColor: \"#FFFFFF\"}, 1500);\n var notLocked = true;\n$.fn.animateHighlight = function(highlightColor, duration) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n var originalBg = this.css(\"backgroundColor\");\n if (notLocked) {\n notLocked = false;\n this.stop().css(\"background-color\", highlightBg)\n .animate({backgroundColor: originalBg}, animateMs);\n setTimeout( function() { notLocked = true; }, animateMs);\n }\n};\n $(\"div\").animateHighlight(\"#dd0000\", 1000);\n" }, { "answer_id": 4672402, "author": "SooDesuNe", "author_id": 64709, "author_profile": "https://Stackoverflow.com/users/64709", "pm_score": 6, "selected": false, "text": "pulsate UI/Effects $(\"div\").click(function () {\n $(this).effect(\"pulsate\", { times:3 }, 2000);\n});\n" }, { "answer_id": 6602513, "author": "danlee", "author_id": 529733, "author_profile": "https://Stackoverflow.com/users/529733", "pm_score": 2, "selected": false, "text": "/* BEGIN jquery color */\n (function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(!fx.colorInit){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);fx.colorInit=true;}\n fx.elem.style[attr]=\"rgb(\"+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(\",\")+\")\";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)\n return color;if(result=/rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(color))\n return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(color))\n return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))\n return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))\n return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\\(0, 0, 0, 0\\)/.exec(color))\n return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()];}\n function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,\"body\"))\n break;attr=\"backgroundColor\";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};})(jQuery);\n /* END jquery color */\n\n\n /* BEGIN highlight */\n jQuery(function() {\n $.fn.highlight = function(options) {\n options = (options) ? options : {start_color:\"#ff0\",end_color:\"#fff\",delay:1500};\n $(this).each(function() {\n $(this).stop().css({\"background-color\":options.start_color}).animate({\"background-color\":options.end_color},options.delay);\n });\n }\n });\n /* END highlight */\n\n /* BEGIN highlight example */\n $(\".some-elements\").highlight();\n /* END highlight example */\n" }, { "answer_id": 7501372, "author": "RicardO", "author_id": 482526, "author_profile": "https://Stackoverflow.com/users/482526", "pm_score": 0, "selected": false, "text": "hlight($(\"#mydiv\")); function hlight(elementid){\n var hlight= \"#fe1414\"; //set the hightlight color\n var aspeed= 2000; //set animation speed\n var orig= \"#ffffff\"; // set default background color\n elementid.stop().css(\"background-color\", hlight).animate({backgroundColor: orig}, aspeed);\n}\n" }, { "answer_id": 7549125, "author": "bthemonarch", "author_id": 964126, "author_profile": "https://Stackoverflow.com/users/964126", "pm_score": 3, "selected": false, "text": "(\"#someElement\").show('highlight',{color: '#C8FB5E'},'fast');\n show() hide()" }, { "answer_id": 8621313, "author": "th3byrdm4n", "author_id": 362716, "author_profile": "https://Stackoverflow.com/users/362716", "pm_score": 1, "selected": false, "text": "// Adds a highlight effect\n$.fn.animateHighlight = function(highlightColor, duration) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n this.stop(true,true);\n var originalBg = this.css(\"backgroundColor\");\n return this.css(\"background-color\", highlightBg).animate({backgroundColor: originalBg}, animateMs);\n};\n" }, { "answer_id": 9097349, "author": "etlds", "author_id": 801790, "author_profile": "https://Stackoverflow.com/users/801790", "pm_score": 9, "selected": false, "text": "$(\"#someElement\").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);\n function go1() { $(\"#demo1\").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}\n\nfunction go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') } #demo1,\n#demo2 {\n text-align: center;\n font-family: Helvetica;\n background: IndianRed;\n height: 50px;\n line-height: 50px;\n width: 150px;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<button onclick=\"go1()\">Click Me</button>\n<div id='demo1'>My Element</div>\n<br>\n<button onclick=\"go2()\">Click Me</button> (from comment)\n<div id='demo2'>My Element</div>" }, { "answer_id": 11054415, "author": "Rob Evans", "author_id": 599020, "author_profile": "https://Stackoverflow.com/users/599020", "pm_score": 4, "selected": false, "text": "// Extend jquery with flashing for elements\n$.fn.flash = function(duration, iterations) {\n duration = duration || 1000; // Default to 1 second\n iterations = iterations || 1; // Default to 1 iteration\n var iterationDuration = Math.floor(duration / iterations);\n\n for (var i = 0; i < iterations; i++) {\n this.fadeOut(iterationDuration).fadeIn(iterationDuration);\n }\n return this;\n}\n $(\"#someElementId\").flash(1000, 4); // Flash 4 times over a period of 1 second\n" }, { "answer_id": 11174405, "author": "Gene Kelly", "author_id": 1477540, "author_profile": "https://Stackoverflow.com/users/1477540", "pm_score": 2, "selected": false, "text": "$('div').click(function() {\n $(this).css('background-color','#FFFFCC');\n setTimeout(function() { $(this).fadeOut('slow').fadeIn('slow'); } , 1000); \n setTimeout(function() { $(this).css('background-color','#FFFFFF'); } , 1000); \n});\n" }, { "answer_id": 11915453, "author": "vinay", "author_id": 428302, "author_profile": "https://Stackoverflow.com/users/428302", "pm_score": 7, "selected": false, "text": ".flash {\n -moz-animation: flash 1s ease-out;\n -moz-animation-iteration-count: 1;\n\n -webkit-animation: flash 1s ease-out;\n -webkit-animation-iteration-count: 1;\n\n -ms-animation: flash 1s ease-out;\n -ms-animation-iteration-count: 1;\n}\n\n@keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-webkit-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-moz-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n\n@-ms-keyframes flash {\n 0% { background-color: transparent; }\n 50% { background-color: #fbf8b2; }\n 100% { background-color: transparent; }\n}\n jQuery(selector).addClass(\"flash\");\n" }, { "answer_id": 12808148, "author": "sporkit", "author_id": 1732979, "author_profile": "https://Stackoverflow.com/users/1732979", "pm_score": 4, "selected": false, "text": "$('#district').css({opacity: 0});\n$('#district').animate({opacity: 1}, 700 );\n" }, { "answer_id": 13132816, "author": "Sankglory", "author_id": 1784582, "author_profile": "https://Stackoverflow.com/users/1784582", "pm_score": 2, "selected": false, "text": "var fIn = function() { $(this).fadeIn(300, fOut); };\nvar fOut = function() { $(this).fadeOut(300, fIn); };\n$('#element').fadeOut(300, fIn);\n var count = 3;\nvar fIn = function() { $(this).fadeIn(300, fOut); };\nvar fOut = function() { if (--count > 0) $(this).fadeOut(300, fIn); };\n$('#element').fadeOut(300, fIn);\n" }, { "answer_id": 14820860, "author": "rcd", "author_id": 642093, "author_profile": "https://Stackoverflow.com/users/642093", "pm_score": 3, "selected": false, "text": "$(\"div\").click(function () {\n $(this).effect(\"highlight\", {}, 3000);\n});\n" }, { "answer_id": 17780161, "author": "phillyd", "author_id": 2605557, "author_profile": "https://Stackoverflow.com/users/2605557", "pm_score": 3, "selected": false, "text": "$( \"#someDiv\" ).hide();\n\nsetInterval(function(){\n $( \"#someDiv\" ).fadeIn(1000).fadeOut(1000);\n},0)\n" }, { "answer_id": 18383287, "author": "Cauêh Q.", "author_id": 2707793, "author_profile": "https://Stackoverflow.com/users/2707793", "pm_score": 0, "selected": false, "text": "$.cssHooks.backgroundColor = {\nget: function(elem) {\n if (elem.currentStyle)\n var bg = elem.currentStyle[\"backgroundColor\"];\n else if (window.getComputedStyle)\n var bg = document.defaultView.getComputedStyle(elem,\n null).getPropertyValue(\"background-color\");\n if (bg.search(\"rgb\") == -1)\n return bg;\n else {\n bg = bg.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/);\n function hex(x) {\n return (\"0\" + parseInt(x).toString(16)).slice(-2);\n }\n return \"#\" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);\n }\n}\n}\nfunction blink(element,blinkTimes,color,originalColor){\n var changeToColor;\n if(blinkTimes === null || blinkTimes === undefined)\n blinkTimes = 1;\n if(!originalColor || originalColor === null || originalColor === undefined)\n originalColor = $(element).css(\"backgroundColor\");\n if(!color || color === null || color === undefined)\n color = \"#ffffdf\";\n if($(element).css(\"backgroundColor\") == color){\n changeToColor = originalColor;\n }else{\n changeToColor = color;\n --blinkTimes;\n }\n if(blinkTimes >= 0){\n $(element).animate({\n \"background-color\": changeToColor,\n }, {\n duration: 500,\n complete: function() {\n blink(element, blinkTimes, color, originalColor);\n return true;\n }\n });\n }else{\n $(element).removeAttr(\"style\");\n }\n return true;\n}\n" }, { "answer_id": 19083993, "author": "SoEzPz", "author_id": 2063096, "author_profile": "https://Stackoverflow.com/users/2063096", "pm_score": 3, "selected": false, "text": ".button_flash {\nbackground-color: #8DABFF !important;\n}//This is the color to change to. \n function flashIt(element, times, klass, delay){\n for (var i=0; i < times; i++){\n setTimeout(function(){\n $(element).toggleClass(klass);\n }, delay + (300 * i));\n };\n};\n\n//Then run the following code with either another delay to delay the original start, or\n// without another delay. I have provided both options below.\n\n//without a start delay just call\nflashIt('.info_status button', 10, 'button_flash', 500)\n\n//with a start delay just call\nsetTimeout(function(){\n flashIt('.info_status button', 10, 'button_flash', 500)\n}, 4700);\n// Just change the 4700 above to your liking for the start delay. In this case, \n//I need about five seconds before the flash started. \n" }, { "answer_id": 21761423, "author": "TonyP", "author_id": 3307168, "author_profile": "https://Stackoverflow.com/users/3307168", "pm_score": 3, "selected": false, "text": "$('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1)" }, { "answer_id": 22949247, "author": "Brad", "author_id": 1316159, "author_profile": "https://Stackoverflow.com/users/1316159", "pm_score": 1, "selected": false, "text": "$.fn.pulseNotify = function(color, duration) {\n\nvar This = $(this);\nconsole.log(This);\n\nvar pulseColor = color || \"#337\";\nvar pulseTime = duration || 3000;\nvar origBg = This.css(\"background-color\");\nvar stop = false;\n\nThis.bind('mouseover.flashPulse', function() {\n stop = true;\n This.stop();\n This.unbind('mouseover.flashPulse');\n This.css('background-color', origBg);\n})\n\nfunction loop() {\n console.log(This);\n if( !stop ) {\n This.animate({backgroundColor: pulseColor}, pulseTime/3, function(){\n This.animate({backgroundColor: origBg}, (pulseTime/3)*2, 'easeInCirc', loop);\n });\n }\n}\n\nloop();\n\nreturn This;\n}\n" }, { "answer_id": 23030299, "author": "Majal", "author_id": 2756066, "author_profile": "https://Stackoverflow.com/users/2756066", "pm_score": 6, "selected": false, "text": "<div style=\"background: #fff;\">\n <input type=\"submit\" class=\"element\" value=\"Whatever\" />\n</div>\n $('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });\n fadeTo() fadeTo()" }, { "answer_id": 23601338, "author": "Chloe", "author_id": 148844, "author_profile": "https://Stackoverflow.com/users/148844", "pm_score": 2, "selected": false, "text": "var flash = \"<div class='flash'></div>\";\n$(\".hello\").prepend(flash);\n$('.flash').show().fadeOut('slow');\n .flash {\n background-color: yellow;\n display: none;\n position: absolute;\n width: 100%;\n height: 100%;\n}\n <div class=\"hello\">Hello World!</div>\n" }, { "answer_id": 24655804, "author": "Duncan", "author_id": 3751876, "author_profile": "https://Stackoverflow.com/users/3751876", "pm_score": 1, "selected": false, "text": "$.fn.flash = function (highlightColor, duration, iterations) {\n var highlightBg = highlightColor || \"#FFFF9C\";\n var animateMs = duration || 1500;\n var originalBg = this.css('backgroundColor');\n var flashString = 'this';\n for (var i = 0; i < iterations; i++) {\n flashString = flashString + '.animate({ backgroundColor: highlightBg }, animateMs).animate({ backgroundColor: originalBg }, animateMs)';\n }\n eval(flashString);\n}\n $('<some element>').flash('#ffffc0', 1000, 3);\n" }, { "answer_id": 26268217, "author": "Xanarus", "author_id": 2525112, "author_profile": "https://Stackoverflow.com/users/2525112", "pm_score": 0, "selected": false, "text": "<script>\n\nsetInterval(function(){\n\n $(\".flash-it\").toggleClass(\"hide\");\n\n},700)\n</script>\n" }, { "answer_id": 27772902, "author": "sffc", "author_id": 1407170, "author_profile": "https://Stackoverflow.com/users/1407170", "pm_score": 1, "selected": false, "text": "$(element).removeClass(\"transition-duration-medium\");\n$(element).addClass(\"transition-duration-instant\");\n$(element).addClass(\"ko-flash\");\nsetTimeout(function () {\n $(element).removeClass(\"transition-duration-instant\");\n $(element).addClass(\"transition-duration-medium\");\n $(element).removeClass(\"ko-flash\");\n}, 500);\n .ko-flash {\n background-color: yellow;\n}\n.transition-duration-instant {\n -webkit-transition-duration: 0s;\n -moz-transition-duration: 0s;\n -o-transition-duration: 0s;\n transition-duration: 0s;\n}\n.transition-duration-medium {\n -webkit-transition-duration: 1s;\n -moz-transition-duration: 1s;\n -o-transition-duration: 1s;\n transition-duration: 1s;\n}\n" }, { "answer_id": 28297754, "author": "shanehoban", "author_id": 1173155, "author_profile": "https://Stackoverflow.com/users/1173155", "pm_score": 0, "selected": false, "text": "// shows the user an error has occurred\n$(\"#myDropdown\").fadeOut(700, function(){\n var text = $(this).find(\"option:selected\").text();\n var background = $(this).css( \"background\" );\n\n $(this).css('background', 'red');\n $(this).find(\"option:selected\").text(\"Error Occurred\");\n\n $(this).fadeIn(700, function(){\n $(this).fadeOut(700, function(){\n $(this).fadeIn(700, function(){\n $(this).fadeOut(700, function(){\n\n $(this).find(\"option:selected\").text(text);\n $(this).css(\"background\", background);\n $(this).fadeIn(700);\n })\n })\n })\n })\n});\n" }, { "answer_id": 28374194, "author": "maudulus", "author_id": 3216297, "author_profile": "https://Stackoverflow.com/users/3216297", "pm_score": 0, "selected": false, "text": ".flash{\n background: yellow;\n}\n\n.noflash{\n background: white;\n}\n <div class=\"noflash\"></div>\n var i = 0, howManyTimes = 7;\nfunction flashingDiv() {\n $('.flash').toggleClass(\"noFlash\")\n i++;\n if( i <= howManyTimes ){\n setTimeout( f, 200 );\n }\n}\nf();\n" }, { "answer_id": 28658753, "author": "NateS", "author_id": 187883, "author_profile": "https://Stackoverflow.com/users/187883", "pm_score": 1, "selected": false, "text": "// Flash linked to hash.\nvar hash = location.hash.substr(1);\nif (hash) {\n hash = $(\"#\" + hash);\n var color = hash.css(\"color\"), count = 1;\n function hashFade () {\n if (++count < 7) setTimeout(hashFade, 300);\n hash.css(\"color\", count % 2 ? color : \"red\");\n }\n hashFade();\n}\n" }, { "answer_id": 28980225, "author": "hakunin", "author_id": 517529, "author_profile": "https://Stackoverflow.com/users/517529", "pm_score": 4, "selected": false, "text": "var flash = function(elements) {\n var opacity = 100;\n var color = \"255, 255, 20\" // has to be in this format since we use rgba\n var interval = setInterval(function() {\n opacity -= 3;\n if (opacity <= 0) clearInterval(interval);\n $(elements).css({background: \"rgba(\"+color+\", \"+opacity/100+\")\"});\n }, 30)\n};\n flash($('#your-element'))\n" }, { "answer_id": 37345060, "author": "Roman Losev", "author_id": 1602375, "author_profile": "https://Stackoverflow.com/users/1602375", "pm_score": 2, "selected": false, "text": "$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);\n" }, { "answer_id": 38136251, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 3, "selected": false, "text": "function pulse() {\n $('.blink').fadeIn(300).fadeOut(500);\n}\nsetInterval(pulse, 1000);\n" }, { "answer_id": 39690011, "author": "Combine", "author_id": 2979938, "author_profile": "https://Stackoverflow.com/users/2979938", "pm_score": 2, "selected": false, "text": "$(\"#someElement\").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); \n" }, { "answer_id": 58101220, "author": "Chris", "author_id": 5786478, "author_profile": "https://Stackoverflow.com/users/5786478", "pm_score": 0, "selected": false, "text": "function blink(target, count, blinkspeed, bc) {\n let promises=[];\n const b=target.css(`background-color`);\n target.css(`background-color`, bc||b);\n for (i=1; i<count; i++) {\n const blink = target.fadeTo(blinkspeed||100, .3).fadeTo(blinkspeed||100, 1.0);\n promises.push(blink);\n }\n // wait for all the blinking to finish before changing the background color back\n $.when.apply(null, promises).done(function() {\n target.css(`background-color`, b);\n });\n promises=undefined;\n}\n blink($(`.alert-danger`), 5, 200, `yellow`);\n" }, { "answer_id": 59550553, "author": "R.Akhlaghi", "author_id": 2830315, "author_profile": "https://Stackoverflow.com/users/2830315", "pm_score": 0, "selected": false, "text": "var mili = 300\nfor (var i = 2; i < 8; i++) {\n if (i % 2 == 0) {\n $(\"#lblTransferCount\").fadeOut(mili)\n } else {\n $(\"#lblTransferCount\").fadeIn(mili)\n }\n}\n" }, { "answer_id": 73336149, "author": "teknopaul", "author_id": 870207, "author_profile": "https://Stackoverflow.com/users/870207", "pm_score": 0, "selected": false, "text": ".flash {\n animation: flash 0.5s ease-out;\n animation-iteration-count: 10;\n}\n@keyframes flash {\n 0% { opacity: 0.5; }\n 50% { opacity: 1.0; }\n 100% { opacity: 0.5; }\n}\n $(elem).addClass(\"flash\");\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
275,944
<p>I have the string </p> <pre><code>a.b.c.d </code></pre> <p>I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.</p> <p>(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).</p>
[ { "answer_id": 275969, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "split public static int countOccurrences(String haystack, char needle)\n{\n int count = 0;\n for (int i=0; i < haystack.length(); i++)\n {\n if (haystack.charAt(i) == needle)\n {\n count++;\n }\n }\n return count;\n}\n" }, { "answer_id": 275975, "author": "Yonatan Maman", "author_id": 20065, "author_profile": "https://Stackoverflow.com/users/20065", "pm_score": 4, "selected": false, "text": "public static int countOccurrences(String haystack, char needle, int i){\n return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}\n\n\nSystem.out.println(\"num of dots is \"+countOccurrences(\"a.b.c.d\",'.',0));\n" }, { "answer_id": 275979, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 5, "selected": false, "text": "String s = \"a.b.c.d\";\nint charCount = s.length() - s.replaceAll(\"\\\\.\", \"\").length();\n" }, { "answer_id": 276062, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": false, "text": "String s = \"a.b.c.d\";\nint charCount = s.replaceAll(\"[^.]\", \"\").length();\nprintln(charCount);\n" }, { "answer_id": 276218, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "length() charAt() public static int countOccurrences(String haystack, char needle)\n{\n return countOccurrences(haystack, needle, 0);\n}\n\nprivate static int countOccurrences(String haystack, char needle, int index)\n{\n if (index >= haystack.length())\n {\n return 0;\n }\n\n int contribution = haystack.charAt(index) == needle ? 1 : 0;\n return contribution + countOccurrences(haystack, needle, index+1);\n}\n" }, { "answer_id": 276246, "author": "tcurdt", "author_id": 33165, "author_profile": "https://Stackoverflow.com/users/33165", "pm_score": 2, "selected": false, "text": "public static int count( final String s, final char c ) {\n final char[] chars = s.toCharArray();\n int count = 0;\n for(int i=0; i<chars.length; i++) {\n if (chars[i] == c) {\n count++;\n }\n }\n return count;\n}\n" }, { "answer_id": 280995, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "public static int countOccurrences(CharSequeunce haystack, char needle) {\n return countOccurrences(haystack, needle, 0, haystack.length);\n}\n\n// Alternatively String.substring/subsequence use to be relatively efficient\n// on most Java library implementations, but isn't any more [2013].\nprivate static int countOccurrences(\n CharSequence haystack, char needle, int start, int end\n) {\n if (start == end) {\n return 0;\n } else if (start+1 == end) {\n return haystack.charAt(start) == needle ? 1 : 0;\n } else {\n int mid = (end+start)>>>1; // Watch for integer overflow...\n return\n countOccurrences(haystack, needle, start, mid) +\n countOccurrences(haystack, needle, mid, end);\n }\n}\n public static int countOccurrences(String haystack, char needle) {\n int count = 0;\n for (char c : haystack.toCharArray()) {\n if (c == needle) {\n ++count;\n }\n }\n return count;\n}\n" }, { "answer_id": 281044, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "int numDots = 0;\nif (s.charAt(0) == '.') {\n numDots++;\n}\n\nif (s.charAt(1) == '.') {\n numDots++;\n}\n\n\nif (s.charAt(2) == '.') {\n numDots++;\n}\n create a project\nposition = 0\nwhile (not end of string) {\n write check for character at position \"position\" (see above)\n}\nwrite code to output variable \"numDots\"\ncompile program\nhand in homework\ndo not think of the loop that your \"if\"s may have been optimized and compiled to\n" }, { "answer_id": 665744, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 2, "selected": false, "text": "public static int countOccurrences(String haystack, char needle)\n{\n return countOccurrences(haystack, needle, 0);\n}\n\nprivate static int countOccurrences(String haystack, char needle, int accumulator)\n{\n if (haystack.length() == 0) return accumulator;\n return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);\n}\n" }, { "answer_id": 1815572, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 5, "selected": false, "text": "String text = \"a.b.c.d\";\nint count = text.split(\"\\\\.\",-1).length-1;\n" }, { "answer_id": 1816989, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 11, "selected": true, "text": "int count = StringUtils.countMatches(\"a.b.c.d\", \".\");\n int occurance = StringUtils.countOccurrencesOf(\"a.b.c.d\", \".\");\n" }, { "answer_id": 3408400, "author": "BeeCreative", "author_id": 411112, "author_profile": "https://Stackoverflow.com/users/411112", "pm_score": 0, "selected": false, "text": "StringTokenizer stOR = new StringTokenizer(someExpression, \"||\");\nint orCount = stOR.countTokens()-1;\n" }, { "answer_id": 6267655, "author": "Hardest", "author_id": 696834, "author_profile": "https://Stackoverflow.com/users/696834", "pm_score": 2, "selected": false, "text": "public static int countOccurrences(String container, String content){\n int lastIndex, currIndex = 0, occurrences = 0;\n while(true) {\n lastIndex = container.indexOf(content, currIndex);\n if(lastIndex == -1) {\n break;\n }\n currIndex = lastIndex + content.length();\n occurrences++;\n }\n return occurrences;\n}\n" }, { "answer_id": 8910767, "author": "Andreas Wederbrand", "author_id": 296452, "author_profile": "https://Stackoverflow.com/users/296452", "pm_score": 10, "selected": false, "text": "int count = line.length() - line.replace(\".\", \"\").length();\n" }, { "answer_id": 9548397, "author": "Benny Neugebauer", "author_id": 451634, "author_profile": "https://Stackoverflow.com/users/451634", "pm_score": 3, "selected": false, "text": "public class CharacterCounter\n{\n\n public static int countOccurrences(String find, String string)\n {\n int count = 0;\n int indexOf = 0;\n\n while (indexOf > -1)\n {\n indexOf = string.indexOf(find, indexOf + 1);\n if (indexOf > -1)\n count++;\n }\n\n return count;\n }\n}\n int occurrences = CharacterCounter.countOccurrences(\"l\", \"Hello World.\");\nSystem.out.println(occurrences); // 3\n" }, { "answer_id": 13389003, "author": "kassim", "author_id": 1825248, "author_profile": "https://Stackoverflow.com/users/1825248", "pm_score": 2, "selected": false, "text": "import java.util.Scanner;\n\nclass apples {\n\n public static void main(String args[]) { \n Scanner bucky = new Scanner(System.in);\n String hello = bucky.nextLine();\n int charCount = hello.length() - hello.replaceAll(\"e\", \"\").length();\n System.out.println(charCount);\n }\n}// COUNTS NUMBER OF \"e\" CHAR´s within any string input\n" }, { "answer_id": 14280103, "author": "KannedFarU", "author_id": 1096126, "author_profile": "https://Stackoverflow.com/users/1096126", "pm_score": 4, "selected": false, "text": "public static int numberOf(String target, String content)\n{\n return (content.split(target).length - 1);\n}\n" }, { "answer_id": 16033843, "author": "0xCAFEBABE", "author_id": 494501, "author_profile": "https://Stackoverflow.com/users/494501", "pm_score": 4, "selected": false, "text": "for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))\n" }, { "answer_id": 16336288, "author": "Shubham", "author_id": 2170138, "author_profile": "https://Stackoverflow.com/users/2170138", "pm_score": 2, "selected": false, "text": "import java.util.Scanner;\n\npublic class CountingOccurences {\n\n public static void main(String[] args) {\n\n Scanner inp= new Scanner(System.in);\n String str;\n char ch;\n int count=0;\n\n System.out.println(\"Enter the string:\");\n str=inp.nextLine();\n\n while(str.length()>0)\n {\n ch=str.charAt(0);\n int i=0;\n\n while(str.charAt(i)==ch)\n {\n count =count+i;\n i++;\n }\n\n str.substring(count);\n System.out.println(ch);\n System.out.println(count);\n }\n\n }\n}\n" }, { "answer_id": 17566410, "author": "Adrian", "author_id": 2169691, "author_profile": "https://Stackoverflow.com/users/2169691", "pm_score": 1, "selected": false, "text": " public static int countSubstring(String subStr, String str) {\n\n int count = 0;\n for (int i = 0; i < str.length(); i++) {\n if (str.substring(i).startsWith(subStr)) {\n count++;\n }\n }\n return count;\n}\n" }, { "answer_id": 18641094, "author": "Sergio", "author_id": 2751435, "author_profile": "https://Stackoverflow.com/users/2751435", "pm_score": 1, "selected": false, "text": "public static int numberOf(String str,int c) {\n int res=0;\n if(str==null)\n return res;\n for(int i=0;i<str.length();i++)\n if(c==str.charAt(i))\n res++;\n return res;\n}\n" }, { "answer_id": 19315079, "author": "fubo", "author_id": 1315444, "author_profile": "https://Stackoverflow.com/users/1315444", "pm_score": 5, "selected": false, "text": "String s = \"a.b.c.d\";\nlong result = s.chars().filter(ch -> ch == '.').count();\n" }, { "answer_id": 19962695, "author": "mlchen850622", "author_id": 2808744, "author_profile": "https://Stackoverflow.com/users/2808744", "pm_score": 5, "selected": false, "text": "int count = \"a.b.c.d\".length() - \"a.b.c.d\".replace(\".\", \"\").length();\n" }, { "answer_id": 23517296, "author": "Shaban", "author_id": 3285421, "author_profile": "https://Stackoverflow.com/users/3285421", "pm_score": 2, "selected": false, "text": "int count = (line.length() - line.replace(\"str\", \"\").length())/\"str\".length();\n" }, { "answer_id": 23874504, "author": "Alexis C.", "author_id": 1587046, "author_profile": "https://Stackoverflow.com/users/1587046", "pm_score": 4, "selected": false, "text": "public static long countOccurences(String s, char c){\n return s.chars().filter(ch -> ch == c).count();\n}\n\ncountOccurences(\"a.b.c.d\", '.'); //3\ncountOccurences(\"hello world\", 'l'); //3\n" }, { "answer_id": 23962604, "author": "Arnab sen", "author_id": 3692714, "author_profile": "https://Stackoverflow.com/users/3692714", "pm_score": 0, "selected": false, "text": "import java.lang.*;\nimport java.util.*;\n\nclass longestSubstr{\n\npublic static void main(String[] args){\n String s=\"ABDEFGABEF\";\n\n\n int ans=calc(s);\n\n System.out.println(\"Max nonrepeating seq= \"+ans);\n\n}\n\npublic static int calc(String s)\n{//s.s\n int n=s.length();\n int max=1;\n if(n==1)\n return 1;\n if(n==2)\n {\n if(s.charAt(0)==s.charAt(1)) return 1;\n else return 2;\n\n\n }\n String s1=s;\n String a=s.charAt(n-1)+\"\";\n s1=s1.replace(a,\"\");\n // System.out.println(s+\" \"+(n-2)+\" \"+s.substring(0,n-1));\n max=Math.max(calc(s.substring(0,n-1)),(calc(s1)+1));\n\n\nreturn max;\n}\n\n\n}\n\n\n</i>\n" }, { "answer_id": 25584803, "author": "Maarten Bodewes", "author_id": 589259, "author_profile": "https://Stackoverflow.com/users/589259", "pm_score": 1, "selected": false, "text": "public static int countOccurances(char c, String input) {\n return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);\n}\n\npublic static int countOccurances(String s, String input) {\n return countOccurancesOfPattern(Pattern.quote(s), input);\n}\n\npublic static int countOccurancesOfPattern(String pattern, String input) {\n Matcher m = Pattern.compile(pattern).matcher(input);\n int count = 0;\n while (m.find()) {\n count++;\n }\n return count;\n}\n" }, { "answer_id": 27059883, "author": "Narendra", "author_id": 4278285, "author_profile": "https://Stackoverflow.com/users/4278285", "pm_score": -1, "selected": false, "text": "public class OccurencesInString { public static void main(String[] args) { String str = \"NARENDRA AMILINENI\"; HashMap occur = new HashMap(); int count =0; String key = null; for(int i=0;i<str.length()-1;i++){ key = String.valueOf(str.charAt(i)); if(occur.containsKey(key)){ count = (Integer)occur.get(key); occur.put(key,++count); }else{ occur.put(key,1); } } System.out.println(occur); } }\n" }, { "answer_id": 29150794, "author": "The_Fresher", "author_id": 3357185, "author_profile": "https://Stackoverflow.com/users/3357185", "pm_score": -1, "selected": false, "text": "public class CharacterCount {\npublic static void main(String args[])\n{\n String message=\"hello how are you\";\n char[] array=message.toCharArray();\n int a=0;\n int b=0;\n int c=0;\n int d=0;\n int e=0;\n int f=0;\n int g=0;\n int h=0;\n int i=0;\n int space=0;\n int j=0;\n int k=0;\n int l=0;\n int m=0;\n int n=0;\n int o=0;\n int p=0;\n int q=0;\n int r=0;\n int s=0;\n int t=0;\n int u=0;\n int v=0;\n int w=0;\n int x=0;\n int y=0;\n int z=0;\n\n\n for(char element:array)\n {\n switch(element)\n {\n case 'a':\n a++;\n break;\n case 'b':\n b++;\n break;\n case 'c':c++;\n break;\n\n case 'd':d++;\n break;\n case 'e':e++;\n break;\n case 'f':f++;\n break;\n\n case 'g':g++;\n break;\n case 'h':\n h++;\n break;\n case 'i':i++;\n break;\n case 'j':j++;\n break;\n case 'k':k++;\n break;\n case 'l':l++;\n break;\n case 'm':m++;\n break;\n case 'n':m++;\n break;\n case 'o':o++;\n break;\n case 'p':p++;\n break;\n case 'q':q++;\n break;\n case 'r':r++;\n break;\n case 's':s++;\n break;\n case 't':t++;\n break;\n case 'u':u++;\n break;\n case 'v':v++;\n break;\n case 'w':w++;\n break;\n case 'x':x++;\n break;\n case 'y':y++;\n break;\n case 'z':z++;\n break;\n case ' ':space++;\n break;\n default :break;\n }\n }\n System.out.println(\"A \"+a+\" B \"+ b +\" C \"+c+\" D \"+d+\" E \"+e+\" F \"+f+\" G \"+g+\" H \"+h);\n System.out.println(\"I \"+i+\" J \"+j+\" K \"+k+\" L \"+l+\" M \"+m+\" N \"+n+\" O \"+o+\" P \"+p);\n System.out.println(\"Q \"+q+\" R \"+r+\" S \"+s+\" T \"+t+\" U \"+u+\" V \"+v+\" W \"+w+\" X \"+x+\" Y \"+y+\" Z \"+z);\n System.out.println(\"SPACE \"+space);\n}\n" }, { "answer_id": 32294112, "author": "Bismaya Kumar Biswal", "author_id": 4793394, "author_profile": "https://Stackoverflow.com/users/4793394", "pm_score": 0, "selected": false, "text": "package com.java.test;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class TestCuntstring {\n\n public static void main(String[] args) {\n\n String name = \"Bissssmmayaa\";\n char[] ar = new char[name.length()];\n for (int i = 0; i < name.length(); i++) {\n ar[i] = name.charAt(i);\n }\n Map<Character, String> map=new HashMap<Character, String>();\n for (int i = 0; i < ar.length; i++) {\n int count=0;\n for (int j = 0; j < ar.length; j++) {\n if(ar[i]==ar[j]){\n count++;\n }\n }\n map.put(ar[i], count+\" no of times\");\n }\n System.out.println(map);\n }\n\n}\n" }, { "answer_id": 34801971, "author": "Christoph Zabinski", "author_id": 1787945, "author_profile": "https://Stackoverflow.com/users/1787945", "pm_score": 2, "selected": false, "text": "\"a.b.c.\".count(\".\")\n" }, { "answer_id": 35242882, "author": "Slava Vedenin", "author_id": 4318868, "author_profile": "https://Stackoverflow.com/users/4318868", "pm_score": 8, "selected": false, "text": " String testString = \"a.b.c.d\";\n int apache = StringUtils.countMatches(testString, \".\");\nSystem.out.println(\"apache = \" + apache);\n int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, \".\");\nSystem.out.println(\"spring = \" + spring);\n int replace = testString.length() - testString.replace(\".\", \"\").length();\nSystem.out.println(\"replace = \" + replace);\n int replaceAll = testString.replaceAll(\"[^.]\", \"\").length();\nSystem.out.println(\"replaceAll = \" + replaceAll);\n int replaceAllCase2 = testString.length() - testString.replaceAll(\"\\\\.\", \"\").length();\nSystem.out.println(\"replaceAll (second case) = \" + replaceAllCase2);\n int split = testString.split(\"\\\\.\",-1).length-1;\nSystem.out.println(\"split = \" + split);\n long java8 = testString.chars().filter(ch -> ch =='.').count();\nSystem.out.println(\"java8 = \" + java8);\n long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();\nSystem.out.println(\"java8 (second case) = \" + java8Case2);\n int stringTokenizer = new StringTokenizer(\" \" +testString + \" \", \".\").countTokens()-1;\nSystem.out.println(\"stringTokenizer = \" + stringTokenizer);\n 0.010 0.351 Benchmark Mode Cnt Score Error Units\n1. countMatches avgt 5 0.010 ± 0.001 us/op\n2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op\n3. stringTokenizer avgt 5 0.028 ± 0.002 us/op\n4. java8_1 avgt 5 0.077 ± 0.005 us/op\n5. java8_2 avgt 5 0.078 ± 0.003 us/op\n6. split avgt 5 0.137 ± 0.009 us/op\n7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op\n8. replace avgt 5 0.303 ± 0.034 us/op\n9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op\n" }, { "answer_id": 37317254, "author": "user3322553", "author_id": 3322553, "author_profile": "https://Stackoverflow.com/users/3322553", "pm_score": 3, "selected": false, "text": "split() int noOccurence=string.split(\"#\",-1).length-1;\n" }, { "answer_id": 43627604, "author": "Ashish Jaiswal", "author_id": 7316914, "author_profile": "https://Stackoverflow.com/users/7316914", "pm_score": 0, "selected": false, "text": "public class Count_Characters_In_String{\n\n public static void main(String []args){\n\n String s = \"SELENIUM\";\n System.out.println(s);\n int counter;\n\n String g = \"\";\n\n for( int i=0; i<s.length(); i++ ) { \n\n if(g.indexOf(s.charAt(i)) == - 1){\n g=g+s.charAt(i); \n }\n\n }\n System.out.println(g + \" \");\n\n\n\n for( int i=0; i<g.length(); i++ ) { \n System.out.print(\",\");\n\n System.out.print(s.charAt(i)+ \" : \");\n counter=0; \n for( int j=0; j<s.length(); j++ ) { \n\n if( g.charAt(i) == s.charAt(j) ) {\n counter=counter+1;\n\n } \n\n }\n System.out.print(counter); \n }\n }\n}\n" }, { "answer_id": 44020468, "author": "Amar Magar", "author_id": 5667861, "author_profile": "https://Stackoverflow.com/users/5667861", "pm_score": 3, "selected": false, "text": "public static void main(String[] args) {\n String string = \"a.b.c.d\";\n String []splitArray = string.split(\"\\\\.\",-1);\n System.out.println(\"No of . chars is : \" + (splitArray.length-1));\n}\n" }, { "answer_id": 44160784, "author": "gil.fernandes", "author_id": 2735286, "author_profile": "https://Stackoverflow.com/users/2735286", "pm_score": 3, "selected": false, "text": "int res = \"abdsd3$asda$asasdd$sadas\".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));\nSystem.out.println(res);\n 3\n" }, { "answer_id": 44713830, "author": "Donald Raab", "author_id": 1570415, "author_profile": "https://Stackoverflow.com/users/1570415", "pm_score": 2, "selected": false, "text": "int count = Strings.asChars(\"a.b.c.d\").count(c -> c == '.');\n CharBag CharBag bag = Strings.asChars(\"a.b.c.d\").toBag();\nint count = bag.occurrencesOf('.');\n" }, { "answer_id": 45393057, "author": "Perry Anderson", "author_id": 8387219, "author_profile": "https://Stackoverflow.com/users/8387219", "pm_score": 0, "selected": false, "text": "String[] parts = text.split(\".\");\nint occurances = parts.length - 1;\n\n\" It's a great day at O.S.G. Dallas! \"\n -- Famous Last Words\n" }, { "answer_id": 51640872, "author": "Baibhav Ghimire", "author_id": 4941710, "author_profile": "https://Stackoverflow.com/users/4941710", "pm_score": -1, "selected": false, "text": "public static void getCharacter(String str){\n\n int count[]= new int[256];\n\n for(int i=0;i<str.length(); i++){\n\n\n count[str.charAt(i)]++;\n\n }\n System.out.println(\"The ascii values are:\"+ Arrays.toString(count));\n\n //Now display wht character is repeated how many times\n\n for (int i = 0; i < count.length; i++) {\n if (count[i] > 0)\n System.out.println(\"Number of \" + (char) i + \": \" + count[i]);\n }\n\n\n }\n}\n" }, { "answer_id": 57606966, "author": "Niklas Lyszio", "author_id": 11860105, "author_profile": "https://Stackoverflow.com/users/11860105", "pm_score": 0, "selected": false, "text": "private static void countChars(String string) {\n HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));\n hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + \":\" + i));\n}\n" }, { "answer_id": 58210549, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 0, "selected": false, "text": "String s = \"a.b.c.d\";\nint count = s.length() - deleteChars.apply( s, \".\" ).length(); // 3\n b c . int count = s.length() - deleteChars.apply( s, \"bc.\" ).length(); // 5\n" }, { "answer_id": 59332508, "author": "Saharcasm", "author_id": 5559138, "author_profile": "https://Stackoverflow.com/users/5559138", "pm_score": 3, "selected": false, "text": "int getOccurences(String characters, String string) {\n String[] words = string.split(characters);\n return words.length - 1;\n} getOccurences(\"o\", \"something about a quick brown fox\");" }, { "answer_id": 62514326, "author": "IonKat", "author_id": 12480986, "author_profile": "https://Stackoverflow.com/users/12480986", "pm_score": 2, "selected": false, "text": " private long countOccurrences(String occurrences, char findChar){\n return occurrences.chars().filter( x -> {\n return x == findChar;\n }).count();\n }\n" }, { "answer_id": 65026287, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 0, "selected": false, "text": "Map<Character,Long> counts = \"a.b.c.d\".codePoints().boxed().collect(\n groupingBy( t -> (char)(int)t, counting() ) );\n {a=1, b=1, c=1, d=1, .=3} '.' counts.get( '.' )" }, { "answer_id": 67026485, "author": "Murali", "author_id": 1759028, "author_profile": "https://Stackoverflow.com/users/1759028", "pm_score": 0, "selected": false, "text": "import java.util.HashMap;\n //The code by muralidharan \n public class FindChars {\n \n public static void main(String[] args) {\n \n findchars(\"rererereerererererererere\");\n }\n \n public static void findchars(String s){\n \n HashMap<Character,Integer> k=new HashMap<Character,Integer>();\n for(int i=0;i<s.length();i++){\n if(k.containsKey(s.charAt(i))){\n Integer v =k.get(s.charAt(i));\n k.put(s.charAt(i), v+1);\n }else{\n k.put(s.charAt(i), 1);\n }\n \n }\n System.out.println(k);\n \n }\n \n }\n findchars(\"The world is beautiful and $#$%%%%%%@@@@ is worst\");\n" }, { "answer_id": 68966764, "author": "hadialaoui", "author_id": 8709853, "author_profile": "https://Stackoverflow.com/users/8709853", "pm_score": 0, "selected": false, "text": " public static String encodeMap(String plainText){\n \n Map<Character,Integer> mapResult=new LinkedHashMap<Character,Integer>();\n String result = \"\";\n for(int i=0;i<plainText.length();i++){\n if(mapResult.containsKey(plainText.charAt(i))){\n Integer v =mapResult.get(plainText.charAt(i));\n mapResult.put(plainText.charAt(i), v+1);\n }else{\n mapResult.put(plainText.charAt(i), 1);\n }\n }\n \n for(Map.Entry<Character, Integer> t : mapResult.entrySet()) {\n result += String.valueOf(t.getKey())+t.getValue();\n }\n \n return result;\n \n }\n\n public static void main(String args[]) {\n String plainText = \"aaavvfff\";\n System.out.println(encodeMap(plainText)); //a3v2f3 \n }\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343/" ]
275,957
<p>I am working on a background program that will be running for a long time, and I have a external logging program (<a href="http://www.gurock.com/products/smartinspect/" rel="noreferrer">SmartInspect</a>) that I want to feed with some values periodically, to monitor it in realtime when debugging.</p> <p>I know I can simply fire up multiple programs, like the Task Manager, or IARSN TaskInfo, but I'd like to keep everything in my own program for this, as I also wants to add some simple rules like if the program uses more than X% CPU, flag this in the log.</p> <p>I have a background thread that periodically feeds some statistics to SmartInspect, like memory consumption, working set, etc.</p> <p>Is it possible for this thread to get a reasonably accurate measure of how much of the computer's CPU resources it consumes? The main program is a single-threaded application (apart from the watchdog thread that logs statistics) so if a technique is limited to <em>how much does a single thread use</em> then that would be good too.</p> <p>I found some entries related to something called <em>rusage</em> for Linux and C. Is there something similar I can use for this?</p> <hr> <p><strong>Edit:</strong> Ok, I tried the performance counter way, but it added quite a lot of GC-data each time called, so the graph for memory usage and garbage collection skyrocketed. I guess I'll just leave this part out for now.</p>
[ { "answer_id": 275963, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 3, "selected": false, "text": "System.Diagnostics.PerformanceCounter perfmon.exe" }, { "answer_id": 276181, "author": "sundar venugopal", "author_id": 32670, "author_profile": "https://Stackoverflow.com/users/32670", "pm_score": 2, "selected": false, "text": "Win32_PerfFormattedData_PerfProc_Process oConn.Username = \"JohnDoe\";\noConn.Password = \"JohnsPass\";\n\nSystem.Management.ManagementScope oMs = new System.Management.ManagementScope(\"\\\\MachineX\", oConn); \n\n//get Fixed disk stats\nSystem.Management.ObjectQuery oQuery = new System.Management.ObjectQuery(\"select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3\");\n\n//Execute the query \nManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,oQuery);\n\n//Get the results\nManagementObjectCollection oReturnCollection = oSearcher.Get(); \n\n//loop through found drives and write out info\nforeach( ManagementObject oReturn in oReturnCollection )\n{\n // Disk name\n Console.WriteLine(\"Name : \" + oReturn[\"Name\"].ToString());\n // Free Space in bytes\n Console.WriteLine(\"FreeSpace: \" + oReturn[\"FreeSpace\"].ToString());\n // Size in bytes\n Console.WriteLine(\"Size: \" + oReturn[\"Size\"].ToString());\n} \n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
275,958
<p>I have a list of say 100 unsorted items. Each item belongs to a group. The group the item belongs to is simply a member of the item class.</p> <p>Using C/C++ I'm looking for the most efficient way of scanning through the list of items, checking which group they are in and printing the item to the screen. Here's the catch though. Once an item from a group has been printed to the screen, I don't want to print any more items belonging to that group.</p> <p>I'm using a pre STL compiler and the size of the executable is critical so I don't want to start defining my own Hash classes.</p>
[ { "answer_id": 275961, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 1, "selected": false, "text": "#include <unordered_map>\n#include <string>\n#include <iostream>\n\nstd::string getGroupForNumber( int num )\n{\n//\n}\n\nint main()\n{\n typedef std::tr1::unordered_map< std::string, bool > hashmap;\n hashmap groupsPrinted;\n\n for( int i = 0 ; i < 100 ; ++i ) {\n if ( groupsPrinted[ getGroupForNumber( i ) ] == false ) {\n groupsPrinted[ getGroupForNumber( i ) ] = true;\n std::cout << i << std::endl;\n }\n }\n return 0;\n}\n" }, { "answer_id": 276018, "author": "Tamir Shomer", "author_id": 35898, "author_profile": "https://Stackoverflow.com/users/35898", "pm_score": 1, "selected": false, "text": " typedef struct node{\n void *item; /* this is your item */\n node *next; \n } node_t;\n\n typedef struct {\n node_t *my_group;\n int used;\n } group_t;\n\n static group_t my_items[NUM_OF_GROUPS]; /* this is your ordered by groups list.*/\n typedef struct group{\n node_t *my_group;\n group *next_free;\n} group_t;\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7129/" ]
275,994
<p>I need to move backwards through an array, so I have code like this:</p> <pre><code>for (int i = myArray.Length - 1; i &gt;= 0; i--) { // Do something myArray[i] = 42; } </code></pre> <p>Is there a better way of doing this?</p> <p>Update: I was hoping that maybe C# had some built-in mechanism for this like:</p> <pre><code>foreachbackwards (int i in myArray) { // so easy } </code></pre>
[ { "answer_id": 275996, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "std::vector for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)\n // blah\n i >= 0" }, { "answer_id": 276001, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "uint pos = arr.Length;\nfor(uint i = 0; i < arr.Length ; i++)\n{\n arr[--pos] = 42;\n}\n" }, { "answer_id": 276003, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < myArray.Length; i++)\n{\n int iBackwards = myArray.Length - 1 - i; // ugh\n myArray[iBackwards] = 666;\n}\n" }, { "answer_id": 276044, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 4, "selected": false, "text": "foreach(var item in myArray.Reverse())\n{\n // do something\n}\n" }, { "answer_id": 276053, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "std::vector std::reverse_iterator: for(std::vector<T>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it) {\n /* std::cout << *it; ... */\n}\n for(std::vector<int>::size_type i = someVector.size() - 1; \n i != (std::vector<int>::size_type) -1; i--) {\n /* std::cout << someVector[i]; ... */\n}\n -N (2 ^ BIT_SIZE) -N for(std::reverse_iterator<element_type*> it(a + sizeof a / sizeof *a), itb(a); \n it != itb; \n ++it) {\n /* std::cout << *it; .... */\n}\n for(std::size_t i = (sizeof a / sizeof *a) - 1; i != (std::size_t) -1; i--) {\n /* std::cout << a[i]; ... */\n}\n template<typename T, std::size_t N> char (& array_size(T(&)[N]) )[N];\n char sizeof sizeof (sizeof a / sizeof *a)\n (sizeof array_size(a))\n" }, { "answer_id": 276056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "for (int i = myArray.Length; i --> 0; )\n{\n //do something\n}\n" }, { "answer_id": 276084, "author": "domain.dot.net team", "author_id": 31626, "author_profile": "https://Stackoverflow.com/users/31626", "pm_score": -1, "selected": false, "text": "public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)\n {\n foreach (var contextItem in sequenceToReverse.Reverse())\n doForEachReversed(contextItem);\n }\n /// <summary>\n /// Most importantly uses yield command for efficiency\n /// </summary>\n /// <param name=\"enumerableInstance\"></param>\n /// <returns></returns>\n public static IEnumerable ToReveresed(IEnumerable enumerableInstance)\n {\n if (enumerableInstance == null)\n {\n throw new ArgumentNullException(\"enumerableInstance\");\n }\n\n // First we need to move forwarad and create a temp\n // copy of a type that allows us to move backwards\n // We can use ArrayList for this as the concrete\n // type\n\n IList reversedEnumerable = new ArrayList();\n IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();\n\n while (tempEnumerator.MoveNext())\n {\n reversedEnumerable.Add(tempEnumerator.Current);\n }\n\n // Now we do the standard reverse over this using yield to return\n // the result\n // NOTE: This is an immutable result by design. That is \n // a design goal for this simple question as well as most other set related \n // requirements, which is why Linq results are immutable for example\n // In fact this is foundational code to understand Linq\n\n for (var i = reversedEnumerable.Count - 1; i >= 0; i--)\n {\n yield return reversedEnumerable[i];\n }\n }\n}\n\n\n\npublic static class ExtensionMethods\n{\n\n public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)\n {\n return ReverserService.ToReveresed(enumerableInstance);\n }\n }\n /// <summary>\n /// .NET 1.1 CLR\n /// </summary>\n [Test]\n public void Tester_fornet_1_dot_1()\n {\n const int initialSize = 1000;\n\n // Create the baseline data\n int[] myArray = new int[initialSize];\n\n for (var i = 0; i < initialSize; i++)\n {\n myArray[i] = i + 1;\n }\n\n IEnumerable _revered = ReverserService.ToReveresed(myArray);\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n }\n\n [Test]\n public void tester_why_this_is_good()\n {\n\n ArrayList names = new ArrayList();\n names.Add(\"Jim\");\n names.Add(\"Bob\");\n names.Add(\"Eric\");\n names.Add(\"Sam\");\n\n IEnumerable _revered = ReverserService.ToReveresed(names);\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(\"Sam\"));\n\n\n }\n\n [Test]\n public void tester_extension_method()\n {\n\n // Extension Methods No Linq (Linq does this for you as I will show)\n var enumerableOfInt = Enumerable.Range(1, 1000);\n\n // Use Extension Method - which simply wraps older clr code\n IEnumerable _revered = enumerableOfInt.ToReveresed();\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n\n\n }\n\n\n [Test]\n public void tester_linq_3_dot_5_clr()\n {\n\n // Extension Methods No Linq (Linq does this for you as I will show)\n IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);\n\n // Reverse is Linq (which is are extension methods off IEnumerable<T>\n // Note you must case IEnumerable (non generic) using OfType or Cast\n IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();\n\n Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));\n\n\n }\n\n\n\n [Test]\n public void tester_final_and_recommended_colution()\n {\n\n var enumerableOfInt = Enumerable.Range(1, 1000);\n enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));\n\n }\n\n\n\n private static object TestAndGetResult(IEnumerable enumerableIn)\n {\n // IEnumerable x = ReverserService.ToReveresed(names);\n\n Assert.IsTrue(enumerableIn != null);\n IEnumerator _test = enumerableIn.GetEnumerator();\n\n // Move to first\n Assert.IsTrue(_test.MoveNext());\n return _test.Current;\n }\n}\n" }, { "answer_id": 276097, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 0, "selected": false, "text": "foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())\n{\n myArray[i] = 42; \n}\n" }, { "answer_id": 276146, "author": "Twotymz", "author_id": 2224, "author_profile": "https://Stackoverflow.com/users/2224", "pm_score": 2, "selected": false, "text": "\nint i = myArray.Length;\nwhile (i--) {\n myArray[i] = 42;\n}\n {int i = myArray.Length; while (i-- > 0)\n{\n myArray[i] = 42;\n}}\n" }, { "answer_id": 276176, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 6, "selected": false, "text": "for Array.Reverse() Enumerable.Reverse()" }, { "answer_id": 276793, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "vector<value_type> range;\nforeach(value_type v, range | reversed)\n cout << v;\n range | transformed(f) | filtered(p) | reversed\n" }, { "answer_id": 369137, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "// this is how I always do it\nfor (i = n; --i >= 0;){\n ...\n}\n" }, { "answer_id": 14136931, "author": "Jack Griffin", "author_id": 1362643, "author_profile": "https://Stackoverflow.com/users/1362643", "pm_score": 6, "selected": false, "text": "for (int i = myArray.Length - 1; i >= 0; i--) \n{ \n // Do something ... \n} \n" }, { "answer_id": 40234452, "author": "Petko Petkov", "author_id": 2240383, "author_profile": "https://Stackoverflow.com/users/2240383", "pm_score": 1, "selected": false, "text": "i int i = arrayLength;\nwhile(i)\n{\n i--;\n //do something with array[i]\n}\n" }, { "answer_id": 65542588, "author": "nspo", "author_id": 997151, "author_profile": "https://Stackoverflow.com/users/997151", "pm_score": 0, "selected": false, "text": "auto std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.rend(); ++it) {\n std::cout<<*it<<\" \";\n}\n 4 3 2 1 std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.rend(); ++it) {\n *it = *it + 10;\n std::cout<<*it<<\" \";\n}\n 14 13 12 11 {11, 12, 13, 14} std::vector for(const auto& element : vec) std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.crbegin(); it != vec.crend(); ++it) { // used crbegin()/crend() here...\n *it = *it + 10; // ... so that this is a compile-time error\n std::cout<<*it<<\" \";\n}\n /tmp/main.cpp:20:9: error: assignment of read-only location ‘it.std::reverse_iterator<__gnu_cxx::__normal_iterator<const int*, std::vector<int> > >::operator*()’\n 20 | *it = *it + 10;\n | ~~~~^~~~~~~~~~\n std::vector<int> vec = {1,2,3,4};\nfor (auto it = vec.rbegin(); it != vec.end(); ++it) { // mixed rbegin() and end()\n std::cout<<*it<<\" \";\n}\n /tmp/main.cpp: In function ‘int main()’:\n/tmp/main.cpp:19:33: error: no match for ‘operator!=’ (operand types are ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >’ and ‘std::vector<int>::iterator’ {aka ‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’})\n 19 | for (auto it = vec.rbegin(); it != vec.end(); ++it) {\n | ~~ ^~ ~~~~~~~~~\n | | |\n | | std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}\n | std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >\n int vec[] = {1,2,3,4};\nfor (auto it = std::crbegin(vec); it != std::crend(vec); ++it) {\n std::cout<<*it<<\" \";\n}\n void loop_reverse(std::vector<int>& vec) {\n if (vec.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {\n throw std::invalid_argument(\"Input too large\");\n }\n const int sz = static_cast<int>(vec.size());\n for(int i=sz-1; i >= 0; --i) {\n // do something with i\n }\n}\n void loop_reverse2(std::vector<int>& vec) {\n for(size_t i=vec.size(); i-- > 0;) { // reverse indices from N-1 to 0\n // do something with i\n }\n}\n void loop_reverse3(std::vector<int>& vec) {\n for(size_t offset=0; offset < vec.size(); ++offset) {\n const size_t i = vec.size()-1-offset; // reverse indices from N-1 to 0\n // do something with i\n }\n}\n" }, { "answer_id": 69274027, "author": "Ibrahim Ozdemir", "author_id": 4950783, "author_profile": "https://Stackoverflow.com/users/4950783", "pm_score": 1, "selected": false, "text": "if (list.Count > 0)\n for (size_t i = list.Count - 1; ; i--)\n {\n //do your thing\n \n if (i == 0) //for preventing unsigned wrap\n break;\n }\n" }, { "answer_id": 74102748, "author": "RecursiveDude", "author_id": 20266692, "author_profile": "https://Stackoverflow.com/users/20266692", "pm_score": -1, "selected": false, "text": "for (int i = myArray.Length - 1; i >= 0; i--)\n{\n // Do something\n myArray[i] = 42;\n}\n for (int i = myArray.Length - 1; i; i--)\n{\n // Do something\n myArray[i] = 42;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
276,022
<p>Do you follow a standard for wrapping long lines in source code? What line length do you find most comfortable to read?</p> <p>Sometimes I find people who program on wide-screen monitors and like to use its full width for displaying source code. I prefer shorter lines, around 80-100 characters, but I have a hard time trying to convince colleagues with the ever-increasing popularity of wide-screen devices.</p> <p><em>Edit:</em></p> <p>Similiar questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/110928/">Is there a valid reason for enforcing a maximum width of 80 characters in a code file, this day and age?</a></li> </ul>
[ { "answer_id": 276048, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 2, "selected": false, "text": "status = do_something(); \nif (status == error)\n{\n do_error_handling();\n return;\n} \n/* do you regular flow */\nstatus = do_more();\nif (status == error)\n{\n do_error_handling();\n return; \n}\n/* do more of you regular flow and keep you line 80 chars*/\n status = do_something(); \nif (status == succes)\n{\n /* do you regular flow */\n status = do_more();\n if (status == success)\n {\n /* do you regular flow */\n /* nest again and get line behind visible screen */\n }\n else\n {\n /* do error handling */ \n }\n\n}\nelse\n{\n /* do error handling */ \n}\n goto do_error_handling()" }, { "answer_id": 276086, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "Conslas" }, { "answer_id": 276491, "author": "orcmid", "author_id": 33810, "author_profile": "https://Stackoverflow.com/users/33810", "pm_score": 0, "selected": false, "text": "/* example.txt 0.00 UTF-8 dh:2008-11-09\n*---|----1----|----2----|----3----|----4----|----5----|----6----|----7----*\n*/\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23193/" ]
276,029
<p>I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.</p> <p>Example:</p> <pre><code> i'm living &lt;a href="Paris" atl="Paris link"&gt;in Paris&lt;/a&gt;, near Paris &lt;a href="gare"&gt;Gare du Nord&lt;/a&gt;, i love Paris. </code></pre> <p>would become </p> <pre><code> i'm living.........near &lt;a href=""&gt;Paris&lt;/a&gt;..........i love &lt;a href=""&gt;Paris&lt;/a&gt;. </code></pre>
[ { "answer_id": 276073, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 0, "selected": false, "text": "!(<a.*</a>.*)*Paris!isU\n $1<a href=\"Paris\">Paris</a>\n <?php\n$s = 'i\\'m living <a href=\"Paris\" atl=\"Paris link\">in Paris</a>, near Paris <a href=\"gare\">Gare du Nord</a>, i love Paris.'; \n$regex = '!(<a.*</a>.*)*Paris!isU'; \n$replace = '$1<a href=\"Paris\">Paris</a>'; \n$result = preg_replace( $regex, $replace, $s); \n?>\n" }, { "answer_id": 276109, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<a href=\"...\"><a href=\"...\">Paris</a></a> \\bParis\\b\n (<a[^>]+>.*?(?!:</a>))<a[^>]+>(Paris)</a>\n <a[^>]+> .*?(?!:</a>) <a[^>]+> </a> (?!:...) Paris <a href\"...\">Paris</a> <a href=\"\">in the <b>capital of France</b>, <a href=\"\">Paris</a></a> <a href=\"\">in the <b>capital of France</b>, Paris</a>" }, { "answer_id": 276800, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": -1, "selected": false, "text": "s/([a-z-']+)/<a href=\"http:\\/\\/en.wikipedia.org\\/wiki\\/$1\">$1<\\/a>/i\n s/([A-Z][a-z-']+)/<a href=\"http:\\/\\/en.wikipedia.org\\/wiki\\/$1\">$1<\\/a>/gi;\n <a href=\"http://en.wikipedia.org/wiki/Baton\">Baton</a> \n<a href=\"http://en.wikipedia.org/wiki/Rouge\">Rouge</a>\n my $barred_list_of_cities \n = join( '|'\n , sort { ( length $a <=> $b ) || ( $a cmp $b ) } keys %url_for_city_of\n );\ns/($barred_list_of_cities)/<a href=\"$url_for_city_of{$1}\">$1<\\/a>/g;\n" }, { "answer_id": 280398, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 3, "selected": true, "text": "(<a[^>]*>.*?</a>)|Paris\n resultString = \n Regex.Replace(\n subjectString, \n \"(<a[^>]*>.*?</a>)|Paris\", \n new MatchEvaluator(ComputeReplacement));\n\npublic String ComputeReplacement(Match m) {\n if (m.groups(1).Success) {\n return m.groups(1).Value;\n } else {\n return \"<a href=\\\"link to paris\\\">Paris</a>\";\n }\n}\n" }, { "answer_id": 3467838, "author": "alexfv", "author_id": 418418, "author_profile": "https://Stackoverflow.com/users/418418", "pm_score": 0, "selected": false, "text": " $pattern = 'Paris';\n $text = 'i\\'m living <a href=\"Paris\" atl=\"Paris link\">in Paris</a>, near Paris <a href=\"gare\">Gare du Nord</a>, i love Paris.';\n\n // 1. Define 2 arrays:\n // $matches[1] - array of links with our keyword\n // $matches[2] - array of keyword\n preg_match_all('@(<a[^>]*?>[^<]*?'.$pattern.'[^<]*?</a>)|(?<!\\pL)('.$pattern.')(?!\\pL)@', $text, $matches);\n\n // Exists keywords for replace? Define first keyword without tag <a>\n $number = array_search($pattern, $matches[2]);\n\n // Keyword exists, let's go rock\n if ($number !== FALSE) {\n\n // Replace all link with temporary value\n foreach ($matches[1] as $k => $tag) {\n $text = preg_replace('@(<a[^>]*?>[^<]*?'.$pattern.'[^<]*?</a>)@', 'KEYWORD_IS_ALREADY_LINK_'.$k, $text, 1);\n }\n\n // Replace our keywords with link\n $text = preg_replace('/(?<!\\pL)('.$pattern.')(?!\\pL)/', '<a href=\"\">'.$pattern.'</a>', $text);\n\n // Return link\n foreach ($matches[1] as $k => $tag) {\n\n $text = str_replace('KEYWORD_IS_ALREADY_LINK_'.$k, $tag, $text);\n }\n\n // It's work!\n echo $text;\n }\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35937/" ]
276,030
<p>As we all know, global data, like the locale settings affecting the numeric decimal point printf() and strtod() are using, is evil. Fortunately, MSVC++ 9 allows to use per-thread locales by a <code>_configthreadlocale(_ENABLE_PER_THREAD_LOCALE)</code> call. Unfortunately, it seems that the localeconv() function does not notice this and still returns the global locale settings, e.g. localeconv()->decimal_point seems to always return the global locale setting before the _configthreadlocale() call. Is this a bug in the MSVC library or is this expected?</p> <p>TIA Paavo</p>
[ { "answer_id": 7516333, "author": "rubenvb", "author_id": 256138, "author_profile": "https://Stackoverflow.com/users/256138", "pm_score": 0, "selected": false, "text": "_configthreadlocale" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34911/" ]
276,033
<p>How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?</p> <p>To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.</p>
[ { "answer_id": 276407, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 3, "selected": true, "text": "function scan_ftp_dir($conn, $dir, $pattern) {\n $files = ftp_nlist($conn, $dir);\n if (!$files) {\n return;\n }\n\n foreach ($files as $file) {\n //the quickest way i can think of to check if is a directory\n if (ftp_size($conn, $file) == -1) {\n\n //get just the directory name\n $dirName = substr($file, strrpos($file, '/') + 1);\n\n if (preg_match($pattern, $dirName)) {\n echo $file . ' matched pattern';\n } else { \n //directory didn't match pattern, recurse \n scan_ftp_dir($conn, $file, $pattern);\n }\n } \n }\n}\n $host = 'localhost';\n$user = 'user';\n$pass = 'pass';\n\n\nif (false === ($conn = ftp_connect($host))) {\n die ('cannot connect');\n}\n\nif (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');\n\n\nscan_ftp_dir($conn, '.', '/^beginswith/');\n ftp_rmdir() ftp_rmAll() ftp_size() ftp_nlist()" }, { "answer_id": 294076, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 0, "selected": false, "text": "\nif( $argc == 2 ) {\n $directoryToSearch = $argv[1];\n $host = '';\n $username = '';\n $password = '';\n $connection = connect( $host, $username, $password );\n deleteDirectoriesWithName( $connection, 'directoryToDelete', $directoryToSearch );\n ftp_close( $connection );\n exit( 0 );\n}\nelse {\n cliPrint( \"This script currently only supports 1 argument.\\n\");\n cliPrint( \"Usage: php deleteDirectories.php directoryNameToSearch\\n\");\n exit( 1 );\n}\n\n/**\n * Recursively traverse directories and files starting with the path\n * passed in and then delete all directories that match the name\n * passed in\n * @param $connection the connection resource to the database. \n * @param $name the name of the directories that should be * deleted.\n * @param $path the path to start searching from\n */\nfunction deleteDirectoriesWithName( &$connection, $name, $path ) {\n global $host, $username, $password;\n cliPrint( \"At path: $path\\n\" );\n //Get a list of files in the directory\n $list = ftp_nlist( $connection, $path );\n if ( empty( $list ) ) {\n $rawList = ftp_rawlist( $connection, $path );\n if( empty( $rawList ) ) {\n cliPrint( \"Reconnecting\\n\");\n ftp_close( $connection );\n $connection = connect( $host, $username, $password );\n cliPrint( \"Reconnected\\n\" );\n deleteDirectoriesWithName( $connection, $name, $path );\n return true;\n }\n\n $pathToPass = addSlashToEnd( $path );\n $list = RawlistToNlist( $rawList, $pathToPass );\n }\n //If we have selected a directory, then 'visit' the files (or directories) in the dir\n if ( $list[0] != $path ) {\n $path = addSlashToEnd( $path );\n //iterate through all of the items listed in the directory\n foreach ( $list as $item ) {\n //if the directory matches the name to be deleted, delete it recursively\n if ( $item == $name ) {\n DeleteDirRecursive( $connection, $path . $item );\n }\n\n //otherwise continue traversing\n else if ( $item != '..' && $item != '.' ) {\n deleteDirectoriesWithName( $connection, $name, $path . $item );\n }\n }\n }\n return true;\n}\n\n/**\n *Put output to STDOUT\n */\nfunction cliPrint( $string ) {\n fwrite( STDOUT, $string );\n}\n\n/**\n *Connect to the ftp server\n */\nfunction connect( $host, $username, $password ) {\n $connection = ftp_connect( $host );\n if ( !$connection ) {\n die('Could not connect to server: ' . $host );\n }\n $loginSuccessful = ftp_login( $connection, $username, $password );\n if ( !$loginSuccessful ) {\n die( 'Could not login as: ' . $username . '@' . $host );\n }\n cliPrint( \"Connection successful\\n\" );\n return $connection;\n}\n\n/**\n * Delete the provided directory and all its contents from the FTP-server.\n *\n * @param string $path Path to the directory on the FTP-server relative to\n * the current working directory\n */\nfunction DeleteDirRecursive(&$resource, $path) {\n global $host, $username, $password;\n cliPrint( $path . \"\\n\" );\n $result_message = \"\";\n\n //Get a list of files and directories in the current directory\n $list = ftp_nlist($resource, $path);\n\n if ( empty($list) ) {\n $listToPass = ftp_rawlist( $resource, $path );\n if ( empty( $listToPass ) ) {\n cliPrint( \"Reconnecting\\n\" );\n ftp_close( $resource );\n $resource = connect( $host, $username, $password );\n $result_message = \"Reconnected\\n\";\n cliPrint( \"Reconnected\\n\" );\n $result_message .= DeleteDirRecursive( $resource, $path );\n return $result_message;\n }\n $list = RawlistToNlist( $listToPass, addSlashToEnd( $path ) );\n }\n\n //if the current path is a directory, recursively delete the file within and then\n //delete the empty directory\n if ($list[0] != $path) {\n $path = addSlashToEnd( $path );\n foreach ($list as $item) {\n if ($item != \"..\" && $item != \".\") {\n $result_message .= DeleteDirRecursive($resource, $path . $item);\n }\n }\n cliPrint( 'Delete: ' . $path . \"\\n\" );\n if (ftp_rmdir ($resource, $path)) {\n\n cliPrint( \"Successfully deleted $path\\n\" );\n } else {\n\n cliPrint( \"There was a problem deleting $path\\n\" );\n }\n }\n //otherwise delete the file\n else {\n cliPrint( 'Delete file: ' . $path . \"\\n\" );\n if (ftp_delete ($resource, $path)) {\n cliPrint( \"Successfully deleted $path\\n\" );\n } else {\n\n cliPrint( \"There was a problem deleting $path\\n\" );\n }\n }\n return $result_message;\n}\n\n/**\n* Convert a result from ftp_rawlist() to a result of ftp_nlist()\n*\n* @param array $rawlist Result from ftp_rawlist();\n* @param string $path Path to the directory on the FTP-server relative \n* to the current working directory\n* @return array An array with the paths of the files in the directory\n*/\nfunction RawlistToNlist($rawlist, $path) {\n $array = array();\n foreach ($rawlist as $item) {\n $filename = trim(substr($item, 55, strlen($item) - 55));\n if ($filename != \".\" || $filename != \"..\") {\n $array[] = $filename;\n }\n }\n return $array;\n}\n\n/**\n *Adds a '/' to the end of the path if it is not already present.\n */\nfunction addSlashToEnd( $path ) {\n $endOfPath = substr( $path, strlen( $path ) - 1, 1 );\n if( $endOfPath == '/' ) {\n $pathEnding = '';\n }\n else {\n $pathEnding = '/';\n }\n\n return $path . $pathEnding;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831/" ]
276,040
<p>Generally I connect and retrieve data using the standard way (error checking removed for simplicity):</p> <pre><code>$db = mysql_select_db("dbname", mysql_connect("host","username","passord")); $items = mysql_query("SELECT * FROM $db"); while($item = mysql_fetch_array($items)) { my_function($item[rowname]); } </code></pre> <p>Where my_function does some useful things witht that particular row.</p> <p>What is the equivalent code using objects?</p>
[ { "answer_id": 276065, "author": "I GIVE TERRIBLE ADVICE", "author_id": 35344, "author_profile": "https://Stackoverflow.com/users/35344", "pm_score": 3, "selected": true, "text": "$dbh = new PDO(\"mysql:host=$hostname;dbname=$db\", $username, $password); //connect to the database\n//each :keyword represents a parameter or value to be bound later\n$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');\n\n# Variables are set here.\n$query->bindParam(':id', $id); // this is a pass by reference \n$query->bindValue(':pass', $pass); // this is a pass by value\n\n$query->execute(); // query is run\n\n// to get all the data at once\n$res = $query->fetchall();\nprint_r($res);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
276,052
<p>How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/" rel="noreferrer">PSI</a> (that currently seems not actively developed and not supported on multiple platforms) or something like <a href="http://www.i-scream.org/pystatgrab/" rel="noreferrer">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p> </li> <li><p>Using platform specific code such as using a <code>os.popen(&quot;ps&quot;)</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/" rel="noreferrer">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p> </li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
[ { "answer_id": 276934, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 4, "selected": false, "text": "'''\nMonitor window processes\n\nderived from:\n>for sys available mem\nhttp://msdn2.microsoft.com/en-us/library/aa455130.aspx\n\n> individual process information and python script examples\nhttp://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true\n\nNOTE: the WMI interface/process is also available for performing similar tasks\n I'm not using it here because the current method covers my needs, but if someday it's needed\n to extend or improve this module, then may want to investigate the WMI tools available.\n WMI for python:\n http://tgolden.sc.sabren.com/python/wmi.html\n'''\n\n__revision__ = 3\n\nimport win32com.client\nfrom ctypes import *\nfrom ctypes.wintypes import *\nimport pythoncom\nimport pywintypes\nimport datetime\n\n\nclass MEMORYSTATUS(Structure):\n _fields_ = [\n ('dwLength', DWORD),\n ('dwMemoryLoad', DWORD),\n ('dwTotalPhys', DWORD),\n ('dwAvailPhys', DWORD),\n ('dwTotalPageFile', DWORD),\n ('dwAvailPageFile', DWORD),\n ('dwTotalVirtual', DWORD),\n ('dwAvailVirtual', DWORD),\n ]\n\n\ndef winmem():\n x = MEMORYSTATUS() # create the structure\n windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes\n return x \n\n\nclass process_stats:\n '''process_stats is able to provide counters of (all?) the items available in perfmon.\n Refer to the self.supported_types keys for the currently supported 'Performance Objects'\n \n To add logging support for other data you can derive the necessary data from perfmon:\n ---------\n perfmon can be run from windows 'run' menu by entering 'perfmon' and enter.\n Clicking on the '+' will open the 'add counters' menu,\n From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key.\n --> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent)\n For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary,\n keyed by the 'Performance Object' name as mentioned above.\n ---------\n \n NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly.\n \n Initially the python implementation was derived from:\n http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true\n '''\n def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]):\n '''process_names_list == the list of all processes to log (if empty log all)\n perf_object_list == list of process counters to log\n filter_list == list of text to filter\n print_results == boolean, output to stdout\n '''\n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n \n self.process_name_list = process_name_list\n self.perf_object_list = perf_object_list\n self.filter_list = filter_list\n \n self.win32_perf_base = 'Win32_PerfFormattedData_'\n \n # Define new datatypes here!\n self.supported_types = {\n 'NETFramework_NETCLRMemory': [\n 'Name',\n 'NumberTotalCommittedBytes',\n 'NumberTotalReservedBytes',\n 'NumberInducedGC', \n 'NumberGen0Collections',\n 'NumberGen1Collections',\n 'NumberGen2Collections',\n 'PromotedMemoryFromGen0',\n 'PromotedMemoryFromGen1',\n 'PercentTimeInGC',\n 'LargeObjectHeapSize'\n ],\n \n 'PerfProc_Process': [\n 'Name',\n 'PrivateBytes',\n 'ElapsedTime',\n 'IDProcess',# pid\n 'Caption',\n 'CreatingProcessID',\n 'Description',\n 'IODataBytesPersec',\n 'IODataOperationsPersec',\n 'IOOtherBytesPersec',\n 'IOOtherOperationsPersec',\n 'IOReadBytesPersec',\n 'IOReadOperationsPersec',\n 'IOWriteBytesPersec',\n 'IOWriteOperationsPersec' \n ]\n }\n \n def get_pid_stats(self, pid):\n this_proc_dict = {}\n \n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n if not self.perf_object_list:\n perf_object_list = self.supported_types.keys()\n \n for counter_type in perf_object_list:\n strComputer = \".\"\n objWMIService = win32com.client.Dispatch(\"WbemScripting.SWbemLocator\")\n objSWbemServices = objWMIService.ConnectServer(strComputer,\"root\\cimv2\")\n \n query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)\n colItems = objSWbemServices.ExecQuery(query_str) # \"Select * from Win32_PerfFormattedData_PerfProc_Process\")# changed from Win32_Thread \n \n if len(colItems) > 0: \n for objItem in colItems:\n if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess:\n \n for attribute in self.supported_types[counter_type]:\n eval_str = 'objItem.%s' % (attribute)\n this_proc_dict[attribute] = eval(eval_str)\n \n this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]\n break\n\n return this_proc_dict \n \n \n def get_stats(self):\n '''\n Show process stats for all processes in given list, if none given return all processes \n If filter list is defined return only the items that match or contained in the list\n Returns a list of result dictionaries\n ''' \n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n proc_results_list = []\n if not self.perf_object_list:\n perf_object_list = self.supported_types.keys()\n \n for counter_type in perf_object_list:\n strComputer = \".\"\n objWMIService = win32com.client.Dispatch(\"WbemScripting.SWbemLocator\")\n objSWbemServices = objWMIService.ConnectServer(strComputer,\"root\\cimv2\")\n \n query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type)\n colItems = objSWbemServices.ExecQuery(query_str) # \"Select * from Win32_PerfFormattedData_PerfProc_Process\")# changed from Win32_Thread\n \n try: \n if len(colItems) > 0:\n for objItem in colItems:\n found_flag = False\n this_proc_dict = {}\n \n if not self.process_name_list:\n found_flag = True\n else:\n # Check if process name is in the process name list, allow print if it is\n for proc_name in self.process_name_list:\n obj_name = objItem.Name\n if proc_name.lower() in obj_name.lower(): # will log if contains name\n found_flag = True\n break\n \n if found_flag:\n for attribute in self.supported_types[counter_type]:\n eval_str = 'objItem.%s' % (attribute)\n this_proc_dict[attribute] = eval(eval_str)\n \n this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3]\n proc_results_list.append(this_proc_dict)\n \n except pywintypes.com_error, err_msg:\n # Ignore and continue (proc_mem_logger calls this function once per second)\n continue\n return proc_results_list \n\n \ndef get_sys_stats():\n ''' Returns a dictionary of the system stats'''\n pythoncom.CoInitialize() # Needed when run by the same process in a thread\n x = winmem()\n \n sys_dict = { \n 'dwAvailPhys': x.dwAvailPhys,\n 'dwAvailVirtual':x.dwAvailVirtual\n }\n return sys_dict\n\n \nif __name__ == '__main__':\n # This area used for testing only\n sys_dict = get_sys_stats()\n \n stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[])\n proc_results = stats_processor.get_stats()\n \n for result_dict in proc_results:\n print result_dict\n \n import os\n this_pid = os.getpid()\n this_proc_results = stats_processor.get_pid_stats(this_pid)\n \n print 'this proc results:'\n print this_proc_results\n" }, { "answer_id": 2468983, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 10, "selected": true, "text": "#!/usr/bin/env python\nimport psutil\n# gives a single float value\npsutil.cpu_percent()\n# gives an object with many fields\npsutil.virtual_memory()\n# you can convert that object to a dictionary \ndict(psutil.virtual_memory()._asdict())\n# you can have the percentage of used RAM\npsutil.virtual_memory().percent\n79.2\n# you can calculate percentage of available memory\npsutil.virtual_memory().available * 100 / psutil.virtual_memory().total\n20.8\n" }, { "answer_id": 36337011, "author": "LeoG", "author_id": 2390826, "author_profile": "https://Stackoverflow.com/users/2390826", "pm_score": 1, "selected": false, "text": "import subprocess\ncmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) \nout,error = cmd.communicate() \nmemory = out.splitlines()\n" }, { "answer_id": 38984517, "author": "wordsforthewise", "author_id": 4549682, "author_profile": "https://Stackoverflow.com/users/4549682", "pm_score": 7, "selected": false, "text": "from __future__ import print_function # for Python2\nimport psutil\nprint(psutil.__versi‌​on__)\n from __future__ import print_function\nimport psutil\nprint(psutil.cpu_percent())\nprint(psutil.virtual_memory()) # physical memory usage\nprint('memory % used:', psutil.virtual_memory()[2])\n virtual_memory import os\nimport psutil\npid = os.getpid()\npython_process = psutil.Process(pid)\nmemoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think\nprint('memory use:', memoryUse)\n" }, { "answer_id": 42249349, "author": "CodeGench", "author_id": 5203370, "author_profile": "https://Stackoverflow.com/users/5203370", "pm_score": 5, "selected": false, "text": "import os\n \nCPU_Pct=str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))\nprint(\"CPU Usage = \" + CPU_Pct) # print results\n import os\nmem=str(os.popen('free -t -m').readlines())\n\"\"\"\nGet a whole line of memory output, it will be something like below\n[' total used free shared buffers cached\\n', \n'Mem: 925 591 334 14 30 355\\n', \n'-/+ buffers/cache: 205 719\\n', \n'Swap: 99 0 99\\n', \n'Total: 1025 591 434\\n']\n So, we need total memory, usage and free memory.\n We should find the index of capital T which is unique at this string\n\"\"\"\nT_ind=mem.index('T')\n\"\"\"\nThan, we can recreate the string with this information. After T we have,\n\"Total: \" which has 14 characters, so we can start from index of T +14\nand last 4 characters are also not necessary.\nWe can create a new sub-string using this information\n\"\"\"\nmem_G=mem[T_ind+14:-4]\n\"\"\"\nThe result will be like\n1025 603 422\nwe need to find first index of the first space, and we can start our substring\nfrom from 0 to this index number, this will give us the string of total memory\n\"\"\"\nS1_ind=mem_G.index(' ')\nmem_T=mem_G[0:S1_ind]\n\"\"\"\nSimilarly we will create a new sub-string, which will start at the second value. \nThe resulting string will be like\n603 422\nAgain, we should find the index of first space and than the \ntake the Used Memory and Free memory.\n\"\"\"\nmem_G1=mem_G[S1_ind+8:]\nS2_ind=mem_G1.index(' ')\nmem_U=mem_G1[0:S2_ind]\n\nmem_F=mem_G1[S2_ind+8:]\nprint 'Summary = ' + mem_G\nprint 'Total Memory = ' + mem_T +' MB'\nprint 'Used Memory = ' + mem_U +' MB'\nprint 'Free Memory = ' + mem_F +' MB'\n" }, { "answer_id": 42275253, "author": "Hrabal", "author_id": 3008185, "author_profile": "https://Stackoverflow.com/users/3008185", "pm_score": 6, "selected": false, "text": "import os\ntot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])\n" }, { "answer_id": 49467859, "author": "anoneemus", "author_id": 8564727, "author_profile": "https://Stackoverflow.com/users/8564727", "pm_score": 3, "selected": false, "text": "resource" }, { "answer_id": 52569857, "author": "Rahul", "author_id": 1249924, "author_profile": "https://Stackoverflow.com/users/1249924", "pm_score": 4, "selected": false, "text": "import os\n\nlinux_filepath = \"/proc/meminfo\"\nmeminfo = dict(\n (i.split()[0].rstrip(\":\"), int(i.split()[1]))\n for i in open(linux_filepath).readlines()\n)\nmeminfo[\"memory_total_gb\"] = meminfo[\"MemTotal\"] / (2 ** 20)\nmeminfo[\"memory_free_gb\"] = meminfo[\"MemFree\"] / (2 ** 20)\nmeminfo[\"memory_available_gb\"] = meminfo[\"MemAvailable\"] / (2 ** 20)\n" }, { "answer_id": 52586129, "author": "Subhash", "author_id": 9691238, "author_profile": "https://Stackoverflow.com/users/9691238", "pm_score": 2, "selected": false, "text": "import os\n\ndef get_cpu_load():\n \"\"\" Returns a list CPU Loads\"\"\"\n result = []\n cmd = \"WMIC CPU GET LoadPercentage \"\n response = os.popen(cmd + ' 2>&1','r').read().strip().split(\"\\r\\n\")\n for load in response[1:]:\n result.append(int(load))\n return result\n\nif __name__ == '__main__':\n print get_cpu_load()\n" }, { "answer_id": 52933232, "author": "Jay", "author_id": 5387972, "author_profile": "https://Stackoverflow.com/users/5387972", "pm_score": 1, "selected": false, "text": "from subprocess import Popen, PIPE\n\ndef get_cpu_usage():\n ''' Get CPU usage on Linux by reading /proc/stat '''\n\n sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)\n top_vals = [int(val) for val in sub.communicate()[0].split('\\n')[0].split[1:5]]\n\n return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])\n" }, { "answer_id": 55782626, "author": "Saptarshi Ghosh", "author_id": 11390909, "author_profile": "https://Stackoverflow.com/users/11390909", "pm_score": 2, "selected": false, "text": "import os os.system(\"echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2\") [i for i in os.popen(\"echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2\").read().split(' ') if i.isdigit()]" }, { "answer_id": 61910245, "author": "Pe Dro", "author_id": 9625777, "author_profile": "https://Stackoverflow.com/users/9625777", "pm_score": 4, "selected": false, "text": "memory_profiler line_profiler # Time profiler\n$ pip install line_profiler\n# Memory profiler\n$ pip install memory_profiler\n# Install the dependency for a faster analysis\n$ pip install psutil\n main.py linearRegressionfit() @profile @profile\ndef linearRegressionfit(Xt,Yt,Xts,Yts):\n lr=LinearRegression()\n model=lr.fit(Xt,Yt)\n predict=lr.predict(Xts)\n # More Code\n $ kernprof -l -v main.py\n Total time: 0.181071 s\nFile: main.py\nFunction: linearRegressionfit at line 35\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 35 @profile\n 36 def linearRegressionfit(Xt,Yt,Xts,Yts):\n 37 1 52.0 52.0 0.1 lr=LinearRegression()\n 38 1 28942.0 28942.0 75.2 model=lr.fit(Xt,Yt)\n 39 1 1347.0 1347.0 3.5 predict=lr.predict(Xts)\n 40 \n 41 1 4924.0 4924.0 12.8 print(\"train Accuracy\",lr.score(Xt,Yt))\n 42 1 3242.0 3242.0 8.4 print(\"test Accuracy\",lr.score(Xts,Yts))\n $ python -m memory_profiler main.py\n Filename: main.py\n\nLine # Mem usage Increment Line Contents\n================================================\n 35 125.992 MiB 125.992 MiB @profile\n 36 def linearRegressionfit(Xt,Yt,Xts,Yts):\n 37 125.992 MiB 0.000 MiB lr=LinearRegression()\n 38 130.547 MiB 4.555 MiB model=lr.fit(Xt,Yt)\n 39 130.547 MiB 0.000 MiB predict=lr.predict(Xts)\n 40 \n 41 130.547 MiB 0.000 MiB print(\"train Accuracy\",lr.score(Xt,Yt))\n 42 130.547 MiB 0.000 MiB print(\"test Accuracy\",lr.score(Xts,Yts))\n matplotlib $ mprof run main.py\n$ mprof plot\n line_profiler memory_profiler psutil" }, { "answer_id": 62778466, "author": "sudhirkondle", "author_id": 10437493, "author_profile": "https://Stackoverflow.com/users/10437493", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env python\n#Execute commond on windows machine to install psutil>>>>python -m pip install psutil\nimport psutil\n\nprint (' ')\nprint ('----------------------CPU Information summary----------------------')\nprint (' ')\n\n# gives a single float value\nvcc=psutil.cpu_count()\nprint ('Total number of CPUs :',vcc)\n\nvcpu=psutil.cpu_percent()\nprint ('Total CPUs utilized percentage :',vcpu,'%')\n\nprint (' ')\nprint ('----------------------RAM Information summary----------------------')\nprint (' ')\n# you can convert that object to a dictionary \n#print(dict(psutil.virtual_memory()._asdict()))\n# gives an object with many fields\nvvm=psutil.virtual_memory()\n\nx=dict(psutil.virtual_memory()._asdict())\n\ndef forloop():\n for i in x:\n print (i,\"--\",x[i]/1024/1024/1024)#Output will be printed in GBs\n\nforloop()\nprint (' ')\nprint ('----------------------RAM Utilization summary----------------------')\nprint (' ')\n# you can have the percentage of used RAM\nprint('Percentage of used RAM :',psutil.virtual_memory().percent,'%')\n#79.2\n# you can calculate percentage of available memory\nprint('Percentage of available RAM :',psutil.virtual_memory().available * 100 / psutil.virtual_memory().total,'%')\n#20.8\n" }, { "answer_id": 64772402, "author": "Leroy Kayanda", "author_id": 1960902, "author_profile": "https://Stackoverflow.com/users/1960902", "pm_score": 2, "selected": false, "text": "file1 = open('/proc/meminfo', 'r') \n\nfor line in file1: \n if 'MemTotal' in line: \n x = line.split()\n memTotal = int(x[1])\n \n if 'Buffers' in line: \n x = line.split()\n buffers = int(x[1])\n \n if 'Cached' in line and 'SwapCached' not in line: \n x = line.split()\n cached = int(x[1])\n \n if 'MemFree' in line: \n x = line.split()\n memFree = int(x[1])\n\nfile1.close()\n\npercentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )\nprint(percentage_used)\n" }, { "answer_id": 65236700, "author": "Rea Haas", "author_id": 8808983, "author_profile": "https://Stackoverflow.com/users/8808983", "pm_score": 3, "selected": false, "text": "psutil os import os\nimport psutil # need: pip install psutil\n\nIn [32]: psutil.virtual_memory()\nOut[32]: svmem(total=6247907328, available=2502328320, percent=59.9, used=3327135744, free=167067648, active=3671199744, inactive=1662668800, buffers=844783616, cached=1908920320, shared=123912192, slab=613048320)\n\nIn [33]: psutil.virtual_memory().percent\nOut[33]: 60.0\n\nIn [34]: psutil.cpu_percent()\nOut[34]: 5.5\n\nIn [35]: os.sep\nOut[35]: '/'\n\nIn [36]: psutil.disk_usage(os.sep)\nOut[36]: sdiskusage(total=50190790656, used=41343860736, free=6467502080, percent=86.5)\n\nIn [37]: psutil.disk_usage(os.sep).percent\nOut[37]: 86.5\n" }, { "answer_id": 68611754, "author": "CodeFarmer", "author_id": 479008, "author_profile": "https://Stackoverflow.com/users/479008", "pm_score": 0, "selected": false, "text": "*/1 * * * * sh dog.sh crontab -e import os\nimport re\n\nCUT_OFF = 90\n\ndef get_cpu_load():\n cmd = \"ps -Ao user,uid,comm,pid,pcpu --sort=-pcpu | head -n 2 | tail -1\"\n response = os.popen(cmd, 'r').read()\n arr = re.findall(r'\\S+', response)\n print(arr)\n needKill = float(arr[-1]) > CUT_OFF\n if needKill:\n r = os.popen(f\"kill -9 {arr[-2]}\")\n print('kill:', r)\n\nif __name__ == '__main__':\n # Test CPU with \n # $ stress --cpu 1\n # crontab -e\n # Every 1 min\n # */1 * * * * sh dog.sh\n # ctlr o, ctlr x\n # crontab -l\n print(get_cpu_load())\n" }, { "answer_id": 69511430, "author": "Karol Zlot", "author_id": 8896457, "author_profile": "https://Stackoverflow.com/users/8896457", "pm_score": 5, "selected": false, "text": "tqdm psutil from tqdm import tqdm\nfrom time import sleep\nimport psutil\n\nwith tqdm(total=100, desc='cpu%', position=1) as cpubar, tqdm(total=100, desc='ram%', position=0) as rambar:\n while True:\n rambar.n=psutil.virtual_memory().percent\n cpubar.n=psutil.cpu_percent()\n rambar.refresh()\n cpubar.refresh()\n sleep(0.5)\n" }, { "answer_id": 70867664, "author": "Chen Levy", "author_id": 110488, "author_profile": "https://Stackoverflow.com/users/110488", "pm_score": 0, "selected": false, "text": "def cpu_load(): \n with open(\"/proc/stat\", \"r\") as stat:\n (key, user, nice, system, idle, _) = (stat.readline().split(None, 5))\n assert key == \"cpu\", \"'cpu ...' should be the first line in /proc/stat\"\n busy = int(user) + int(nice) + int(system)\n return 100 * busy / (busy + int(idle))\n\n" }, { "answer_id": 74062355, "author": "user19926715", "author_id": 19926715, "author_profile": "https://Stackoverflow.com/users/19926715", "pm_score": 1, "selected": false, "text": "SystemScripter pip install SystemScripter psutil SystemScripter.CPU.CpuPerCurrentUtil(SystemScripter.CPU()) #class init as self param if not work\n SystemScripter.CPU.CpuCurrentUtil(SystemScripter.CPU())\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35935/" ]
276,066
<p>I need a function count_permutations() that returns the number of permutations of a given range. <em>Assuming that the range is allowed to be modified, and starts at the first permutation,</em> I could naively implement this as repeated calls to next_permutation() as below:</p> <pre><code>template&lt;class Ret, class Iter&gt; Ret count_permutations(Iter first, Iter last) { Ret ret = 0; do { ++ret; } while (next_permutation(first, last)); return ret; } </code></pre> <p><em>Is there a faster way that doesn't require iterating through all the permutations to find the answer? It could still assume that the input can be modified, and starts in the first permutation, but obviously if it is possible to implement without those assumtions it'd be great too.</em></p>
[ { "answer_id": 276077, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 0, "selected": false, "text": "// generic factorial implementation...\n\nint factorial(int number) {\n int temp;\n if(number <= 1) return 1;\n temp = number * factorial(number - 1);\n return temp;\n}\n\ntemplate<class Ret, class Iter>\nRet count_permutations(Iter first, Iter end)\n{\n std::map<typename Iter::value_type, int> counter;\n Iter it = first;\n for( ; it != end; ++it) {\n counter[*it]++;\n }\n\n int n = 0;\n typename std::map<typename Iter::value_type, int>::iterator mi = counter.begin();\n for(; mi != counter.end() ; mi++)\n if ( mi->second > 1 )\n n += factorial(mi->second);\n\n return factorial(std::distance(first,end))/n;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
276,072
<p>I just picked up Agile Web Development with Rails 3rd Ed., and I'm going thru the Depot Application chapters, and I have a question about Product/Item options.</p> <p>If I wanted to modify the product catalog and store so that products could have options (size, color, whatever), where/how would I do that?</p> <p>Let's say I'm selling t-shirts, and they come in different sizes. I don't feel like that's something that really needs a model created to handle sizes, so I thought I could just add it as a select box in the html in the store's view.</p> <p>But, each Add to Cart button is wrapped by a form tag that is automatically generated by button_to, and doesn't seem to give me the ability to pass additional parameters to my cart. How can I get the size of the item added into the POST to add_to_cart?</p> <p>The helper in my view:</p> <pre><code>&lt;%= button_to &quot;Add to Cart&quot; , :action =&gt; :add_to_cart, :id =&gt; product %&gt; </code></pre> <p>The form that it generates:</p> <pre><code>&lt;form method=&quot;post&quot; action=&quot;/store/add_to_cart/3&quot; class=&quot;button-to&quot;&gt; </code></pre>
[ { "answer_id": 276083, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 0, "selected": false, "text": "button_to add_to_cart <% form_for(@product) do |f| %>\n<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>\n# other properties...\n<%= f.submit 'Add to Cart' %>\n<% end %>\n" }, { "answer_id": 278388, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 1, "selected": false, "text": "<% form_for(@cart_item) do |f| %>\n<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>\n<%= f.hidden_field :product_id, :value => @product.id %> \n# other properties...\n<%= f.submit 'Add to Cart' %>\n<% end %>\n" }, { "answer_id": 280000, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<% form_for @product, :url => {:action => \"add_to_cart\", :id => @product} do |f| %>\n <select name=\"productsize\" id=\"productsize\">\n <option value=\"L\">L</option>\n <option value=\"XL\">XL</option>\n </select>\n <%= f.submit 'Add to Cart' %>\n<% end %>\n productsize = params[:productsize]\n@cart.add_product(product, productsize)\n @items << CartItem.new(product, productsize)\n attr_reader :product, :quantity, :productsize\n\ndef initialize(product, productsize)\n@product = product\n@productsize = productsize\n Size: <%=h item.productsize %>\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,087
<p>I am working on a web application that is designed to display a bunch of data that is updated periodically with AJAX. The general usage scenario would be that a user would leave it open all day and take a glance at it now and then.</p> <p>I am encountering a problem where the browsers memory footprint is growing slowly over time. This is happening in both Firefox and IE 7 (Although not in Chrome). After a few hours, it can cause IE7 to have a footprint of ~200MB and FF3 to have a footprint of ~400MB.</p> <p>After a lot of testing, I have found that the memory leak only occurs if the AJAX calls are being responded to. If the server doesn't respond to anything, I can leave the page open for hours and the footprint won't grow.</p> <p>I am using prototype for my AJAX calls. So, I'm guessing there is an issue with the onSuccess callback creating these memory leaks. </p> <p>Does anyone have any tips on preventing memory leaks with prototype / AJAX? Or any methods on how to troubleshoot this problem?</p> <p>EDIT: found out the issue lies in a js graphing library I am using. Can be seen <a href="http://code.google.com/p/flotr/issues/detail?id=5" rel="noreferrer">here</a>. </p>
[ { "answer_id": 276124, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": true, "text": "<div id=\"ajaxResponseTarget\">\n ...\n</div>\n<script type=\"text/javascript\">\n $(someButton).observe('click', function() {\n new Ajax.Updater($('ajaxResponseTarget'), someUrl, {\n onSuccess: function() {\n $$('#ajaxResponseTarget .someButtonClass').invoke('observe', 'click', function() {\n ...\n });\n }\n });\n });\n</script>\n #ajaxResponseTarget innerHTML click someButton <div id=\"ajaxResponseTarget\">\n ...\n</div>\n<script type=\"text/javascript\">\n $('ajaxResponseTarget').observe('click', function(e) {\n if(e.element().match('.someButtonClass')) {\n ...\n }\n });\n $(someButton).observe('click', function() {\n new Ajax.Updater($('ajaxResponseTarget'), someUrl);\n });\n</script>\n .someButtonClass #ajaxResponseTarget #ajaxResponseTarget" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
276,088
<p>My ASP.NET application allows users to upload and download large files. Both procedures involve reading and writing filestreams. What should I do to ensure the application doesn't hang or crash when it handles a large file? Should the file operations be handled on a worker thread for example?</p>
[ { "answer_id": 276098, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 2, "selected": true, "text": "// Read the data in buffer.\nlength = iStream.Read(buffer, 0, bufferSize);\n\n// Write the data to the current output stream.\nResponse.OutputStream.Write(buffer, 0, length);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
276,099
<p>I want to read a mac id from command line and convert it to an array of <code>uint8_t</code> values to use it in a struct. I can not get it to work. I have a vector of string for the mac id split about <code>:</code> and I want to use <code>stringstream</code> to convert them with no luck. What I am missing?</p> <pre><code>int parseHex(const string &amp;num){ stringstream ss(num); ss &lt;&lt; std::hex; int n; ss &gt;&gt; n; return n; } uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0}; v = StringSplit( mac , ":" ); for( int j = 0 ; j &lt; v.size() ; j++ ){ tgt_mac[j] = parseHex(v.at(j)); } </code></pre>
[ { "answer_id": 276149, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "#include <sstream>\n#include <iostream>\n\nint main()\n{\n std::string h(\"a5\");\n std::stringstream s(h);\n int x;\n\n s >> std::hex >> x;\n std::cout << \"X(\" << x << \")\\n\";\n}\n" }, { "answer_id": 276496, "author": "Steven", "author_id": 27577, "author_profile": "https://Stackoverflow.com/users/27577", "pm_score": 2, "selected": false, "text": "uint8_t tgt_mac[6] = {0};\nstd::stringstream ss( \"AA:BB:CC:DD:EE:11\" );\nchar trash;\n\nfor ( int i = 0; i < 6; i++ )\n{\n int foo;\n ss >> std::hex >> foo >> trash;\n tgt_mac[i] = foo;\n std::cout << std::hex << \"Reading: \" << foo << std::endl;\n}\n\nstd::cout << \"As int array: \" << std::hex\n << (int) tgt_mac[0]\n << \":\"\n << (int) tgt_mac[1]\n << \":\"\n << (int) tgt_mac[2]\n << \":\"\n << (int) tgt_mac[3]\n << \":\"\n << (int) tgt_mac[4]\n << \":\"\n << (int) tgt_mac[5]\n << std::endl;\nstd::cout << \"As unint8_t array: \" << std::hex\n << tgt_mac[0]\n << \":\"\n << tgt_mac[1]\n << \":\"\n << tgt_mac[2]\n << \":\"\n << tgt_mac[3]\n << \":\"\n << tgt_mac[4]\n << \":\"\n << tgt_mac[5]\n << std::endl;\n Reading: aa\nReading: bb\nReading: cc\nReading: dd\nReading: ee\nReading: 11\nAs int array: aa:bb:cc:dd:ee:11\nAs unint8_t array: ª:»:I:Y:î:◄\n" }, { "answer_id": 276534, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "ostream& operator<<( ostream&, unsigned char ) uint8_t unsigned char unsigned __int8 char assert( uint8_t( parseHex( \"00\" ) ) == uint8_t(0) );\nassert( uint8_t( parseHex( \"01\" ) ) == uint8_t(1) );\n//...\nassert( uint8_t( parseHex( \"ff\" ) ) == uint8_t(255) );\n transform for( int j = 0 ; j < v.size() ; j++ ){\n tgt_mac[j] = parseHex(v.at(j)); \n}\n std::transform( v.begin(), v.end(), tgt_mac, &parseHex );\n" }, { "answer_id": 328332, "author": "D.Shawley", "author_id": 41747, "author_profile": "https://Stackoverflow.com/users/41747", "pm_score": 2, "selected": false, "text": "sscanf() void\nparse_mac(std::vector<uint8_t>& out, std::string const& in) {\n unsigned int bytes[6];\n if (std::sscanf(in.c_str(),\n \"%02x:%02x:%02x:%02x:%02x:%02x\",\n &bytes[0], &bytes[1], &bytes[2],\n &bytes[3], &bytes[4], &bytes[5]) != 6)\n {\n throw std::runtime_error(in+std::string(\" is an invalid MAC address\"));\n }\n out.assign(&bytes[0], &bytes[6]);\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29742/" ]
276,102
<p>Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?</p> <p>I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.</p> <p>something like:</p> <pre><code>global_catch() { MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR); exit(-1); } global_catch(Exception *except) { MessageBox(NULL,L"Fatal Error", except-&gt;ToString(), MB_ICONERROR); exit(-1); } </code></pre>
[ { "answer_id": 276110, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 6, "selected": true, "text": "catch (...)\n{\n std::cout << \"OMG! an unexpected exception has been caught\" << std::endl;\n}\n" }, { "answer_id": 276141, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "int main()\n{\n try\n {\n // Do Work\n }\n catch(std::exception const& e)\n {\n Log(e.what());\n // If you are feeling mad (not in main) you could rethrow! \n }\n catch(...)\n {\n Log(\"UNKNOWN EXCEPTION\");\n // If you are feeling mad (not in main) you could rethrow! \n }\n}\n" }, { "answer_id": 276280, "author": "paavo256", "author_id": 34911, "author_profile": "https://Stackoverflow.com/users/34911", "pm_score": 3, "selected": false, "text": "std::string ResurrectException()\n try {\n throw;\n } catch (const std::exception& e) {\n return e.what();\n } catch (your_custom_exception_type& e) {\n return e.ToString();\n } catch(...) {\n return \"Ünknown exception!\";\n }\n}\n\n\nint main() {\n try {\n // your code here\n } catch(...) {\n std::string message = ResurrectException();\n std::cerr << \"Fatal exception: \" << message << \"\\n\";\n }\n}\n" }, { "answer_id": 276296, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "void convertUnexpected()\n{\n // You could redefine the exception here into a known exception\n // throw UnexpectedException();\n\n // ... or I suppose you could log an error and exit.\n}\n std::set_unexpected( convertUnexpected );\n" }, { "answer_id": 9618664, "author": "kralyk", "author_id": 786102, "author_profile": "https://Stackoverflow.com/users/786102", "pm_score": 5, "selected": false, "text": "std::set_terminate() #include <iostream>\n#include <exception>\n#include <stdexcept>\n\nstruct FooException: std::runtime_error {\n FooException(const std::string& what): std::runtime_error(what) {}\n};\n\nint main() {\n std::set_terminate([]() {\n try {\n std::rethrow_exception(std::current_exception());\n } catch (const FooException& e) {\n std::cerr << \"Unhandled FooException: \" << e.what() << std::endl;\n } catch (const std::exception& e) {\n std::cerr << \"Unhandled exception: \" << e.what() << std::endl;\n } catch (...) {\n std::cerr << \"Unhandled exception of unknown type\" << std::endl;\n }\n\n std::abort();\n });\n\n throw FooException(\"Bad things have happened.\");\n // throw std::runtime_error(\"Bad things have happened.\");\n // throw 9001;\n}\n" }, { "answer_id": 37947336, "author": "scrutari", "author_id": 547270, "author_profile": "https://Stackoverflow.com/users/547270", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <exception>\n\nvoid onterminate() {\n try {\n auto unknown = std::current_exception();\n if (unknown) {\n std::rethrow_exception(unknown);\n } else {\n std::cerr << \"normal termination\" << std::endl;\n }\n } catch (const std::exception& e) { // for proper `std::` exceptions\n std::cerr << \"unexpected exception: \" << e.what() << std::endl;\n } catch (...) { // last resort for things like `throw 1;`\n std::cerr << \"unknown exception\" << std::endl;\n }\n}\n\nint main () {\n std::set_terminate(onterminate); // set custom terminate handler\n // code which may throw...\n return 0;\n}\n unexpected exception: wrong input parameters\nAborted\n terminate called after throwing an instance of 'std::logic_error'\n what(): wrong input parameters\nAborted\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
276,113
<p>Do bubble sorts have any real world use? Every time I see one mentioned, it's always either:</p> <ol> <li>A sorting algorithm to learn with.</li> <li>An example of a sorting algorithm <em>not</em> to use.</li> </ol>
[ { "answer_id": 276156, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 1, "selected": false, "text": "// Use sort of stooge to sort the three elements by cpFirst\n\nSwapElementsIfNeeded(&elementTop, &elementBottom);\nSwapElementsIfNeeded(&elementTop, &elementMiddle);\nSwapElementsIfNeeded(&elementMiddle, &elementBottom);\n\n*pelement1 = elementTop;\n*pelement2 = elementMiddle;\n*pelement3 = elementBottom;\n" }, { "answer_id": 328071, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 2, "selected": false, "text": "void bubbleSort(vector<int>& v) { // sort in ascending order\n bool go = true;\n while (go) {\n go = false;\n for (int i = 0; i+1 < v.size(); ++i)\n if (v[i] > v[i+1]) {\n swap(v[i], v[j]);\n go = true;\n }\n for (int i = (int)v.size()-1; i > 0; --i) \n if (v[i-1] > v[i]) {\n swap(v[i-1], v[i]);\n go = true;\n }\n }\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
276,121
<p>I have been using netbeans as a tool for my java, and i have a problem. I read <a href="http://www.netbeans.org/kb/61/java/gui-db-custom.html" rel="nofollow noreferrer">this tutorial</a> and then i tried to create a table using this SQL:</p> <pre><code>CREATE TABLE CUSTOMERS ( ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, FIRST_NAME VARCHAR(20), LAST_NAME VARCHAR(30), ADDRESS VARCHAR(30), CITY VARCHAR(30), STATE_ VARCHAR(30), ZIP VARCHAR(15), COUNTRY_ID INTEGER, PHONE VARCHAR(15), EMAIL_ADDRESS VARCHAR(50) )ENGINE=INNODB; </code></pre> <p>When i tried to run it, I got this error message:</p> <blockquote> <p>sql state 42X01 : Syntax error : encountered "AUTO_INCREMENT" at line 2 column 29</p> </blockquote> <p>and when i delete the AUTO_INCREMENT, another error:</p> <blockquote> <p>detected ENGINE=INNODB;</p> </blockquote> <p>can someone help me? Thanks.</p>
[ { "answer_id": 276129, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 1, "selected": false, "text": "CREATE TABLE CUSTOMERS \n( ID INTEGER NOT NULL auto_increment,\nFIRST_NAME VARCHAR(20), \nLAST_NAME VARCHAR(30), \nADDRESS VARCHAR(30), \nCITY VARCHAR(30), \nSTATE_ VARCHAR(30), \nZIP VARCHAR(15), \nCOUNTRY_ID INTEGER, \nPHONE VARCHAR(15), \nEMAIL_ADDRESS VARCHAR(50),\nPRIMARY KEY (ID));\n" }, { "answer_id": 29659770, "author": "Siegs", "author_id": 4793693, "author_profile": "https://Stackoverflow.com/users/4793693", "pm_score": -1, "selected": false, "text": "auto_increment ID INTEGER GENERATED ALWAYS AS IDENTITY, WHATEVER VARCHAR(20), ETC ETC..." } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,126
<p>Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).</p> <p>I would probably be making two separate queries, one to first find the list of questions, then another query to find all tags which belonged to the list of questions.</p> <p><em>Approach 1:</em></p> <p>Then I would probably be using nested repeaters and doing a select statement in the code-behind on each nested repeater "OnItemDataBind"...</p> <p><em>Approach 2:</em></p> <p>Or with the two datasets, I would use C# code to create a business entity of each of the "Questions" and have a property called "Tags". I would then loop through my tags dataset and assign the property.</p> <p>What's more efficient? Are there any other alternatives?</p>
[ { "answer_id": 276240, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 3, "selected": true, "text": "<asp:DataList ID=\"dlMenuOne\" runat=\"server\" onitemdatabound=\"dlMenu_ItemDataBound\" >\n <ItemTemplate>\n //your object\n\n <asp:DataList ID=\"dlMenuTwo\" runat=\"server\" onitemdatabound=\"dlMenuTwo_ItemDataBound\">\n <ItemTemplate>\n //your object's child items\n\n <asp:DataList ID=\"dlMenuThree\" runat=\"server\">\n <ItemTemplate>\n //child item's child items \n </ItemTemplate>\n </asp:DataList>\n\n </ItemTemplate>\n </asp:DataList> \n\n </ItemTemplate>\n </asp:DataList>\n protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n DataListItem parentList = e.Item;\n DataList dlMenuTwo = (DataList)parentList.FindControl(\"dlMenuTwo\");\n MenuItem item = (MenuItem)parentList.DataItem;\n dlMenuTwo.DataSource = _menu.GetChildItems(item);\n dlMenuTwo.DataBind();\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
276,132
<p>I'm setting up an Internet-facing ASP.NET MVC application, on Windows 2008. It uses SQL Server 2008 for its database. I'm looking for best-practices for securing it.</p> <p>I found <a href="http://www.enterprisenetworkingplanet.com/netsecur/article.php/3552711" rel="nofollow noreferrer">this article</a>, but it's a bit dated now. How much of that advice is still valuable?</p> <p>Some background -- it's a personal site, behind my home NAT/firewall box; and I'll only forward ports 80 and 443 to it. The IIS server itself is a Windows 2008 host running on HyperV (I only have one physical box to spare).</p> <p>One useful thing that's mentioned in that article (which had occurred to me already) is that the IIS box shouldn't be a member of the domain, so that an intruder can't easily get off the box. I'll be removing it from the domain in a moment :)</p> <p>What other tips should I (and anyone deploying to a bigger environment) bear in mind?</p> <p>I know that this isn't strictly a programming-related question (there's no source code in it!), but I guess that most programmers have to dabble in operations stuff when it comes to deployment recommendations.</p>
[ { "answer_id": 276240, "author": "flesh", "author_id": 27805, "author_profile": "https://Stackoverflow.com/users/27805", "pm_score": 3, "selected": true, "text": "<asp:DataList ID=\"dlMenuOne\" runat=\"server\" onitemdatabound=\"dlMenu_ItemDataBound\" >\n <ItemTemplate>\n //your object\n\n <asp:DataList ID=\"dlMenuTwo\" runat=\"server\" onitemdatabound=\"dlMenuTwo_ItemDataBound\">\n <ItemTemplate>\n //your object's child items\n\n <asp:DataList ID=\"dlMenuThree\" runat=\"server\">\n <ItemTemplate>\n //child item's child items \n </ItemTemplate>\n </asp:DataList>\n\n </ItemTemplate>\n </asp:DataList> \n\n </ItemTemplate>\n </asp:DataList>\n protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n DataListItem parentList = e.Item;\n DataList dlMenuTwo = (DataList)parentList.FindControl(\"dlMenuTwo\");\n MenuItem item = (MenuItem)parentList.DataItem;\n dlMenuTwo.DataSource = _menu.GetChildItems(item);\n dlMenuTwo.DataBind();\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446/" ]
276,166
<p>table data of 2 columns "category" and "subcategory"</p> <p>i want to get a collection of "category", [subcategories] using code below i get duplicates. Puting .Distinct() after outer "from" does not help much. What do i miss?</p> <pre><code> var rootcategories = (from p in sr.products orderby p.category select new { category = p.category, subcategories = ( from p2 in sr.products where p2.category == p.category select p2.subcategory).Distinct() }).Distinct(); </code></pre> <p>sr.products looks like this</p> <pre><code>category subcategory ---------------------- cat1 subcat1 cat1 subcat2 cat2 subcat3 cat2 subcat3 </code></pre> <p>what i get in results is </p> <pre><code>cat1, [subcat1,subcat2] cat1, [subcat1,subcat2] </code></pre> <p>but i only want one entry</p> <p>solved my problem with this code:</p> <pre><code> var rootcategories2 = (from p in sr.products group p.subcategory by p.category into subcats select subcats); </code></pre> <p>now maybe it is time to think of what was the right question.. (-:</p>
[ { "answer_id": 276171, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "var mainCategories = (from p in products select p.category).Distinct();\n\nvar rootCategories =\n from c in mainCategories\n select new {\n category = c,\n subcategories = (from p in products\n where p.category == c\n select p.subcategory).Distinct()\n };\n" }, { "answer_id": 276202, "author": "Alexander Taran", "author_id": 35954, "author_profile": "https://Stackoverflow.com/users/35954", "pm_score": 4, "selected": true, "text": " var rootcategories2 = (from p in sr.products\n group p.subcategory by p.category into subcats\n\n select subcats);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35954/" ]
276,173
<p>What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with <code>delete[]</code>. </p> <p>Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.</p> <pre><code>TextFileProcessor:: TextFileProcessor( class ConstStringFinder&amp; theConstStringFinder ) : TextFileProcessor_Base( theConstStringFinder ) , m_ThreadHandle ( NULL ) , m_startNLSearch ( 0 ) , m_endNLSearch ( 0 ) , m_LineEndGetIdx ( 0 ) , m_LineEndPutIdx ( 0 ) , m_LineEnds ( new const void*[ sc_LineEndSize ] ) { ; } </code></pre>
[ { "answer_id": 276201, "author": "Ather", "author_id": 1065163, "author_profile": "https://Stackoverflow.com/users/1065163", "pm_score": 1, "selected": false, "text": "int ReturnMaxValue(\n int* inputList, /* the list of integer values from which to get the maximum */\n long size, /* count of the number of integer values in inputList */\n char* extraArgs /* additional arguments that a caller can provide. */\n)\n" }, { "answer_id": 276276, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "int function(void) /* return 1 on success, 0 on failure */ \n{\n return 1;\n};\n" }, { "answer_id": 276302, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "bool MyObjects::isUpToSomething() ///< Is my object up to something \n" }, { "answer_id": 276481, "author": "zerbp", "author_id": 35744, "author_profile": "https://Stackoverflow.com/users/35744", "pm_score": 4, "selected": false, "text": "if if ( ( (var1A == var2A)\n || (var1B == var2B))\n && ( (var1C == var2C)\n || (var1D == var2D)))\n{\n // do something\n}\n" }, { "answer_id": 276550, "author": "Prembo", "author_id": 24376, "author_profile": "https://Stackoverflow.com/users/24376", "pm_score": 5, "selected": false, "text": "int myVar = 1; // comment 1\nint myLongerVar = 200; // comment 2\n\nMyStruct arrayOfMyStruct[] = \n{ \n // Name, timeout, valid\n {\"A string\", 1000, true }, // Comment 1\n {\"Another string\", 2000, false }, // Comment 2 \n {\"Yet another string\", 11111000, false }, // Comment 3\n {NULL, 5, true }, // Comment 4\n};\n int myVar = 1; // comment 1\nint myLongerVar = 200; // comment 2\n\nMyStruct arrayOfMyStruct[] = \n{ \n // Name, timeout, valid\n {\"A string\", 1000, true},// Comment 1\n {\"Another string\", 2000, false }, // Comment 2 \n {\"Yet another string\", 11111000,false}, // Comment 3\n {NULL, 5, true }, // Comment 4\n};\n" }, { "answer_id": 276560, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 3, "selected": false, "text": "git grep -I -E '<tab>|.{81,}| *$' | cut -f1 -d: | sort -u\n <tab>" }, { "answer_id": 276570, "author": "kshahar", "author_id": 33982, "author_profile": "https://Stackoverflow.com/users/33982", "pm_score": 7, "selected": true, "text": "namespace EntityType {\n enum Enum {\n Ground = 0,\n Human,\n Aerial,\n Total\n };\n}\n\nvoid foo(EntityType::Enum entityType)\n{\n if (entityType == EntityType::Ground) {\n /*code*/\n }\n}\n enum class enum struct enum class enum class EntityType {\n Ground = 0,\n Human,\n Aerial,\n Total\n};\n\nvoid foo(EntityType entityType)\n{\n if (entityType == EntityType::Ground) {\n /*code*/\n }\n}\n int" }, { "answer_id": 278764, "author": "mempko", "author_id": 8863, "author_profile": "https://Stackoverflow.com/users/8863", "pm_score": 2, "selected": false, "text": "int myFunc(int x) {\n if(x >20) return -1;\n //do other stuff ....\n}\n" }, { "answer_id": 280625, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "grep -R '^fun_name' .\n static void\nfun_name (int a, int b) {\n /* ... */\n}\n" }, { "answer_id": 282402, "author": "Jamie Hale", "author_id": 34533, "author_profile": "https://Stackoverflow.com/users/34533", "pm_score": 3, "selected": false, "text": "void foo( int a, int b )\n{\n int c = a + ( a * ( a * b ) );\n if ( c > 12 )\n c += 9;\n return foo( 2, c );\n}\n" }, { "answer_id": 282745, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": -1, "selected": false, "text": "if (condition)\n{\n complicated code goes here\n}\nelse\n{\n /* This is a comment as to why the else path isn't significant */ \n}\n" }, { "answer_id": 2034320, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 6, "selected": false, "text": "void foo() {\n std::fstream file(\"bar.txt\"); // open a file \"bar.txt\"\n if (rand() % 2) {\n // if this exception is thrown, we leave the function, and so\n // file's destructor is called, which closes the file handle.\n throw std::exception();\n }\n // if the exception is not called, we leave the function normally, and so\n // again, file's destructor is called, which closes the file handle.\n}\n" }, { "answer_id": 2034352, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 5, "selected": false, "text": "windows.h HANDLE HANDLE windows.h class private_foo; // a forward declaration a pointer may be used\n\n// foo.h\nclass foo {\npublic:\n foo();\n ~foo();\n void bar();\nprivate:\n private_foo* pImpl;\n};\n\n// foo.cpp\n#include whichever header defines the types T and U\n\n// define the private implementation class\nclass private_foo {\npublic:\n void bar() { /*...*/ }\n\nprivate:\n T member1;\n U member2;\n};\n\n// fill in the public interface function definitions:\nfoo::foo() : pImpl(new private_foo()) {}\nfoo::~foo() { delete pImpl; }\nvoid foo::bar() { pImpl->bar(); }\n foo foo.cpp" }, { "answer_id": 2034439, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "template<class Derived>\nstruct BaseCRTP {};\n\nstruct Example : BaseCRTP<Example> {};\n template<class Derived>\nstruct BaseCRTP {\n void call_foo() {\n Derived& self = *static_cast<Derived*>(this);\n self.foo();\n }\n};\n\nstruct Example : BaseCRTP<Example> {\n void foo() { cout << \"foo()\\n\"; }\n};\n" }, { "answer_id": 2034447, "author": "RC.", "author_id": 22118, "author_profile": "https://Stackoverflow.com/users/22118", "pm_score": 5, "selected": false, "text": "struct String {\n String(String const& other);\n\n String& operator=(String copy) { // passed by value\n copy.swap(*this); // nothrow swap\n return *this; // old resources now in copy, released in its dtor\n }\n\n void swap(String& other) throw() {\n using std::swap; // enable ADL, defaulting to std::swap\n swap(data_members, other.data_members);\n }\n\nprivate:\n Various data_members;\n};\nvoid swap(String& a, String& b) { // provide non-member for ADL\n a.swap(b);\n}\n *this" }, { "answer_id": 2034614, "author": "seh", "author_id": 31818, "author_profile": "https://Stackoverflow.com/users/31818", "pm_score": 3, "selected": false, "text": "#include <stdexcept>\n\ntemplate <typename T>\nT twice(T n) {\n return 2 * n;\n}\n\nInIt find(InIt f, InIt l,\n typename std::iterator_traits<InIt>::reference v)\n{\n while (f != l && *f != v)\n ++f;\n return f;\n} \n\nint main(int argc, char* argv[]) {\n if (6 != twice(3))\n throw std::logic_error(\"3 x 2 = 6\");\n\n int const nums[] = { 1, 2, 3 };\n if (nums + 4 != find(nums, nums + 4, 42))\n throw std::logic_error(\"42 should not have been found.\");\n\n return 0;\n}\n twice * find()" }, { "answer_id": 2034627, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 3, "selected": false, "text": "class Class {\n void PrintInvoice(); // Called Template (boilerplate) which uses CalcRate()\n virtual void CalcRate() = 0; // Called Hook\n}\n\nclass SubClass : public Class {\n virtual void CalcRate(); // Customized method\n}\n" }, { "answer_id": 3852294, "author": "franji1", "author_id": 346104, "author_profile": "https://Stackoverflow.com/users/346104", "pm_score": 3, "selected": false, "text": "if (expression) // preferred - if keyword sticks out more\n if(expression) // looks too much like a void function call\n foo(parm1, parm2);\n" }, { "answer_id": 6424851, "author": "Sebastian Mach", "author_id": 76722, "author_profile": "https://Stackoverflow.com/users/76722", "pm_score": 4, "selected": false, "text": "private: class Widget : public Purple {\npublic:\n // Factory methods.\n Widget FromRadians (float);\n Widget FromDegrees (float);\n\n // Ctors, rule of three, swap\n Widget();\n Widget (Widget const&);\n Widget &operator = (Widget const &);\n void swap (Widget &) throw();\n\n // Member methods.\n float area() const;\n\n // in case of qt {{ \npublic slots:\n void invalidateBlackHole();\n\nsignals:\n void areaChanged (float);\n // }}\n\nprotected: \n // same as public, but for protected members\n\n\nprivate: \n // same as public, but for private members\n\nprivate:\n // data\n float widgetness_;\n bool isMale_;\n};\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18256/" ]
276,177
<p>In my ASP.NET 1.1 application, I am compressing and replacing the hidden Viewstate variable with an alternate compressed value, stored in a hidden field called __VSTATE. This works well but on a few occasions, submitting a page causes the common "potentially dangerous Request.Form value ..." error.</p> <p>I examined the __VSTATE value and nothing seems to be potentially dangerous. I was able to reproduce the error with a completely stripped down version of the page and __VSTATE value as shown below. Pressing the submit button causes the error. The page works fine if I change the value to "".</p> <pre><code>&lt;%@ Page Language="vb" AutoEventWireup="false" Codebehind="Dangerous.aspx.vb" Inherits="Dynalabs.Dangerous" %&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt; &lt;html&gt; &lt;body MS_POSITIONING="FlowLayout"&gt; &lt;form id="Form1" method="post" runat="server"&gt; &lt;input type="hidden" id="__VSTATE" runat="server" value="Onw=" /&gt; &lt;asp:Button ID="btnSubmit" Runat="server" Text="Submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Changing the field name to "MyHiddenWT" made no difference. Removing the runat="server" did stop the error but that just means that .NET only examines server side controls. I also tried some additional values and found that of the following:</p> <pre><code>"Anw=", "Bnw=", "Cnw=", ... "Nnw=", "Onw=", "Pnw=", ... "Znw=", </code></pre> <p>"Onw=" is the only one that causes the problem. Is the captial O being seen as an octal value somehow?</p> <p>Can someone explain why this value is triggering the error message? I'm also looking for a solution but, please, do not tell me to remove page validation. That's the same as saying a car with bad brakes can be fixed by not driving the car.</p> <p>Thank you in advance.</p>
[ { "answer_id": 276270, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<input type=\"hidden\" id=\"__VSTATE\" runat=\"server\" value=\"vOnw=\" />\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35955/" ]
276,179
<p>Does anyone know which property sets the text color for disabled control? I have to display some text in a disabled <code>TextBox</code> and I want to set its color to black.</p>
[ { "answer_id": 276193, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 7, "selected": true, "text": "BackColor TextBox TextBox ReadOnly true TextBox OnPaint ReadOnly !Enabled TextBox TextBox TextBox Label TextBox" }, { "answer_id": 631983, "author": "Cheetah", "author_id": 7649, "author_profile": "https://Stackoverflow.com/users/7649", "pm_score": 6, "selected": false, "text": "private void FormFoo_Load(...) {\n txtFoo.BackColor = txtFoo.BackColor;\n}\n" }, { "answer_id": 4989598, "author": "syed qaiser", "author_id": 615830, "author_profile": "https://Stackoverflow.com/users/615830", "pm_score": 3, "selected": false, "text": "txtFingerPrints.BackColor = System.Drawing.SystemColors.Info;\ntxtFingerPrints.ReadOnly = true;\n" }, { "answer_id": 6214818, "author": "Zain Ali", "author_id": 538789, "author_profile": "https://Stackoverflow.com/users/538789", "pm_score": 2, "selected": false, "text": " protected override void OnPaint(PaintEventArgs e)\n{\n SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property\n // Draw string to screen.\n e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property\n}\n public MyTextBox()//constructor\n{\n // This call is required by the Windows.Forms Form Designer.\n this.SetStyle(ControlStyles.UserPaint,true);\n\n InitializeComponent();\n\n // TODO: Add any initialization after the InitForm call\n}\n int index=this.Controls.IndexOf(this.textBox1);\n\nthis.Controls[index-1].Focus();\n" }, { "answer_id": 22564822, "author": "Johnie Karr", "author_id": 403404, "author_profile": "https://Stackoverflow.com/users/403404", "pm_score": 1, "selected": false, "text": "tabstop private void FormFoo_Load(...) {\n txtFoo.Select(0, 0);\n}\n private void FormFoo_Load(...) {\n txtFoo.SelectionLength = 0;\n}\n" }, { "answer_id": 27027829, "author": "edoedoedo", "author_id": 3834178, "author_profile": "https://Stackoverflow.com/users/3834178", "pm_score": 3, "selected": false, "text": "public class DisabledRichTextBox : System.Windows.Forms.RichTextBox\n{\n // See: http://wiki.winehq.org/List_Of_Windows_Messages\n\n private const int WM_SETFOCUS = 0x07;\n private const int WM_ENABLE = 0x0A;\n private const int WM_SETCURSOR = 0x20;\n\n protected override void WndProc(ref System.Windows.Forms.Message m)\n {\n if (!(m.Msg == WM_SETFOCUS || m.Msg == WM_ENABLE || m.Msg == WM_SETCURSOR))\n base.WndProc(ref m);\n }\n}\n" }, { "answer_id": 27971127, "author": "Mahmoud Salah", "author_id": 4408537, "author_profile": "https://Stackoverflow.com/users/4408537", "pm_score": 1, "selected": false, "text": "private void TextBoxName_EnabledChanged(System.Object sender, System.EventArgs e)\n{\n ((TextBox)sender).ForeColor = Color.Black;\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
276,180
<p>What software does everyone use to monitor hardware? I know about nagios and cacti, but does anyone use any other software?</p>
[ { "answer_id": 3765800, "author": "VxJasonxV", "author_id": 106813, "author_profile": "https://Stackoverflow.com/users/106813", "pm_score": 0, "selected": false, "text": "god" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,184
<p>Is there any example code of a <a href="http://www.python.org/" rel="noreferrer">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
[ { "answer_id": 3865315, "author": "r3nrut", "author_id": 373428, "author_profile": "https://Stackoverflow.com/users/373428", "pm_score": 4, "selected": false, "text": "from suds.client import Client\n\nprint \"Connecting to Service...\"\nwsdl = \"http://serviceurl.com/service.svc?WSDL\"\nclient = Client(wsdl)\nresult = client.service.Method(variable1, variable2)\nprint result\n" }, { "answer_id": 36152458, "author": "Sovetnikov", "author_id": 590233, "author_profile": "https://Stackoverflow.com/users/590233", "pm_score": 2, "selected": false, "text": "from suds.plugin import MessagePlugin\nfrom suds.sax.text import Text\nfrom suds.wsse import Security, UsernameToken\nfrom suds.sax.element import Element\nfrom suds.sax.attribute import Attribute\nfrom suds.xsd.sxbasic import Import\n\napi_username = 'some'\napi_password = 'none'\n\nclass api(object):\n api_direct_url = 'some/mex'\n api_url = 'some.svc?singleWsdl|Wsdl'\n\n NS_WSA = ('wsa', 'http://www.w3.org/2005/08/addressing')\n\n _client_instance = None\n @property\n def client(self):\n if self._client_instance:\n return self._client_instance\n from suds.bindings import binding\n binding.envns = ('SOAP-ENV', 'http://www.w3.org/2003/05/soap-envelope')\n\n api_inst = self\n class _WSAPlugin(MessagePlugin):\n def marshalled(self, context):\n api_inst._marshalled_message(context)\n\n self._client_instance = Client(self.api_url,\n plugins=[_WSAPlugin()],\n headers={'Content-Type': 'application/soap+xml',\n 'login':api_username,\n 'password': api_password}\n )\n headers = []\n headers.append(Element('To', ns=self.NS_WSA).setText(self.api_direct_url))\n headers.append(Element('Action', ns=self.NS_WSA).setText('Blank'))\n self._client_instance.set_options(soapheaders=headers)\n\n cache = self._client_instance.options.cache\n cache.setduration(days=10)\n return self._client_instance\n\n def _marshalled_message(self, context):\n def _children(r):\n if hasattr(r, 'children'):\n for c in r.children:\n yield from _children(c)\n yield c\n for el in _children(context.envelope):\n if el.name == 'Action':\n el.text = Text(self._current_action)\n return\n\n _current_action = None\n def _invoke(self, method, *args):\n try:\n self._current_action = method.method.soap.action.strip('\"')\n return method(*args)\n finally:\n self._current_action = None\n\n def GetRequestTypes(self):\n return self._invoke(self.client.service.GetRequestTypes)[0]\n\n def GetTemplateByRequestType(self, request_type_id):\n js = self._invoke(self.client.service.GetTemplateByRequestType, request_type_id)\n return json.loads(js)\n\n def GetRequestStatus(self, request_guid):\n return self._invoke(self.client.service.GetRequestStatus, request_guid)\n\n def SendRequest(self, request_type_id, request_json):\n r = json.dumps(request_json, ensure_ascii=False)\n return self._invoke(self.client.service.SendRequest, request_type_id, r)\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30289/" ]
276,188
<p>C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ?</p>
[ { "answer_id": 276197, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "printf" }, { "answer_id": 277487, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "template<typename... T> struct flexible : T... { flexible(): T()... { } };\n struct my_container { template<typename... T> my_container(T&&... t) { } };\nmy_container c = { a, b, c };\n template<char... digits>\nint operator \"\" b() { return convert<digits...>::value; }\n" }, { "answer_id": 12038087, "author": "cppist", "author_id": 1486168, "author_profile": "https://Stackoverflow.com/users/1486168", "pm_score": 1, "selected": false, "text": "void setSizes(uintmax_t currentSize) {\n static_assert(1 == NDimensions, \"Invalid count of arguments given to setSizes.\");\n\n size_ = currentSize;\n data_ = new NDArrayReferenceType[currentSize];\n}\n\ntemplate <typename... Sizes>\nvoid setSizes(uintmax_t currentSize, Sizes... sizes) {\n static_assert(sizeof...(Sizes) + 1 == NDimensions, \"Invalid count of arguments given to setSizes.\");\n\n size_ = currentSize;\n data_ = new NDArrayReferenceType[currentSize];\n\n for (uintmax_t i = 0; i < currentSize; i++) {\n data_[i]->setSizes(sizes...);\n }\n}\n template <typename TSmartPointer, typename... Args>\nstatic inline void initialize(TSmartPointer *smartPointer, Args... args) {\n smartPointer->pointer_ = new typename TSmartPointer::PointerType(std::forward<Args>(args)...);\n smartPointer->__retain();\n}\n AbstractObject object = ConcreteObject(42, 42);\n" }, { "answer_id": 35366278, "author": "vitaut", "author_id": 471164, "author_profile": "https://Stackoverflow.com/users/471164", "pm_score": 0, "selected": false, "text": "fmt::print(\"I'd rather be {1} than {0}.\", \"right\", \"happy\");\n lld PRIdPTR std::printf(\"Local number: %\" PRIdPTR \"\\n\\n\", someIntPtr);\n fmt::printf(\"Local number: %d\\n\\n\", someIntPtr);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630/" ]
276,198
<p>What would be the best way to manage large number of instances of the same class in MATLAB?</p> <p>Using the naive way produces absymal results:</p> <pre><code>classdef Request properties num=7; end methods function f=foo(this) f = this.num + 4; end end end &gt;&gt; a=[]; &gt;&gt; tic,for i=1:1000 a=[a Request];end;toc Elapsed time is 5.426852 seconds. &gt;&gt; tic,for i=1:1000 a=[a Request];end;toc Elapsed time is 31.261500 seconds. </code></pre> <p>Inheriting handle drastically improve the results:</p> <pre><code>classdef RequestH &lt; handle properties num=7; end methods function f=foo(this) f = this.num + 4; end end end &gt;&gt; tic,for i=1:1000 a=[a RequestH];end;toc Elapsed time is 0.097472 seconds. &gt;&gt; tic,for i=1:1000 a=[a RequestH];end;toc Elapsed time is 0.134007 seconds. &gt;&gt; tic,for i=1:1000 a=[a RequestH];end;toc Elapsed time is 0.174573 seconds. </code></pre> <p>but still not an acceptable performance, especially considering the increasing reallocation overhead </p> <p>Is there a way to preallocate class array? Any ideas on how to manage lange quantities of object effectively?</p> <p>Thanks,<br> Dani</p>
[ { "answer_id": 276530, "author": "Marc", "author_id": 8478, "author_profile": "https://Stackoverflow.com/users/8478", "pm_score": 2, "selected": false, "text": "repmat b = repmat(Request, 1000, 1);\n\nElapsed time is 0.056720 seconds\n\n\nb = repmat(RequestH, 1000, 1);\nElapsed time is 0.021749 seconds.\n" }, { "answer_id": 285407, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 3, "selected": true, "text": ">> a = repmat(RequestH,10000,1);tic,for i=1:10000 a(i)=RequestH;end;toc\nElapsed time is 0.396645 seconds.\n >> a=[];tic,for i=1:10000 a=[a RequestH];end;toc\nElapsed time is 2.313368 seconds.\n" }, { "answer_id": 2417773, "author": "jjkparker", "author_id": 283735, "author_profile": "https://Stackoverflow.com/users/283735", "pm_score": 3, "selected": false, "text": "a = Request.empty(1000,0); tic; for i=1:1000, a(i)=Request; end; toc;\nElapsed time is 0.087539 seconds.\n a(1000, 1) = Request;\nElapsed time is 0.019755 seconds.\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28772/" ]
276,206
<p>I have a form made up of multiple, optional subparts - each of which is enclosed in a</p> <pre><code>&lt;div class="details"&gt;&lt;/div&gt; </code></pre> <p>When editing the form I would like to hide those subparts which aren't as yet completed, and obviously I would like to do it unobtrusively. To simplify things I'm just checking to see if those fields whose name ends in 'surname' are empty, and then show/hide appropriately. So far, I have this.</p> <pre><code>//hide the all of the element class details $(".details").each(function (i) { if ($('input[name$=surname]:empty',this).length == 1) { $(this).hide(); } else { $(this).show(); } }); </code></pre> <p>Of course, the :empty selector may be wrong, or indeed inappropriate. (Of course what I really want to do is show any parts where any fields are completed, but I thought I'd start with just checking the most important one.)</p> <p>I would be greatful if anyone could anyone point me in the right direction...</p>
[ { "answer_id": 276221, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 4, "selected": true, "text": "<div class=\"details\">\n <input type=\"text\" name=\"surname\" />\n</div>\n\n<script type=\"text/javascript\">\n $(\".details input[@value='']\").parents(\".details\").hide();\n</script>\n" }, { "answer_id": 276294, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "$(\"div.details input\").each(function () {\n if (this.value == \"\")\n $(this).parents(\"div.details\").eq(1).hide();\n else\n $(this).parents(\"div.details\").eq(1).show();\n});\n $(\"div.details input[name$=surname]\").each(function () { /* etc... */\n" }, { "answer_id": 276327, "author": "Dycey", "author_id": 35961, "author_profile": "https://Stackoverflow.com/users/35961", "pm_score": 2, "selected": false, "text": " //hide the all of the element class details\n $(\".details\").each(function (i) {\n if ($('input[name$=surname][value=\"\"]',this).length == 1) { \n $(this).hide();\n console.log('hiding');\n } else {\n $(this).show();\n console.log('showing');\n }\n });\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35961/" ]
276,212
<p>I have a table in a database that represents dates textually (i.e. "2008-11-09") and I would like to replace them with the UNIX timestamp. However, I don't think that MySQL is capable of doing the conversion on its own, so I'd like to write a little script to do the conversion. The way I can think to do it involves getting all the records in the table, iterating through them, and updating the database records. However, with no primary key, I can't easily get the exact record I need to update.</p> <p>Is there a way to get MySQL to assign temporary IDs to records during a SELECT so that I refer back to them when doing UPDATEs?</p>
[ { "answer_id": 276226, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 1, "selected": false, "text": "ALTER TABLE t ADD COLUMN dates DATETIME;\nUPDATE t set t.dates=t.olddate;\n" }, { "answer_id": 276228, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "UPDATE\n MyTable\nSET\n MyTimeStamp = UNIX_TIMESTAMP(MyDateTime);\n" }, { "answer_id": 276234, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "SELECT UPDATE SET @v := 0;\nSELECT @v:=@v+1, * FROM mytable;\n ALTER TABLE mytable ADD COLUMN unix_timestamp INT UNSIGNED NOT NULL DEFAULT 0;\n\nUPDATE mytable\nSET unix_timestamp = UNIX_TIMESTAMP( STR_TO_DATE( text_timestamp, '%Y-%m-%d' ) );\n\nALTER TABLE mytable DROP COLUMN text_timestamp;\n UNIX_TIMESTAMP() STR_TO_DATE()" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
276,249
<p>I have this form:</p> <pre><code>&lt;form name="customize"&gt; Only show results within &lt;select name="distance" id="slct_distance"&gt; &lt;option&gt;25&lt;/option&gt; &lt;option&gt;50&lt;/option&gt; &lt;option&gt;100&lt;/option&gt; &lt;option value="10000" selected="selected"&gt;Any&lt;/option&gt; &lt;/select&gt; miles of zip code &lt;input type="text" class="text" name="zip_code" id="txt_zip_code" /&gt; &lt;span id="customize_validation_msg"&gt;&lt;/span&gt; &lt;/form&gt; </code></pre> <p>How can I select the <code>input</code> and <code>select</code> with one jQuery selector?</p> <p>I tried this but it selected all of the selects and inputs on the page:</p> <pre><code>$("form[name='customize'] select,input") </code></pre>
[ { "answer_id": 276267, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 2, "selected": false, "text": "form[name='customize'] select, form[name='customize'] input\n $(\"form[name='customize'] select, input\").css( 'font-size', '80px' );\n" }, { "answer_id": 276284, "author": "Kevin Gorski", "author_id": 35806, "author_profile": "https://Stackoverflow.com/users/35806", "pm_score": 6, "selected": true, "text": "$(\"form[name='customize'] select, form[name='customize'] input\")\n $(\"form[name='customize']\").children(\"select, input\")\n" }, { "answer_id": 276299, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 3, "selected": false, "text": "// all spans\n$(\"span\").css(\"background-color\",\"#ff0\");\n\n// spans below a post-text class\n$(\"span\", \".post-text\").css(\"background-color\",\"#f00\");\n // spans and p's below a post-text class\n$(\"span,p\", \".post-text\").css(\"background-color\",\"#f00\");\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
276,253
<p>C#: How do you pass an object in a function parameter?</p> <pre><code>public void MyFunction(TextBox txtField) { txtField.Text = "Hi."; } </code></pre> <p>Would the above be valid? Or?</p>
[ { "answer_id": 276279, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "public void MyFunction(ref MyMutableStruct whatever)\n{\n whatever.Value = \"Hi.\"; // but avoid mutable structs in the first place!\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,254
<p>I have a window (derived from JFrame) and I want to disable the close button during certain operations which are not interruptible. I know I can make the button not do anything (or call a handler in a WindowListener) by calling</p> <pre><code>setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); </code></pre> <p>but I would like to make it clear visually that it is pointless to click it.</p>
[ { "answer_id": 279826, "author": "Malfist", "author_id": 12243, "author_profile": "https://Stackoverflow.com/users/12243", "pm_score": 5, "selected": false, "text": "setUndecorated(true);\ngetRootPane().setWindowDecorationStyle(JRootPane.NONE);\n" }, { "answer_id": 27587807, "author": "Ab Hin", "author_id": 1497868, "author_profile": "https://Stackoverflow.com/users/1497868", "pm_score": -1, "selected": false, "text": "frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {\n e.getWindow().setVisible(false);\n try {\n wait();\n } catch (InterruptedException ex) {\n Logger.getLogger(WindowsActions.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n });\n" }, { "answer_id": 29060254, "author": "Vörös Richárd", "author_id": 4673020, "author_profile": "https://Stackoverflow.com/users/4673020", "pm_score": 3, "selected": false, "text": "frame.setDefaultCloseOperation(0);\n" }, { "answer_id": 53951512, "author": "Cancer000", "author_id": 10840859, "author_profile": "https://Stackoverflow.com/users/10840859", "pm_score": 0, "selected": false, "text": "setUndecorated(true);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18308/" ]
276,266
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p> <blockquote> <p>The error is "IOError: [Errorno Invalid output device (no default output device)] -9996</p> </blockquote> <p>Is there another library I could try to use? Another method?</p>
[ { "answer_id": 276322, "author": "lpfavreau", "author_id": 35935, "author_profile": "https://Stackoverflow.com/users/35935", "pm_score": 2, "selected": false, "text": "import time, wave, pymedia.audio.sound as sound\nf= wave.open('YOUR FILE NAME', 'rb')\nsampleRate= f.getframerate()\nchannels= f.getnchannels()\nformat= sound.AFMT_S16_LE\nsnd= sound.Output(sampleRate, channels, format)\ns= f.readframes(300000)\nsnd.play(s)\nwhile snd.isPlaying(): time.sleep(0.05)\n get_default_output_device_info" }, { "answer_id": 277274, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 4, "selected": false, "text": "sound = wx.Sound('sound.wav')\nsound.Play(wx.SOUND_SYNC)\n sound.Play(wx.SOUND_ASYNC)\n" }, { "answer_id": 277429, "author": "Mauli", "author_id": 917, "author_profile": "https://Stackoverflow.com/users/917", "pm_score": 1, "selected": false, "text": "from pygame import mixer\n\nmixer.init()\ns = mixer.Sound('sound.wav')\ns.play()\n" }, { "answer_id": 36284017, "author": "Erwin Mayer", "author_id": 541420, "author_profile": "https://Stackoverflow.com/users/541420", "pm_score": 2, "selected": false, "text": "> pip install simpleaudio\n import simpleaudio as sa\n\nwave_obj = sa.WaveObject.from_wave_file(\"path/to/file.wav\")\nplay_obj = wave_obj.play()\nplay_obj.wait_done()\n" }, { "answer_id": 48409739, "author": "Nae", "author_id": 7032856, "author_profile": "https://Stackoverflow.com/users/7032856", "pm_score": 1, "selected": false, "text": "playsound from playsound import playsound\n\nis_synchronus = False\nplaysound(r\"C:\\Windows\\Media\\chimes.wav\", is_synchronus)\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14520/" ]
276,278
<p>Comparing LinkedLists and Arrays while also comparing their differences with sorted and unsorted data</p> <ul> <li>Adding </li> <li>Removing</li> <li>Retrieving </li> <li>Sorting</li> <li>Overall speed</li> <li>Overall memory usage</li> </ul> <p>Actual questions</p> <blockquote> <p>Discuss the feasibility of implementing an unsorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application?</p> <p>Discuss the feasibility of implementing a sorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application? </p> <p>Based on your answers to the previous questions, summarize the costs and benefits of using linked lists in an application.</p> </blockquote> <p>My answers/input:</p> <blockquote> <p>LinkedLists have to allocate memory everytime a new Node is added, useful when adding many Nodes and size keeps changing but generally slower when adding few elements</p> <p>Arrays allocated memory at the beggining of the program run, resizing list slow (adding many elements slow if have to resize)</p> <p>Retrieval is faster in array due to indexing</p> <p>Adding/removing faster in LinkedList due to pointers</p> </blockquote>
[ { "answer_id": 276361, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 3, "selected": true, "text": "* Adding\n * Removing\n* Retrieving\n* Sorting\n* Overall speed\n* Overall memory usage\n" }, { "answer_id": 50168373, "author": "Sandeep Singh", "author_id": 4067548, "author_profile": "https://Stackoverflow.com/users/4067548", "pm_score": 1, "selected": false, "text": "Here is a C++ code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let’s try out a sample C++ program to understand the problem statement better.\n #include <iostream>\n#include <algorithm>\n#include <ctime>\nusing namespace std;\n\nconst int N = 100001;\n\nint main()\n{\n int arr[N];\n\n // Assign random values to array\n for (int i=0; i<N; i++)\n arr[i] = rand()%N;\n\n // for loop for unsorted array\n int count = 0;\n double start = clock();\n for (int i=0; i<N; i++)\n if (arr[i] < N/2)\n count++;\n\n double end = clock();\n cout << \"Time for unsorted array :: \"\n << ((end - start)/CLOCKS_PER_SEC)\n << endl;\n sort(arr, arr+N);\n\n // for loop for sorted array\n count = 0;\n start = clock();\n\n for (int i=0; i<N; i++)\n if (arr[i] < N/2)\n count++;\n\n end = clock();\n cout << \"Time for sorted array :: \"\n << ((end - start)/CLOCKS_PER_SEC)\n << endl;\n\n return 0;\n}\n Output :\n\nExecution 1:\nTime for an unsorted array: 0.00108\nTime for a sorted array: 0.00053\n\nExecution 2:\nTime for an unsorted array: 0.001101\nTime for a sorted array: 0.000593\n\nExecution 3:\nTime for an unsorted array: 0.0011\nTime for a sorted array: 0.000418\nObserve that time taken for processing a sorted array is less as compared to an unsorted array. The reason for this optimization for a sorted array is branch prediction.\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27570/" ]
276,281
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p> <p>Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p> <p>Target platform is *nix, however I would like to do it on a Win host also.</p>
[ { "answer_id": 276289, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "resource getrusage os.times" }, { "answer_id": 276295, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 6, "selected": true, "text": ">>> import os\n>>> os.times()\n(1.296875, 0.765625, 0.0, 0.0, 0.0)\n>>> print os.times.__doc__\ntimes() -> (utime, stime, cutime, cstime, elapsed_time)\n\nReturn a tuple of floating point numbers indicating process times.\n" }, { "answer_id": 4815145, "author": "Ramchandra Apte", "author_id": 443348, "author_profile": "https://Stackoverflow.com/users/443348", "pm_score": 0, "selected": false, "text": "time.clock() import decimal,timeit\ndecimal.getcontext().prec=1000\ndef torture():\n decimal.Decimal(2).sqrt()\n time.sleep(0.1)\nimport time\nclock=time.clock()\nwhile 1:\n clock=timeit.timeit(torture,number=10)\n tclock=time.clock()\n print((tclock-clock)*p)\n clock=tclock\n" }, { "answer_id": 6265475, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 4, "selected": false, "text": ">>> import psutil\n>>> p = psutil.Process()\n>>> p.cpu_times()\ncputimes(user=0.06, system=0.03)\n>>> p.cpu_percent(interval=1)\n0.0\n>>> \n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
276,286
<p>When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in <a href="http://djangoproject.com/" rel="nofollow noreferrer">Django</a>?</p>
[ { "answer_id": 276326, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": " from django import http\n\n return http.HttpResponsePermanentRedirect('/yournewpage.html')\n /yournewpage.html Browser Python HTTP\n -------------------> GET /youroldpage.html HTTP/1.1\n\n <------------------- HTTP/1.1 301 Moved Permanently\n Location: /yournewpage.html\n -------------------> GET /yournewpage.html HTTP/1.1\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11452/" ]
276,292
<p>How can I continuously capture images from a webcam?</p> <p>I want to experiment with object recognition (by maybe using java media framework). </p> <p>I was thinking of creating two threads</p> <p>one thread:</p> <ul> <li>Node 1: capture live image</li> <li>Node 2: save image as "1.jpg"</li> <li>Node 3: wait 5 seconds</li> <li>Node 4: repeat...</li> </ul> <p>other thread:</p> <ul> <li>Node 1: wait until image is captured</li> <li>Node 2: using the "1.jpg" get colors from every pixle</li> <li>Node 3: save data in arrays</li> <li>Node 4: repeat...</li> </ul>
[ { "answer_id": 971686, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "import javax.media.*;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.net.*;\nimport java.awt.event.*;\nimport javax.swing.event.*;\n\npublic class JMFTest extends JFrame {\n Player _player;\n JMFTest() {\n addWindowListener( new WindowAdapter() {\n public void windowClosing( WindowEvent e ) {\n _player.stop();\n _player.deallocate();\n _player.close();\n System.exit( 0 );\n }\n });\n setExtent( 0, 0, 320, 260 );\n JPanel panel = (JPanel)getContentPane();\n panel.setLayout( new BorderLayout() );\n String mediaFile = \"vfw://1\";\n try {\n MediaLocator mlr = new MediaLocator( mediaFile );\n _player = Manager.createRealizedPlayer( mlr );\n if (_player.getVisualComponent() != null)\n panel.add(\"Center\", _player.getVisualComponent());\n if (_player.getControlPanelComponent() != null)\n panel.add(\"South\", _player.getControlPanelComponent());\n }\n catch (Exception e) {\n System.err.println( \"Got exception \" + e );\n }\n }\n\n public static void main(String[] args) {\n JMFTest jmfTest = new JMFTest();\n jmfTest.show();\n }\n}\n" }, { "answer_id": 4383406, "author": "Nile", "author_id": 243667, "author_profile": "https://Stackoverflow.com/users/243667", "pm_score": 3, "selected": false, "text": "myron = new JMyron();\nmyron.start(imgw, imgh);\nmyron.update();\nint[] img = myron.image();\n" }, { "answer_id": 8185050, "author": "Hugo", "author_id": 1054135, "author_profile": "https://Stackoverflow.com/users/1054135", "pm_score": 2, "selected": false, "text": "public class SimpleVideoTest extends JFrame implements Runnable{\n\n private MarvinVideoInterface videoAdapter;\n private MarvinImage image;\n private MarvinImagePanel videoPanel;\n\n public SimpleVideoTest(){\n super(\"Simple Video Test\");\n videoAdapter = new MarvinJavaCVAdapter();\n videoAdapter.connect(0);\n videoPanel = new MarvinImagePanel();\n add(videoPanel);\n new Thread(this).start();\n setSize(800,600);\n setVisible(true);\n }\n @Override\n public void run() {\n while(true){\n // Request a video frame and set into the VideoPanel\n image = videoAdapter.getFrame();\n videoPanel.setImage(image);\n }\n }\n public static void main(String[] args) {\n SimpleVideoTest t = new SimpleVideoTest();\n t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n}\n public class WebcamPicture {\n public static void main(String[] args) {\n try{\n MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();\n videoAdapter.connect(0);\n MarvinImage image = videoAdapter.getFrame();\n MarvinImageIO.saveImage(image, \"./res/webcam_picture.jpg\");\n } catch(MarvinVideoInterfaceException e){\n e.printStackTrace();\n }\n }\n}\n" }, { "answer_id": 9046345, "author": "gtiwari333", "author_id": 607637, "author_profile": "https://Stackoverflow.com/users/607637", "pm_score": 6, "selected": false, "text": "import org.bytedeco.javacv.*;\nimport org.bytedeco.opencv.opencv_core.IplImage;\n\nimport java.io.File;\n\nimport static org.bytedeco.opencv.global.opencv_core.cvFlip;\nimport static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;\n\npublic class Test implements Runnable {\n final int INTERVAL = 100;///you may use interval\n CanvasFrame canvas = new CanvasFrame(\"Web Cam\");\n\n public Test() {\n canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);\n }\n\n public void run() {\n\n new File(\"images\").mkdir();\n\n FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera\n OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();\n IplImage img;\n int i = 0;\n try {\n grabber.start();\n\n while (true) {\n Frame frame = grabber.grab();\n\n img = converter.convert(frame);\n\n //the grabbed frame will be flipped, re-flip to make it right\n cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise\n\n //save\n cvSaveImage(\"images\" + File.separator + (i++) + \"-aa.jpg\", img);\n\n canvas.showImage(converter.convert(img));\n\n Thread.sleep(INTERVAL);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n Test gs = new Test();\n Thread th = new Thread(gs);\n th.start();\n }\n}\n" }, { "answer_id": 13347845, "author": "Bartosz Firyn", "author_id": 626311, "author_profile": "https://Stackoverflow.com/users/626311", "pm_score": 5, "selected": false, "text": "Webcam webcam = Webcam.getDefault();\nwebcam.open();\nBufferedImage image = webcam.getImage();\nImageIO.write(image, \"JPG\", new File(\"test.jpg\"));\n" }, { "answer_id": 15982047, "author": "syb0rg", "author_id": 1937270, "author_profile": "https://Stackoverflow.com/users/1937270", "pm_score": 3, "selected": false, "text": "import java.awt.event.ActionEvent;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.image.BufferedImage;\n\nimport javax.swing.AbstractAction;\nimport javax.swing.ActionMap;\nimport javax.swing.InputMap;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\nimport javax.swing.KeyStroke;\n\nimport com.googlecode.javacv.CanvasFrame;\nimport com.googlecode.javacv.OpenCVFrameGrabber;\nimport com.googlecode.javacv.cpp.opencv_core.IplImage;\n\npublic class HighRes extends JComponent implements Runnable {\n private static final long serialVersionUID = 1L;\n\n private static CanvasFrame frame = new CanvasFrame(\"Web Cam\");\n private static boolean running = false;\n private static int frameWidth = 800;\n private static int frameHeight = 600;\n private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);\n private static BufferedImage bufImg;\n\n public HighRes()\n {\n // setup key bindings\n ActionMap actionMap = frame.getRootPane().getActionMap();\n InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);\n\n for (Keys direction : Keys.values())\n {\n actionMap.put(direction.getText(), new KeyBinding(direction.getText()));\n inputMap.put(direction.getKeyStroke(), direction.getText());\n }\n\n frame.getRootPane().setActionMap(actionMap);\n frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);\n\n // setup window listener for close action\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.addWindowListener(new WindowAdapter()\n {\n public void windowClosing(WindowEvent e)\n {\n stop();\n }\n });\n }\n\n public static void main(String... args)\n {\n HighRes webcam = new HighRes();\n webcam.start();\n }\n\n @Override\n public void run()\n {\n try\n {\n\n grabber.setImageWidth(frameWidth);\n grabber.setImageHeight(frameHeight);\n grabber.start();\n while (running)\n {\n\n final IplImage cvimg = grabber.grab();\n if (cvimg != null)\n {\n\n // cvFlip(cvimg, cvimg, 1); // mirror\n\n // show image on window\n bufImg = cvimg.getBufferedImage();\n frame.showImage(bufImg);\n }\n }\n grabber.stop();\n grabber.release();\n frame.dispose();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n public void start()\n {\n new Thread(this).start();\n running = true;\n }\n\n public void stop()\n {\n running = false;\n }\n\n private class KeyBinding extends AbstractAction {\n\n private static final long serialVersionUID = 1L;\n\n public KeyBinding(String text)\n {\n super(text);\n putValue(ACTION_COMMAND_KEY, text);\n }\n\n @Override\n public void actionPerformed(ActionEvent e)\n {\n String action = e.getActionCommand();\n if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();\n else System.out.println(\"Key Binding: \" + action);\n }\n }\n}\n\nenum Keys\n{\n ESCAPE(\"Escape\", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),\n CTRLC(\"Control-C\", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),\n UP(\"Up\", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),\n DOWN(\"Down\", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),\n LEFT(\"Left\", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),\n RIGHT(\"Right\", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));\n\n private String text;\n private KeyStroke keyStroke;\n\n Keys(String text, KeyStroke keyStroke)\n {\n this.text = text;\n this.keyStroke = keyStroke;\n }\n\n public String getText()\n {\n return text;\n }\n\n public KeyStroke getKeyStroke()\n {\n return keyStroke;\n }\n\n @Override\n public String toString()\n {\n return text;\n }\n}\n" }, { "answer_id": 46145364, "author": "Uddika Dilshan", "author_id": 7368579, "author_profile": "https://Stackoverflow.com/users/7368579", "pm_score": 2, "selected": false, "text": "webcam = Webcam.getDefault();\nwebcam.open();\n\nif (webcam.isOpen()) { //if web cam open \n BufferedImage image = webcam.getImage();\n JLabel imageLbl = new JLabel();\n imageLbl.setSize(640, 480); //show captured image\n imageLbl.setIcon(new ImageIcon(image));\n\n int showConfirmDialog = JOptionPane.showConfirmDialog(null, imageLbl, \"Image Viewer\", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(\"\"));\n\n if (showConfirmDialog == JOptionPane.YES_OPTION) {\n JFileChooser chooser = new JFileChooser();\n chooser.setDialogTitle(\"Save Image\");\n chooser.setFileFilter(new FileNameExtensionFilter(\"IMAGES ONLY\", \"png\", \"jpeg\", \"jpg\")); //this file extentions are shown\n int showSaveDialog = chooser.showSaveDialog(this);\n if (showSaveDialog == 0) { //if pressed 'Save' button\n String filePath = chooser.getCurrentDirectory().toString().replace(\"\\\\\", \"/\");\n String fileName = chooser.getSelectedFile().getName(); //get user entered file name to save\n ImageIO.write(image, \"PNG\", new File(filePath + \"/\" + fileName + \".png\"));\n\n }\n }\n}\n\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35962/" ]
276,310
<p>I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site.</p> <p>There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an overkill in my scenario.</p> <p>So I've got two questions, really:</p> <ul> <li>is there another OpenID plugin for Symfony supporting OpenID 2.0?</li> <li>what would be the hack required to make sfOpenID support OpenID 2.0?</li> </ul> <p>I suppose I could study OpenID specs and hack it myself, but then, I am a lazy programmer :)</p>
[ { "answer_id": 276339, "author": "lpfavreau", "author_id": 35935, "author_profile": "https://Stackoverflow.com/users/35935", "pm_score": 4, "selected": true, "text": "sfUser" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2706/" ]
276,319
<p>Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.</p> <p>It would be nice to be able to do this using SharpZipLib.</p>
[ { "answer_id": 276330, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "MemoryStream" }, { "answer_id": 276347, "author": "Cory", "author_id": 8207, "author_profile": "https://Stackoverflow.com/users/8207", "pm_score": 6, "selected": true, "text": "ZipEntry PutNextEntry() FileStream fZip = File.Create(compressedOutputFile);\nZipOutputStream zipOStream = new ZipOutputStream(fZip);\nforeach (FileInfo fi in allfiles)\n{\n ZipEntry entry = new ZipEntry((fi.Name));\n zipOStream.PutNextEntry(entry);\n FileStream fs = File.OpenRead(fi.FullName);\n try\n {\n byte[] transferBuffer[1024];\n do\n {\n bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);\n zipOStream.Write(transferBuffer, 0, bytesRead);\n }\n while (bytesRead > 0);\n }\n finally\n {\n fs.Close();\n }\n}\nzipOStream.Finish();\nzipOStream.Close();\n" }, { "answer_id": 276399, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 2, "selected": false, "text": "ZipArchive [Serializable]\npublic class MyStrings {\n public string Foo { get; set; }\n public string Bar { get; set; }\n}\n" }, { "answer_id": 384068, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 4, "selected": false, "text": "using (ZipFile zip = new ZipFile())\n{\n zip.AddEntry(\"Readme.txt\", stringContent1);\n zip.AddEntry(\"readings/Data.csv\", stringContent2);\n zip.AddEntry(\"readings/Index.xml\", stringContent3);\n zip.Save(\"Archive1.zip\"); \n}\n" }, { "answer_id": 7689375, "author": "Ashleigh", "author_id": 984230, "author_profile": "https://Stackoverflow.com/users/984230", "pm_score": 3, "selected": false, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.IO.Packaging; \nusing System.IO; \n\npublic class ZipSticle \n{ \n Package package; \n\n public ZipSticle(Stream s) \n { \n package = ZipPackage.Open(s, FileMode.Create); \n } \n\n public void Add(Stream stream, string Name) \n { \n Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Name, UriKind.Relative)); \n PackagePart packagePartDocument = package.CreatePart(partUriDocument, \"\"); \n\n CopyStream(stream, packagePartDocument.GetStream()); \n stream.Close(); \n } \n\n private static void CopyStream(Stream source, Stream target) \n { \n const int bufSize = 0x1000; \n byte[] buf = new byte[bufSize]; \n int bytesRead = 0; \n while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) \n target.Write(buf, 0, bytesRead); \n } \n\n public void Close() \n { \n package.Close(); \n } \n}\n FileStream str = File.Open(\"MyAwesomeZip.zip\", FileMode.Create); \nZipSticle zip = new ZipSticle(str); \n\nzip.Add(File.OpenRead(\"C:/Users/C0BRA/SimpleFile.txt\"), \"Some directory/SimpleFile.txt\"); \nzip.Add(File.OpenRead(\"C:/Users/C0BRA/Hurp.derp\"), \"hurp.Derp\"); \n\nzip.Close();\nstr.Close();\n MemoryStream Stream ZipSticle.Add FileStream str = File.Open(\"MyAwesomeZip.zip\", FileMode.Create); \nZipSticle zip = new ZipSticle(str); \n\nbyte[] fileinmem = new byte[1000];\n// Do stuff to FileInMemory\nMemoryStream memstr = new MemoryStream(fileinmem);\nzip.Add(memstr, \"Some directory/SimpleFile.txt\");\n\nmemstr.Close();\nzip.Close();\nstr.Close();\n" }, { "answer_id": 45067125, "author": "johnny 5", "author_id": 1938988, "author_profile": "https://Stackoverflow.com/users/1938988", "pm_score": 3, "selected": false, "text": "public interface IHasDocumentProperties\n{\n byte[] Content { get; set; }\n string Name { get; set; }\n}\n\npublic void CreateZipFileContent(string filePath, IEnumerable<IHasDocumentProperties> fileInfos)\n{ \n using (var memoryStream = new MemoryStream())\n {\n using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))\n {\n foreach(var fileInfo in fileInfos)\n {\n var entry = zipArchive.CreateEntry(fileInfo.Name);\n\n using (var entryStream = entry.Open())\n {\n entryStream.Write(fileInfo.Content, 0, fileInfo.Content.Length);\n } \n }\n }\n \n using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, System.IO.FileAccess.Write))\n {\n memoryStream.Position = 0;\n memoryStream.CopyTo(fileStream);\n }\n }\n}\n" }, { "answer_id": 46324856, "author": "krillgar", "author_id": 1195056, "author_profile": "https://Stackoverflow.com/users/1195056", "pm_score": 2, "selected": false, "text": "MemoryStream byte[] using (var memoryStream = new MemoryStream())\nusing (var zip = new ZipFile())\n{\n zip.AddEntry(\"Excel File 1.xlsx\", excelFileStream1.ToArray());\n zip.AddEntry(\"Excel File 2.xlsx\", excelFileStream2.ToArray());\n\n // Keep the file off of disk, and in memory.\n zip.Save(memoryStream);\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
276,324
<p>I'm trying to create a horizontal navigation bar in css with 5 evenly spaced links. The html hopefully will remain like this:</p> <pre><code>&lt;div id="footer"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="one.html"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="two.html"&gt;Two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="three.html"&gt;Three&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="four.html"&gt;Four&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="five.html"&gt;Five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>So with CSS, I want to space them evenly within the footer div. So far I'm using this:</p> <pre><code>div#footer{ height:1.5em; background-color:green; clear:both; padding-top:.5em; font-size:1.5em; width:800px; } div#footer ul{ margin:0; padding:0; list-style:none; } div#footer li{ width:155px; display:inline-block; text-align:center; } </code></pre> <p>This works pretty well, but there is spacing between the li's that I do not want. That is why I've used the 155px instead of 160px for their width, there is about 5px of space being put in between each li. Where is that spacing coming from? How can I get rid of it? If I increase the fontsize, the spacing increases as well. </p>
[ { "answer_id": 276333, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 4, "selected": false, "text": "div#footer li{\n width:160px;\n display:block;\n float: left;\n text-align:center;\n}\n" }, { "answer_id": 276340, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 6, "selected": true, "text": "<div id=\"footer\">\n <ul>\n <li><a href=\"one.html\">One</a></li><li><a href=\"two.html\">Two</a></li><li><a href=\"three.html\">Three</a></li><li><a href=\"four.html\">Four</a></li><li><a href=\"five.html\">Five</a></li>\n </ul>\n</div>\n" }, { "answer_id": 276352, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 2, "selected": false, "text": "<li> <li><a href=\"one.html\">One</a></li><li><a href=\"two.html\">Two</a></li><li><a href=\"three.html\">Three</a></li><li><a href=\"four.html\">Four</a></li><li><a href=\"five.html\">Five</a></li>\n" }, { "answer_id": 289890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "div#footer ul{\n margin:0;\n padding:0;\n list-style:none;\n}\n\ndiv#footer li{\n width:155px;\n float:left;\n display:block; \n}\n div#footer li{\n width:155px;\n margin-right: 5px; //5px Space between li elements \n float:left;\n display:block; \n}\n" }, { "answer_id": 30617166, "author": "JeremyTM", "author_id": 3122800, "author_profile": "https://Stackoverflow.com/users/3122800", "pm_score": 1, "selected": false, "text": "<ul> .flex-container {\n padding: 0;\n margin: 0;\n list-style: none;\n \n display: -webkit-box;\n display: -moz-box;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n \n -webkit-flex-flow: row nowrap;\n justify-content: space-around;\n}\n\n.flex-item {\n background: tomato;\n padding: 5px;\n margin: 0px;\n \n line-height: 40px;\n color: white;\n font-weight: bold;\n font-size: 2em;\n text-align: center;\n flex: 1 1 auto;\n} <ul class=\"flex-container\">\n <li class=\"flex-item\">1</li>\n <li class=\"flex-item\">2</li>\n <li class=\"flex-item\">3</li>\n <li class=\"flex-item\">4</li>\n <li class=\"flex-item\">5</li>\n <li class=\"flex-item\">6</li>\n</ul>" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,336
<p>This is what I am working with to get back to the web dev world</p> <p>ASP.Net with VS2008</p> <p>Subsonic as Data Access Layer</p> <p>SqlServer DB</p> <p>Home Project description: I have a student registration system. I have a web page which should display the student records. </p> <p>At present I have a gridview control which shows the records</p> <p>The user logs on and gets to the view students page. The gridview shows the students in the system, where one of the columns is the registration status of open, pending, complete.</p> <p>I want the user to be able to apply dynamic sorting or filters on the result returned so as to obtain a more refined result they wish to see. I envisioned allowing user to filter the results by applying where clause or like clause on the result returned, via a dataset interface by a subsonic method. I do not want to query the databse again to apply the filter</p> <p>example: initial query </p> <pre><code>Select * from studentrecords where date = convert(varchar(32,getdate(),101) </code></pre> <p>The user then should be able to applly filter on the resultset returned so that they can do a last name like '%Souza%'</p> <p>Is this even possible and is binding a datasource to a gridview control the best approach or should i create a custom collection inheriting from collectionbase and then binding that to the gridview control?</p> <p>PS: Sorry about the typo's. My machine is under the influence of tea spill on my laptop </p>
[ { "answer_id": 276405, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "SET @today = GETDATE()\nSET @today = CAST(FLOOR(CAST(@today as float)) as datetime)\n var query = from row in ctx.SomeComplexUdf(someArg)\n where row.IsOpen && row.Value > 0\n select row;\n SELECT u1.*\nFROM dbo.SomeComplexUdf(@p1) u1\nWHERE u1.IsOpen = 1 -- might end up parameterized\nAND u1.Value > 0 -- might end up parameterized\n SELECT u1.*\nFROM dbo.SomeComplexUdf(@p1) u1\n" }, { "answer_id": 278515, "author": "Rostov", "author_id": 2108310, "author_profile": "https://Stackoverflow.com/users/2108310", "pm_score": 0, "selected": false, "text": "DataTable myDataTable = GetDataTableFromSomewhere(); \nDataGridView dgv = new DataGridView();\nDataView dv = new DataView(myDataTable);\n\n//Then you can specify things like:\ndv.Sort = \"StudentStatus DESC\";\ndv.Filter = \"StudentName LIKE '\" + searchName + '\";\ndgv.DataSource = dv;\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
[ { "answer_id": 276387, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 2, "selected": false, "text": "embed_list.append(embed.replace(\"&lt;\", \"<\"))\n {{embed|safe}}" }, { "answer_id": 276394, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 3, "selected": true, "text": "embed_list[len(embed_list):] = [foo] embed_list.append(foo)" }, { "answer_id": 276395, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 2, "selected": false, "text": "embed_list = []\nfor embed in embeds:\n embed_list.append(embed.replace(\"&lt;\", \"<\")) #this is line 35\nreturn render_to_response(\"scanvideos.html\", {\"embed_list\":embed_list})\n embed_list = [embed.replace(\"&lt;\", \"<\") for embed in embeds]\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
276,355
<p>I could really do with updating a user's session variables from within my HTTPModule, but from what I can see, it isn't possible.</p> <p><em>UPDATE:</em> My code is currently running inside the <code>OnBeginRequest ()</code> event handler.</p> <p><em>UPDATE:</em> Following advice received so far, I tried adding this to the <code>Init ()</code> routine in my HTTPModule:</p> <p><code>AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute</code></p> <p>But in my <code>OnPreRequestHandlerExecute</code> routine, the session state is still unavailable!</p> <p>Thanks, and apologies if I'm missing something!</p>
[ { "answer_id": 276373, "author": "Jim Harte", "author_id": 4544, "author_profile": "https://Stackoverflow.com/users/4544", "pm_score": 7, "selected": true, "text": "using System;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.SessionState;\nusing System.Diagnostics;\n\n// This code demonstrates how to make session state available in HttpModule,\n// regardless of requested resource.\n// author: Tomasz Jastrzebski\n\npublic class MyHttpModule : IHttpModule\n{\n public void Init(HttpApplication application)\n {\n application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);\n application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);\n }\n\n void Application_PostMapRequestHandler(object source, EventArgs e)\n {\n HttpApplication app = (HttpApplication)source;\n\n if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState) {\n // no need to replace the current handler\n return;\n }\n\n // swap the current handler\n app.Context.Handler = new MyHttpHandler(app.Context.Handler);\n }\n\n void Application_PostAcquireRequestState(object source, EventArgs e)\n {\n HttpApplication app = (HttpApplication)source;\n\n MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;\n\n if (resourceHttpHandler != null) {\n // set the original handler back\n HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;\n }\n\n // -> at this point session state should be available\n\n Debug.Assert(app.Session != null, \"it did not work :(\");\n }\n\n public void Dispose()\n {\n\n }\n\n // a temp handler used to force the SessionStateModule to load session state\n public class MyHttpHandler : IHttpHandler, IRequiresSessionState\n {\n internal readonly IHttpHandler OriginalHandler;\n\n public MyHttpHandler(IHttpHandler originalHandler)\n {\n OriginalHandler = originalHandler;\n }\n\n public void ProcessRequest(HttpContext context)\n {\n // do not worry, ProcessRequest() will not be called, but let's be safe\n throw new InvalidOperationException(\"MyHttpHandler cannot process requests.\");\n }\n\n public bool IsReusable\n {\n // IsReusable must be set to false since class has a member!\n get { return false; }\n }\n }\n}\n" }, { "answer_id": 7400727, "author": "Bert Persyn", "author_id": 638016, "author_profile": "https://Stackoverflow.com/users/638016", "pm_score": 4, "selected": false, "text": "HttpContext.Current.Session IHttpModule PreRequestHandlerExecute public class SessionModule : IHttpModule \n {\n public void Init(HttpApplication context)\n {\n context.BeginRequest += BeginTransaction;\n context.EndRequest += CommitAndCloseSession;\n context.PreRequestHandlerExecute += PreRequestHandlerExecute;\n }\n\n\n\n public void Dispose() { }\n\n public void PreRequestHandlerExecute(object sender, EventArgs e)\n {\n var context = ((HttpApplication)sender).Context;\n context.Session[\"some_sesion\"] = new SomeObject();\n }\n...\n}\n" }, { "answer_id": 30310208, "author": "aTest", "author_id": 4913278, "author_profile": "https://Stackoverflow.com/users/4913278", "pm_score": 0, "selected": false, "text": "private HttpApplication contextapp;\n public void Init(HttpApplication application)\n{\n //Must be after AcquireRequestState - the session exist after RequestState\n application.PostAcquireRequestState += new EventHandler(MyNewEvent);\n this.contextapp=application;\n} \n public void MyNewEvent(object sender, EventArgs e)\n{\n //A example...\n if(contextoapp.Context.Session != null)\n {\n this.contextapp.Context.Session.Timeout=30;\n System.Diagnostics.Debug.WriteLine(\"Timeout changed\");\n }\n}\n" }, { "answer_id": 67877994, "author": "Antonio Bakula", "author_id": 351383, "author_profile": "https://Stackoverflow.com/users/351383", "pm_score": 1, "selected": false, "text": "runAllManagedModulesForAllRequests preCondition=\"managedHandler\" <system.webServer>\n <modules runAllManagedModulesForAllRequests=\"true\">\n <add name=\"ModuleWithSessionAccess\" type=\"HttpModuleWithSessionAccess.ModuleWithSessionAccess, HttpModuleWithSessionAccess\"/>\n </modules>\n</system.webServer>\n <system.webServer>\n <modules>\n <add name=\"ModuleWithSessionAccess\" type=\"HttpModuleWithSessionAccess.ModuleWithSessionAccess, HttpModuleWithSessionAccess\" preCondition=\"managedHandler\"/>\n </modules>\n</system.webServer>\n namespace HttpModuleWithSessionAccess\n{\n public class ModuleWithSessionAccess : IHttpModule\n {\n public void Init(HttpApplication context)\n {\n context.BeginRequest += Context_BeginRequest;\n context.PreRequestHandlerExecute += Context_PreRequestHandlerExecute;\n }\n\n private void Context_BeginRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n app.Context.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);\n }\n \n private void Context_PreRequestHandlerExecute(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n if (app.Context.Session != null)\n {\n app.Context.Session[\"Random\"] = $\"Random value: {new Random().Next()}\";\n }\n }\n\n public void Dispose()\n {\n }\n }\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475/" ]
276,360
<p>Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage.</p> <p>What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code-tree-building time. My reasoning is that while it's easy to just include() every class that you <strong>might</strong> need for every page that you have on a site, the CPU overhead can't be "free". I'd like to know how "expensive" parse time really is.</p> <p>I am assuming that an opcode cache such as APC is <strong>not</strong> part of the scenario.</p> <p>Would I be correct that measurement of parse time in PHP is something that would have to take place in mod_php?</p> <p><strong>EDIT</strong>: If possible, taking into account <code>$_SERVER['DOCUMENT_ROOT']</code> usage in code would be helpful. Command solutions might take a bit of tinkering to do this (but still be valuable answers).</p>
[ { "answer_id": 276366, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "$ time php5 -r 'echo \"Hello world\";'\nHello world\nreal 0m1.565s\nuser 0m0.036s\nsys 0m0.024s\n" }, { "answer_id": 276367, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": true, "text": "<?php return; rest of the code ?>\n <?php whole code; $%^parse erorr!@! ?>\n time php empty.php\n time php test.php\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12694/" ]
276,362
<p>I'm working on a project for OSX where the user can pick a collection of documents (from any application) which I need to generate PDF's from. The standard Macintosh Print dialog has a PDF button which has a number of PDF-related commands including "Save as PDF...". However, I need to generate the PDF file without requiring user interactions. I ideally want this to work with any type of document.</p> <p>Here's the options I've explored so far:</p> <ul> <li>Automator actions. There's a PDF library for Automator but it provides actions for working with PDF files, not generating them. There's a Finder action for printing any file but only to a real printer.</li> <li>AppleScript. Some applications have the ability to generate PDF files (for instance, if you send 'save doc in "test.pdf"' to Pages it will generate a PDF (but this only works for Pages - I need support for any type of document).</li> <li>Custom Printer. I could create a virtual printer driver and then use the automator action but I don't like the idea of confusing the user with an extra printer in the print list.</li> </ul> <p>My hope is that there's some way to interact with the active application as if the user was carrying out the following steps:</p> <ol> <li>Do Cmd-P (opens the print dialog)</li> <li>Click the "PDF" button</li> <li>Select "Save as PDF..." (second item in menu)</li> <li>Type in filename in save dialog</li> <li>Click "Save"</li> </ol> <p>If that's the best approach (is it?) then the real problem is: how do I send UI Events to an external application (keystrokes, mouse events, menu selections) ?</p> <p><strong>Update:</strong> Just to clarify one point: the documents I need to convert to PDF are documents that are created by <em>other applications</em>. For example, the user might pick a Word document or a Numbers spreadsheet or an OmniGraffle drawing or a Web Page. The common denominator is that each of these documents has an associated application and that application knows how to print it (and OSX knows how to render print output to a PDF file).</p> <p>So, the samples at Cocoa Dev Central don't help because they're about generating a PDF from <em>my application</em>.</p>
[ { "answer_id": 277015, "author": "Timour", "author_id": 21105, "author_profile": "https://Stackoverflow.com/users/21105", "pm_score": 4, "selected": true, "text": "tell application \"System Events\"\n tell window of process \"Safari\"\n set foremost to true\n keystroke \"p\" using {command down}\n delay 3\n click menu button \"PDF\" of sheet 2\n click menu item \"Save as PDF…\" of menu 1 of menu button \"PDF\" of sheet 2\n keystroke \"my_test.file\"\n keystroke return\n delay 10\n end tell\n\n end tell\n" }, { "answer_id": 2907895, "author": "Sebastian Gallese", "author_id": 254573, "author_profile": "https://Stackoverflow.com/users/254573", "pm_score": 0, "selected": false, "text": "# Convert the current Safari window to a PDF\n# by Sebastain Gallese\n\n# props to the following for helping me get frontmost window\n# http://stackoverflow.com/questions/480866/get-the-title-of-the-current-active-window- document-in-mac-os-x\n\nglobal window_name\n\n# This script works with Safari, you might have\n# to tweak it to work with other applications \nset myApplication to \"Safari\"\n\n# You can name the PDF whatever you want\n# Just make sure to delete it or move it or rename it\n# Before running the script again\nset myPDFName to \"mynewpdfile\"\n\ntell application myApplication\n activate\n if the (count of windows) is not 0 then\n set window_name to name of front window\n end if\nend tell\n\nset timeoutSeconds to 2.0\nset uiScript to \"keystroke \\\"p\\\" using command down\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"click menu button \\\"PDF\\\" of sheet 1 of window \\\"\" & window_name & \"\\\" of application process \\\"\" & myApplication & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"click menu item 2 of menu 1 of menu button \\\"PDF\\\" of sheet 1 of window \\\"\" & window_name & \"\\\" of application process \\\"\" & myApplication & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"keystroke \\\"\" & myPDFName & \"\\\"\"\nmy doWithTimeout(uiScript, timeoutSeconds)\nset uiScript to \"keystroke return\"\nmy doWithTimeout(uiScript, timeoutSeconds)\n\non doWithTimeout(uiScript, timeoutSeconds)\n set endDate to (current date) + timeoutSeconds\n repeat\n try\n run script \"tell application \\\"System Events\\\"\n\" & uiScript & \"\nend tell\"\n exit repeat\n on error errorMessage\n if ((current date) > endDate) then\n error \"Can not \" & uiScript\n end if\n end try\n end repeat\nend doWithTimeout\n" }, { "answer_id": 4297984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "do shell script \"lp -d CUPS_PDF test.txt\"\n" }, { "answer_id": 4430008, "author": "mcgrailm", "author_id": 234670, "author_profile": "https://Stackoverflow.com/users/234670", "pm_score": 1, "selected": false, "text": " on open afile\n set filename to name of (info for afile)\n tell application \"Finder\"\n set filepath to (container of (afile as alias)) as alias\n end tell\n set filepath to quoted form of POSIX path of filepath\n set tid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to \".\"\n set filename to text item 1 of filename\n set AppleScript's text item delimiters to tid\n set afile to quoted form of POSIX path of afile\n do shell script \"cupsfilter \" & afile & \" > \" & filepath & filename & \".pdf\"\n end open\n" }, { "answer_id": 11575976, "author": "PH.", "author_id": 825624, "author_profile": "https://Stackoverflow.com/users/825624", "pm_score": 1, "selected": false, "text": "convert2pdf() {\n /System/Library/Printers/Libraries/convert -f \"$1\" -o \"$2\" -j \"application/pdf\"\n}\n" }, { "answer_id": 71097317, "author": "Daryl Hansen", "author_id": 4466755, "author_profile": "https://Stackoverflow.com/users/4466755", "pm_score": 0, "selected": false, "text": "\"/System/Library/Printers/Libraries/./convert\" sips -s format pdf Filename.jpg --out Filename.pdf" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35958/" ]
276,382
<p>In my app users need to be able to enter numeric values with decimal places. The iPhone doesn't provides a keyboard that's specific for this purpose - only a number pad and a keyboard with numbers and symbols.</p> <p>Is there an easy way to use the latter and prevent any non-numeric input from being entered without having to regex the final result?</p> <p>Thanks!</p>
[ { "answer_id": 321605, "author": "shek", "author_id": 40618, "author_profile": "https://Stackoverflow.com/users/40618", "pm_score": 7, "selected": true, "text": "NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];\n[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\nint currencyScale = [currencyFormatter maximumFractionDigits];\n" }, { "answer_id": 2636699, "author": "Mike Weller", "author_id": 49658, "author_profile": "https://Stackoverflow.com/users/49658", "pm_score": 4, "selected": false, "text": "-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range\n replacementString:(NSString *)string {\n\n double currentValue = [textField.text doubleValue];\n //Replace line above with this\n //double currentValue = [[textField text] substringFromIndex:1] doubleValue];\n double cents = round(currentValue * 100.0f);\n\n if ([string length]) {\n for (size_t i = 0; i < [string length]; i++) {\n unichar c = [string characterAtIndex:i];\n if (isnumber(c)) {\n cents *= 10;\n cents += c - '0'; \n } \n }\n } else {\n // back Space\n cents = floor(cents / 10);\n }\n\n textField.text = [NSString stringWithFormat:@\"%.2f\", cents / 100.0f];\n //Add this line\n //[textField setText:[NSString stringWithFormat:@\"$%@\",[textField text]]];\n return NO;\n}\n" }, { "answer_id": 4924522, "author": "Daniel Thorpe", "author_id": 197626, "author_profile": "https://Stackoverflow.com/users/197626", "pm_score": 1, "selected": false, "text": "@interface MyViewController : UIViewController <UITextFieldDelegate> {\n@private\n UITextField *firstResponder;\n NSNumberFormatter *formatter;\n NSInteger currencyScale;\n NSString *enteredDigits;\n}\n\n@property (nonatomic, readwrite, assign) UITextField *firstResponder;\n@property (nonatomic, readwrite, retain) NSNumberFormatter *formatter;\n@property (nonatomic, readwrite, retain) NSString *enteredDigits;\n\n@end\n - (void)viewDidLoad {\n [super viewDidLoad];\n\n NSNumberFormatter *aFormatter = [[NSNumberFormatter alloc] init];\n [aFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\n currencyScale = -1 * [aFormatter maximumFractionDigits];\n self.formatter = aFormatter;\n [aFormatter release];\n}\n #pragma mark -\n#pragma mark UITextFieldDelegate methods\n\n- (void)textFieldDidBeginEditing:(UITextField *)textField {\n // Keep a pointer to the field, so we can resign it from a toolbar\n self.firstResponder = textField;\n self.enteredDigits = @\"\";\n}\n\n- (void)textFieldDidEndEditing:(UITextField *)textField {\n if ([self.enteredDigits length] > 0) {\n // Get the amount\n NSDecimalNumber *result = [[NSDecimalNumber decimalNumberWithString:self.enteredDigits] decimalNumberByMultiplyingByPowerOf10:currencyScale];\n NSLog(@\"result: %@\", result);\n }\n}\n\n- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {\n\n // Check the length of the string\n if ([string length]) {\n self.enteredDigits = [self.enteredDigits stringByAppendingFormat:@\"%d\", [string integerValue]];\n } else {\n // This is a backspace\n NSUInteger len = [self.enteredDigits length];\n if (len > 1) {\n self.enteredDigits = [self.enteredDigits substringWithRange:NSMakeRange(0, len - 1)];\n } else {\n self.enteredDigits = @\"\";\n }\n }\n\n NSDecimalNumber *decimal = nil;\n\n if ( ![self.enteredDigits isEqualToString:@\"\"]) {\n decimal = [[NSDecimalNumber decimalNumberWithString:self.enteredDigits] decimalNumberByMultiplyingByPowerOf10:currencyScale];\n } else {\n decimal = [NSDecimalNumber zero];\n }\n\n // Replace the text with the localized decimal number\n textField.text = [self.formatter stringFromNumber:decimal];\n\n return NO; \n}\n" }, { "answer_id": 4983084, "author": "Zebs", "author_id": 382489, "author_profile": "https://Stackoverflow.com/users/382489", "pm_score": 6, "selected": false, "text": "UIKeyboardTypeDecimalPad myTextField.keyboardType=UIKeyboardTypeDecimalPad;\n" }, { "answer_id": 32772338, "author": "ccwasden", "author_id": 431271, "author_profile": "https://Stackoverflow.com/users/431271", "pm_score": 0, "selected": false, "text": " func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {\n guard let str = textField.text else {\n textField.text = \"0.00\"\n return false\n }\n\n let value = (str as NSString).doubleValue\n\n var cents = round(value * 100)\n if string.characters.count > 0 {\n for c in string.characters {\n if let num = Int(String(c)) {\n cents *= 10\n cents += Double(num)\n }\n }\n }\n else {\n cents = floor(cents / 10)\n }\n\n textField.text = NSString(format: \"%.2f\", cents/100) as String\n\n return false\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
276,383
<p>I have a Dictionary that when I add multiple values to it, the items that were entered before take the values of the item added. I am using the .Net 3.5 Here is the code:</p> <pre><code>public static Dictionary&lt;string, Neighborhoods&gt; Families() { if (File.Exists(calculatePath() + "Family.txt")){} else {File.Create(calculatePath() + "Family.txt").Close();} string[] inp = File.ReadAllLines(calculatePath() + "Family.txt"); Neighborhoods temp = new Neighborhoods(); Dictionary&lt;string, Neighborhoods&gt; All_Families = new Dictionary&lt;string, Neighborhoods&gt;(); string currentphase = null; foreach (string s in inp) { switch (s) { case "!&lt;Start Family&gt;!": temp = new Neighborhoods(); break; case "&lt;Family Name&gt;": currentphase = "&lt;Family Name&gt;"; break; case "&lt;End Family Name&gt;": currentphase = null; break; case "&lt;Neighbour Enabled&gt;True": temp.Neighbourhood_Enabled1 = true; currentphase = "&lt;Neighbour Enabled&gt;True"; break; case "&lt;Neighbour Enabled&gt;False": temp.Neighbourhood_Enabled1 = false; temp.Neighbourhood_Input1 = null; break; case "&lt;University Enabled&gt;True": temp.University_Enabled1 = true; currentphase = "&lt;University Enabled&gt;True"; break; case "&lt;University Enabled&gt;False": temp.University_Enabled1 = false; temp.University_Input1 = null; currentphase = null; break; case "&lt;Downtown Enabled&gt;True": temp.Downtown_Enabled1 = true; currentphase = "&lt;Downtown Enabled&gt;True"; break; case "&lt;Downtown Enabled&gt;False": temp.Downtown_Enabled1 = false; temp.Downtown_Input1 = null; currentphase = null; break; case "!&lt;End Family&gt;!": All_Families.Add(temp.Name, temp); break; default: if (currentphase == "&lt;Family Name&gt;") temp.Name = s; if (currentphase == "&lt;Neighbour Enabled&gt;True") temp.Neighbourhood_Input1 = s; if (currentphase == "&lt;University Enabled&gt;True") temp.University_Input1 = s; if (currentphase == "&lt;Downtown Enabled&gt;True") temp.Downtown_Input1 = s; break; } } return All_Families; } </code></pre> <p>How can I make it so that when I add new keys and values, the old keys keep their original value</p> <hr> <p>Sample data:</p> <pre><code>!&lt;Start Family&gt;! Family Name&gt; qwe &lt;End Family Name&gt; &lt;Neighbour Enabled&gt;True qwe &lt;University Enabled&gt;True we &lt;Downtown Enabled&gt;True qwe !&lt;End Family&gt;! !&lt;Start Family&gt;! &lt;Family Name&gt; 123 &lt;End Family Name&gt; &lt;Neighbour Enabled&gt;True 123 &lt;University Enabled&gt;True 123 &lt;Downtown Enabled&gt;True 123 !&lt;End Family&gt;! </code></pre> <hr> <p>Here is the nieghbourhoods class for reference. I will try the xml methods but it wont be finished quickly, I'm still learning this stuff.</p> <pre><code>class Neighborhoods { public Neighborhoods() { name = ""; Neighbourhood_Enabled = false; Neighbourhood_Input = ""; University_Enabled = false; University_Input = ""; Downtown_Enabled = false; Downtown_Input = ""; } static string name; public string Name { get { return Neighborhoods.name; } set { Neighborhoods.name = value; } } static bool Neighbourhood_Enabled; public bool Neighbourhood_Enabled1 { get { return Neighborhoods.Neighbourhood_Enabled; } set { Neighborhoods.Neighbourhood_Enabled = value; } } static string Neighbourhood_Input; public string Neighbourhood_Input1 { get { return Neighborhoods.Neighbourhood_Input; } set { Neighborhoods.Neighbourhood_Input = value; } } static bool University_Enabled; public bool University_Enabled1 { get { return Neighborhoods.University_Enabled; } set { Neighborhoods.University_Enabled = value; } } static string University_Input; public string University_Input1 { get { return Neighborhoods.University_Input; } set { Neighborhoods.University_Input = value; } } static bool Downtown_Enabled; public bool Downtown_Enabled1 { get { return Neighborhoods.Downtown_Enabled; } set { Neighborhoods.Downtown_Enabled = value; } } static string Downtown_Input; public string Downtown_Input1 { get { return Neighborhoods.Downtown_Input; } set { Neighborhoods.Downtown_Input = value; } } } </code></pre>
[ { "answer_id": 276411, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<families>\n <family>\n <name>Smith</name>\n <neighborhood>true</neighborhood>\n <university>false</university>\n <downtown>false</downtown>\n </family>\n <family>\n <name>Jones</name>\n <neighborhood>false</neighborhood>\n <university>true</university>\n <downtown>false</downtown>\n </family>\n</families>\n Dictionary<String, Neighborhood> families = new Dictionary<string, Neighborhood>();\n\n XmlDocument doc = new XmlDocument();\n doc.Load(\"family.xml\");\n\n foreach (XmlNode familyNode in doc.SelectNodes(\"//family\"))\n {\n Neighborhood n = new Neighborhood();\n n.Name = familyNode.SelectSingleNode(\"name\").InnerText;\n n.InNeighborhood = Boolean.Parse(familyNode.SelectSingleNode(\"neighborhood\").InnerText);\n n.InDowntown = Boolean.Parse(familyNode.SelectSingleNode(\"downtown\").InnerText);\n n.InUniversity = Boolean.Parse(familyNode.SelectSingleNode(\"university\").InnerText);\n\n families.Add(n.Name,n);\n }\n" }, { "answer_id": 276455, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "Neighborhoods public class Neighborhoods\n{\n public string Name { get; set; }\n public string Neighbourhood_Input1 { get; set; }\n public string University_Input1 { get; set; }\n public string Downtown_Input1 { get; set; }\n public bool Neighbourhood_Enabled1 { get; set; }\n public bool University_Enabled1 { get; set; }\n public bool Downtown_Enabled1 { get; set; }\n}\n static void Main()\n{\n var families = Families();\n\n foreach (var family in x.Values)\n {\n Console.WriteLine(y.Name);\n }\n}\n Neighborhoods Neighborhoods first = new Neighborhoods();\nNeighborhoods second = new Neighborhoods();\n\nfirst.Name = \"First\";\nConsole.WriteLine(second.Name);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35984/" ]
276,386
<p>Say I have a C program which is broken to a set of *.c and *.h files. If code from one file uses functions from another file, where should I include the header file? Inside the *.c file that used the function, or inside the header of that file?</p> <p>E.g. file <code>foo.c</code> includes <code>foo.h</code>, which contains all declarations for <code>foo.c</code>; same for <code>bar.c</code> and <code>bar.h</code>. Function <code>foo1()</code> inside <code>foo.c</code> calls <code>bar1()</code>, which is declared in <code>bar.h</code> and defined in <code>bar.c</code>. Now the question is, should I include <code>bar.h</code> inside <code>foo.h</code>, or inside <code>foo.c</code>?</p> <p>What would be a good set of rules-of-thumb for such issues?</p>
[ { "answer_id": 276391, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": ".h .c foo.h bar.h foo.h bar.h bar.h" }, { "answer_id": 276573, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "foo.c foo.h foo.h foo.c foo.c foo.h foo.c foo.c #include \"foo.h foo.c foo.c foo.h foo.h foo.h .c foo.c foo.h .c .c foo.c // foo.c\n#define _foo_c_ // Tell foo.h it's being included from foo.c\n#include \"foo.h\"\n. . .\n // foo.h\n#if !defined(_foo_h_) // Prevent multiple inclusion\n#define _foo_h_\n\n// This section is used only internally to foo.c\n#ifdef _foo_c_\n. . .\n#endif\n\n// Public interface continues to end of file.\n\n#endif // _foo_h_ // Last-ish line in foo.h\n" }, { "answer_id": 276588, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": " #ifndef FOO_H_INCLUDED\n #define FOO_H_INCLUDED\n ...rest of the contents of foo.h...\n #endif /* FOO_H_INCLUDED */\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35324/" ]
276,400
<p>I'm trying to make a webpage that allows the uploading of multiple files at the same times. I will limit the file extensions to the most common images like JPG, JPEG, PNG and GIF.</p> <p>I've done some research on this and everywhere I look it's flash this and flash that.</p> <p>I don't want to use flash really. Especially with Flash 10, which disables the most common used method to enable multifile upload.</p> <p>What I'm looking for is a way to keep creating more and more input fields, each with a browse button and then with one final upload button at the bottom of the form. Creating the new input fields with a Javascript is nog big deal really.</p> <p>So I'm wondering how this works. Do I need to give all file-input fields the same name atribute so I can use 1 piece of PHP code to solve this? Or Is there some way for PHP to detect howmany files have been sumbitted and simply put the code for parsing a file inside a for-loop?</p>
[ { "answer_id": 276414, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 4, "selected": false, "text": "<input type=\"file\" name=\"upload[]\">\n foreach ($_FILES['upload'] as $file) {\n echo $file['size'];\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
276,433
<p>With LINQ to SQL most likely going to not get as much active development as Entity Framework do you think it's best to switch to Entity Framework?</p> <p>I've personally found EF to be very clunky and hard to use compared to LINQ to SQL which feels very natural.</p> <p>EDIT: I recently posted an article on my blog about my feelings towards this potential decision...</p> <p><a href="http://weblogs.asp.net/chadmoran/archive/2008/11/09/ado-net-v-linq-to-sql.aspx" rel="noreferrer">ADO.NET v LINQ to SQL</a></p>
[ { "answer_id": 506433, "author": "LaserJesus", "author_id": 45207, "author_profile": "https://Stackoverflow.com/users/45207", "pm_score": 3, "selected": false, "text": "foo.Foreign_TypeReference.EntityKey = \n new EntityKey(\"DataContextName.Foreign_Type\", \"Foreign_Type_Id\", ForeignTypeId);\n foo.Foreign_Type_Id = ForeignTypeId;\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25416/" ]
276,443
<p>I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from <a href="http://site.example.com/" rel="noreferrer">http://site.example.com/</a> to <a href="http://example.com/site/" rel="noreferrer">http://example.com/site/</a> without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, like css files, images and so on. </p> <p>For example, let's assume that the view for the action <code>index</code> of the controller <code>welcome</code> contains the image <code>img/banner.jpg</code>. If the page is requested with the url <a href="http://site.example.com/welcome" rel="noreferrer">http://site.example.com/welcome</a>, the browser will request the image as <a href="http://site.example.com/img/banner.jpg" rel="noreferrer">http://site.example.com/img/banner.jpg</a>, which is perfectly fine. But if the page is requested with the url <a href="http://site.example.com/welcome/index" rel="noreferrer">http://site.example.com/welcome/index</a>, the browser will think that <code>welcome</code> is a directory and will try to fetch the image as <a href="http://site.example.com/welcome/img/banner.jpg" rel="noreferrer">http://site.example.com/welcome/img/banner.jpg</a>, which is obviously wrong.</p> <p>I've already considered some options, but they all seem imperfect to me:</p> <ul> <li><p>Use url rewriting to redirect requests from (<strong>*.css</strong>|<strong>*.js</strong>|...) or (<strong>css/*</strong>|<strong>js/*</strong>|...) to the right path. </p> <p><em>Problems</em>: Every extension would have to be named in the rewrite rules. If someone would add a new filetype (e.g. an mp3 file), it wouldn't be rewritten.</p></li> <li><p>Prepend the base path to each relative path with a php function. For example:<br> <code>&lt;img src="&lt;?php echo url::base(); ?&gt;img/banner.jpg" /&gt;</code> </p> <p><em>Problems</em>: Looks messy; <strong>css</strong>- and <strong>js</strong>-files containing paths would have to be processed by PHP.</p></li> </ul> <p>So, how do you keep a website directory independent? Is there a better/cleaner way than the ones I came up with?</p>
[ { "answer_id": 276444, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 4, "selected": true, "text": "<base href=\"<?php echo url::base(); ?>\" /> \n" }, { "answer_id": 276583, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 1, "selected": false, "text": "/inc/images/\n/inc/css/\n/inc/javascript/\netc\n <img src=\"/inc/images/foo.jpg\" />\netc\n" }, { "answer_id": 277860, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<base> <a> <!-- this page is http://oursite.com/index.html -->\n<html>\n <head>\n <base href=\"http://static.oursite.com/\" />\n </head>\n <body>\n <img src=\"logo.gif\" alt=\"this is http://static.oursite.com/logo.gif\" />\n <a href=\"/login\">this links to http://static.oursite.com/login which is not what we wanted. we wanted http://oursite.com/login</a>\n </body>\n</html>\n <a> <a> <img>" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35951/" ]
276,479
<p>I saw a potential answer here but that was for YYYY-MM-DD: <a href="http://paulschreiber.com/blog/2007/03/02/javascript-date-validation/" rel="noreferrer">JavaScript date validation</a></p> <p>I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:</p> <pre><code>String.prototype.isValidDate = function() { var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$"); var matches = IsoDateRe.exec(this); if (!matches) return false; var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]); return ((composedDate.getMonth() == (matches[1] - 1)) &amp;&amp; (composedDate.getDate() == matches[2]) &amp;&amp; (composedDate.getFullYear() == matches[3])); } </code></pre> <p>How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?</p> <p>Thanks.</p>
[ { "answer_id": 276488, "author": "Kevin Gorski", "author_id": 35806, "author_profile": "https://Stackoverflow.com/users/35806", "pm_score": 1, "selected": false, "text": "var matches = this.match(/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/);\n ^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$\n" }, { "answer_id": 276497, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "String.prototype.isValidDate = function() {\n\n const match = this.match(/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/);\n if (!match || match.length !== 4) {\n return false\n }\n\n const test = new Date(match[3], match[1] - 1, match[2]);\n\n return (\n (test.getMonth() == match[1] - 1) &&\n (test.getDate() == match[2]) &&\n (test.getFullYear() == match[3])\n );\n}\n\nvar date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'\nalert(date.isValidDate() ); // true\n" }, { "answer_id": 276511, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "function isValidDate(subject){\n if (subject.match(/^(?:(0[1-9]|1[012])[\\- \\/.](0[1-9]|[12][0-9]|3[01])[\\- \\/.](19|20)[0-9]{2})$/)){\n return true;\n }else{\n return false;\n }\n}\n" }, { "answer_id": 276622, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": false, "text": "function isValidDate(date)\n{\n var matches = /^(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{4})$/.exec(date);\n if (matches == null) return false;\n var d = matches[2];\n var m = matches[1] - 1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n}\nconsole.log(isValidDate('10-12-1961'));\nconsole.log(isValidDate('12/11/1961'));\nconsole.log(isValidDate('02-11-1961'));\nconsole.log(isValidDate('12/01/1961'));\nconsole.log(isValidDate('13-11-1961'));\nconsole.log(isValidDate('11-31-1961'));\nconsole.log(isValidDate('11-31-1061'));\n" }, { "answer_id": 8390325, "author": "Matthew Carroll", "author_id": 227070, "author_profile": "https://Stackoverflow.com/users/227070", "pm_score": 4, "selected": false, "text": "function isValidDate(date) {\n var valid = true;\n\n date = date.replace('/-/g', '');\n\n var month = parseInt(date.substring(0, 2),10);\n var day = parseInt(date.substring(2, 4),10);\n var year = parseInt(date.substring(4, 8),10);\n\n if(isNaN(month) || isNaN(day) || isNaN(year)) return false;\n\n if((month < 1) || (month > 12)) valid = false;\n else if((day < 1) || (day > 31)) valid = false;\n else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;\n else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;\n else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;\n else if((month == 2) && (day > 28)) valid = false;\n\n return valid;\n}\n" }, { "answer_id": 10582772, "author": "Jawad", "author_id": 1393651, "author_profile": "https://Stackoverflow.com/users/1393651", "pm_score": 0, "selected": false, "text": "function isValidDateFormat(date, id)\n{\n var todayDate = new Date();\n var matches = /^(\\d{2})[-\\/](\\d{2})[-\\/](\\d{4})$/.exec(date);\n\n if (matches == null)\n {\n if(date != '__-__-____')\n {\n alert('Please enter valid date');\n }\n }\n else\n {\n var day = 31;\n var month = 12;\n var b_date = date.split(\"-\");\n if(b_date[0] <= day)\n {\n if(b_date[1] <= month)\n {\n if(b_date[2] >= 1900 && b_date[2] <= todayDate.getFullYear())\n {\n return true;\n }\n else\n {\n $(\"#\"+id).val('');\n alert('Please enter valid Year'); \n } \n }\n else\n {\n $(\"#\"+id).val('');\n alert('Please enter valid Month'); \n } \n }\n else\n {\n alert('Please enter valid Day');\n $(\"#\"+id).val(''); \n }\n }\n}\n" }, { "answer_id": 12570083, "author": "Srimitha", "author_id": 1695191, "author_profile": "https://Stackoverflow.com/users/1695191", "pm_score": 1, "selected": false, "text": "var day = document.getElementById(\"DayTextBox\").value;\n\nvar regExp = /^([1-9]|[1][012])\\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;\n\nreturn regExp.test(day);\n" }, { "answer_id": 13971620, "author": "Jyotish", "author_id": 1918694, "author_profile": "https://Stackoverflow.com/users/1918694", "pm_score": 0, "selected": false, "text": "function isInteger(s){\n var i;\n for (i = 0; i < s.length; i++){ \n // Check that current character is number.\n var c = s.charAt(i);\n if (((c < \"0\") || (c > \"9\"))) return false;\n }\n // All characters are numbers.\n return true;\n}\n\nfunction stripCharsInBag(s, bag){\n var i;\n var returnString = \"\";\n // Search through string's characters one by one.\n // If character is not in bag, append to returnString.\n for (i = 0; i < s.length; i++){ \n var c = s.charAt(i);\n if (bag.indexOf(c) == -1) returnString += c;\n }\n return returnString;\n}\n\nfunction daysInFebruary (year){\n // February has 29 days in any year evenly divisible by four,\n // EXCEPT for centurial years which are not also divisible by 400.\n return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );\n}\nfunction DaysArray(n) {\n for (var i = 1; i <= n; i++) {\n this[i] = 31;\n if (i==4 || i==6 || i==9 || i==11) {\n this[i] = 30;\n }\n if (i==2) {\n this[i] = 29;\n }\n } \n return this;\n}\n\nfunction isValidDate(dtStr){\n var daysInMonth = DaysArray(12);\n var pos1=dtStr.indexOf(dtCh);\n var pos2=dtStr.indexOf(dtCh,pos1+1);\n var strDay=dtStr.substring(0,pos1);\n var strMonth=dtStr.substring(pos1+1,pos2);\n var strYear=dtStr.substring(pos2+1);\n strYr=strYear;\n if (strDay.charAt(0)==\"0\" && strDay.length>1) \n strDay=strDay.substring(1);\n if (strMonth.charAt(0)==\"0\" && strMonth.length>1) \n strMonth=strMonth.substring(1);\n for (var i = 1; i <= 3; i++) {\n if (strYr.charAt(0)==\"0\" && strYr.length>1) \n strYr=strYr.substring(1);\n }\n month=parseInt(strMonth);\n day=parseInt(strDay);\n year=parseInt(strYr);\n if (pos1==-1 || pos2==-1){\n alert(\"The date format should be : dd.mm.yyyy\");\n return false;\n }\n if (strMonth.length<1 || month<1 || month>12){\n alert(\"Please enter a valid month\");\n return false;\n }\n if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){\n alert(\"Please enter a valid day\");\n return false;\n }\n if (strYear.length != 4 || year==0 || year<minYear){\n alert(\"Please enter a valid 4 digit year after \"+minYear);\n return false;\n }\n if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){\n alert(\"Please enter a valid date\");\n return false;\n }\n return true;\n}\n" }, { "answer_id": 16033681, "author": "niraj Verma", "author_id": 2285845, "author_profile": "https://Stackoverflow.com/users/2285845", "pm_score": -1, "selected": false, "text": "<script language = \"Javascript\">\n// Declaring valid date character, minimum year and maximum year\nvar dtCh= \"/\";\nvar minYear=1900;\nvar maxYear=2100;\n\nfunction isInteger(s){\n var i;\n for (i = 0; i < s.length; i++){ \n // Check that current character is number.\n var c = s.charAt(i);\n if (((c < \"0\") || (c > \"9\"))) return false;\n }\n // All characters are numbers.\n return true;\n}\n\nfunction stripCharsInBag(s, bag){\n var i;\n var returnString = \"\";\n // Search through string's characters one by one.\n // If character is not in bag, append to returnString.\n for (i = 0; i < s.length; i++){ \n var c = s.charAt(i);\n if (bag.indexOf(c) == -1) returnString += c;\n }\n return returnString;\n}\n\nfunction daysInFebruary (year){\n // February has 29 days in any year evenly divisible by four,\n // EXCEPT for centurial years which are not also divisible by 400.\n return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );\n}\nfunction DaysArray(n) {\n for (var i = 1; i <= n; i++) {\n this[i] = 31\n if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}\n if (i==2) {this[i] = 29}\n } \n return this\n}\n\nfunction isDate(dtStr){\n var daysInMonth = DaysArray(12)\n var pos1=dtStr.indexOf(dtCh)\n var pos2=dtStr.indexOf(dtCh,pos1+1)\n var strDay=dtStr.substring(0,pos1)\n var strMonth=dtStr.substring(pos1+1,pos2)\n var strYear=dtStr.substring(pos2+1)\n strYr=strYear\n if (strDay.charAt(0)==\"0\" && strDay.length>1) strDay=strDay.substring(1)\n if (strMonth.charAt(0)==\"0\" && strMonth.length>1) strMonth=strMonth.substring(1)\n for (var i = 1; i <= 3; i++) {\n if (strYr.charAt(0)==\"0\" && strYr.length>1) strYr=strYr.substring(1)\n }\n month=parseInt(strMonth)\n day=parseInt(strDay)\n year=parseInt(strYr)\n if (pos1==-1 || pos2==-1){\n alert(\"The date format should be : dd/mm/yyyy\")\n return false\n }\n if (strMonth.length<1 || month<1 || month>12){\n alert(\"Please enter a valid month\")\n return false\n }\n if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){\n alert(\"Please enter a valid day\")\n return false\n }\n if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){\n alert(\"Please enter a valid 4 digit year between \"+minYear+\" and \"+maxYear)\n return false\n }\n if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){\n alert(\"Please enter a valid date\")\n return false\n }\nreturn true\n}\n\nfunction ValidateForm(){\n var dt=document.frmSample.txtDateenter code here\n if (isDate(dt.value)==false){\n dt.focus()\n return false\n }\n return true\n }\n\n</script>\n" }, { "answer_id": 19364439, "author": "José Gabriel González", "author_id": 2019906, "author_profile": "https://Stackoverflow.com/users/2019906", "pm_score": 2, "selected": false, "text": "function isValidDate(date)\n{\n var matches = /^(\\d{2})[-\\/](\\d{2})[-\\/](\\d{4})$/.exec(date);\n if (matches == null) return false;\n var d = matches[1];\n var m = matches[2]-1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n}\nconsole.log(isValidDate('10-12-1961'));\nconsole.log(isValidDate('12/11/1961'));\nconsole.log(isValidDate('02-11-1961'));\nconsole.log(isValidDate('12/01/1961'));\nconsole.log(isValidDate('13-11-1961'));\nconsole.log(isValidDate('11-31-1961'));\nconsole.log(isValidDate('11-31-1061'));\n" }, { "answer_id": 19775735, "author": "user2864740", "author_id": 2864740, "author_profile": "https://Stackoverflow.com/users/2864740", "pm_score": 2, "selected": false, "text": "var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']\n\nmoment('11/28/1981', formats).isValid() // true\nmoment('2-29-2003', formats).isValid() // false (not leap year)\nmoment('2-29-2004', formats).isValid() // true (leap year)\n moment(.., formats) isValid String.prototype.isValidDate = function() {\n var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];\n return moment(\"\" + this, formats).isValid();\n}\n" }, { "answer_id": 21839943, "author": "Adam", "author_id": 3320907, "author_profile": "https://Stackoverflow.com/users/3320907", "pm_score": 0, "selected": false, "text": "if (document.getElementById('expiryDay').value != test(match(\"/^([0-9]{2})\\/([0-9]{2})$/\"))){\n alert(\"Enter the date in two digit month flowed by two digits year \\n\");\n}\n" }, { "answer_id": 32240782, "author": "Mayur Narula", "author_id": 5268385, "author_profile": "https://Stackoverflow.com/users/5268385", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html> \n<html> \n<head> \n\n<title></title> \n <script>\n function dateCheck(inputText) {\n debugger;\n\n var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$/;\n\n var flag = 1;\n\n if (inputText.value.match(dateFormat)) {\n document.myForm.dateInput.focus();\n\n var inputFormat1 = inputText.value.split('/');\n var inputFormat2 = inputText.value.split('-');\n linputFormat1 = inputFormat1.length;\n linputFormat2 = inputFormat2.length;\n\n if (linputFormat1 > 1) {\n var pdate = inputText.value.split('/');\n }\n else if (linputFormat2 > 1) {\n var pdate = inputText.value.split('-');\n }\n var date = parseInt(pdate[0]);\n var month = parseInt(pdate[1]);\n var year = parseInt(pdate[2]);\n\n var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n if (month == 1 || month > 2) {\n if (date > ListofDays[month - 1]) {\n alert(\"Invalid date format!\");\n return false;\n }\n }\n\n if (month == 2) {\n var leapYear = false;\n\n if ((!(year % 4) && year % 100) || !(year % 400)) {\n leapYear = true;\n\n }\n if ((leapYear == false) && (date >= 29)) {\n alert(\"Invalid date format!\");\n return false;\n }\n if ((leapYear == true) && (date > 29)) {\n alert(\"Invalid date format!\");\n return false;\n }\n }\n if (flag == 1) {\n alert(\"Valid Date\");\n }\n }\n else {\n alert(\"Invalid date format!\");\n document.myForm.dateInput.focus();\n return false;\n }\n }\n function restrictCharacters(evt) {\n\n evt = (evt) ? evt : window.event;\n var charCode = (evt.which) ? evt.which : evt.keyCode;\n if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {\n return true;\n }\n else {\n return false;\n }\n }\n\n\n </script> \n</head>\n\n\n\n<body> \n <div> \n <form name=\"myForm\" action=\"#\"> \n <table>\n <tr>\n <td>Enter Date</td>\n <td><input type=\"text\" onkeypress=\"return restrictCharacters(event);\" name=\"dateInput\"/></td>\n <td></td>\n <td><span id=\"span2\"></span></td>\n </tr>\n\n <tr>\n <td></td>\n <td><input type=\"button\" name=\"submit\" value=\"Submit\" onclick=\"dateCheck(document.myForm.dateInput)\" /></td>\n </tr>\n </table>\n </form> \n </div> \n</body> \n</html> \n" }, { "answer_id": 36956722, "author": "Dinesh Lomte", "author_id": 2436314, "author_profile": "https://Stackoverflow.com/users/2436314", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\nfunction validate(format) {\n\n if(isAfterCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is after the current date.');\n } else {\n alert('Date is not after the current date.');\n }\n if(isBeforeCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is before current date.');\n } else {\n alert('Date is not before current date.');\n }\n if(isCurrentDate(document.getElementById('start').value, format)) {\n alert('Date is current date.');\n } else {\n alert('Date is not a current date.');\n }\n if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('Start/Effective Date cannot be greater than End/Expiration Date');\n } else {\n alert('Valid dates...');\n }\n if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('End/Expiration Date cannot be less than Start/Effective Date');\n } else {\n alert('Valid dates...');\n }\n if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {\n alert('Dates are equals...');\n } else {\n alert('Dates are not equals...');\n }\n if (isDate(document.getElementById('start').value, format)) {\n alert('Is valid date...');\n } else {\n alert('Is invalid date...');\n }\n}\n\n/**\n * This method gets the year index from the supplied format\n */\nfunction getYearIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'YYYY'\n || tokens[0] === 'yyyy') {\n return 0;\n } else if (tokens[1]=== 'YYYY'\n || tokens[1] === 'yyyy') {\n return 1;\n } else if (tokens[2] === 'YYYY'\n || tokens[2] === 'yyyy') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the year string located at the supplied index\n */\nfunction getYear(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method gets the month index from the supplied format\n */\nfunction getMonthIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'MM'\n || tokens[0] === 'mm') {\n return 0;\n } else if (tokens[1] === 'MM'\n || tokens[1] === 'mm') {\n return 1;\n } else if (tokens[2] === 'MM'\n || tokens[2] === 'mm') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the month string located at the supplied index\n */\nfunction getMonth(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method gets the date index from the supplied format\n */\nfunction getDateIndex(format) {\n\n var tokens = splitDateFormat(format);\n\n if (tokens[0] === 'DD'\n || tokens[0] === 'dd') {\n return 0;\n } else if (tokens[1] === 'DD'\n || tokens[1] === 'dd') {\n return 1;\n } else if (tokens[2] === 'DD'\n || tokens[2] === 'dd') {\n return 2;\n }\n // Returning the default value as -1\n return -1;\n}\n\n/**\n * This method returns the date string located at the supplied index\n */\nfunction getDate(date, index) {\n\n var tokens = splitDateFormat(date);\n return tokens[index];\n}\n\n/**\n * This method returns true if date1 is before date2 else return false\n */\nfunction isBefore(date1, date2, format) {\n // Validating if date1 date is greater than the date2 date\n if (new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n > new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method returns true if date1 is after date2 else return false\n */\nfunction isAfter(date1, date2, format) {\n // Validating if date2 date is less than the date1 date\n if (new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()\n < new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n ) {\n return true;\n } \n return false; \n}\n\n/**\n * This method returns true if date1 is equals to date2 else return false\n */\nfunction isEquals(date1, date2, format) {\n // Validating if date1 date is equals to the date2 date\n if (new Date(getYear(date1, getYearIndex(format)), \n getMonth(date1, getMonthIndex(format)) - 1, \n getDate(date1, getDateIndex(format))).getTime()\n === new Date(getYear(date2, getYearIndex(format)), \n getMonth(date2, getMonthIndex(format)) - 1, \n getDate(date2, getDateIndex(format))).getTime()) {\n return true;\n } \n return false;\n}\n\n/**\n * This method validates and returns true if the supplied date is \n * equals to the current date.\n */\nfunction isCurrentDate(date, format) {\n // Validating if the supplied date is the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n === new Date(new Date().getFullYear(), \n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method validates and returns true if the supplied date value \n * is before the current date.\n */\nfunction isBeforeCurrentDate(date, format) {\n // Validating if the supplied date is before the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n < new Date(new Date().getFullYear(), \n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method validates and returns true if the supplied date value \n * is after the current date.\n */\nfunction isAfterCurrentDate(date, format) {\n // Validating if the supplied date is before the current date\n if (new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))).getTime()\n > new Date(new Date().getFullYear(),\n new Date().getMonth(), \n new Date().getDate()).getTime()) {\n return true;\n } \n return false; \n}\n\n/**\n * This method splits the supplied date OR format based \n * on non alpha numeric characters in the supplied string.\n */\nfunction splitDateFormat(dateFormat) {\n // Spliting the supplied string based on non characters\n return dateFormat.split(/\\W/);\n}\n\n/*\n * This method validates if the supplied value is a valid date.\n */\nfunction isDate(date, format) { \n // Validating if the supplied date string is valid and not a NaN (Not a Number)\n if (!isNaN(new Date(getYear(date, getYearIndex(format)), \n getMonth(date, getMonthIndex(format)) - 1, \n getDate(date, getDateIndex(format))))) { \n return true;\n } \n return false; \n}\n <input type=\"text\" name=\"start\" id=\"start\" size=\"10\" value=\"05/31/2016\" />\n<br/> \n<input type=\"text\" name=\"end\" id=\"end\" size=\"10\" value=\"04/28/2016\" />\n<br/>\n<input type=\"button\" value=\"Submit\" onclick=\"javascript:validate('MM/dd/yyyy');\" />\n" }, { "answer_id": 39654657, "author": "Dominik Baran", "author_id": 6503328, "author_profile": "https://Stackoverflow.com/users/6503328", "pm_score": 0, "selected": false, "text": "$scope.validDate = function(value){\n var matches = /^(\\d{1,2})[.](\\d{1,2})[.](\\d{4})$/.exec(value);\n if (matches == null) return false;\n var d = matches[1];\n var m = matches[2] - 1;\n var y = matches[3];\n var composedDate = new Date(y, m, d);\n return composedDate.getDate() == d &&\n composedDate.getMonth() == m &&\n composedDate.getFullYear() == y;\n };\n console.log($scope.validDate('22.04.2001'));\n console.log($scope.validDate('03.10.2001'));\n console.log($scope.validDate('30.02.2001'));\n console.log($scope.validDate('23.09.2016'));\n console.log($scope.validDate('29.02.2016'));\n console.log($scope.validDate('31.02.2016'));\n ValidDate = new function(value) {\n var MyDate= ValidDate('29.09.2016');\n" }, { "answer_id": 42264474, "author": "Fox", "author_id": 7572533, "author_profile": "https://Stackoverflow.com/users/7572533", "pm_score": 0, "selected": false, "text": "function dateValidate(val){ \nvar dateStr = val.split('.'); \n var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]); \n if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])\n { return date; }\n else{ return 'NotValid';} \n}\n" }, { "answer_id": 43465071, "author": "Harish Gupta", "author_id": 5227100, "author_profile": "https://Stackoverflow.com/users/5227100", "pm_score": 0, "selected": false, "text": "function validateDate(dates){\n re = /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/; \n var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);\n\n if(regs = dates.match(re)) {\n // day value between 1 and 31\n if(regs[1] < 1 || regs[1] > 31) { \n return false;\n }\n // month value between 1 and 12\n if(regs[2] < 1 || regs[2] > 12) { \n return false;\n }\n\n var maxday=days[regs[2]-1];\n\n if(regs[2]==2){\n if(regs[3]%4==0){\n maxday=maxday+1; \n }\n }\n\n if(regs[1]>maxday){\n return false;\n }\n\n return true;\n }else{\n return false;\n } \n}\n" }, { "answer_id": 54227074, "author": "Adam Leggett", "author_id": 4735342, "author_profile": "https://Stackoverflow.com/users/4735342", "pm_score": 0, "selected": false, "text": "function dateValid(date) {\n var match = date.match(/^(\\d\\d)-(\\d\\d)-(\\d{4})$/) || [];\n var m = (match[1] | 0) - 1;\n var d = match[2] | 0;\n var y = match[3] | 0;\n return !(\n m < 0 || // Before January\n m > 11 || // After December\n d < 1 || // Before the 1st of the month\n d - 30 > (2773 >> m & 1) || // After the 30th or 31st of the month using bitmap\n m == 1 && d - 28 > // After the 28th or 29th of February depending on leap year\n (!(y % 4) && y % 100 || !(y % 400)));\n}\n\nconsole.log('02-29-2000', dateValid('02-29-2000'));\nconsole.log('02-29-2001', dateValid('02-29-2001'));\nconsole.log('12-31-1970', dateValid('12-31-1970'));\nconsole.log('Hello', dateValid('Hello'));" }, { "answer_id": 54945688, "author": "Michael Janssen", "author_id": 11089162, "author_profile": "https://Stackoverflow.com/users/11089162", "pm_score": 0, "selected": false, "text": "export function isLeapYear(year) {\n return (\n year % 4 === 0 && (year % 100 != 0 || year % 1000 === 0 || year % 400 === 0)\n )\n}\n\nexport function isValidGermanDate(germanDate) {\n if (\n !germanDate ||\n germanDate.length < 5 ||\n germanDate.split('.').length < 3\n ) {\n return false\n }\n\n const day = parseInt(germanDate.split('.')[0])\n const month = parseInt(germanDate.split('.')[1])\n const year = parseInt(germanDate.split('.')[2])\n\n if (isNaN(month) || isNaN(day) || isNaN(year)) {\n return false\n }\n\n if (month < 1 || month > 12) {\n return false\n }\n\n if (day < 1 || day > 31) {\n return false\n }\n\n if ((month === 4 || month === 6 || month === 9 || month === 11) && day > 30) {\n return false\n }\n\n if (isLeapYear(year)) {\n if (month === 2 && day > 29) {\n return false\n }\n } else {\n if (month === 2 && day > 28) {\n return false\n }\n }\n\n return true\n}\n" }, { "answer_id": 64623472, "author": "Patrick_B", "author_id": 9745415, "author_profile": "https://Stackoverflow.com/users/9745415", "pm_score": 0, "selected": false, "text": "true false const dateValid = (date) => {\n const isLeapYear = (yearNum) => {\n return ((yearNum % 100 === 0) ? (yearNum % 400 === 0) : (yearNum % 4 === 0))?\n 1:\n 0;\n }\n const match = date.match(/^(\\d\\d)\\/(\\d\\d)\\/(\\d{4})$/) || [];\n const month = (match[1] | 0) - 1;\n const day = match[2] | 0;\n const year = match[3] | 0;\n\nconst dateEval=!( month < 0 || // Before January\n month > 11 || // After December\n day < 1 || // Before the 1st of the month\n day - 30 > (2773 >> month & 1) ||\n month === 1 && day - 28 > isLeapYear(year) \n // Day is 28 or 29, month is 02, year is leap year ==> true\n );\n\nreturn `\\nDate: ${date}\\n\\n \n Valid Date?: ${dateEval}\\n\n =======================================`\n}\n\nconsole.log(dateValid('02/28/2020')) // true\nconsole.log(dateValid('02/29/2020')) // true\nconsole.log(dateValid('02/30/2020')) // false\nconsole.log(dateValid('01/31/2020')) // true\nconsole.log(dateValid('01/31/2000')) // true\nconsole.log(dateValid('04/31/2020')) // false\nconsole.log(dateValid('04/31/2000')) // false\nconsole.log(dateValid('04/30/2020')) // true\nconsole.log(dateValid('01/32/2020')) // false\nconsole.log(dateValid('02/28/2021')) // true\nconsole.log(dateValid('02/29/2021')) // false\nconsole.log(dateValid('02/30/2021')) // false\nconsole.log(dateValid('02/28/2000')) // true\nconsole.log(dateValid('02/29/2000')) // true\nconsole.log(dateValid('02/30/2000')) // false\nconsole.log(dateValid('02/28/2001')) // true\nconsole.log(dateValid('02/29/2001')) // false\nconsole.log(dateValid('02/30/2001')) // false\n \\/ match -" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
276,489
<p>We'll soon be embarking on the development of a new mobile application. This particular app will be used for heavy searching of text based fields. Any suggestions from the group at large for what sort of database engine is best suited to allowing these types of searches on a mobile platform?</p> <p>Specifics include Windows Mobile 6 and we'll be using the .Net CF. Also some of the text based fields will be anywhere between 35 and 500 characters. The device will operate in two different methods, batch and WiFi. Of course for WiFi we can just submit requests to a full blown DB engine and just fetch results back. This question centres around the "batch" version which will house a database loaded with information on the devices flash/removable storage card.</p> <p>At any rate, I know SQLCE has some basic indexing but you don't get into the real fancy "full text" style indexes until you've got the full blown version which of course isn't available on a mobile platform.</p> <p>An example of what the data would look like:</p> <p><em>"apron carpenter adjustable leather container pocket waist hardware belt"</em> etc. etc.</p> <p>I haven't gotten into the evaluation of any other specific options yet as I figure I'd leverage the experience of this group in order to first point me down some specific avenues.</p> <p>Any suggestions/tips?</p>
[ { "answer_id": 451671, "author": "Jason Down", "author_id": 9732, "author_profile": "https://Stackoverflow.com/users/9732", "pm_score": 4, "selected": true, "text": "public class SmallItem\n{\n private int _sku;\n public int Sku\n {\n get { return _sku; }\n set { _sku = value; }\n }\n\n // Size of max description size + 1 for null terminator.\n private char[] _description = new char[36];\n public char[] Description\n {\n get { return _description; }\n set { _description = value; }\n }\n\n public SmallItem()\n {\n }\n}\n public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)\n{\n // Don't allow more than the maximum allowable results constant. \n int[] matchingSkus = new int[maxResults];\n\n // Indexes and counters.\n int matchNumber = 0;\n int currentWord = 0;\n int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes\n\n bool matchedWord;\n\n try\n { \n /* Character array of character arrays. Each array is a word we want to match.\n * We need the + 1 because totalWords had - 1 (We are setting a size/length here,\n * so it is not 0 based... we used - 1 on totalWords because it is used for 0\n * based index referencing.)\n * */\n char[][] allWordsToMatch = new char[totalWords + 1][];\n\n // Character array to hold the current word to match. \n char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.\n\n // Loop through the original string array or words to match and create the character arrays. \n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n char[] desc = new char[descriptionTerms[currentWord].Length + 1];\n Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);\n allWordsToMatch[currentWord] = desc;\n }\n\n // Offsets for description and filter(word to match) pointers.\n int descriptionOffset = 0, filterOffset = 0;\n\n // Loop through the list of items trying to find matching words.\n foreach (SmallItem i in itemList)\n {\n // If we have reached our maximum allowable matches, we should stop searching and just return the results.\n if (matchNumber == maxResults)\n break;\n\n // Loop through the \"words to match\" filter list.\n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n // Reset our match flag and current word to match.\n matchedWord = false;\n wordToMatch = allWordsToMatch[currentWord];\n\n // Delving into unmanaged code for SCREAMING performance ;)\n unsafe\n {\n // Pointer to the description of the current item on the list (starting at first char).\n fixed (char* pdesc = &i.Description[0])\n {\n // Pointer to the current word we are trying to match (starting at first char).\n fixed (char* pfilter = &wordToMatch[0])\n {\n // Reset the description offset.\n descriptionOffset = 0;\n\n // Continue our search on the current word until we hit a null terminator for the char array.\n while (*(pdesc + descriptionOffset) != '\\0')\n {\n // We've matched the first character of the word we're trying to match.\n if (*(pdesc + descriptionOffset) == *pfilter)\n {\n // Reset the filter offset.\n filterOffset = 0;\n\n /* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match\n * or a null terminator, we need to jump out of this loop.\n * */\n while (*(pfilter + filterOffset) != '\\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))\n {\n // Increase the offsets together to the next character.\n ++filterOffset;\n ++descriptionOffset;\n }\n\n // We hit matches all the way to the null terminator. The entire word was a match.\n if (*(pfilter + filterOffset) == '\\0')\n {\n // If our current word matched is the last word on the match list, we have matched all words.\n if (currentWord == totalWords)\n {\n // Add the sku as a match.\n matchingSkus[matchNumber] = i.Sku.ToString();\n matchNumber++;\n\n /* Break out of this item description. We have matched all needed words and can move to\n * the next item.\n * */\n break;\n }\n\n /* We've matched a word, but still have more words left in our list of words to match.\n * Set our match flag to true, which will mean we continue continue to search for the\n * next word on the list.\n * */\n matchedWord = true;\n }\n }\n\n // No match on the current character. Move to next one.\n descriptionOffset++;\n }\n\n /* The current word had no match, so no sense in looking for the rest of the words. Break to the\n * next item description.\n * */\n if (!matchedWord)\n break;\n }\n }\n }\n }\n };\n\n // We have our list of matching skus. We'll resize the array and pass it back.\n Array.Resize(ref matchingSkus, matchNumber);\n return matchingSkus;\n }\n catch (Exception ex)\n {\n // Handle the exception\n }\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26853/" ]
276,499
<p>I have a custom UILabel subclass for displaying currency values. I only want the user to be able to enter digits and let the view format those digits into a currency value -- like a cash register. This makes UITextField an inappropriate choice for this kind of input.</p> <p>I've already overridden hitTest: so that the UILabel will return itself -- this is apparently a bug. Also, I've overridden both canBecomeFirstResponder and becomeFirstResponder to return YES. Neither of these methods are being called, though.</p> <p>I only want to let the user type numbers and use the backspace key. I've implemented UITextInputTraits, but the keyboard does not appear. So, can this be done? And does if so, what am I missing?</p>
[ { "answer_id": 451671, "author": "Jason Down", "author_id": 9732, "author_profile": "https://Stackoverflow.com/users/9732", "pm_score": 4, "selected": true, "text": "public class SmallItem\n{\n private int _sku;\n public int Sku\n {\n get { return _sku; }\n set { _sku = value; }\n }\n\n // Size of max description size + 1 for null terminator.\n private char[] _description = new char[36];\n public char[] Description\n {\n get { return _description; }\n set { _description = value; }\n }\n\n public SmallItem()\n {\n }\n}\n public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)\n{\n // Don't allow more than the maximum allowable results constant. \n int[] matchingSkus = new int[maxResults];\n\n // Indexes and counters.\n int matchNumber = 0;\n int currentWord = 0;\n int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes\n\n bool matchedWord;\n\n try\n { \n /* Character array of character arrays. Each array is a word we want to match.\n * We need the + 1 because totalWords had - 1 (We are setting a size/length here,\n * so it is not 0 based... we used - 1 on totalWords because it is used for 0\n * based index referencing.)\n * */\n char[][] allWordsToMatch = new char[totalWords + 1][];\n\n // Character array to hold the current word to match. \n char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.\n\n // Loop through the original string array or words to match and create the character arrays. \n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n char[] desc = new char[descriptionTerms[currentWord].Length + 1];\n Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);\n allWordsToMatch[currentWord] = desc;\n }\n\n // Offsets for description and filter(word to match) pointers.\n int descriptionOffset = 0, filterOffset = 0;\n\n // Loop through the list of items trying to find matching words.\n foreach (SmallItem i in itemList)\n {\n // If we have reached our maximum allowable matches, we should stop searching and just return the results.\n if (matchNumber == maxResults)\n break;\n\n // Loop through the \"words to match\" filter list.\n for (currentWord = 0; currentWord <= totalWords; currentWord++)\n {\n // Reset our match flag and current word to match.\n matchedWord = false;\n wordToMatch = allWordsToMatch[currentWord];\n\n // Delving into unmanaged code for SCREAMING performance ;)\n unsafe\n {\n // Pointer to the description of the current item on the list (starting at first char).\n fixed (char* pdesc = &i.Description[0])\n {\n // Pointer to the current word we are trying to match (starting at first char).\n fixed (char* pfilter = &wordToMatch[0])\n {\n // Reset the description offset.\n descriptionOffset = 0;\n\n // Continue our search on the current word until we hit a null terminator for the char array.\n while (*(pdesc + descriptionOffset) != '\\0')\n {\n // We've matched the first character of the word we're trying to match.\n if (*(pdesc + descriptionOffset) == *pfilter)\n {\n // Reset the filter offset.\n filterOffset = 0;\n\n /* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match\n * or a null terminator, we need to jump out of this loop.\n * */\n while (*(pfilter + filterOffset) != '\\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))\n {\n // Increase the offsets together to the next character.\n ++filterOffset;\n ++descriptionOffset;\n }\n\n // We hit matches all the way to the null terminator. The entire word was a match.\n if (*(pfilter + filterOffset) == '\\0')\n {\n // If our current word matched is the last word on the match list, we have matched all words.\n if (currentWord == totalWords)\n {\n // Add the sku as a match.\n matchingSkus[matchNumber] = i.Sku.ToString();\n matchNumber++;\n\n /* Break out of this item description. We have matched all needed words and can move to\n * the next item.\n * */\n break;\n }\n\n /* We've matched a word, but still have more words left in our list of words to match.\n * Set our match flag to true, which will mean we continue continue to search for the\n * next word on the list.\n * */\n matchedWord = true;\n }\n }\n\n // No match on the current character. Move to next one.\n descriptionOffset++;\n }\n\n /* The current word had no match, so no sense in looking for the rest of the words. Break to the\n * next item description.\n * */\n if (!matchedWord)\n break;\n }\n }\n }\n }\n };\n\n // We have our list of matching skus. We'll resize the array and pass it back.\n Array.Resize(ref matchingSkus, matchNumber);\n return matchingSkus;\n }\n catch (Exception ex)\n {\n // Handle the exception\n }\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35999/" ]
276,512
<p>I have seen some very weird <code>for</code> loops when reading other people's code. I have been trying to search for a full syntax explanation for the <code>for</code> loop in C but it is very hard because the word "for" appears in unrelated sentences making the search almost impossible to Google effectively.</p> <p>This question came to my mind after reading <a href="https://stackoverflow.com/questions/260511/russian-peasant-multiplication">this thread</a> which made me curious again.</p> <p>The <code>for</code> here: </p> <pre><code>for(p=0;p+=(a&amp;1)*b,a!=1;a&gt;&gt;=1,b&lt;&lt;=1); </code></pre> <p>In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both <code>a&gt;&gt;=1</code> and <code>b&lt;&lt;=1</code>. </p> <p>But within a loop exit condition, what happens? Does it exit when <code>p==0</code>, when <code>a==1</code> or when both happen?</p> <p>It would be great if anyone could help me understand this and maybe point me in the direction of a full <code>for</code> loop syntax description.</p>
[ { "answer_id": 276518, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "for false" }, { "answer_id": 276519, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 8, "selected": true, "text": "x = (a, b);\n for (init; condition; increment)\n ...\n continue break init;\nwhile (condition) {\n ...\n increment;\n}\n continue break p=0;\nwhile (p+=(a&1)*b,a!=1) {\n ...\n a>>=1,b<<=1;\n}\n continue break p=0; \nwhile (true) {\n p+=(a&1)*b;\n if (a == 1) break;\n ...\n a>>=1;\n b<<=1;\n}\n true break goto continue continue && || for (...) { ... }\n {\nfor (...) { ... }\n}\n init for (int i = 0; i < sizeof(something); i++) { ... }\n i for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }\n for ( clause-1 ; expression-2 ; expression-3 ) statement\n" }, { "answer_id": 276540, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "for (initializer; condition; counter) statement_or_statement_block;\n" }, { "answer_id": 626359, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "for for for(;;) \n" }, { "answer_id": 2631986, "author": "Bob", "author_id": 315773, "author_profile": "https://Stackoverflow.com/users/315773", "pm_score": 0, "selected": false, "text": "warning: left-hand operand of comma expression has no effect\n" }, { "answer_id": 26359481, "author": "R.M.VIVEK ARNI", "author_id": 4140951, "author_profile": "https://Stackoverflow.com/users/4140951", "pm_score": -1, "selected": false, "text": "i=10;i<10 the condition is false terminate for block,\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
276,514
<p>I am trying to install SQL server express 2008 on my machine. I get an error message that says that older version of VS 2008 in installed on the computer. Upgrade to VS2008 SP1 before installing Sql server 2008. </p> <p>I tried to install sp1 but I get an error message that a compatible version of vs2008 is not detected on the system. the upgrade is not compatible with express editions. </p> <p>I am having trouble installing sql server 2008 express installed on my machine and I am having problems. Please help me. </p>
[ { "answer_id": 2397422, "author": "sergiopereira", "author_id": 21420, "author_profile": "https://Stackoverflow.com/users/21420", "pm_score": 2, "selected": false, "text": "HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\DevDiv\\VS\\Servicing\\9.0\\IDE\\1033 SP = dword:00000001\nSPIndex = dword:00000001\nSPName = \"SP1\"\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35948/" ]
276,516
<p>I need to build a function which parses the domain from a URL.</p> <p>So, with</p> <pre><code>http://google.com/dhasjkdas/sadsdds/sdda/sdads.html </code></pre> <p>or</p> <pre><code>http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html </code></pre> <p>it should return <code>google.com</code></p> <p>with</p> <pre><code>http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html </code></pre> <p>it should return <code>google.co.uk</code>.</p>
[ { "answer_id": 276525, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 10, "selected": true, "text": "parse_url() $url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$parse = parse_url($url);\necho $parse['host']; // prints 'google.com'\n parse_url" }, { "answer_id": 1974047, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 5, "selected": false, "text": "function getHost($Address) { \n $parseUrl = parse_url(trim($Address)); \n return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); \n} \n\ngetHost(\"example.com\"); // Gives example.com \ngetHost(\"http://example.com\"); // Gives example.com \ngetHost(\"www.example.com\"); // Gives www.example.com \ngetHost(\"http://example.com/xyz\"); // Gives example.com \n" }, { "answer_id": 1974074, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 7, "selected": false, "text": "$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));\n google.com" }, { "answer_id": 6095829, "author": "Luka", "author_id": 744234, "author_profile": "https://Stackoverflow.com/users/744234", "pm_score": 2, "selected": false, "text": "//=====================================================\nstatic function domain($url)\n{\n $slds = \"\";\n $url = strtolower($url);\n\n $address = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';\n if(!$subtlds = @kohana::cache('subtlds', null, 60)) \n {\n $content = file($address);\n foreach($content as $num => $line)\n {\n $line = trim($line);\n if($line == '') continue;\n if(@substr($line[0], 0, 2) == '/') continue;\n $line = @preg_replace(\"/[^a-zA-Z0-9\\.]/\", '', $line);\n if($line == '') continue; //$line = '.'.$line;\n if(@$line[0] == '.') $line = substr($line, 1);\n if(!strstr($line, '.')) continue;\n $subtlds[] = $line;\n //echo \"{$num}: '{$line}'\"; echo \"<br>\";\n }\n $subtlds = array_merge(Array(\n 'co.uk', 'me.uk', 'net.uk', 'org.uk', 'sch.uk', 'ac.uk', \n 'gov.uk', 'nhs.uk', 'police.uk', 'mod.uk', 'asn.au', 'com.au',\n 'net.au', 'id.au', 'org.au', 'edu.au', 'gov.au', 'csiro.au',\n ),$subtlds);\n\n $subtlds = array_unique($subtlds);\n //echo var_dump($subtlds);\n @kohana::cache('subtlds', $subtlds);\n }\n\n\n preg_match('/^(http:[\\/]{2,})?([^\\/]+)/i', $url, $matches);\n //preg_match(\"/^(http:\\/\\/|https:\\/\\/|)[a-zA-Z-]([^\\/]+)/i\", $url, $matches);\n $host = @$matches[2];\n //echo var_dump($matches);\n\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n foreach($subtlds as $sub) \n {\n if (preg_match(\"/{$sub}$/\", $host, $xyz))\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n }\n\n return @$matches[0];\n}\n" }, { "answer_id": 7573307, "author": "Shaun", "author_id": 967608, "author_profile": "https://Stackoverflow.com/users/967608", "pm_score": 4, "selected": false, "text": "function domain($url)\n{\n global $subtlds;\n $slds = \"\";\n $url = strtolower($url);\n\n $host = parse_url('http://'.$url,PHP_URL_HOST);\n\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n foreach($subtlds as $sub){\n if (preg_match('/\\.'.preg_quote($sub).'$/', $host, $xyz)){\n preg_match(\"/[^\\.\\/]+\\.[^\\.\\/]+\\.[^\\.\\/]+$/\", $host, $matches);\n }\n }\n\n return @$matches[0];\n}\n\nfunction get_tlds() {\n $address = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';\n $content = file($address);\n foreach ($content as $num => $line) {\n $line = trim($line);\n if($line == '') continue;\n if(@substr($line[0], 0, 2) == '/') continue;\n $line = @preg_replace(\"/[^a-zA-Z0-9\\.]/\", '', $line);\n if($line == '') continue; //$line = '.'.$line;\n if(@$line[0] == '.') $line = substr($line, 1);\n if(!strstr($line, '.')) continue;\n $subtlds[] = $line;\n //echo \"{$num}: '{$line}'\"; echo \"<br>\";\n }\n\n $subtlds = array_merge(array(\n 'co.uk', 'me.uk', 'net.uk', 'org.uk', 'sch.uk', 'ac.uk', \n 'gov.uk', 'nhs.uk', 'police.uk', 'mod.uk', 'asn.au', 'com.au',\n 'net.au', 'id.au', 'org.au', 'edu.au', 'gov.au', 'csiro.au'\n ), $subtlds);\n\n $subtlds = array_unique($subtlds);\n\n return $subtlds; \n}\n $subtlds = get_tlds();\necho domain('www.example.com') //outputs: example.com\necho domain('www.example.uk.com') //outputs: example.uk.com\necho domain('www.example.fr') //outputs: example.fr\n" }, { "answer_id": 13617167, "author": "Will", "author_id": 514860, "author_profile": "https://Stackoverflow.com/users/514860", "pm_score": 1, "selected": false, "text": "$url = str_replace('http://', '', strtolower( $s->website));\nif (strpos($url, '/')) $url = strstr($url, '/', true);\n" }, { "answer_id": 22996720, "author": "T. Brian Jones", "author_id": 456578, "author_profile": "https://Stackoverflow.com/users/456578", "pm_score": 0, "selected": false, "text": "$host = parse_url( $Row->url, PHP_URL_HOST );\n$parts = explode( '.', $host );\n$parts = array_reverse( $parts );\n$domain = $parts[1].'.'.$parts[0];\n http://www2.website.com:8080/some/file/structure?some=parameters website.com" }, { "answer_id": 24870112, "author": "Oleg Matei", "author_id": 2862657, "author_profile": "https://Stackoverflow.com/users/2862657", "pm_score": 2, "selected": false, "text": "$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$host = parse_url($url, PHP_URL_HOST);\nprint $host; // prints 'google.com'\n" }, { "answer_id": 25348605, "author": "NotFound Life", "author_id": 3234197, "author_profile": "https://Stackoverflow.com/users/3234197", "pm_score": 1, "selected": false, "text": "function getHost($Address) { \n $parseUrl = parse_url(trim($Address));\n $host = trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); \n\n $parts = explode( '.', $host );\n $num_parts = count($parts);\n\n if ($parts[0] == \"www\") {\n for ($i=1; $i < $num_parts; $i++) { \n $h .= $parts[$i] . '.';\n }\n }else {\n for ($i=0; $i < $num_parts; $i++) { \n $h .= $parts[$i] . '.';\n }\n }\n return substr($h,0,-1);\n}\n" }, { "answer_id": 26532119, "author": "Michael", "author_id": 555343, "author_profile": "https://Stackoverflow.com/users/555343", "pm_score": 2, "selected": false, "text": "$domain = parse_url($url, PHP_URL_HOST);\necho implode('.', array_slice(explode('.', $domain), -2, 2))\n" }, { "answer_id": 27129446, "author": "nikmauro", "author_id": 2078274, "author_profile": "https://Stackoverflow.com/users/2078274", "pm_score": 4, "selected": false, "text": "function get_domain($url = SITE_URL)\n{\n preg_match(\"/[a-z0-9\\-]{1,63}\\.[a-z\\.]{2,6}$/\", parse_url($url, PHP_URL_HOST), $_domain_tld);\n return $_domain_tld[0];\n}\n\nget_domain('http://www.cdl.gr'); //cdl.gr\nget_domain('http://cdl.gr'); //cdl.gr\nget_domain('http://www2.cdl.gr'); //cdl.gr\n" }, { "answer_id": 27675712, "author": "Md. Maruf Hossain", "author_id": 1232912, "author_profile": "https://Stackoverflow.com/users/1232912", "pm_score": -1, "selected": false, "text": "<?php\n echo $_SERVER['SERVER_NAME'];\n?>\n" }, { "answer_id": 37791210, "author": "Michael Giovanni Pumo", "author_id": 695749, "author_profile": "https://Stackoverflow.com/users/695749", "pm_score": 0, "selected": false, "text": "function get_url_hostname($url) {\n\n $parse = parse_url($url);\n return str_ireplace('www.', '', $parse['host']);\n\n}\n\nget_url_hostname('http://www.google.com/example/path/file.html'); // google.com\n" }, { "answer_id": 37987242, "author": "Oleksandr Fediashov", "author_id": 6488546, "author_profile": "https://Stackoverflow.com/users/6488546", "pm_score": 3, "selected": false, "text": "http://google.com/dhasjkdas/sadsdds/sdda/sdads.html $extract = new LayerShifter\\TLDExtract\\Extract();\n\n# For 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'\n\n$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n\nparse_url($url, PHP_URL_HOST); // will return google.com\n\n$result = $extract->parse($url);\n$result->getFullHost(); // will return 'google.com'\n$result->getRegistrableDomain(); // will return 'google.com'\n$result->getSuffix(); // will return 'com'\n\n# For 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html'\n\n$url = 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n\nparse_url($url, PHP_URL_HOST); // will return 'search.google.com'\n\n$result = $extract->parse($url);\n$result->getFullHost(); // will return 'search.google.com'\n$result->getRegistrableDomain(); // will return 'google.com'\n" }, { "answer_id": 39401781, "author": "Andy Jones", "author_id": 1422512, "author_profile": "https://Stackoverflow.com/users/1422512", "pm_score": 2, "selected": false, "text": "$url = \"www.google.co.uk\";\n$host = parse_url($url, PHP_URL_HOST);\n// $host == \"www.google.co.uk\"\n www.google.co.uk google.co.uk $domain = get_private_domain(\"www.google.co.uk\");\n // find some way to parse the above list of public suffix\n// then add them to a PHP array\n$suffix = [... all valid public suffix ...];\n\nfunction get_public_suffix($host) {\n $parts = split(\"\\.\", $host);\n while (count($parts) > 0) {\n if (is_public_suffix(join(\".\", $parts)))\n return join(\".\", $parts);\n\n array_shift($parts);\n }\n\n return false;\n}\n\nfunction is_public_suffix($host) {\n global $suffix;\n return isset($suffix[$host]);\n}\n\nfunction get_private_domain($host) {\n $public = get_public_suffix($host);\n $public_parts = split(\"\\.\", $public);\n $all_parts = split(\"\\.\", $host);\n\n $private = [];\n\n for ($x = 0; $x < count($public_parts); ++$x) \n $private[] = array_pop($all_parts);\n\n if (count($all_parts) > 0)\n $private[] = array_pop($all_parts);\n\n return join(\".\", array_reverse($private));\n}\n" }, { "answer_id": 46145181, "author": "fatih", "author_id": 1112246, "author_profile": "https://Stackoverflow.com/users/1112246", "pm_score": 2, "selected": false, "text": "function getHost($url) { \n $parseUrl = parse_url(trim($url)); \n if(isset($parseUrl['host']))\n {\n $host = $parseUrl['host'];\n }\n else\n {\n $path = explode('/', $parseUrl['path']);\n $host = $path[0];\n }\n return trim($host); \n} \n\necho getHost(\"http://example.com/anything.html\"); // example.com\necho getHost(\"http://www.example.net/directory/post.php\"); // www.example.net\necho getHost(\"https://example.co.uk\"); // example.co.uk\necho getHost(\"www.example.net\"); // example.net\necho getHost(\"subdomain.example.net/anything\"); // subdomain.example.net\necho getHost(\"example.net\"); // example.net\n" }, { "answer_id": 53990049, "author": "Kristoffer Bohmann", "author_id": 169224, "author_profile": "https://Stackoverflow.com/users/169224", "pm_score": 3, "selected": false, "text": "$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html';\n$parse = parse_url($url);\necho $parse['host']; // prints 'www.google.com'\n\necho parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);\n// Output: subdomain.example.com\n\necho parse_url('https://subdomain.example.co.uk/foo/bar', PHP_URL_HOST);\n// Output: subdomain.example.co.uk\n function getDomain($url) {\n $host = parse_url($url, PHP_URL_HOST);\n\n if(filter_var($host,FILTER_VALIDATE_IP)) {\n // IP address returned as domain\n return $host; //* or replace with null if you don't want an IP back\n }\n\n $domain_array = explode(\".\", str_replace('www.', '', $host));\n $count = count($domain_array);\n if( $count>=3 && strlen($domain_array[$count-2])==2 ) {\n // SLD (example.co.uk)\n return implode('.', array_splice($domain_array, $count-3,3));\n } else if( $count>=2 ) {\n // TLD (example.com)\n return implode('.', array_splice($domain_array, $count-2,2));\n }\n}\n\n// Your domains\n echo getDomain('http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com\n echo getDomain('http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com\n echo getDomain('http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'); // google.co.uk\n\n// TLD\n echo getDomain('https://shop.example.com'); // example.com\n echo getDomain('https://foo.bar.example.com'); // example.com\n echo getDomain('https://www.example.com'); // example.com\n echo getDomain('https://example.com'); // example.com\n\n// SLD\n echo getDomain('https://more.news.bbc.co.uk'); // bbc.co.uk\n echo getDomain('https://www.bbc.co.uk'); // bbc.co.uk\n echo getDomain('https://bbc.co.uk'); // bbc.co.uk\n\n// IP\n echo getDomain('https://1.2.3.45'); // 1.2.3.45\n" }, { "answer_id": 60099587, "author": "rk3263025", "author_id": 3263025, "author_profile": "https://Stackoverflow.com/users/3263025", "pm_score": 2, "selected": false, "text": "function getTrimmedUrl($link)\n{\n $str = str_replace([\"www.\",\"https://\",\"http://\"],[''],$link);\n $link = explode(\"/\",$str);\n return strtolower($link[0]); \n}\n" }, { "answer_id": 72008830, "author": "Rawburner", "author_id": 5884988, "author_profile": "https://Stackoverflow.com/users/5884988", "pm_score": 1, "selected": false, "text": "public function getTestCases(): array\n{\n return [\n //input expected\n ['http://google.com/dhasjkdas', 'google.com'],\n ['https://google.com/dhasjkdas', 'google.com'],\n ['https://www.google.com/dhasjkdas', 'google.com'],\n ['http://www.google.com/dhasjkdas', 'google.com'],\n ['www.google.com/dhasjkdas', 'google.com'],\n ['google.com/dhasjkdas', 'google.com'],\n ];\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
276,531
<p>If I have the LINQ objects:</p> <pre><code>public class SampleDataContext : DataContext { public Table&lt;Customer&gt; Customers { get { return this.GetTable&lt;Customer&gt;(); } } public SampleDataContext( string connectionString ) : base( connectionString ) { } } [Table( Name="dbo.tblCustomers" )] public class Customer { private Guid? customerID; [Column( Storage="customerID", DbType="uniqueidentifier NOT NULL", IsPrimaryKey=true )] public Guid? CustomerID { get { return this.customerID; } set { this.customerID = value; } } private string customerName; [Column( Storage = "customerName", DbType = "nvarchar(255) NOT NULL" )] public string CustomerName { get { return this.customerName; } set { this.customerName = value; } } } </code></pre> <p>and somewhere else in application:</p> <pre><code>public static void DoSomethingWithCustomer( Customer customer ) { // some operations // now, I want save changes to the database } </code></pre> <p>how can I get instance of DataContext which tracks changes of the "customer" object?</p> <p><strong>Edit: Why I don't want pass the DataContext into method.</strong></p> <p>1) Passing always 2 objects instead of 1 is "ugly" pattern for whole application.</p> <ul> <li>Methods will need next parameter for every business object.</li> <li>Collection will needs changed from "List" to "List>".</li> </ul> <p>Both points will more hard to maintain - developer must every-time sets the correct instance of DataContext (easy to create a bug), despite the DataContext know that the concrete object is(or not) attached to another DataContext.</p> <p>2) I want (current version of application use it) process "any" business logic on collection of objects which came from different "places" ( floating windows by drag &amp; drop for example ).</p> <p>Currentyl we use custom typed DataSets, so informations about changes are in the data rows (DataRow = business object) and wasn't problem to get it, or create a clone and then save it into database.</p>
[ { "answer_id": 986109, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 4, "selected": true, "text": "Private Const StandardChangeTrackerName As String = \"System.Data.Linq.ChangeTracker+StandardChangeTracker\"\n\nPrivate _context As DataClasses1DataContext\nPublic Property Context() As DataClasses1DataContext\n Get\n Dim hasContext As Boolean = False\n Dim myType As Type = Me.GetType()\n Dim propertyChangingField As FieldInfo = myType.GetField(\"PropertyChangingEvent\", BindingFlags.NonPublic Or BindingFlags.Instance)\n Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me)\n Dim delegateType As Type = Nothing\n\n For Each thisDelegate In propertyChangingDelegate.GetInvocationList()\n delegateType = thisDelegate.Target.GetType()\n If delegateType.FullName.Equals(StandardChangeTrackerName) Then\n propertyChangingDelegate = thisDelegate\n hasContext = True\n Exit For\n End If\n Next\n\n If hasContext Then\n Dim targetField = propertyChangingDelegate.Target\n Dim servicesField As FieldInfo = targetField.GetType().GetField(\"services\", BindingFlags.NonPublic Or BindingFlags.Instance)\n If servicesField IsNot Nothing Then\n\n Dim servicesObject = servicesField.GetValue(targetField)\n\n Dim contextField As FieldInfo = servicesObject.GetType.GetField(\"context\", BindingFlags.NonPublic Or BindingFlags.Instance)\n\n _context = contextField.GetValue(servicesObject)\n\n End If\n End If\n \n Return _context\n End Get\n Set(ByVal value As DataClasses1DataContext)\n\n _context = value\n\n End Set\n\nEnd Property\n public DataContext GetMyDataContext()\n{\n // Find the StandardChangeTracker listening to property changes on this object.\n // If no StandardChangeTracker is listening, then this object is probably not\n // attached to a data context.\n var eventField = this.GetType().GetField(\"PropertyChangingEvent\", BindingFlags.NonPublic | BindingFlags.Instance);\n var eventDelegate = eventField.GetValue(this) as Delegate;\n if (eventDelegate == null)\n return null;\n eventDelegate = eventDelegate.GetInvocationList().FirstOrDefault(\n del => del.Target.GetType().FullName == \"System.Data.Linq.ChangeTracker+StandardChangeTracker\");\n if (eventDelegate == null)\n return null;\n\n // Dig through the objects to get the underlying DataContext.\n // If the following fails, then there was most likely an internal change\n // to the LINQ-to-SQL framework classes.\n var targetField = eventDelegate.Target;\n var servicesField = targetField.GetType().GetField(\"services\", BindingFlags.NonPublic | BindingFlags.Instance);\n var servicesObject = servicesField.GetValue(targetField);\n var contextField = servicesObject.GetType().GetField(\"context\", BindingFlags.NonPublic | BindingFlags.Instance);\n return (DataContext)contextField.GetValue(servicesObject);\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20382/" ]
276,546
<p>Let's say you have a text file like this one: <a href="http://www.gutenberg.org/files/17921/17921-8.txt" rel="noreferrer">http://www.gutenberg.org/files/17921/17921-8.txt</a></p> <p>Does anyone has a good algorithm, or open-source code, to extract words from a text file? How to get all the words, while avoiding special characters, and keeping things like "it's", etc...</p> <p>I'm working in Java. Thanks</p>
[ { "answer_id": 276559, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "create words, a list of words, by splitting the input by whitespace\nfor every word, strip out whitespace and punctuation on the left and the right\n words = input.split()\nwords = [word.strip(PUNCTUATION) for word in words]\n PUNCTUATION = \",. \\n\\t\\\\\\\"'][#*:\"\n >>> print words[:100]\n['Project', \"Gutenberg's\", 'Manual', 'of', 'Surgery', 'by', 'Alexis', \n'Thomson', 'and', 'Alexander', 'Miles', 'This', 'eBook', 'is', 'for', \n'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no', 'cost', 'and', \n'with', 'almost', 'no', 'restrictions', 'whatsoever', 'You', 'may', \n'copy', 'it', 'give', 'it', 'away', 'or', 're-use', 'it', 'under', \n... etc etc.\n" }, { "answer_id": 276569, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "String input = \"Input text, with words, punctuation, etc. Well, it's rather short.\";\nPattern p = Pattern.compile(\"[\\\\w']+\");\nMatcher m = p.matcher(input);\n\nwhile ( m.find() ) {\n System.out.println(input.substring(m.start(), m.end()));\n}\n [\\w']+" }, { "answer_id": 11898071, "author": "Rafael Frost", "author_id": 1344860, "author_profile": "https://Stackoverflow.com/users/1344860", "pm_score": 2, "selected": false, "text": "private ArrayList<String> get_Words(String SInput){\n\n StringBuilder stringBuffer = new StringBuilder(SInput);\n ArrayList<String> all_Words_List = new ArrayList<String>();\n\n String SWord = \"\";\n for(int i=0; i<stringBuffer.length(); i++){\n Character charAt = stringBuffer.charAt(i);\n if(Character.isAlphabetic(charAt) || Character.isDigit(charAt)){\n SWord = SWord + charAt;\n }\n else{\n if(!SWord.isEmpty()) all_Words_List.add(new String(SWord));\n SWord = \"\";\n }\n\n }\n\n return all_Words_List;\n\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25645/" ]
276,555
<p>I'm looking to implement something in Java along the lines of:</p> <pre><code>class Foo{ private int lorem; // private int ipsum; public setAttribute(String attr, int val){ //sets attribute based on name } public static void main(String [] args){ Foo f = new Foo(); f.setAttribute("lorem",1); f.setAttribute("ipsum",2); } public Foo(){} } </code></pre> <p>...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?</p>
[ { "answer_id": 276576, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "setAttribute public void setIntField(String fieldName, int value)\n throws NoSuchFieldException, IllegalAccessException {\n Field field = getClass().getDeclaredField(fieldName);\n field.setInt(this, value);\n}\n" }, { "answer_id": 276653, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": -1, "selected": false, "text": "import java.lang.reflect.Field;\nimport java.util.HashMap;\n\nclass Foo {\n private HashMap<String, Field> fields = new HashMap<String, Field>();\n\n private void setAttribute(Field field, Object value) {\n field.set(this, value);\n }\n\n public void setAttribute(String fieldName, Object value) {\n if (!fields.containsKey(fieldName)) {\n fields.put(fieldName, value);\n }\n setAttribute(fields.get(fieldName), value);\n }\n}\n" }, { "answer_id": 30310215, "author": "Brian Risk", "author_id": 2595659, "author_profile": "https://Stackoverflow.com/users/2595659", "pm_score": 2, "selected": false, "text": "String import java.lang.reflect.Field;\n\npublic class FieldTest {\n\n static boolean isValid = false;\n static int count = 5;\n\n public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {\n FieldTest test = new FieldTest();\n test.setProperty(\"count\", \"24\");\n System.out.println(count);\n test.setProperty(\"isValid\", \"true\");\n System.out.println(isValid);\n }\n\n public void setProperty(String fieldName, String value) throws NoSuchFieldException, IllegalAccessException {\n Field field = this.getClass().getDeclaredField(fieldName);\n if (field.getType() == Character.TYPE) {field.set(getClass(), value.charAt(0)); return;}\n if (field.getType() == Short.TYPE) {field.set(getClass(), Short.parseShort(value)); return;}\n if (field.getType() == Integer.TYPE) {field.set(getClass(), Integer.parseInt(value)); return;}\n if (field.getType() == Long.TYPE) {field.set(getClass(), Long.parseLong(value)); return;}\n if (field.getType() == Float.TYPE) {field.set(getClass(), Float.parseFloat(value)); return;}\n if (field.getType() == Double.TYPE) {field.set(getClass(), Double.parseDouble(value)); return;}\n if (field.getType() == Byte.TYPE) {field.set(getClass(), Byte.parseByte(value)); return;}\n if (field.getType() == Boolean.TYPE) {field.set(getClass(), Boolean.parseBoolean(value)); return;}\n field.set(getClass(), value);\n }\n\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/276555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25985/" ]