qid int64 4 22.2M | 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"
}
] | 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"
},
{
"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"
}
] | 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"
},
{
"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 << test << 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"
}
] | 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"
},
{
"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"
},
{
"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><meta></code> tags and other things you can place in the <code><head></code> of your HTML document. What <code><meta></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"
},
{
"answer_id": 275673,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<base>"
},
{
"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>"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 48756531,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "Path.GetRelativePath()"
},
{
"answer_id": 51181785,
"author": "Anton Krouglov",
"author_id": 2746150,
"author_profile": "https://Stackoverflow.com/users/2746150",
"pm_score": 3,
"selected": false,
"text": "Path.GetRelativePath"
},
{
"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"
},
{
"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"
}
] | 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"
}
] | 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 < 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"
},
{
"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), &dwBytesWritten,&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(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&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(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= 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(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&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),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&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), &dwBytesWritten,&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"
}
] | 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"
},
{
"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"
}
] | 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 "Lorem ipsum" 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"
},
{
"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"
},
{
"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}"
},
{
"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});"
},
{
"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"
}
] | 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()"
},
{
"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(\".\")"
},
{
"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)"
},
{
"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(\".\")"
}
] | 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& 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<<"
},
{
"answer_id": 275819,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "return"
}
] | 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"
}
] | 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 < 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"
},
{
"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\""
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 624710,
"author": "ashawley",
"author_id": 73449,
"author_profile": "https://Stackoverflow.com/users/73449",
"pm_score": 6,
"selected": false,
"text": "repeat"
},
{
"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 < 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 < 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 < static_cast<int>(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 <typename T> struct vector : public std::vector<T>
{
typedef std::vector<T> 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& t) : base(n, t) {}
vector(const base& other) : base(other) {}
};
template <typename Key, typename Data> struct map : public std::map<Key, Data>
{
typedef std::map<Key, Data> 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& k) { return base::erase(k); }
int count(const Key& k) { return base::count(k); }
map() : base() {}
map(const key_compare& comp) : base(comp) {}
template <class InputIterator> map(InputIterator f, InputIterator l) : base(f, l) {}
template <class InputIterator> map(InputIterator f, InputIterator l, const key_compare& comp) : base(f, l, comp) {}
map(const base& 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<>::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'"
},
{
"answer_id": 275889,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": false,
"text": "using"
},
{
"answer_id": 275897,
"author": "Lodle",
"author_id": 23339,
"author_profile": "https://Stackoverflow.com/users/23339",
"pm_score": 0,
"selected": false,
"text": "vector.size()"
},
{
"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"
}
] | 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]"
}
] | 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<class T, T initial_t> class Bar {
// something
}
</code></pre>
<p>And then try to use it like this:</p>
<pre><code>Bar<Foo*, NULL> 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>"
}
] | 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"
},
{
"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"
},
{
"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<,>"
}
] | 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"
},
{
"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><div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
</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>"
},
{
"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"
},
{
"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 ;"
},
{
"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"
},
{
"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><add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</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"
}
] | 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 — 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"
},
{
"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"
},
{
"answer_id": 4672402,
"author": "SooDesuNe",
"author_id": 64709,
"author_profile": "https://Stackoverflow.com/users/64709",
"pm_score": 6,
"selected": false,
"text": "pulsate"
},
{
"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\"));"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 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"
},
{
"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()"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 37317254,
"author": "user3322553",
"author_id": 3322553,
"author_profile": "https://Stackoverflow.com/users/3322553",
"pm_score": 3,
"selected": false,
"text": "split()"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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}"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 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"
}
] | 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 >= 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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 276176,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": false,
"text": "for"
},
{
"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"
},
{
"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"
},
{
"answer_id": 65542588,
"author": "nspo",
"author_id": 997151,
"author_profile": "https://Stackoverflow.com/users/997151",
"pm_score": 0,
"selected": false,
"text": "auto"
},
{
"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"
}
] | 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"
},
{
"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 <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>, i love Paris.
</code></pre>
<p>would become </p>
<pre><code> i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.
</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"
},
{
"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>"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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("ps")</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.__version__)\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"
},
{
"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"
},
{
"answer_id": 61910245,
"author": "Pe Dro",
"author_id": 9625777,
"author_profile": "https://Stackoverflow.com/users/9625777",
"pm_score": 4,
"selected": false,
"text": "memory_profiler"
},
{
"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"
},
{
"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"
},
{
"answer_id": 69511430,
"author": "Karol Zlot",
"author_id": 8896457,
"author_profile": "https://Stackoverflow.com/users/8896457",
"pm_score": 5,
"selected": false,
"text": "tqdm"
},
{
"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"
}
] | 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<class Ret, class Iter>
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><%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>
</code></pre>
<p>The form that it generates:</p>
<pre><code><form method="post" action="/store/add_to_cart/3" class="button-to">
</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"
},
{
"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"
}
] | 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"
}
] | 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 &num){
stringstream ss(num);
ss << std::hex;
int n;
ss >> n;
return n;
}
uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
v = StringSplit( mac , ":" );
for( int j = 0 ; j < 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"
},
{
"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 )"
},
{
"answer_id": 328332,
"author": "D.Shawley",
"author_id": 41747,
"author_profile": "https://Stackoverflow.com/users/41747",
"pm_score": 2,
"selected": false,
"text": "sscanf()"
}
] | 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->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"
},
{
"answer_id": 9618664,
"author": "kralyk",
"author_id": 786102,
"author_profile": "https://Stackoverflow.com/users/786102",
"pm_score": 5,
"selected": false,
"text": "std::set_terminate()"
},
{
"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"
}
] | 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"
}
] | 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"
}
] | 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"
}
] | 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& 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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 6424851,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 4,
"selected": false,
"text": "private:"
}
] | 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><%@ Page Language="vb" AutoEventWireup="false" Codebehind="Dangerous.aspx.vb" Inherits="Dynalabs.Dangerous" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body MS_POSITIONING="FlowLayout">
<form id="Form1" method="post" runat="server">
<input type="hidden" id="__VSTATE" runat="server" value="Onw=" />
<asp:Button ID="btnSubmit" Runat="server" Text="Submit" />
</form>
</body>
</html>
</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"
},
{
"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"
},
{
"answer_id": 22564822,
"author": "Johnie Karr",
"author_id": 403404,
"author_profile": "https://Stackoverflow.com/users/403404",
"pm_score": 1,
"selected": false,
"text": "tabstop"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 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
>> a=[];
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 5.426852 seconds.
>> 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 < handle
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> 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"
},
{
"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"
},
{
"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"
}
] | 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><div class="details"></div>
</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"
},
{
"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"
}
] | 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><form name="customize">
Only show results within
<select name="distance" id="slct_distance">
<option>25</option>
<option>50</option>
<option>100</option>
<option value="10000" selected="selected">Any</option>
</select> miles of zip code
<input type="text" class="text" name="zip_code" id="txt_zip_code" />
<span id="customize_validation_msg"></span>
</form>
</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"
},
{
"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"
},
{
"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"
}
] | 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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 48409739,
"author": "Nae",
"author_id": 7032856,
"author_profile": "https://Stackoverflow.com/users/7032856",
"pm_score": 1,
"selected": false,
"text": "playsound"
}
] | 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"
},
{
"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"
}
] | 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"
},
{
"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()"
},
{
"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"
}
] | 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"
},
{
"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"
},
{
"answer_id": 276399,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "ZipArchive"
},
{
"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"
},
{
"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"
}
] | 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><div id="footer">
<ul>
<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>
</ul>
</div>
</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>"
},
{
"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"
},
{
"answer_id": 30617166,
"author": "JeremyTM",
"author_id": 3122800,
"author_profile": "https://Stackoverflow.com/users/3122800",
"pm_score": 1,
"selected": false,
"text": "<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"
},
{
"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("&lt;", "<") %}
{{embed2}}<br />
{% 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("&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(\"<\", \"<\"))\n"
},
{
"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]"
},
{
"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(\"<\", \"<\")) #this is line 35\nreturn render_to_response(\"scanvideos.html\", {\"embed_list\":embed_list})\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"
},
{
"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"
},
{
"answer_id": 67877994,
"author": "Antonio Bakula",
"author_id": 351383,
"author_profile": "https://Stackoverflow.com/users/351383",
"pm_score": 1,
"selected": false,
"text": "runAllManagedModulesForAllRequests"
}
] | 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"
}
] | 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\" "
}
] | 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"
},
{
"answer_id": 4983084,
"author": "Zebs",
"author_id": 382489,
"author_profile": "https://Stackoverflow.com/users/382489",
"pm_score": 6,
"selected": false,
"text": "UIKeyboardTypeDecimalPad"
},
{
"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<string, Neighborhoods> 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<string, Neighborhoods> All_Families = new Dictionary<string, Neighborhoods>();
string currentphase = null;
foreach (string s in inp)
{
switch (s)
{
case "!<Start Family>!": temp = new Neighborhoods();
break;
case "<Family Name>": currentphase = "<Family Name>";
break;
case "<End Family Name>": currentphase = null;
break;
case "<Neighbour Enabled>True": temp.Neighbourhood_Enabled1 = true;
currentphase = "<Neighbour Enabled>True";
break;
case "<Neighbour Enabled>False": temp.Neighbourhood_Enabled1 = false;
temp.Neighbourhood_Input1 = null;
break;
case "<University Enabled>True": temp.University_Enabled1 = true;
currentphase = "<University Enabled>True";
break;
case "<University Enabled>False": temp.University_Enabled1 = false;
temp.University_Input1 = null;
currentphase = null;
break;
case "<Downtown Enabled>True": temp.Downtown_Enabled1 = true;
currentphase = "<Downtown Enabled>True";
break;
case "<Downtown Enabled>False": temp.Downtown_Enabled1 = false;
temp.Downtown_Input1 = null;
currentphase = null;
break;
case "!<End Family>!": All_Families.Add(temp.Name, temp);
break;
default: if (currentphase == "<Family Name>") temp.Name = s;
if (currentphase == "<Neighbour Enabled>True") temp.Neighbourhood_Input1 = s;
if (currentphase == "<University Enabled>True") temp.University_Input1 = s;
if (currentphase == "<Downtown Enabled>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>!<Start Family>!
Family Name>
qwe
<End Family Name>
<Neighbour Enabled>True
qwe
<University Enabled>True
we
<Downtown Enabled>True
qwe
!<End Family>!
!<Start Family>!
<Family Name>
123
<End Family Name>
<Neighbour Enabled>True
123
<University Enabled>True
123
<Downtown Enabled>True
123
!<End Family>!
</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"
},
{
"answer_id": 276455,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "Neighborhoods"
}
] | 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"
},
{
"answer_id": 276573,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "foo.c"
},
{
"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"
}
] | 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"
}
] | 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><img src="<?php echo url::base(); ?>img/banner.jpg" /></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"
},
{
"answer_id": 277860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<base>"
}
] | 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)) &&
(composedDate.getDate() == matches[2]) &&
(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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 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"
}
] | 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"
}
] | 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&1)*b,a!=1;a>>=1,b<<=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>>=1</code> and <code>b<<=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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 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()"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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<Customer> Customers { get { return this.GetTable<Customer>(); } }
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 & 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"
}
] | 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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] | 2008/11/09 | [
"https://Stackoverflow.com/questions/276555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25985/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.