qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
196,390
<p>I heard somewhere that you can drop down to C++ directly inside C# code. How is this done? Or did I hear wrong?</p> <p>Note: I do not mean C++ / CLI.</p>
[ { "answer_id": 196397, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "unsafe" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
196,407
<p>From within a DLL that's being called by a C#.NET web app, how do you find the base url of the web app?</p>
[ { "answer_id": 196464, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 5, "selected": true, "text": "HttpContext.Current.Request.Url\n HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)\n" }, { "answer_id": 196473, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 0, "selected": false, "text": "string _baseUrl = String.Empty;\nHttpContext httpContext = HttpContext.Current;\nif (httpContext != null)\n{\n _baseURL = \"http://\" + HttpContext.Current.Request.Url.Host;\n if (!HttpContext.Current.Request.Url.IsDefaultPort)\n {\n _baseURL += \":\" + HttpContext.Current.Request.Url.Port;\n }\n}\n" }, { "answer_id": 303631, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 1, "selected": false, "text": "HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
196,415
<p>For a current project I am working I need to return an aggregate report based on date ranges. </p> <p>I have 3 types of reports, yearly, monthly and daily.</p> <p>To assist in returning this report I need a function that will return all of the sub-ranges of datetimes, within a big range.</p> <p>So for example if I as for all the daily ranges between '2006-01-01 11:10:00' and '2006-01-05 08:00:00' I would expect the following results.</p> <pre><code>select * from dbo.fnGetDateRanges('d', '2006-01-01 11:10:00', '2006-01-05 08:00:00') 2006-01-01 11:10:00.000, 2006-01-02 00:00:00.000 2006-01-02 00:00:00.000, 2006-01-03 00:00:00.000 2006-01-03 00:00:00.000, 2006-01-04 00:00:00.000 2006-01-04 00:00:00.000, 2006-01-05 00:00:00.000 2006-01-05 00:00:00.000, 2006-01-05 08:00:00.000 </code></pre> <p>For the yearly range of '2006-01-01 11:10:00' to '2009-05-05 08:00:00', I would expect.</p> <pre><code>select * from dbo.fnGetDateRanges('y', '2006-01-01 11:10:00', '2009-05-05 08:00:00') 2006-01-01 11:10:00.000, 2007-01-01 00:00:00.000 2007-01-01 00:00:00.000, 2008-01-01 00:00:00.000 2008-01-01 00:00:00.000, 2009-01-01 00:00:00.000 2009-01-01 00:00:00.000, 2009-05-05 08:00:00.000 </code></pre> <p>How would I implement this function? </p>
[ { "answer_id": 196416, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": true, "text": "create function dbo.fnGetDateRanges\n(\n @type char(1),\n @start datetime,\n @finish datetime\n)\nreturns @ranges table(start datetime, finish datetime)\nas \nbegin\n\n declare @from datetime \n declare @to datetime \n set @from = @start \n\n if @type = 'd'\n begin \n set @to = dateadd(day, 1,\n convert\n ( datetime,\n cast(DatePart(d,@start) as varchar) + '/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end\n\n if @type = 'm'\n begin\n set @to = dateadd(month, 1, \n convert\n ( \n datetime,\n '1/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end \n\n if @type = 'y'\n begin\n set @to = dateadd(year, 1, \n convert\n ( \n datetime,\n '1/1/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end \n\n while @to < @finish\n begin \n insert @ranges values (@from, @to)\n set @from = @to \n if @type = 'd'\n set @to = dateadd(day, 1, @to)\n if @type = 'm'\n set @to = dateadd(month, 1, @to)\n if @type = 'y'\n set @to = dateadd(year, 1, @to)\n end\n\n insert @ranges values (@from, @finish)\n\n return \nend\n" }, { "answer_id": 198399, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 2, "selected": false, "text": "DECLARE @Start smalldatetime, @End smalldatetime, @Diff int\n\nSELECT @Start = '2006-01-01 11:10:00', @End = '2009-05-05 08:00:00', @diff = DATEDIFF(year,@start,@end)\n\nSELECT\n DATEADD(year,N.Number,@Start)\nFROM\n dbo.Number N\nWHERE\n N.Number <= @diff\n" }, { "answer_id": 198449, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "@myDate > dbo.MyFunc() SELECT TOP 1000000\n IDENTITY(INT,1,1) as N\n INTO dbo.NumbersTable\n FROM Master.dbo.SysColumns \n Master.dbo.SysColumns \n DECLARE @DaysFromStart int\nDECLARE @StartDate datetime\nSET @StartDate = '10/01/2008'\n\nSET @ DaysFromStart = (SELECT (DATEDIFF(dd,@StartDate,GETDATE()) + 1))\n\nCREATE TABLE [dbo].[TableOfDates](\n [fld_date] [datetime] NOT NULL,\n CONSTRAINT [PK_TableOfDates] PRIMARY KEY CLUSTERED \n(\n [fld_date] ASC\n)WITH FILLFACTOR = 99 ON [PRIMARY]\n) ON [PRIMARY]\n\n\nINSERT INTO\n dbo.TableOfDates\nSELECT \n DATEADD(dd,nums.n - @DaysFromStart ,CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)) as FLD_Date\nFROM #NumbersTable nums\n\nSELECT MIN(FLD_Date) FROM dbo.TableOfDates\nSELECT MAX(FLD_Date) FROM dbo.TableOfDates\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
196,418
<p>I know of many utilities that can tell me the bitrate of an MP3 file, but I've never seen one that can tell me whether or not the MP3 file is VBR (variable bit rate - the bit rate fluctuates within the file) or a CBR (constant bit rate - the bit rate stays the same within the file). My guess is that most programs aren't interested in finding this out since it involves analyzing the file somewhat to see if the bitrate changes, which takes away from speed.</p> <p>So, in lieu of finding a utility, I'd like to write one - so how could I programmatically determine whether or not an MP3 file is VBR or CBR? I have about 15,000 files to go through to find this out for, so I need to automate the process.</p>
[ { "answer_id": 196447, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "...\nboolVBitRate = LoadVBRHeader(bytVBitRate);\n...\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
196,424
<p>Should I be using this method of throwing errors:</p> <pre><code>if (isset($this-&gt;dbfields[$var])) { return $this-&gt;dbfields[$var]; } else { throw new FieldNotFoundException($var); } </code></pre> <p>or this style:</p> <pre><code>try { return $this-&gt;dbfields[$var]; } catch (Exception $e) { throw new FieldNotFoundException($var); } </code></pre> <p>...or something else altogether?</p> <p><em>quick explanation of the code:</em> <code>$this-&gt;dbfields</code> is an array. <code>isset()</code> checks if a variable is set, in this case, whether the array element exists.</p>
[ { "answer_id": 196428, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": true, "text": "try catch try except" }, { "answer_id": 196431, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "//First let's do the checks.\nif(!isset($this->dbfields[$var]))\n throw new FieldNotFoundException($var);\n//Now we're in the clear!\nreturn $this->dbfields[$var];\n" }, { "answer_id": 196453, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "Exception" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
196,465
<p>The <a href="http://en.wikipedia.org/wiki/Effect_system" rel="noreferrer">Wikipedia article on <em>Effect system</em></a> is currently just a short stub and I've been wondering for a while as to what is an effect system. </p> <ul> <li>Are there any languages that have an effect system in addition to a type system? </li> <li>What would a possible (hypothetical) notation in a <strong>mainstream</strong> language, that you're familiar, with look like with effects? </li> </ul>
[ { "answer_id": 196748, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": true, "text": "close void close close File open(String name) [+File]; // open creates a new file handle\nvoid close(File f) [-f] ; // close destroys f \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
196,468
<p>I am using the Maven (2) Cobertura plug-in to create reports on code coverage, and I have the following stub I am using in a method:</p> <pre><code>try { System.exit(0); } catch (final SecurityException exception) { exception.printStackTrace(); } System.err.println("The program never exited!"); </code></pre> <p>I know that I need to log the exception, etc, but that's not the point right now...Cobertura is refusing to acknowledge that the line after the stack trace is printed is covered. That is, the line with the '}' before the <code>System.err.println</code> statement is not being shown as covered. Before, the ending curly brace of the method was not being shown as covered, hence the <code>System.err</code> statement. Any idea how I can convince cobertura's maven plugin that, since the <code>System.err.println</code> statement is covered, that ending brace has to have been covered?</p> <p>Oh yeah, and I use a mock security manager to throw the security exception, since that's the easiest way I have found of making the test continue executing after the <code>System.exit</code> call.</p>
[ { "answer_id": 16798306, "author": "Bruno D. Rodrigues", "author_id": 661475, "author_profile": "https://Stackoverflow.com/users/661475", "pm_score": 0, "selected": false, "text": "try {\n System.exit(0);\n} catch (final SecurityException exception) {\n exception.printStackTrace();\n} finally {\n // noop\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8026/" ]
196,480
<p>I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME. The ID identifies the submitter of the data - several thousand rows. The DATETIME is not necessarily unique, either. (The primary keys are other fields of the table.)</p> <p>Data for this table is submitted every six months. In December, we receive July-December data from each submitter, and in June we receive July-June data. My task is to write a script that identifies people who have only submitted half their data, or only submitted January-June data in June.</p> <p>...Does anyone have a solution?</p>
[ { "answer_id": 196499, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "select * from (\n select T.submitterId,\n (select count(*) \n from TABLE T1\n where T1.datefield between [july] and [december]\n and T1.submitterId = T.submitterId\n group by T1.submitterId) as JDCount,\n (select count(*)\n from TABLE T2\n where T2.datefield between [december] and [june]\n and T2.submitterId = T.submitterId\n group by T2.submitterId) as DJCount\n from TABLE T) X\nwhere X.JDCount <= 0 OR X.DJCount <= 0\n" }, { "answer_id": 203555, "author": "Margaret", "author_id": 27290, "author_profile": "https://Stackoverflow.com/users/27290", "pm_score": 1, "selected": false, "text": "IF @FullYear = 1 \n BEGIN\n DECLARE @FirstDate AS DATETIME\n DECLARE @LastDayFirstYear AS DATETIME\n DECLARE @SecondYear AS INT\n DECLARE @NewYearsDay AS DATETIME\n DECLARE @LastDate AS DATETIME\n\n SELECT @FirstDate = MIN(dscdate), @LastDate = MAX(dscdate)\n FROM TheTable\n \n SELECT @SecondYear = DATEPART(yyyy, @FirstDate) + 1\n SELECT @NewYearsDay = CAST(CAST(@SecondYear AS VARCHAR) \n + '-01-01' AS DATETIME)\n\n INSERT INTO @AuditResults\n SELECT DISTINCT\n 'Submitter missing Jan-Jun data', t.id\n FROM TheTable t\n WHERE \n EXISTS ( \n SELECT 1\n FROM TheTable t1\n WHERE t.id = t1.id \n AND t1.date >= @FirstDate\n AND t1.date < @NewYearsDay )\n AND NOT EXISTS ( \n SELECT 1\n FROM TheTable t2\n WHERE t2.date >= @NewYearsDay\n AND t2.date <= @LastDate\n AND t2.id = t.id\n GROUP BY t2.id )\n GROUP BY t.id\n END\n" }, { "answer_id": 555538, "author": "Margaret", "author_id": 27290, "author_profile": "https://Stackoverflow.com/users/27290", "pm_score": 1, "selected": true, "text": "SELECT @avgmonths = AVG(x.[count])\nFROM ( SELECT CAST(COUNT(DISTINCT DATEPART(month,\n DATEADD(month,\n DATEDIFF(month, 0, dscdate),\n 0))) AS FLOAT) AS [count]\n FROM HospDscDate\n GROUP BY hosp\n ) x\n\nIF @avgmonths > 7 \n SET @months = 12\nELSE \n SET @months = 6\n\n\nSELECT 'Submitter missing data for some months' AS [WarningType],\n t.id\nFROM TheTable t\nWHERE EXISTS ( SELECT 1\n FROM TheTable t1\n WHERE t.id = t1.id\n HAVING COUNT(DISTINCT DATEPART(month,\n DATEADD(month, DATEDIFF(month, 0, t1.Date), 0))) < @months )\nGROUP BY t.id\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27290/" ]
196,488
<p>Hey all I'm hoping someone has enough experience with Cake PHP to make this work. </p> <p>I'm working on something that at the moment could affectionately be called a twitter clone. Essentially I have a set up like this. </p> <p>Users have many friends. This is a many to many relationship to the user table. It is stored in a link tabled called friends_users with columns user_id, friend_id. Users is a table with column user_id. </p> <p>Then I have a table called tips which associates to a user. A user can have many tips. </p> <p>I want to figure out a way to do a find on the Tip model that returns all tips owned by the userid i pass in as well as any tips owned by any friends of that user. </p> <p>This SQL query works perfectly - </p> <pre><code>SELECT * FROM `tips` JOIN users ON users.id = tips.user_id JOIN friends_users ON tips.user_id = friends_users.friend_id WHERE (friends_users.user_id =2 or tips.user_id=2) LIMIT 0 , 30 </code></pre> <p>That returns user#2s Tips as well as the tips of anyone who is a friend of User 2. </p> <p>Now how can I do the same thing using <code>$this-&gt;Tip-&gt;findxxxxx(user_id)</code></p> <p>I know I can use <code>Tip-&gt;query</code> if need be but I'm trying to learn the hard way. </p>
[ { "answer_id": 197040, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 3, "selected": true, "text": "function findTipsByUserAndFriends($userId) {\n //FriendsUser is automagically created by CakePHP \"with\" association\n $conditions = array('FriendsUser.user_id'=>$userId);\n $fields = 'FriendsUser.friend_id';\n //get a list friend ids for the given user\n $friendIds = $this->Tip->User->FriendsUser->find('list', compact('conditions', 'fields'));\n //get list of all userIds for whom you want the tips\n $userIds = array($userId) + $friendIds;\n $conditions = array('Tip.user_id'=>$userIds);\n $tips = $this->Tip->find('all', compact('conditions'));\n return $tips;\n}\n" }, { "answer_id": 6705344, "author": "rees", "author_id": 846203, "author_profile": "https://Stackoverflow.com/users/846203", "pm_score": 1, "selected": false, "text": "$aCond = array(\n 'fields' => array(\n 'Discount.*'\n ),\n 'contain' => array(\n 'Event' => array(\n 'conditions' => array('Event.id' => $iEventId)\n )\n )\n );\n$aBulkDiscounts = $this->Discount->find('first', $aCond);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7018/" ]
196,498
<p>I have a text file in the root of my web app <em><a href="http://localhost/foo.txt" rel="noreferrer">http://localhost/foo.txt</a></em> and I'd like to load it into a variable in javascript.. in groovy I would do this:</p> <pre><code>def fileContents = 'http://localhost/foo.txt'.toURL().text; println fileContents; </code></pre> <p>How can I get a similar result in javascript?</p>
[ { "answer_id": 196510, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 8, "selected": true, "text": "var client = new XMLHttpRequest();\nclient.open('GET', '/foo.txt');\nclient.onreadystatechange = function() {\n alert(client.responseText);\n}\nclient.send();\n" }, { "answer_id": 196550, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 7, "selected": false, "text": "jQuery.get('http://localhost/foo.txt', function(data) {\n alert(data);\n});\n" }, { "answer_id": 20724888, "author": "atmelino", "author_id": 1502734, "author_profile": "https://Stackoverflow.com/users/1502734", "pm_score": 3, "selected": false, "text": " client.onreadystatechange = function() {\n function(data) {\n" }, { "answer_id": 34477256, "author": "yvesonline", "author_id": 1278518, "author_profile": "https://Stackoverflow.com/users/1278518", "pm_score": 2, "selected": false, "text": "jQuery.get jQuery.get(\"foo.txt\", undefined, function(data) {\n alert(data);\n}, \"html\").done(function() {\n alert(\"second success\");\n}).fail(function(jqXHR, textStatus) {\n alert(textStatus);\n}).always(function() {\n alert(\"finished\");\n});\n .load $(\"#myelement\").load(\"foo.txt\");\n .load" }, { "answer_id": 39007446, "author": "Erik Uggeldahl", "author_id": 2736686, "author_profile": "https://Stackoverflow.com/users/2736686", "pm_score": 5, "selected": false, "text": "// This becomes the content of your foo.txt file\nlet text = `\nMy test text goes here!\n`; <script src=\"foo.txt\"></script>\n<script>\n console.log(text);\n</script> file://" }, { "answer_id": 49673756, "author": "12Me21", "author_id": 6232794, "author_profile": "https://Stackoverflow.com/users/6232794", "pm_score": 3, "selected": false, "text": "var xhr=new XMLHttpRequest();\nxhr.open(\"GET\",\"https://12Me21.github.io/test.txt\");\nxhr.onload=function(){\n console.log(xhr.responseText);\n}\nxhr.send();\n Fetch fetch(\"https://12Me21.github.io/test.txt\")\n.then( response => response.text() )\n.then( text => console.log(text) )\n" }, { "answer_id": 49680132, "author": "Vic", "author_id": 826290, "author_profile": "https://Stackoverflow.com/users/826290", "pm_score": 6, "selected": false, "text": "fetch('http://localhost/foo.txt')\n .then(response => response.text())\n .then((data) => {\n console.log(data)\n })\n" }, { "answer_id": 61195369, "author": "gman", "author_id": 128511, "author_profile": "https://Stackoverflow.com/users/128511", "pm_score": 4, "selected": false, "text": "const response = await fetch('http://localhost/foo.txt');\nconst data = await response.text();\nconsole.log(data);\n await async async function loadFileAndPrintToConsole(url) {\n try {\n const response = await fetch(url);\n const data = await response.text();\n console.log(data);\n } catch (err) {\n console.error(err);\n }\n}\n\nloadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
196,500
<p>I have a WordPress installation with an <code>.htaccess</code> file that looks like this:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the <code>.htaccess</code> file. </p> <p>How do I change it so that I can view the subfolder?</p>
[ { "answer_id": 196553, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "# BEGIN WordPress\n<IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n RewriteCond %{REQUEST_URI} !^/blog2/.*\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n wp-config.php $table_prefix http://yourdomain.com/blog2/\n wp-config.php" }, { "answer_id": 8042392, "author": "Sterling Hamilton", "author_id": 1034494, "author_profile": "https://Stackoverflow.com/users/1034494", "pm_score": 5, "selected": false, "text": "# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /blog2/\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /blog2/index.php [L]\n</IfModule>\n# END WordPress\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12765/" ]
196,505
<p>Is there a way to use <strong>THE LOOP</strong> in <strong>Wordpress</strong> to load pages instead of posts?</p> <p>I would like to be able to query a set of child pages, and then use <strong>THE LOOP</strong> function calls on it - things like <code>the_permalink()</code> and <code>the_title()</code>.</p> <p>Is there a way to do this? I didn't see anything in <code>query_posts()</code> documentation.</p>
[ { "answer_id": 196742, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 7, "selected": true, "text": "query_posts(array('showposts' => <number_of_pages_to_show>, 'post_parent' => <ID of the parent page>, 'post_type' => 'page'));\n\nwhile (have_posts()) { the_post();\n /* Do whatever you want to do for every page... */\n}\n\nwp_reset_query(); // Restore global post data\n post_parent post_type ./wp-include/query.php" }, { "answer_id": 21748630, "author": "Nathan Dawson", "author_id": 1310929, "author_profile": "https://Stackoverflow.com/users/1310929", "pm_score": 5, "selected": false, "text": "$child_pages = new WP_Query( array(\n 'post_type' => 'page', // set the post type to page\n 'posts_per_page' => 10, // number of posts (pages) to show\n 'post_parent' => <ID of the parent page>, // enter the post ID of the parent page\n 'no_found_rows' => true, // no pagination necessary so improve efficiency of loop\n) );\n\nif ( $child_pages->have_posts() ) : while ( $child_pages->have_posts() ) : $child_pages->the_post();\n // Do whatever you want to do for every page. the_title(), the_permalink(), etc...\nendwhile; endif; \n\nwp_reset_postdata();\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
196,509
<p>I want to delete <strong>all</strong> the previously created indices. I am using <code>Lucene.net</code>.</p> <p>I tried the following:</p> <pre><code>Term term = new Term(); //empty because I want to delete all the indices IndexReader rdr = IndexReader.Open(_directory); rdr.DeleteDocuments(term); rdr.Close(); </code></pre> <p>But I get error. Any idea how to go about it?</p>
[ { "answer_id": 3242491, "author": "Jeremy Cade", "author_id": 99240, "author_profile": "https://Stackoverflow.com/users/99240", "pm_score": 1, "selected": false, "text": "DirectoryInfo directoryInfo = new DirectoryInfo(@\"IndexLocation\");\nParallel.ForEach(directoryInfo.GetFiles(), file => {\n file.Delete();\n });\n" }, { "answer_id": 4449046, "author": "cuh", "author_id": 292352, "author_profile": "https://Stackoverflow.com/users/292352", "pm_score": 1, "selected": false, "text": "public static IndexReader Open(Directory); IndexReader rdr = IndexReader.Open(_directory, true);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
196,512
<p>I'm looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also just use an unsorted container and explicitly sort it after each insert.</p> <p>Usage:</p> <ul> <li>Occasional insert</li> <li>Frequent traversal in order</li> <li>Ideally not working with keys separate from the actual object, using a compare function to sort.</li> <li>Stable sorting for equivalent objects is desired, but not required. </li> <li>Random access is not required.</li> </ul> <p>I realize I can just build myself a balanced tree structure, I was just wondering if the framework already contains such a beast.</p>
[ { "answer_id": 196539, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "System.Collections.ObjectModel.KeyedCollection<TKey, TItem>" }, { "answer_id": 196615, "author": "Perry Pederson", "author_id": 26037, "author_profile": "https://Stackoverflow.com/users/26037", "pm_score": -1, "selected": false, "text": " static void Main(string[] args)\n {\n ListBox sortedList = new ListBox();\n sortedList.Sorted = true;\n\n sortedList.Items.Add(\"foo\");\n sortedList.Items.Add(\"bar\");\n sortedList.Items.Add(true);\n sortedList.Items.Add(432); \n\n foreach (object o in sortedList.Items)\n {\n Console.WriteLine(o);\n }\n\n Console.ReadKey();\n }\n" }, { "answer_id": 1470465, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 2, "selected": false, "text": "Sort(IComparer<>) List<> Comparer<> public class PositionDateComparer : IComparer<VehiclePosition>\n{\n public int Compare(VehiclePosition x, VehiclePosition y)\n {\n if (x.DateTime == DateTime.MinValue)\n {\n if (y.DateTime == DateTime.MinValue)\n {\n // If x is null and y is null, they're\n // equal. \n return 0;\n }\n\n // If x is null and y is not null, y\n // is greater. \n return -1;\n }\n\n // If x is not null...\n //\n if (y.DateTime == DateTime.MinValue)\n // ...and y is null, x is greater.\n {\n return 1;\n }\n\n // ...and y is not null, compare the dates\n //\n if (x.DateTime == y.DateTime)\n {\n // x and y are equal\n return 0;\n }\n\n if (x.DateTime > y.DateTime)\n {\n // x is greater\n return 1;\n }\n\n // y is greater\n return -1;\n }\n}\n vehiclePositionsList.Sort(new PositionDateComparer())" }, { "answer_id": 21623742, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "SortedSet<T>" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701/" ]
196,518
<p>Problem with dynamic controls</p> <p>Hello all,</p> <p>I'm wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough, right? All I have to do is re-create the controls upon each page load, using the same IDs. HOWEVER, here's the catch - in my PreRender event, I'm wanting to clear the controls collection, and then recreate the dynamic controls with new values. The reasons for this are complicated, and it would probably take me about a page or so to explain why I want to do it. So, in the interests of brevity, let's just assume that I absolutely must do this, and that there's no other way.</p> <p>The problem comes in after I re-create the controls in my PreRender event. The re-created controls never bind to the viewstate, and their values do not persist across page loads. I don't understand why this happens. I'm already re-creating the controls in my OnLoad event. When I do this, the newly created controls bind to the ViewState just fine, provided that I use the same IDs every time. However, when I try to do the same thing in the PreRender event, it fails.</p> <p>In any case, here is my example code : </p> <p>namespace TestFramework.WebControls {</p> <pre><code>public class ValueLinkButton : LinkButton { public string Value { get { return (string)ViewState[ID + "vlbValue"]; } set { ViewState[ID + "vlbValue"] = value; } } } public class TestControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); Controls.Clear(); ValueLinkButton tempLink = null; tempLink = new ValueLinkButton(); tempLink.ID = "valueLinkButton"; tempLink.Click += new EventHandler(Value_Click); if (!Page.IsPostBack) { tempLink.Value = "old value"; } Controls.Add(tempLink); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ValueLinkButton tempLink = ((ValueLinkButton)FindControl("valueLinkButton")); //[CASE 1] //ValueLinkButton tempLink = new ValueLinkButton(); [CASE 2] tempLink.ID = "valueLinkButton"; tempLink.Value = "new value"; tempLink.Text = "Click"; Controls.Clear(); Controls.Add(tempLink); } void Value_Click(object sender, EventArgs e) { Page.Response.Write("[" + ((ValueLinkButton)sender).Value + "]"); } } </code></pre> <p>}</p> <p>So, let's examine case 1, where the line next to [CASE 1] is not commented out, but the line next to [CASE 2] is commented out. Here, everything works just fine. When I put this control on a page and load the page, I see a link that says "Click". When I click the link, the page outputs the text "[new value]", and on the next line, we see the familiar "Click" link. Every subesquent time I click on the "Click" link, we see the same thing. So far, so good.</p> <p>But now let's examine case 2, where the line next to [CASE 1] is commented out, but the line next to [CASE 2] is not commented out. Here we run into problems. When we load the page, we see the "Click" link. However, when I click on the link, the page outputs the text "[]" instead of "[new value]". The click event is firing normally. However, the "new value" text that I assigned to the Value attribute of the control does not get persisted. Once again, this is a bit of a mystery to me. How come, when I recreate the control in OnLoad, everything's fine and dandy, but when I recreate the control in PreRender, the value doesn't get persisted?</p> <p>I feel like there simply has to be a way to do this. When I re-create the control in PreRender, is there some way to bind the newly created control to the ViewState?</p> <p>I've struggled with this for days. Any help that you can give me will be appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 196568, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "Page.RegisterRequiresControlState() RequiresControlState()" }, { "answer_id": 196614, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 0, "selected": false, "text": "ValueLinkButton tempLink = new ValueLinkButton();\nControl parent = FindControl(\"valueLinkButton\").Parent;\nparent.Remove(FindControl(\"valueLinkButton\"));\nparent.AddAt(0, tempLink);\n" }, { "answer_id": 196963, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": true, "text": "protected override void OnPreRender(EventArgs e)\n{\n base.OnPreRender(e);\n ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2] \n tempLink.ID = \"valueLinkButton\"; // Not persisted to ViewState\n Controls.Clear();\n Controls.Add(tempLink);\n tempLink.Value = \"new value\"; // Persisted to ViewState\n tempLink.Text = \"Click\"; // Persisted to ViewState\n}\n" }, { "answer_id": 1137559, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "Protected Overrides Sub LoadViewState(ByVal savedState As Object)\n MyBase.LoadViewState(savedState)\n If IsPostBack Then\n CreateMyControls()\n End If\nEnd Sub\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27293/" ]
196,520
<p>What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.</p> <p>So far, the best I've come up with is this:</p> <pre><code>$fullString = "ignore everything except this (text)"; $start = strpos('(', $fullString); $end = strlen($fullString) - strpos(')', $fullString); $shortString = substr($fullString, $start, $end); </code></pre> <p>Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?</p>
[ { "answer_id": 196536, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 8, "selected": true, "text": "$text = 'ignore everything except this (text)';\npreg_match('#\\((.*?)\\)#', $text, $match);\nprint $match[1];\n" }, { "answer_id": 196538, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 4, "selected": false, "text": "substr()'s strpos()'s $haystack $needle $start + 1 strpos() $start $length $start $end substr strpos/substr strpos/substr" }, { "answer_id": 196645, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 4, "selected": false, "text": "if( preg_match( '!\\(([^\\)]+)\\)!', $text, $match ) )\n $text = $match[1];\n" }, { "answer_id": 21425624, "author": "Sachin Murali G", "author_id": 2653123, "author_profile": "https://Stackoverflow.com/users/2653123", "pm_score": 2, "selected": false, "text": " function extract_text($string)\n {\n $text_outside=array();\n $text_inside=array();\n $t=\"\";\n for($i=0;$i<strlen($string);$i++)\n {\n if($string[$i]=='[')\n {\n $text_outside[]=$t;\n $t=\"\";\n $t1=\"\";\n $i++;\n while($string[$i]!=']')\n {\n $t1.=$string[$i];\n $i++;\n }\n $text_inside[] = $t1;\n\n }\n else {\n if($string[$i]!=']')\n $t.=$string[$i];\n else {\n continue;\n }\n\n }\n }\n if($t!=\"\")\n $text_outside[]=$t;\n\n var_dump($text_outside);\n echo \"\\n\\n\";\n var_dump($text_inside);\n }\n array(1) {\n [0]=>\n string(18) \"hello how are you?\"\n}\n\narray(0) {\n}\n array(2) {\n [0]=>\n string(6) \"hello \"\n [1]=>\n string(13) \" how are you?\"\n}\n\n\narray(1) {\n [0]=>\n string(30) \"http://www.google.com/test.mp3\"\n}\n" }, { "answer_id": 43729786, "author": "vijay", "author_id": 3111836, "author_profile": "https://Stackoverflow.com/users/3111836", "pm_score": 2, "selected": false, "text": " public static function getStringBetween($str,$from,$to, $withFromAndTo = false)\n {\n $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));\n if ($withFromAndTo)\n return $from . substr($sub,0, strrpos($sub,$to)) . $to;\n else\n return substr($sub,0, strrpos($sub,$to));\n }\n $inputString = \"ignore everything except this (text)\";\n $outputString = getStringBetween($inputString, '(', ')'));\n echo $outputString; \n //output will be test\n\n $outputString = getStringBetween($inputString, '(', ')', true));\n echo $outputString; \n //output will be (test)\n" }, { "answer_id": 55569026, "author": "Mamed Shahmaliyev", "author_id": 628176, "author_profile": "https://Stackoverflow.com/users/628176", "pm_score": 0, "selected": false, "text": "function getStringsBetween($str, $start='[', $end=']', $with_from_to=true){\n$arr = [];\n$last_pos = 0;\n$last_pos = strpos($str, $start, $last_pos);\nwhile ($last_pos !== false) {\n $t = strpos($str, $end, $last_pos);\n $arr[] = ($with_from_to ? $start : '').substr($str, $last_pos + 1, $t - $last_pos - 1).($with_from_to ? $end : '');\n $last_pos = strpos($str, $start, $last_pos+1);\n}\nreturn $arr; }\n" }, { "answer_id": 56114128, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "\\((.*?)\\) \\(([^\\)]+)\\) Text (abc(xyz 123) (abc(xyz 123) (xyz 123) preg_match preg_match_all \\([^()]*\\)\n \\(([^()]*)\\) // get Group 1 values after a successful call to preg_match_all, see code below\n\\(\\K[^()]*(?=\\)) // this and the one below get the values without parentheses as whole matches \n(?<=\\()[^()]*(?=\\)) // less efficient, not recommended\n * + ( ) \\( [^()]* ( ) ( ) ( ) \\) \\(\\K ( \\K (?<=\\() ( ( (?=\\() ) $fullString = 'ignore everything except this (text) and (that (text here))';\nif (preg_match_all('~\\(([^()]*)\\)~', $fullString, $matches)) {\n print_r($matches[0]); // Get whole match values\n print_r($matches[1]); // Get Group 1 values\n}\n Array ( [0] => (text) [1] => (text here) )\nArray ( [0] => text [1] => text here )\n" }, { "answer_id": 61134103, "author": "rüff0", "author_id": 7092472, "author_profile": "https://Stackoverflow.com/users/7092472", "pm_score": 3, "selected": false, "text": "$string = 'ignore everything except this (text)';\n$string = explode(')', (explode('(', $string)[1]))[0];\necho $string;\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
196,521
<p>There's something I want to customize in the System.Web.Script.Services.ScriptHandlerFactory and other .NET stuff inside an internal class. Unfortunately, it's an internal class. What options do I have when trying to customize a method in this class?</p>
[ { "answer_id": 196525, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "internal" }, { "answer_id": 196551, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 3, "selected": false, "text": "using System;\n...\nusing System.Web.Script.Services\n\nnamespace MyGreatCompany.ScriptServices \n{\n public class MyScriptHandlerFactory /* implement all the interfaces */\n {\n private ScriptHandlerFactory internalFactory;\n public MyScriptHandlerFactory()\n {\n internalFactory = new ScriptHandlerFactory();\n }\n ...\n }\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
196,522
<p>I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes? </p>
[ { "answer_id": 196537, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "int DoSomeThings()\n{\n int error = 0;\n HandleA hA;\n error = CreateAObject(&ha);\n if (error)\n goto cleanUpFailedA;\n\n HandleB hB;\n error = CreateBObjectWithA(hA, &hB);\n if (error)\n goto cleanUpFailedB;\n\n HandleC hC;\n error = CreateCObjectWithA(hB, &hC);\n if (error)\n goto cleanUpFailedC;\n\n ...\n\n cleanUpFailedC:\n DeleteCObject(hC);\n cleanUpFailedB:\n DeleteBObject(hB);\n cleanUpFailedA:\n DeleteAObject(hA);\n\n return error;\n}\n void DoSomeThings()\n{\n RAIIHandleA hA = CreateAObject();\n RAIIHandleB hB = CreateBObjectWithA(hA);\n RAIIHandleC hC = CreateCObjectWithB(hB);\n ...\n}\n\nstruct RAIIHandleA\n{\n HandleA Handle;\n RAIIHandleA(HandleA handle) : Handle(handle) {}\n ~RAIIHandleA() { DeleteAObject(Handle); }\n}\n...\n" }, { "answer_id": 196813, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 1, "selected": false, "text": "int divide(int a, int b)\n{\n if( b == 0 )\n // then what? no integer can be used for an error flag!\n else\n return a / b;\n}\n" }, { "answer_id": 197131, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 3, "selected": false, "text": "catch if goto" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
196,566
<p>I am trying to connect to a webservice over ssl with a client certificate. Is there an elegant way of doing this apart from shoving things like "javax.net.ssl.keyStore" into System.properties.</p> <p>Any pointers to code examples would be appreciated.</p>
[ { "answer_id": 196537, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "int DoSomeThings()\n{\n int error = 0;\n HandleA hA;\n error = CreateAObject(&ha);\n if (error)\n goto cleanUpFailedA;\n\n HandleB hB;\n error = CreateBObjectWithA(hA, &hB);\n if (error)\n goto cleanUpFailedB;\n\n HandleC hC;\n error = CreateCObjectWithA(hB, &hC);\n if (error)\n goto cleanUpFailedC;\n\n ...\n\n cleanUpFailedC:\n DeleteCObject(hC);\n cleanUpFailedB:\n DeleteBObject(hB);\n cleanUpFailedA:\n DeleteAObject(hA);\n\n return error;\n}\n void DoSomeThings()\n{\n RAIIHandleA hA = CreateAObject();\n RAIIHandleB hB = CreateBObjectWithA(hA);\n RAIIHandleC hC = CreateCObjectWithB(hB);\n ...\n}\n\nstruct RAIIHandleA\n{\n HandleA Handle;\n RAIIHandleA(HandleA handle) : Handle(handle) {}\n ~RAIIHandleA() { DeleteAObject(Handle); }\n}\n...\n" }, { "answer_id": 196813, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 1, "selected": false, "text": "int divide(int a, int b)\n{\n if( b == 0 )\n // then what? no integer can be used for an error flag!\n else\n return a / b;\n}\n" }, { "answer_id": 197131, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 3, "selected": false, "text": "catch if goto" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22888/" ]
196,567
<p>I have a mockup layout for something <a href="http://www.mylittlepwnage.com/misc/forms-editor.html" rel="nofollow noreferrer">here</a>. Essentially there are sections, columns and fields, which are all written as a combination of <code>&lt;ul&gt;</code> and <code>&lt;li&gt;</code> elements. This is done specifically for later parsing. </p> <p>A snippet of the HTML:</p> <pre><code>&lt;li class="layout"&gt;&lt;span class="type"&gt;[Column] &lt;/span&gt; &lt;ul class="layout-children"&gt; &lt;li class="field"&gt;&lt;span class="type"&gt;[Text] &lt;/span&gt;A field&lt;/li&gt; &lt;li class="field"&gt;&lt;span class="type"&gt;[Text] &lt;/span&gt;Another field&lt;/li&gt; &lt;li class="field"&gt;&lt;span class="type"&gt;[Text] &lt;/span&gt;Yet another field&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="layout"&gt;&lt;span class="type"&gt;[Column] &lt;/span&gt; &lt;ul class="layout-children"&gt; &lt;li class="field"&gt;&lt;span class="type"&gt;[Text] &lt;/span&gt;More fields&lt;/li&gt; &lt;li class="field"&gt;&lt;span class="type"&gt;[Text] &lt;/span&gt;And one more field&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>If you go to the <a href="http://www.mylittlepwnage.com/misc/forms-editor.html" rel="nofollow noreferrer">linked content</a> you'll note that those columns sit vertically. I want the columns to sit beside each other, but I am not sure how to go about it.</p> <p>It would be preferable if the HTML didn't change, just the CSS.</p>
[ { "answer_id": 196571, "author": "Joe Basirico", "author_id": 20795, "author_profile": "https://Stackoverflow.com/users/20795", "pm_score": 2, "selected": false, "text": "<UL> <li>" }, { "answer_id": 196573, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 0, "selected": false, "text": ".layout { float: left; width: 50%; margin: 0; border: 0; padding: 0; /* background: transparent */ }\n* html .layout { display: inline } /* IE margin hack */\n.field { clear: both }\n" }, { "answer_id": 196576, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 0, "selected": false, "text": "display:block display:inline" }, { "answer_id": 196579, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 4, "selected": true, "text": "ul .section-children li.layout {\n display : inline-block;\n}\n" }, { "answer_id": 196588, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "display: -moz-inline-box;\ndisplay: inline-block;\n*display: inline;\n*zoom: 1;\n" }, { "answer_id": 196604, "author": "Elle H", "author_id": 23666, "author_profile": "https://Stackoverflow.com/users/23666", "pm_score": 0, "selected": false, "text": ".layout-children:after\n{\n content: \"\";\n display: block;\n height: 0px;\n clear: both;\n}\n\n.layout-children .field\n{\n float: left;\n}\n" }, { "answer_id": 197657, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "inline inline-block" }, { "answer_id": 202012, "author": "Traingamer", "author_id": 27609, "author_profile": "https://Stackoverflow.com/users/27609", "pm_score": 0, "selected": false, "text": "li {\n margin: .5em 1em;\n padding: .1em;\n\n font-family: sans-serif;\n list-style-type: none;\n border: 1px #666 solid;\n float: left;\n}\n#layout-section {\n width: 85%;\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
196,585
<p>I've got some LINQ to SQL that sometimes throws a </p> <blockquote> <p>"Cannot insert duplicate key row in object 'dbo.Table' with unique index 'IX_Indexname'.The statement has been terminated."</p> </blockquote> <p>Is there some way I can turn on logging or at least debug into the datacontext to see what sql is being executed at the time that error is raised?</p> <p><strong>Update:</strong> I should have mentioned I know about the <code>GetChangeSet()</code> method, I was wondering if there is a property on the DataContext that shows the last SQL that was executed, or a property on the sql exception that shows the SQL.</p> <p>The odd thing about this error is that in the change sets, there is only one update &amp; the only field that's changing is a datetime field that isn't in the index that causing the error.</p>
[ { "answer_id": 196594, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "context.GetChangedSet();\n" }, { "answer_id": 196607, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "using (MyDataContext ctx = new MyDataContext())\n{\n StringWriter sw = new StringWriter();\n ctx.Log = sw;\n\n // execute some LINQ to SQL operations...\n\n string sql = sw.ToString();\n // put a breakpoint here, log it to a file, etc...\n} \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
196,591
<p>I need to pad the output of an integer to a given length.</p> <p>For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?</p>
[ { "answer_id": 196599, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 6, "selected": true, "text": "output = String.Format(\"{0:0000}\", intVariable); \n" }, { "answer_id": 68529323, "author": "Rob Hoff", "author_id": 211764, "author_profile": "https://Stackoverflow.com/users/211764", "pm_score": 0, "selected": false, "text": "int myint = 100;\nstring zeroPadded = $\"{myint:d8}\"; // \"00000100\"\nstring leftPadded = $\"{myint,8}\"; // \" 100\"\nstring rightPadded = $\"{myint,-8}\"; // \"100 \"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20910/" ]
196,603
<p>My company has a large application written in VB6, and for historical reasons, the application is navigated with the Enter key instead of with the Tab key. I don't know VB6, but I know that they currently set the focus for each control in a big select statement in the Form's KeyUp event if it's an EnterKey. Now we are starting to convert to .NET, and have to keep things consistent so the users won't have to TAB on some forms and ENTER on others. I want to write ancestor forms that will automatically ENTER from field to field instead of tabbing. A coworker told me that the way it's done in VB6 is to process buttons not on the CLICK event but on the KEYUP event. I need to continue doing this so I won't have leftover KeyUp events to pass back to VB6 after my form is finished. The order of events for buttons is</p> <ol> <li>button_PreviewKeyDown </li> <li>button_Click (apparently replacing the KeyPress event)</li> <li>form_KeyUp </li> <li>button_KeyUp</li> </ol> <p>I created forms as follows:</p> <ul> <li>On the ANCESTOR form's KeyUp event, checks to see if it's an enter key. If it is an enter key, and the active control is not a button, it moves to the next field in tab order. Otherwise it ignores the key and lets the control handle it. If it is a button, the ancestor doesn't presume to know where the button wants control to go, because it will depend on what the button wants to do when it is "clicked".</li> <li>On the CHILD form's buttons, the click event does nothing, and the processing is duplicated in the KeyUp event and the MouseClick event. </li> <li>The ANCESTOR form has a protected Boolean, EatKeyUp, that can be set to True by the CHILD. This is used when the child form needs to send a MessageBox, because if the user enters through the OK button on the MessageBox, there is still a leftover KeyUp event that will be consumed by the ancestor form.</li> </ul> <p>Although klugey, this actually seems to work. What I want to know is, is there a better way? Perhaps some setting somewhere that I can tell my application "Enter through forms instead of tabbing"? Are the events that I'm using instead of the click events the best ones?</p>
[ { "answer_id": 196599, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 6, "selected": true, "text": "output = String.Format(\"{0:0000}\", intVariable); \n" }, { "answer_id": 68529323, "author": "Rob Hoff", "author_id": 211764, "author_profile": "https://Stackoverflow.com/users/211764", "pm_score": 0, "selected": false, "text": "int myint = 100;\nstring zeroPadded = $\"{myint:d8}\"; // \"00000100\"\nstring leftPadded = $\"{myint,8}\"; // \" 100\"\nstring rightPadded = $\"{myint,-8}\"; // \"100 \"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
196,626
<p>I need to do a query that search for a text with <strong>'Nome % teste \ / '</strong> as prefix. I'm doing the query using:</p> <p><strong>where "name" ILIKE 'Nome a% teste \ /%' ESCAPE 'a'</strong> (using a as escape character).</p> <p>There is a row that match this, but this query returns nothing. Removing the slash (<strong>'Nome % teste \'</strong>), it works. But I don't see why the <strong>slash</strong> is a problem, since the default escape is a <strong>backslash</strong> and I've changed it to <strong>'a'</strong> in this test.</p> <p>There is something that I'm missing? (I've consulted TFM)</p>
[ { "answer_id": 196631, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "where \"name\" ILIKE 'Nome \\% teste \\\\\\/';\n" }, { "answer_id": 196648, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "WHERE \"name\" ILIKE 'Nome ~% teste \\\\/' ESCAPE '~' \n WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\/' \n WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\/%' \n WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\%' \n WHERE \"name\" ILIKE 'Nome \\% ' AND \"name\" ~* '\\\\.{1,10}/' \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18403/" ]
196,628
<p>I have the following problem in my <i>Data Structures and Problem Solving using Java</i> book:</p> <blockquote> <p>Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.</p> </blockquote> <p>I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!</p> <p>When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).</p> <p>If anybody could guide me in the right direction, I would greatly appreciate it.</p>
[ { "answer_id": 196638, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 2, "selected": false, "text": "void printReverseList(Collection col) {}\n" }, { "answer_id": 196642, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 5, "selected": true, "text": "List temp = new ArrayList(src);\nCollections.reverse(temp);\nSystem.out.println(temp);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
196,661
<p>I was hoping to do something like this, but it appears to be illegal in C#:</p> <pre><code>public Collection MethodThatFetchesSomething&lt;T&gt;() where T : SomeBaseClass { return T.StaticMethodOnSomeBaseClassThatReturnsCollection(); } </code></pre> <p>I get a compile-time error:</p> <blockquote> <p>'T' is a 'type parameter', which is not valid in the given context.</p> </blockquote> <p>Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.</p>
[ { "answer_id": 196977, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 7, "selected": true, "text": "T.StaticMethodOnSomeBaseClassThatReturnsCollection\n SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection\n" }, { "answer_id": 462136, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public interface eInterface {\n void MethodOnSomeBaseClassThatReturnsCollection();\n}\n\npublic T:SomeBaseClass, eInterface {\n\n public void MethodOnSomeBaseClassThatReturnsCollection() \n { StaticMethodOnSomeBaseClassThatReturnsCollection() }\n\n}\n\npublic Collection MethodThatFetchesSomething<T>() where T : SomeBaseClass, eInterface\n{ \n return ((eInterface)(new T()).StaticMethodOnSomeBaseClassThatReturnsCollection();\n}\n" }, { "answer_id": 4982366, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 2, "selected": false, "text": "class ClassWithGenericStaticMethod\n{\n public static void PrintName<T>(string prefix) where T : class\n {\n Console.WriteLine(prefix + \" \" + typeof(T).FullName);\n }\n}\n // Grabbing the type that has the static generic method\nType typeofClassWithGenericStaticMethod = typeof(ClassWithGenericStaticMethod);\n\n// Grabbing the specific static method\nMethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod(\"PrintName\", System.Reflection.BindingFlags.Static | BindingFlags.Public);\n\n// Binding the method info to generic arguments\nType[] genericArguments = new Type[] { typeof(Program) };\nMethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);\n\n// Simply invoking the method and passing parameters\n// The null parameter is the object to call the method from. Since the method is\n// static, pass null.\nobject returnValue = genericMethodInfo.Invoke(null, new object[] { \"hello\" });\n" }, { "answer_id": 8358651, "author": "Joshua Pech", "author_id": 629423, "author_profile": "https://Stackoverflow.com/users/629423", "pm_score": 5, "selected": false, "text": "public void doSomething<T>() where T : someParent\n{\n List<T> items=(List<T>)typeof(T).GetMethod(\"fetchAll\").Invoke(null,new object[]{});\n //do something with items\n}\n" }, { "answer_id": 8657544, "author": "Amir Abiri", "author_id": 800334, "author_profile": "https://Stackoverflow.com/users/800334", "pm_score": 2, "selected": false, "text": "class Factory<TProduct> where TProduct : new()\n{\n public delegate void ProductInitializationMethod(TProduct newProduct);\n\n\n private ProductInitializationMethod m_ProductInitializationMethod;\n\n\n public Factory(ProductInitializationMethod p_ProductInitializationMethod)\n {\n m_ProductInitializationMethod = p_ProductInitializationMethod;\n }\n\n public TProduct CreateProduct()\n {\n var prod = new TProduct();\n m_ProductInitializationMethod(prod);\n return prod;\n }\n}\n\nclass ProductA\n{\n public static void InitializeProduct(ProductA newProduct)\n {\n // .. Do something with a new ProductA\n }\n}\n\nclass ProductB\n{\n public static void InitializeProduct(ProductB newProduct)\n {\n // .. Do something with a new ProductA\n }\n}\n\nclass GenericAndDelegateTest\n{\n public static void Main()\n {\n var factoryA = new Factory<ProductA>(ProductA.InitializeProduct);\n var factoryB = new Factory<ProductB>(ProductB.InitializeProduct);\n\n ProductA prodA = factoryA.CreateProduct();\n ProductB prodB = factoryB.CreateProduct();\n }\n}\n" }, { "answer_id": 66927384, "author": "micahneitz", "author_id": 6417406, "author_profile": "https://Stackoverflow.com/users/6417406", "pm_score": 3, "selected": false, "text": "interface IFoo<T> where T : IFoo<T>, new()\n{\n ICollection<T> ReturnsCollection();\n}\n\nstatic class Foo<T> where T : IFoo<T>, new()\n{\n private static readonly T value = new();\n public static ICollection<T> ReturnsCollection() => value.ReturnsCollection();\n}\n\n// Use case\n\npublic ICollection<T> DoSomething<T>() where T : IFoo<T>, new()\n{\n return Foo<T>.ReturnsCollection();\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8169/" ]
196,664
<p>I have a form that has multiple fields, and for testing purposes is there a way I could print out the values entered in all the fields, without having to individually print each value.</p>
[ { "answer_id": 196672, "author": "defeated", "author_id": 16997, "author_profile": "https://Stackoverflow.com/users/16997", "pm_score": 6, "selected": true, "text": "var_dump($_REQUEST);" }, { "answer_id": 196714, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": false, "text": "function pre($data) {\n print '<pre>' . print_r($data, true) . '</pre>';\n}\n" }, { "answer_id": 196777, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 4, "selected": false, "text": "print_r() var_dump() print_r() var_dump()" }, { "answer_id": 261268, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 2, "selected": false, "text": "<?php\n// loop through every form field\nwhile( list( $field, $value ) = each( $_POST )) {\n // display values\n if( is_array( $value )) {\n // if checkbox (or other multiple value fields)\n while( list( $arrayField, $arrayValue ) = each( $value ) {\n echo \"<p>\" . $arrayValue . \"</p>\\n\";\n }\n } else {\n echo \"<p>\" . $value . \"</p>\\n\";\n }\n}\n?>\n" }, { "answer_id": 10632623, "author": "ajmakoni", "author_id": 1400544, "author_profile": "https://Stackoverflow.com/users/1400544", "pm_score": 3, "selected": false, "text": "$_POST[] $_GET[] print_r($_POST)" }, { "answer_id": 13250271, "author": "Rinzler", "author_id": 1077101, "author_profile": "https://Stackoverflow.com/users/1077101", "pm_score": 3, "selected": false, "text": "echo \"<pre>\"; print_r($_POST) ; echo \"</pre>\";\n" }, { "answer_id": 18892327, "author": "Mar Taylor", "author_id": 2795019, "author_profile": "https://Stackoverflow.com/users/2795019", "pm_score": -1, "selected": false, "text": "phpinfo();\n" }, { "answer_id": 39783441, "author": "Tyler Mecham", "author_id": 1054412, "author_profile": "https://Stackoverflow.com/users/1054412", "pm_score": 1, "selected": false, "text": "<?php\n phpinfo(INFO_VARIABLES);\n?>\n" }, { "answer_id": 65883802, "author": "Damiano93", "author_id": 11951053, "author_profile": "https://Stackoverflow.com/users/11951053", "pm_score": 0, "selected": false, "text": "print_r($_POST); var_dump($_POST); echo ($_POST['value']); \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
196,668
<p>I'm working on a system that includes a large number of reports, generated using <a href="http://jasperforge.org/plugins/project/project_home.php?group_id=102" rel="noreferrer">JasperReports</a>. One of the newer features is that you can define styles for reports.</p> <p>From the available docs I believe there is some way to have an external file defining styles to use, and you can reference that in your jasper reports. This allows a single style to be used by multiple reports.</p> <p>I can't find any concrete information on whether this is an actual feature, and if it is, how to use it. Does anyone know if it is possible to have external styles for jasper reports, and if so, how to do it?</p>
[ { "answer_id": 206403, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 6, "selected": true, "text": ".jrtx styles.jrtx <?xml version=\"1.0\"?>\n<!DOCTYPE jasperTemplate\n PUBLIC \"-//JasperReports//DTD Template//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd\">\n\n<jasperTemplate>\n <style name=\"Report Title\" isDefault=\"false\" hAlign=\"Center\" fontSize=\"24\" isBold=\"true\"/>\n <style name=\"Heading 1\" isDefault=\"false\" fontSize=\"18\" isBold=\"true\"/>\n <style name=\"Heading 2\" isDefault=\"false\" fontSize=\"14\" isBold=\"true\"/>\n</jasperTemplate>\n .jrxml ...\n<template><![CDATA[\"styles.jrtx\"]]></template>\n...\n" }, { "answer_id": 595933, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<template> <parameter name=\"TEMPLATE_FILE\" isForPrompting=\"false\" class=\"java.lang.String\"/> <template><![CDATA[$P{TEMPLATE_FILE}]]></template>" }, { "answer_id": 3563302, "author": "roshani", "author_id": 430185, "author_profile": "https://Stackoverflow.com/users/430185", "pm_score": 3, "selected": false, "text": "<template><![CDATA[\"C:\\\\ BigBoldRedTemplate.jrtx\"]]></template>\n <reportElement> //style applied to a rectangle\n<rectangle radius=\"10\">\n <reportElement style=\"BigBoldRed\" mode=\"Transparent\" x=\"0\" y=\"0\" width=\"555\" height=\"44\"/>\n</rectangle>\n//style applied to a the text field\n<staticText>\n <reportElement style=\"BigBoldRed\" x=\"0\" y=\"0\" width=\"555\" height=\"66\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Monthly Customer Invoices]]></text>\n</staticText>\n <li> \"<li>\"+\"Invoice # \"+$F{InvoiceID}+\", \"+\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27308/" ]
196,684
<p>All right, say I have this:</p> <pre><code>&lt;select id='list'&gt; &lt;option value='1'&gt;Option A&lt;/option&gt; &lt;option value='2'&gt;Option B&lt;/option&gt; &lt;option value='3'&gt;Option C&lt;/option&gt; &lt;/select&gt; </code></pre> <p>What would the selector look like if I wanted to get "Option B" when I have the value '2'?</p> <p>Please note that this is not asking how to get the <em>selected</em> text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:</p> <pre><code>$("#list[value='2']").text(); </code></pre> <p>But it is not working.</p>
[ { "answer_id": 196687, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 11, "selected": true, "text": "list value 2 option list $(\"#list option[value='2']\").text()\n" }, { "answer_id": 196689, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 5, "selected": false, "text": "$(\"#list option[value=2]\").text();\n OPTION SELECT id list" }, { "answer_id": 869486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 10, "selected": false, "text": "$(\"#list option[value='2']\").text();\n $(\"#list option:selected\").text();\n" }, { "answer_id": 2941793, "author": "Mon", "author_id": 354353, "author_profile": "https://Stackoverflow.com/users/354353", "pm_score": 4, "selected": false, "text": "$(\"#list [value='2']\").text();\n" }, { "answer_id": 2975038, "author": "m3ct0n", "author_id": 358544, "author_profile": "https://Stackoverflow.com/users/358544", "pm_score": 5, "selected": false, "text": "$(\"#list option:selected\").each(function() {\n alert($(this).text());\n}); \n #list" }, { "answer_id": 5150943, "author": "Dilantha", "author_id": 302281, "author_profile": "https://Stackoverflow.com/users/302281", "pm_score": 4, "selected": false, "text": "$(\"#list :selected\").text();\n" }, { "answer_id": 5857108, "author": "asyadiqin", "author_id": 483050, "author_profile": "https://Stackoverflow.com/users/483050", "pm_score": 7, "selected": false, "text": "$(\"#list\").change(function() {\n alert($(this).find(\"option:selected\").text()+' clicked!');\n});\n" }, { "answer_id": 6143723, "author": "eon", "author_id": 717833, "author_profile": "https://Stackoverflow.com/users/717833", "pm_score": 3, "selected": false, "text": "$(\"option:selected\").text(); $(this + \" option:selected\").text() $(this).find(\"option:selected\").text();\n .each() $('#list option:selected\").each()" }, { "answer_id": 6658076, "author": "Mary Daisy Sanchez", "author_id": 560756, "author_profile": "https://Stackoverflow.com/users/560756", "pm_score": 3, "selected": false, "text": "function selected_state(){\n jQuery(\"#list option\").each(function(){\n if(jQuery(this).val() == \"2\"){\n jQuery(this).attr(\"selected\",\"selected\");\n return false;\n }else\n jQuery(this).removeAttr(\"selected\",\"selected\"); // For toggle effect\n });\n}\n\njQuery(document).ready(function(){\n selected_state();\n});\n" }, { "answer_id": 6877694, "author": "raphie", "author_id": 424543, "author_profile": "https://Stackoverflow.com/users/424543", "pm_score": 7, "selected": false, "text": "$(this).find(\"option:selected\").text(); $(this).find(\":selected\").text();\n" }, { "answer_id": 8718582, "author": "gordon", "author_id": 778294, "author_profile": "https://Stackoverflow.com/users/778294", "pm_score": 2, "selected": false, "text": "$(this).find <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"select[showChoices]\").each(function(){\n $(this).after(\"<span id='spn\"+$(this).attr('id')+\"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>\");\n doShowSelected($(this).attr('id'));//shows initial selections\n }).change(function(){\n doShowSelected($(this).attr('id'));//as user makes new selections\n });\n });\n function doShowSelected(inId){\n var aryVals=$(\"#\"+inId).val();\n var selText=\"\";\n for(var i=0; i<aryVals.length; i++){\n var o=\"#\"+inId+\" option[value='\"+aryVals[i]+\"']\";\n selText+=$(o).text()+\"<br>\";\n }\n $(\"#spn\"+inId).html(selText);\n }\n</script>\n<select style=\"float:left;\" multiple=\"true\" id=\"mySelect\" name=\"mySelect\" showChoices=\"true\">\n <option selected=\"selected\" value=1>opt 1</option>\n <option selected=\"selected\" value=2>opt 2</option>\n <option value=3>opt 3</option>\n <option value=4>opt 4</option>\n</select>\n" }, { "answer_id": 11007952, "author": "Beena Shetty", "author_id": 853453, "author_profile": "https://Stackoverflow.com/users/853453", "pm_score": 5, "selected": false, "text": "jQuery(\"select option[value=2]\").text();\n jQuery(\"select option:selected\").text();\n" }, { "answer_id": 14425761, "author": "VisioN", "author_id": 1249581, "author_profile": "https://Stackoverflow.com/users/1249581", "pm_score": 2, "selected": false, "text": "<option> value=\"2\" $(\"option[value='2']\", \"#list\").text();\n" }, { "answer_id": 14836080, "author": "Martin Clemens Bloch", "author_id": 1265209, "author_profile": "https://Stackoverflow.com/users/1265209", "pm_score": 2, "selected": false, "text": "element.options[element.selectedIndex].text\n" }, { "answer_id": 15785944, "author": "Avinash Saini", "author_id": 2226601, "author_profile": "https://Stackoverflow.com/users/2226601", "pm_score": 4, "selected": false, "text": "$(this).children(\":selected\").text()\n" }, { "answer_id": 19799860, "author": "FAA", "author_id": 1212739, "author_profile": "https://Stackoverflow.com/users/1212739", "pm_score": 3, "selected": false, "text": "var e = $('select[title=\"IntenalFieldName\"] option:selected').text(); \n" }, { "answer_id": 24542571, "author": "mindmyweb", "author_id": 730763, "author_profile": "https://Stackoverflow.com/users/730763", "pm_score": 4, "selected": false, "text": "$(\"#action\").on('change',function() {\n alert($(this).find(\"option:selected\").text()+' clicked!');\n});\n" }, { "answer_id": 28935856, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 3, "selected": false, "text": "$(\"#list option[value='\"+aDynamicValue+\"']\").text();\n $(\"#list option\").filter(function() {\n return this.value === aDynamicValue;\n}).text();\n" }, { "answer_id": 42551632, "author": "Dilipkumar63", "author_id": 7639213, "author_profile": "https://Stackoverflow.com/users/7639213", "pm_score": 4, "selected": false, "text": ".text(); jQuery(\"select option:selected\").text();\n" }, { "answer_id": 50230859, "author": "Anfath Hifans", "author_id": 7352537, "author_profile": "https://Stackoverflow.com/users/7352537", "pm_score": 2, "selected": false, "text": "$(\"#list\").find('option').filter('[value=2]').text()\n\n$(\"#list\").find('option[value=2]').text()\n\n$(\"#list\").children('option[value=2]').text()\n\n$(\"#list option[value='2']\").text()\n $(function(){ \n \n console.log($(\"#list\").find('option').filter('[value=2]').text());\n console.log($(\"#list\").find('option[value=2]').text());\n console.log($(\"#list\").children('option[value=2]').text());\n console.log($(\"#list option[value='2']\").text());\n \n}); <script src=\"//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\n<select id='list'>\n <option value='1'>Option A</option>\n <option value='2'>Option B</option>\n <option value='3'>Option C</option>\n</select>" }, { "answer_id": 63507191, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "[...list.options].find(o=> o.value=='2').text\n let text = [...list.options].find(o=> o.value=='2').text;\n\nconsole.log(text); <select id='list'>\n <option value='1'>Option A</option>\n <option value='2'>Option B</option>\n <option value='3'>Option C</option>\n</select>" }, { "answer_id": 64465676, "author": "Zakaria Binsaifullah", "author_id": 8381482, "author_profile": "https://Stackoverflow.com/users/8381482", "pm_score": 2, "selected": false, "text": "jQuery(\"#list option[value='2']\").text()\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16417/" ]
196,702
<p>Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <code>&lt;script src="..."&gt;</code>, not pasted into the HTML itself.</p> <p>Where’s the best place to put this in the HTML?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;!-- here? --&gt; &lt;link rel="stylesheet" href="stylez.css" type="text/css" /&gt; &lt;!-- here? --&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- here? --&gt; &lt;p&gt;All the page content ...&lt;/p&gt; &lt;!-- or here? --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Will there be any functional difference between each of the options?</p>
[ { "answer_id": 196933, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 2, "selected": false, "text": "x.js x.js.gz src" }, { "answer_id": 23476758, "author": "martynas", "author_id": 3300831, "author_profile": "https://Stackoverflow.com/users/3300831", "pm_score": 6, "selected": false, "text": "<script> </body> <html>\n <head>\n <title>My awesome page</title>\n\n <!-- CSS -->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n\n </head>\n <body>\n <!-- Content content content -->\n\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n </body>\n</html>\n" }, { "answer_id": 62213234, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<head> <body> <script async src=\"script.js\"></script>" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
196,713
<p>I need to match something in the form </p> <pre><code>&lt;a href="pic/5" id="piclink"&gt;&lt;img src="thumb/5" /&gt;&lt;/a&gt; </code></pre> <p>to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out.</p>
[ { "answer_id": 196717, "author": "num1", "author_id": 306, "author_profile": "https://Stackoverflow.com/users/306", "pm_score": 1, "selected": false, "text": "'<a href=\"pic/5\" id=\"piclink\"><img src=\"thumb/5\" /></a>'.match(/[0-9]/);\n" }, { "answer_id": 196743, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 3, "selected": true, "text": "/[0-9]+/\n" }, { "answer_id": 196749, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 1, "selected": false, "text": "$('#picklink > img').attr('src').split('/').pop();\n \"$('#picklink > img').attr('src')\" \".split('/').pop();\"" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306/" ]
196,721
<p>I'm trying to configure my WAR project build to fail if the line or branch coverage is below given thresholds. I've been using the configuration provided on page 455 of the excellent book <a href="http://oreilly.com/catalog/9780596527938/" rel="noreferrer">Java Power Tools</a>, but with no success. Here's the relevant snippet of my project's Maven 2 POM:</p> <pre><code>&lt;build&gt; ... &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;configuration&gt; &lt;check&gt; &lt;!-- Per-class thresholds --&gt; &lt;lineRate&gt;80&lt;/lineRate&gt; &lt;branchRate&gt;80&lt;/branchRate&gt; &lt;!-- Project-wide thresholds --&gt; &lt;totalLineRate&gt;90&lt;/totalLineRate&gt; &lt;totalBranchRate&gt;90&lt;/totalBranchRate&gt; &lt;/check&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;clean&lt;/goal&gt; &lt;goal&gt;check&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;coverage-tests&lt;/id&gt; &lt;!-- The &quot;verify&quot; phase occurs just before &quot;install&quot; --&gt; &lt;phase&gt;verify&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;clean&lt;/goal&gt; &lt;goal&gt;check&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;instrumentation&gt; &lt;excludes&gt; &lt;exclude&gt;au/**/*Constants.*&lt;/exclude&gt; &lt;/excludes&gt; &lt;ignores&gt; &lt;ignore&gt;au/**/*Constants.*&lt;/ignore&gt; &lt;/ignores&gt; &lt;/instrumentation&gt; &lt;/configuration&gt; &lt;/plugin&gt; ... &lt;/plugins&gt; ... &lt;/build&gt; </code></pre> <p>As I say, the coverage report works fine, the problem is that the &quot;install&quot; goal isn't failing as it should if the line or branch coverage is below my specified thresholds. Does anyone have this working, and if so, what does your POM look like and which version of Cobertura and Maven are you using? I'm using Maven 2.0.9 and Cobertura 2.2.</p> <p>I've tried Googling and reading the Cobertura docs, but no luck (the latter are sparse to say the least).</p>
[ { "answer_id": 1618213, "author": "Pascal Thivent", "author_id": 70604, "author_profile": "https://Stackoverflow.com/users/70604", "pm_score": 5, "selected": true, "text": "<haltOnFailure> true haltOnFailure <execution> verify <execution> <project>\n ...\n <build>\n ...\n <plugins>\n ...\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>cobertura-maven-plugin</artifactId>\n <version>2.3</version>\n <configuration>\n <check>\n <!--<haltOnFailure>true</haltOnFailure>--><!-- optional -->\n <!-- Per-class thresholds -->\n <lineRate>80</lineRate>\n <branchRate>80</branchRate>\n <!-- Project-wide thresholds -->\n <totalLineRate>90</totalLineRate>\n <totalBranchRate>90</totalBranchRate>\n </check>\n </configuration>\n <executions>\n <execution>\n <phase>verify</phase>\n <goals>\n <!--<goal>clean</goal>--><!-- works if uncommented -->\n <goal>check</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>\n mvn clean install mvn archetype:create $ mvn archetype:create -DgroupId=com.mycompany.samples -DartifactId=cobertura-haltonfailure-testcase\n...\n$ mvn clean install\n[INFO] Scanning for projects...\n[INFO] ------------------------------------------------------------------------\n[INFO] Building cobertura-haltonfailure-testcase\n[INFO] task-segment: [clean, install]\n[INFO] ------------------------------------------------------------------------\n[INFO] [clean:clean {execution: default-clean}]\n[INFO] Deleting directory /home/pascal/Projects/cobertura-haltonfailure-testcase/target\n[INFO] [resources:resources {execution: default-resources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources\n[INFO] [compiler:compile {execution: default-compile}]\n[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/classes\n[INFO] [resources:testResources {execution: default-testResources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/test-classes\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.mycompany.samples.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.09 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/cobertura-haltonfailure-testcase-1.0-SNAPSHOT.jar\n[INFO] Preparing cobertura:check\n[WARNING] Removing: check from forked lifecycle, to prevent recursive invocation.\n[INFO] [resources:resources {execution: default-resources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources\n[INFO] [compiler:compile {execution: default-compile}]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [cobertura:instrument {execution: default}]\n[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file\nInstrumenting 1 file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/generated-classes/cobertura\nCobertura: Saved information on 1 classes.\nInstrument time: 337ms\n\n[INFO] Instrumentation was successful.\n[INFO] [resources:testResources {execution: default-testResources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.mycompany.samples.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.098 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [cobertura:check {execution: default}]\n[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file\nCobertura: Loaded information on 1 classes.\n\n[ERROR] com.mycompany.samples.App failed check. Line coverage rate of 0.0% is below 80.0%\nProject failed check. Total line coverage rate of 0.0% is below 90.0%\n\n[INFO] ------------------------------------------------------------------------\n[ERROR] BUILD ERROR\n[INFO] ------------------------------------------------------------------------\n[INFO] Coverage check failed. See messages above.\n[INFO] ------------------------------------------------------------------------\n[INFO] For more information, run Maven with the -e switch\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 18 seconds\n[INFO] Finished at: Sat Oct 24 21:00:39 CEST 2009\n[INFO] Final Memory: 17M/70M\n[INFO] ------------------------------------------------------------------------\n$ \n haltOnFailure" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10433/" ]
196,729
<p>I'm developing an operating system and rather than programming the kernel, I'm designing the kernel. This operating system is targeted at the x86 architecture and my target is for modern computers. The estimated number of required RAM is 256Mb or more.</p> <p>What is a good size to make the stack for each thread run on the system? Should I try to design the system in such a way that the stack can be extended automatically if the maximum length is reached?</p> <p>I think if I remember correctly that a page in RAM is 4k or 4096 bytes and that just doesn't seem like a lot to me. I can definitely see times, especially when using lots of recursion, that I would want to have more than 1000 integars in RAM at once. Now, the real solution would be to have the program doing this by using <code>malloc</code> and manage its own memory resources, but really I would like to know the user opinion on this.</p> <p>Is 4k big enough for a stack with modern computer programs? Should the stack be bigger than that? Should the stack be auto-expanding to accommodate any types of sizes? I'm interested in this both from a practical developer's standpoint and a security standpoint.</p> <p>Is 4k too big for a stack? Considering normal program execution, especially from the point of view of classes in C++, I notice that good source code tends to <code>malloc/new</code> the data it needs when classes are created, to minimize the data being thrown around in a function call.</p> <p>What I haven't even gotten into is the size of the processor's cache memory. Ideally, I think the stack would reside in the cache to speed things up and I'm not sure if I need to achieve this, or if the processor can handle it for me. I was just planning on using regular boring old RAM for testing purposes. I can't decide. What are the options?</p>
[ { "answer_id": 6001984, "author": "Peter Teoh", "author_id": 315046, "author_profile": "https://Stackoverflow.com/users/315046", "pm_score": 2, "selected": false, "text": "./arch/cris/include/asm/processor.h:\n#define KERNEL_STACK_SIZE PAGE_SIZE\n\n./arch/ia64/include/asm/ptrace.h:\n# define KERNEL_STACK_SIZE_ORDER 3\n# define KERNEL_STACK_SIZE_ORDER 2\n# define KERNEL_STACK_SIZE_ORDER 1\n# define KERNEL_STACK_SIZE_ORDER 0\n#define IA64_STK_OFFSET ((1 << KERNEL_STACK_SIZE_ORDER)*PAGE_SIZE)\n#define KERNEL_STACK_SIZE IA64_STK_OFFSET\n\n./arch/ia64/include/asm/mca.h:\n u64 mca_stack[KERNEL_STACK_SIZE/8];\n u64 init_stack[KERNEL_STACK_SIZE/8];\n\n./arch/ia64/include/asm/thread_info.h:\n#define THREAD_SIZE KERNEL_STACK_SIZE\n\n./arch/ia64/include/asm/mca_asm.h:\n#define MCA_PT_REGS_OFFSET ALIGN16(KERNEL_STACK_SIZE-IA64_PT_REGS_SIZE)\n\n./arch/parisc/include/asm/processor.h:\n#define KERNEL_STACK_SIZE (4*PAGE_SIZE)\n\n./arch/xtensa/include/asm/ptrace.h:\n#define KERNEL_STACK_SIZE (2 * PAGE_SIZE)\n\n./arch/microblaze/include/asm/processor.h:\n# define KERNEL_STACK_SIZE 0x2000\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
196,730
<p>I need to extract only the 2nd level part of the domain from request.servervariables("HTTP_HOST") what is the best way to do this?</p>
[ { "answer_id": 196752, "author": "Brian Boatright", "author_id": 3747, "author_profile": "https://Stackoverflow.com/users/3747", "pm_score": 1, "selected": false, "text": "If Len(strHostDomain) > 0 Then \n aryDomain = Split(strHostDomain,\".\")\n\n If uBound(aryDomain) >= 1 Then\n str2ndLevel = aryDomain(uBound(aryDomain)-1)\n strTopLevel = aryDomain(uBound(aryDomain)) \n strDomainOnly = str2ndLevel & \".\" & strTopLevel\n End If\nEnd If\n" }, { "answer_id": 196907, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": true, "text": "HTTP_HOST 3.2.1 .com .de .co.uk co ^(.*?)\\.? (\\w+)\\. (\\w{2,}(?:\\.\\w{2})?)$ Dim re, matches, match\n\nSet re = New RegExp\n\nre.Pattern = \"^(.*?)\\.?(\\w+)\\.(\\w{2,}(?:\\.\\w{2})?)$\"\n\nSet matches = re.Execute( Request.ServerVariables(\"HTTP_HOST\") )\n\nIf matches.Count = 1 Then\n Set match = matches(0)\n\n ' assuming \"images.res.somedomain.co.uk\"\n Response.Write match.SubMatches(0) & \"<br>\" ' will be \"images.res\"\n Response.Write match.SubMatches(1) & \"<br>\" ' will be \"somedomain\"\n Response.Write match.SubMatches(2) & \"<br>\" ' will be \"co.uk\"\n\n ' assuming \"somedomain.com\"\n Response.Write match.SubMatches(0) & \"<br>\" ' will be \"\"\n Response.Write match.SubMatches(1) & \"<br>\" ' will be \"somedomain\"\n Response.Write match.SubMatches(2) & \"<br>\" ' will be \"com\"\nElse\n ' You have an IP address in HTTP_HOST\nEnd If\n" }, { "answer_id": 207164, "author": "defeated", "author_id": 16997, "author_profile": "https://Stackoverflow.com/users/16997", "pm_score": -1, "selected": false, "text": "'example: sample.com\n'example: sample.co.uk\nhost = split(request.serverVariables(\"HTTP_HOST\"), \".\")\nhost(0) = \"\" 'clear the \"sample\" part\n\nextension = join(host, \".\") 'put it back together, \".com\" or \".co.uk\"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
196,732
<p>I've inherited a piece of code with a snippet which empties the database as follows:</p> <pre><code>dbmopen (%db,"file.db",0666); foreach $key (keys %db) { delete $db{$key}; } dbmclose (%db); </code></pre> <p>This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.</p> <p>Is there a better way of doing this?</p>
[ { "answer_id": 196816, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "dbmopen (%db,\"file.db\",0666);\n%db = ();\ndbmclose (%db);\n" }, { "answer_id": 196884, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "unlink (\"file.db\");\ndbmopen (%db,\"file.db\",0666);\ndbmclose (%db);\n" }, { "answer_id": 197696, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": true, "text": "unlink $file;\n undef dbmopen dbmopen my %db, $file, 0666;\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14860/" ]
196,733
<p>I have code like this:</p> <pre><code>class RetInterface {...} class Ret1: public RetInterface {...} class AInterface { public: virtual boost::shared_ptr&lt;RetInterface&gt; get_r() const = 0; ... }; class A1: public AInterface { public: boost::shared_ptr&lt;Ret1&gt; get_r() const {...} ... }; </code></pre> <p><strong>This code does not compile.</strong></p> <p>In visual studio it raises</p> <blockquote> <p>C2555: overriding virtual function return type differs and is not covariant</p> </blockquote> <p>If I do not use <code>boost::shared_ptr</code> but return raw pointers, the code compiles (I understand this is due to <a href="http://en.wikipedia.org/wiki/Parameter_covariance#C.2B.2B" rel="noreferrer">covariant return types</a> in C++). I can see the problem is because <code>boost::shared_ptr</code> of <code>Ret1</code> is not derived from <code>boost::shared_ptr</code> of <code>RetInterface</code>. But I want to return <code>boost::shared_ptr</code> of <code>Ret1</code> for use in other classes, else I must cast the returned value after the return. </p> <ol> <li>Am I doing something wrong? </li> <li>If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?</li> </ol>
[ { "answer_id": 196744, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "A1::get_r boost::shared_ptr<RetInterface>" }, { "answer_id": 197157, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 6, "selected": true, "text": "shared_ptr RetInterface get_r virtual AInterface A1 get_r1 A1 class A1: public AInterface\n{\n public:\n boost::shared_ptr<RetInterface> get_r() const\n {\n return get_r1();\n }\n boost::shared_ptr<Ret1> get_r1() const {...}\n ...\n};\n" }, { "answer_id": 970078, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": " void get_r_to(boost::shared_ptr<RetInterface>& ) ...\n" }, { "answer_id": 16069528, "author": "morabot", "author_id": 2292452, "author_profile": "https://Stackoverflow.com/users/2292452", "pm_score": 1, "selected": false, "text": "template<typename Derived, typename Base>\nclass SharedCovariant : public shared_ptr<Base>\n{\npublic:\n\ntypedef Base BaseOf;\n\nSharedCovariant(shared_ptr<Base> & container) :\n shared_ptr<Base>(container)\n{\n}\n\nshared_ptr<Derived> operator ->()\n{\n return boost::dynamic_pointer_cast<Derived>(*this);\n}\n};\n struct A {};\n\nstruct B : A {};\n\nstruct Test\n{\n shared_ptr<A> get() {return a_; }\n\n shared_ptr<A> a_;\n};\n\ntypedef SharedCovariant<B,A> SharedBFromA;\n\nstruct TestDerived : Test\n{\n SharedBFromA get() { return a_; }\n};\n" }, { "answer_id": 32529006, "author": "Grégory MALLET", "author_id": 4512497, "author_profile": "https://Stackoverflow.com/users/4512497", "pm_score": 1, "selected": false, "text": "template<class T>\nclass Child : public T\n{\npublic:\n typedef T Parent;\n};\n\ntemplate<typename _T>\nclass has_parent\n{\nprivate:\n typedef char One;\n typedef struct { char array[2]; } Two;\n\n template<typename _C>\n static One test(typename _C::Parent *);\n template<typename _C>\n static Two test(...);\n\npublic:\n enum { value = (sizeof(test<_T>(nullptr)) == sizeof(One)) };\n};\n\nclass A\n{\npublic :\n virtual void print() = 0;\n};\n\nclass B : public Child<A>\n{\npublic:\n void print() override\n {\n printf(\"toto \\n\");\n }\n};\n\ntemplate<class T, bool hasParent = has_parent<T>::value>\nclass ICovariantSharedPtr;\n\ntemplate<class T>\nclass ICovariantSharedPtr<T, true> : public ICovariantSharedPtr<typename T::Parent>\n{\npublic:\n T * get() override = 0;\n};\n\ntemplate<class T>\nclass ICovariantSharedPtr<T, false>\n{\npublic:\n virtual T * get() = 0;\n};\n\ntemplate<class T>\nclass CovariantSharedPtr : public ICovariantSharedPtr<T>\n{\npublic:\n CovariantSharedPtr(){}\n\n CovariantSharedPtr(std::shared_ptr<T> a_ptr) : m_ptr(std::move(a_ptr)){}\n\n T * get() final\n {\n return m_ptr.get();\n }\nprivate:\n std::shared_ptr<T> m_ptr;\n};\n class UseA\n{\npublic:\n virtual ICovariantSharedPtr<A> & GetPtr() = 0;\n};\n\nclass UseB : public UseA\n{\npublic:\n CovariantSharedPtr<B> & GetPtr() final\n {\n return m_ptrB;\n }\nprivate:\n CovariantSharedPtr<B> m_ptrB = std::make_shared<B>();\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n UseB b;\n UseA & a = b;\n a.GetPtr().get()->print();\n}\n Child Parent Child<T> T T Parent has_parent Parent CovariantSharedPtr<B> ICovariantSharedPtr<B> ICovariantSharedPtr<B, has_parent<B>::value> B Child<A> has_parent<B>::value ICovariantSharedPtr<B> ICovariantSharedPtr<B, true> ICovariantSharedPtr<B::Parent> ICovariantSharedPtr<A> A Parent has_parent<A>::value ICovariantSharedPtr<A> ICovariantSharedPtr<A, false> B A ICovariantSharedPtr<B> ICovariantSharedPtr<A> ICovariantSharedPtr<A> ICovariantSharedPtr<B>" }, { "answer_id": 56542651, "author": "Bruce Adams", "author_id": 1569204, "author_profile": "https://Stackoverflow.com/users/1569204", "pm_score": 3, "selected": false, "text": "template <typename Derived, typename Base>\nclass clone_inherit<Derived, Base> : public Base\n{\npublic:\n std::unique_ptr<Derived> clone() const\n {\n return std::unique_ptr<Derived>(static_cast<Derived *>(this->clone_impl()));\n }\n \nprivate:\n virtual clone_inherit * clone_impl() const override\n {\n return new Derived(*this);\n }\n};\n\nclass concrete: public clone_inherit<concrete, cloneable>\n{\n};\n\nint main()\n{\n std::unique_ptr<concrete> c = std::make_unique<concrete>();\n std::unique_ptr<concrete> cc = c->clone();\n \n cloneable * p = c.get();\n std::unique_ptr<clonable> pp = p->clone();\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19501/" ]
196,737
<p>I've been working with the Joomla framework and I have noticed that they use a convention to designate private or protected methods (they put an underscore "<code>_</code>" in front of the method name), but they do not explicitly declare any methods <code>public</code>, <code>private</code>, or <code>protected</code>. Why is this? Does it have to do with portability? Are the <code>public</code>, <code>private</code>, or <code>protected</code> keywords not available in older versions of PHP?</p>
[ { "answer_id": 4299774, "author": "naught101", "author_id": 210945, "author_profile": "https://Stackoverflow.com/users/210945", "pm_score": 2, "selected": false, "text": "private" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831/" ]
196,741
<p>How are arrays manipulated in D?</p>
[ { "answer_id": 196799, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "int[7] a;\nint[] b;\nb = a[5..7];\n int[7] a;\nint[2] b;\nb[0..1] = a[5..7];\n" }, { "answer_id": 269166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "int[7] a;\nint[] b;\nb = a[5..7].dup;\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
196,754
<p>I've seen some horrific code written in Perl, but I can't make head nor tail of this one:</p> <pre><code>select((select(s),$|=1)[0]) </code></pre> <p>It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets <code>$|</code>).</p> <p>But I can't figure out why there's multiple <code>select</code> calls or the array reference. Can anyone help me out?</p>
[ { "answer_id": 196768, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 7, "selected": true, "text": "select() (select($s),$|=1) select $| = 1 (...)[0] select select use IO::Handle;\n$fh->autoflush;\n" }, { "answer_id": 196769, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 3, "selected": false, "text": "s perldoc -f select" }, { "answer_id": 197687, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": false, "text": "( select(s), $|=1 )\n s $| $| select ( PREVIOUS_DEFAULT, 1 )[0]\n select select( PREVIOUS_DEFAULT );\n $|" }, { "answer_id": 200096, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "for ( select $fh ) { $| = 1; select $_ }\n $_ for my $prevfh ( select $fh ) { $| = 1; select $prevfh }\n $prevfh for $_" }, { "answer_id": 2287544, "author": "ghostdog74", "author_id": 131527, "author_profile": "https://Stackoverflow.com/users/131527", "pm_score": 2, "selected": false, "text": "$|" }, { "answer_id": 2287567, "author": "kennytm", "author_id": 224671, "author_profile": "https://Stackoverflow.com/users/224671", "pm_score": 4, "selected": false, "text": "select($fh)\n (select($fh), $|=1)\n (select($fh), $|=1)[0]\n select((select($fh), $|=1)[0])\n select $oldfh = select($fh);\n$| = 1;\nselect($oldfh);\n use IO::Handle;\n$fh->autoflush(1);\n" }, { "answer_id": 2287632, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 2, "selected": false, "text": "use IO::Handle;\n$fh->autoflush(1);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14860/" ]
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
[ { "answer_id": 196763, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<h3><a href=\"/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150\" class=\"answer-title\">What are the best RSS feeds for programmers/developers?</a></h3>\n" }, { "answer_id": 196851, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 4, "selected": true, "text": ">>> from urllib import urlencode\n>>> params = urlencode({'q': 'python best practices', 'sort': 'relevance'})\n>>> params\n'q=python+best+practices&sort=relevance'\n>>> from urllib2 import urlopen\n>>> html = urlopen(\"http://stackoverflow.com/search?%s\" % params).read()\n>>> import re\n>>> links = re.findall(r'<h3><a href=\"([^\"]*)\" class=\"answer-title\">([^<]*)</a></h3>', html)\n>>> links\n[('/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &#8220;pythonian&#8221; or &#8220;pythonic&#8221;?'), ('/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]\n>>> from urlparse import urljoin\n>>> links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links]\n>>> links\n[('http://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('http://stackoverflow.com/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &#8220;pythonian&#8221; or &#8220;pythonic&#8221;?'), ('http://stackoverflow.com/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('http://stackoverflow.com/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('http://stackoverflow.com/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]\n def get_stackoverflow(query):\n import urllib, urllib2, re, urlparse\n params = urllib.urlencode({'q': query, 'sort': 'relevance'})\n html = urllib2.urlopen(\"http://stackoverflow.com/search?%s\" % params).read()\n links = re.findall(r'<h3><a href=\"([^\"]*)\" class=\"answer-title\">([^<]*)</a></h3>', html)\n links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links]\n\n return links\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
[ { "answer_id": 196783, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": -1, "selected": false, "text": "function escape_string($text, $type) {\n // Escape backslashes for all types of strings?\n $text = str_replace('\\\\', '\\\\\\\\', $text);\n\n switch($type) {\n case 'single':\n $text = str_replace(\"'\", \"\\\\'\", $text);\n break;\n case 'double':\n $text = str_replace('\"', '\\\\\"', $text);\n break;\n // etc...\n }\n\n return $text;\n}\n" }, { "answer_id": 200315, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 3, "selected": true, "text": "repr() <?php\n\nfunction py_escape($input) {\n $descriptorspec = array(\n 0 => array(\"pipe\", \"r\"),\n 1 => array(\"pipe\", \"w\")\n );\n $process = proc_open(\n \"python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'\",\n $descriptorspec, $pipes);\n fwrite($pipes[0], $input);\n fclose($pipes[0]);\n $chunk_size = 8192;\n $escaped = fread($pipes[1], $chunk_size);\n if (strlen($escaped) == $chunk_size) {\n // This is important for security.\n die(\"That string's too big.\\n\");\n }\n proc_close($process);\n return $escaped;\n}\n\n// Example usage:\n$x = \"string \\rfull \\nof\\t crappy stuff\";\nprint py_escape($x);\n chunk_size (\"hello \" + (\".\" * chunk_size)) '; os.system(\"do bad stuff\") system() os.system(map(chr, ...))" }, { "answer_id": 1813364, "author": "Christopher Gutteridge", "author_id": 220559, "author_profile": "https://Stackoverflow.com/users/220559", "pm_score": 0, "selected": false, "text": "function python_string_escape( $string ) {\n $string = preg_replace( \"/\\\\\\\\/\", \"\\\\\\\\\", $string ); # \\\\ (first to avoid string re-escaping)\n $string = preg_replace( \"/\\n/\", \"\\\\n\", $string ); # \\n\n $string = preg_replace( \"/\\r/\", \"\\\\r\", $string ); # \\r \n $string = preg_replace( \"/\\t/\", \"\\\\t\", $string ); # \\t \n $string = preg_replace( \"/\\\"/\", \"\\\\\\\"\", $string ); # \\\"\n $string = preg_replace( \"/([\\x{00}-\\x{1F}]|[\\x{7F}-\\x{FFFF}])/ue\",\n \"sprintf(\\\"\\\\u%04X\\\",uniord(\\\"$1\\\"))\",\n $string );\n return $string;\n}\n\nfunction uniord($c) {\n $h = ord($c{0});\n if ($h <= 0x7F) {\n return $h;\n } else if ($h < 0xC2) {\n return false;\n } else if ($h <= 0xDF) {\n return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);\n } else if ($h <= 0xEF) {\n return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);\n } else if ($h <= 0xF4) {\n return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);\n } else {\n return false;\n }\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3528/" ]
196,776
<p>I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the <a href="http://rubyforge.org/projects/ruby-aes" rel="nofollow noreferrer">ruby-aes</a> gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?</p> <p>Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)</p>
[ { "answer_id": 196794, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 1, "selected": false, "text": "f = open('/path/to/file', 'rb')\n f = open('/path/to/file', 'wb')\nf.write(encrypted_data)\n" }, { "answer_id": 196896, "author": "HughE", "author_id": 7875, "author_profile": "https://Stackoverflow.com/users/7875", "pm_score": 2, "selected": false, "text": "IV AES.new() mode AES.new() IV mode" }, { "answer_id": 197520, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 1, "selected": false, "text": "puts" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
196,788
<p>I'm trying to implement search result highlighting for pdfs in a web app. I have the original pdfs, and small png versions that are used in search results. Essentially I'm looking for an api like:</p> <pre><code>pdf_document.find_offsets('somestring') # =&gt; { top: 501, left: 100, bottom: 520, right: 150 }, { ... another box ... }, ... </code></pre> <p>I know it's possible to get this information out of a pdf because Apple's Preview.app implements this.</p> <p>Need something that runs on Linux and ideally is open source. I'm aware you can do this with acrobat on windows.</p>
[ { "answer_id": 203553, "author": "Chris Dolan", "author_id": 14783, "author_profile": "https://Stackoverflow.com/users/14783", "pm_score": 2, "selected": false, "text": "use CAM::PDF;\nmy $pdf = CAM::PDF->new('my.pdf') or die $CAM::PDF::errstr;\nfor my $pagenum (1 .. $pdf->numPages) {\n my $pagetree = $pdf->getPageContentTree($pagenum) or die;\n my @text = $pagetree->traverse('MyRenderer')->getTextBlocks;\n for my $textblock (@text) {\n print \"text '$textblock->{str}' at \",\n \"($textblock->{left},$textblock->{bottom})\\n\";\n }\n}\n\npackage MyRenderer;\nuse base 'CAM::PDF::GS';\n\nsub new {\n my ($pkg, @args) = @_;\n my $self = $pkg->SUPER::new(@args);\n $self->{refs}->{text} = [];\n return $self;\n}\nsub getTextBlocks {\n my ($self) = @_;\n return @{$self->{refs}->{text}};\n}\nsub renderText {\n my ($self, $string, $width) = @_;\n my ($x, $y) = $self->textToDevice(0,0);\n push @{$self->{refs}->{text}}, {\n str => $string,\n left => $x,\n bottom => $y,\n right => $x + $width,\n #top => $y + ???, \n };\n return;\n}\n text 'E' at (52.08,704.16)\ntext 'm' at (73.62096,704.16)\ntext 'p' at (113.58936,704.16)\ntext 'lo' at (140.49648,704.16)\ntext 'y' at (181.19904,704.16)\ntext 'e' at (204.43584,704.16)\ntext 'e' at (230.93808,704.16)\ntext ' N' at (257.44032,704.16)\ntext 'a' at (294.6504,704.16)\ntext 'm' at (320.772,704.16)\ntext 'e' at (360.7416,704.16)\ntext 'Employee Name' at (56.4,124.56)\ntext 'Employee Title' at (56.4,114.24)\ntext 'Company Name' at (56.4,103.92)\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3624/" ]
196,820
<p>I need a cross-platform editor control to use as GUI-part in an in-house tool. The control may be commercial, but with reasonable price.</p> <p>Required features:</p> <ul> <li>Platforms: Win32, OS X, Linux</li> <li>UTF-8 support</li> <li>Fine-grained run-time control to the text style (or at least color)</li> <li>Nice low-level plain C API without usual horrible bloat</li> <li>Should not prevent me to have these features (even if I'll have to implement them myself): <ul> <li>Undo / Redo</li> <li>Copy / Paste</li> <li>Context menu, depending on click position in text</li> <li>Toolbar, depending on cursor position in text</li> <li>Sidebar panel, depending on cursor position in text</li> </ul></li> </ul> <p>Actually above requires not simple control, but whole cross-platform GUI library.</p> <p>Discarded options:</p> <ul> <li>Scintilla and descendants</li> <li>FLTK</li> <li>Fox-toolkit</li> <li>gtksourceview</li> </ul> <p><strong>Update:</strong> </p> <p>Note: I've slipped in some half-written discard reasoning here, I apologize. Scintilla indeed does work on OS X. However, if I get it correctly, Scintilla's API is in C++. </p> <p>Use-case:</p> <p>My use-case is to write custom "semi-rigid" logic editor, where user is free to copy-paste around, add comments where he wishes, even type in text directly if he wish. But text structure is a rigid natural language representation of logic tree (somewhat AST-like in nature). I plan to write something intellisense-like (or code-template-like) to be used as the main authoring tool (instead of typing logic by hand).</p> <p>BTW, storage format would not be plain text, but instead internal representation of mentioned logic tree (with comments and whitespaces etc. metainfo).</p> <p>So, I have all necessary information to render text in needed colors by myself. I do not need any external lexers etc.</p>
[ { "answer_id": 196856, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "GtkTextView QTextEdit" }, { "answer_id": 197714, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "scintilla->WndProc(SCI_STYLESETFORE, 0, 0x808080);" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236/" ]
196,824
<p>How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is: abcdefghizzzzjklmnop azzbcdefghijklmnop</p> <p>My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"</p> <pre><code>class Test { public static void main(String[] args) { System.out.println(args[0]); } } </code></pre> <p>The command I have been using throws an array out of bound exception. This command is:</p> <blockquote> <blockquote> <p>java Test &lt; input.txt</p> </blockquote> </blockquote> <p>Non-file based arguments work fine though. ie. java Test hello,a nd java Test &lt; input.txt hello. </p> <p>More information: I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help. </p> <p>Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).</p> <p>Any help?</p>
[ { "answer_id": 196831, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "System.in javac Test.java; java Test < Test.java class Test\n{\n public static void main (String[] args)\n {\n byte[] bytes = new byte[1024];\n try\n {\n while (System.in.available() > 0)\n {\n int read = System.in.read (bytes, 0, 1024);\n System.out.write (bytes, 0, read);\n }\n } catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
196,830
<p>Some ways to iterate through the characters of a string in Java are:</p> <ol> <li>Using <code>StringTokenizer</code>?</li> <li>Converting the <code>String</code> to a <code>char[]</code> and iterating over that.</li> </ol> <p>What is the easiest/best/most correct way to iterate?</p>
[ { "answer_id": 196834, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 10, "selected": true, "text": "charAt() charAt() String s = \"...stuff...\";\n\nfor (int i = 0; i < s.length(); i++){\n char c = s.charAt(i); \n //Process char\n}\n" }, { "answer_id": 196842, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 2, "selected": false, "text": "StringTokenizer StringTokenizer String java.util.regex" }, { "answer_id": 196858, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 0, "selected": false, "text": "public class StringDemo {\n public static void main(String[] args) {\n String palindrome = \"Dot saw I was Tod\";\n int len = palindrome.length();\n char[] tempCharArray = new char[len];\n char[] charArray = new char[len];\n\n // put original string in an array of chars\n for (int i = 0; i < len; i++) {\n tempCharArray[i] = palindrome.charAt(i);\n } \n\n // reverse array of chars\n for (int j = 0; j < len; j++) {\n charArray[j] = tempCharArray[len - 1 - j];\n }\n\n String reversePalindrome = new String(charArray);\n System.out.println(reversePalindrome);\n }\n}\n int len for" }, { "answer_id": 196866, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 4, "selected": false, "text": "import java.text.*;\n\nfinal CharacterIterator it = new StringCharacterIterator(s);\nfor(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {\n // process c\n ...\n}\n" }, { "answer_id": 196975, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 8, "selected": false, "text": "for(int i = 0, n = s.length() ; i < n ; i++) { \n char c = s.charAt(i); \n}\n for(char c : s.toCharArray()) {\n // process c\n}\n" }, { "answer_id": 197390, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "String#split() String[] theChars = str.split(\"|\");\n StringTokenizer st = new StringTokenizer(str, str, true);\n" }, { "answer_id": 360930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": " int count = 1000;\n ...\n\n System.out.println(\"Test 1: charAt + String\");\n long t = System.currentTimeMillis();\n int sum=0;\n for (int i=0; i<count; i++) {\n int len = str.length();\n for (int j=0; j<len; j++) {\n if (str.charAt(j) == 'b')\n sum = sum + 1;\n }\n }\n t = System.currentTimeMillis()-t;\n System.out.println(\"result: \"+ sum + \" after \" + t + \"msec\");\n" }, { "answer_id": 361345, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 7, "selected": false, "text": "String str = \"....\";\nint offset = 0, strLen = str.length();\nwhile (offset < strLen) {\n int curChar = str.codePointAt(offset);\n offset += Character.charCount(curChar);\n // do something with curChar\n}\n Character.charCount(int)" }, { "answer_id": 5233839, "author": "Touko", "author_id": 28482, "author_profile": "https://Stackoverflow.com/users/28482", "pm_score": 4, "selected": false, "text": "for(char c : Lists.charactersOf(yourString)) {\n // Do whatever you want \n}\n CharSequence#chars yourString.chars()\n .mapToObj(c -> Character.valueOf((char) c))\n .forEach(c -> System.out.println(c)); // Or whatever you want\n" }, { "answer_id": 27796856, "author": "Alex - GlassEditor.com", "author_id": 3179759, "author_profile": "https://Stackoverflow.com/users/3179759", "pm_score": 4, "selected": false, "text": "String CharSequence#codePoints for(int c : string.codePoints().toArray()){\n ...\n}\n string.codePoints().forEach(c -> ...);\n CharSequence#chars IntStream CharStream" }, { "answer_id": 40444598, "author": "Hawkeye Parker", "author_id": 99717, "author_profile": "https://Stackoverflow.com/users/99717", "pm_score": 0, "selected": false, "text": " String supplementary = \"Some Supplementary: \";\n supplementary.codePoints().forEach(cp -> \n System.out.print(new String(Character.toChars(cp))));\n" }, { "answer_id": 42805927, "author": "devDeejay", "author_id": 6145568, "author_profile": "https://Stackoverflow.com/users/6145568", "pm_score": 0, "selected": false, "text": "import java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class Solution {\n public static void main(String[] args) {\n HashMap<String, Integer> map = new HashMap<String, Integer>();\n map.put(\"a\", 10);\n map.put(\"b\", 30);\n map.put(\"c\", 50);\n map.put(\"d\", 40);\n map.put(\"e\", 20);\n System.out.println(map);\n\n Map sortedMap = sortByValue(map);\n System.out.println(sortedMap);\n }\n\n public static Map sortByValue(Map unsortedMap) {\n Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));\n sortedMap.putAll(unsortedMap);\n return sortedMap;\n }\n\n}\n\nclass ValueComparator implements Comparator {\n Map map;\n\n public ValueComparator(Map map) {\n this.map = map;\n }\n\n public int compare(Object keyA, Object keyB) {\n Comparable valueA = (Comparable) map.get(keyA);\n Comparable valueB = (Comparable) map.get(keyB);\n return valueB.compareTo(valueA);\n }\n}\n" }, { "answer_id": 47736566, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 5, "selected": false, "text": "String str = \"xyz\";\nstr.chars().forEachOrdered(i -> System.out.print((char)i));\nstr.codePoints().forEachOrdered(i -> System.out.print((char)i));\n IntStream codePoints() IntStream char char char char forEachOrdered forEach forEach forEachOrdered forEach" }, { "answer_id": 53912454, "author": "Enyby", "author_id": 1504248, "author_profile": "https://Stackoverflow.com/users/1504248", "pm_score": 2, "selected": false, "text": "int tmp = 0;\nString s = new String(new byte[64*1024]);\n{\n long st = System.nanoTime();\n for(int i = 0, n = s.length(); i < n; i++) {\n tmp += s.charAt(i);\n }\n st = System.nanoTime() - st;\n System.out.println(\"1 \" + st);\n}\n\n{\n long st = System.nanoTime();\n char[] ch = s.toCharArray();\n for(int i = 0, n = ch.length; i < n; i++) {\n tmp += ch[i];\n }\n st = System.nanoTime() - st;\n System.out.println(\"2 \" + st);\n}\n{\n long st = System.nanoTime();\n for(char c : s.toCharArray()) {\n tmp += c;\n }\n st = System.nanoTime() - st;\n System.out.println(\"3 \" + st);\n}\nSystem.out.println(\"\" + tmp);\n 1 10349420\n2 526130\n3 484200\n0\n 1 9122107\n2 13486911\n3 12700778\n0\n" }, { "answer_id": 61562687, "author": "Sumit Kapoor", "author_id": 4184808, "author_profile": "https://Stackoverflow.com/users/4184808", "pm_score": 0, "selected": false, "text": "String s = sc.next() // assuming scanner class is defined above\nfor(int i=0; i<s.length(); i++){\n s.charAt(i) // This being the first way and is a constant time operation will hardly add any overhead\n }\n\nchar[] str = new char[10];\nstr = s.toCharArray() // this is another way of doing so and it takes O(n) amount of time for copying contents from your string class to the character array\n" }, { "answer_id": 71684064, "author": "unpluggeDloop", "author_id": 12247187, "author_profile": "https://Stackoverflow.com/users/12247187", "pm_score": 1, "selected": false, "text": "public class Main {\n\npublic static void main(String[] args) {\n String myStr = \"Hello\";\n String myStr2 = \"World\";\n \n for (int i = 0; i < myStr.length(); i++) { \n char result = myStr.charAt(i);\n System.out.println(result);\n } \n \n for (int i = 0; i < myStr2.length(); i++) { \n char result = myStr2.charAt(i);\n System.out.print(result); \n } \n }\n}\n H\ne\nl\nl\no\nWorld\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
196,840
<p>I am looking for a way to add a drop down list in WPF to a menu. This used to be really easy in winforms and so I am expecting you experts to know just now to do it in WPF. Thanks.</p> <p>Sorry if this is a bad question, it is late and I don't want to think.</p>
[ { "answer_id": 196873, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 6, "selected": true, "text": "<Menu>\n <MenuItem Header=\"File\">\n <MenuItem Header=\"Open\"/>\n <MenuItem Header=\"Close\"/>\n <Separator/>\n <ComboBox Width=\"85\" Height=\"21.96\" />\n </MenuItem>\n</Menu>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22914/" ]
196,841
<p>In Python, you can do this:</p> <pre><code>print &quot;Hi! I'm %(name)s, and I'm %(age)d years old.&quot; % ({&quot;name&quot;:&quot;Brian&quot;,&quot;age&quot;:30}) </code></pre> <p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p> <p>One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a &quot;template&quot;, like so:</p> <pre><code>template = &quot;Hi! I'm %(name)s, and I'm %(age)d years old.&quot; def greet(template,name,age): print template % ({&quot;name&quot;:name,&quot;age&quot;:age}) </code></pre> <p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>&quot;Hi! I'm #{name}&quot;</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p>
[ { "answer_id": 196847, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "puts \"Hi! I'm #{name}, and I'm #{age} years old.\"\n" }, { "answer_id": 196854, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 3, "selected": false, "text": "name = \"Peter\"\n@age = 15 # instance variable\nputs \"Hi, you are #{name} and your age is #@age\"\n" }, { "answer_id": 198795, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 2, "selected": false, "text": " class Template\n\n def %(h)\n \"Hi! I'm #{h[:name]}s, and I'm #{h[:age]}d years old.\"\n\n\n end\nend\n t=Template.new\nt%({:name => \"Peter\", :age => 18})\n" }, { "answer_id": 12562639, "author": "mdik", "author_id": 1694005, "author_profile": "https://Stackoverflow.com/users/1694005", "pm_score": 2, "selected": false, "text": "d = {\"key1\" => \"value1\", \"key2\" => \"value2\"}\ns = \"string to be magically induced with variables, which are \\n * %s and \\n * %s.\\n\"\nprint s%d.values()\n# or\nprint s%[d[\"key1\"], d[\"key2\"]]\n" }, { "answer_id": 12563022, "author": "knut", "author_id": 676874, "author_profile": "https://Stackoverflow.com/users/676874", "pm_score": 5, "selected": true, "text": "printf \"1: %<key1>s 2: %<key2>s\\n\", {:key1 => \"value1\", :key2 => \"value2\"}\n data = {:key1 => \"value1\", :key2 => \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\", data\n data = {key1: \"value1\", key2: \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\", data\n 1: value1 2: value2\n printf String#% printf \"1: %<key1>s 2: %<key2>s\\n\" , {:key1 => \"value1\", :key2 => \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\" % {:key1 => \"value1\", :key2 => \"value2\"}\nprint \"1: %<key1>s 2: %<key2>s\\n\" % {:key1 => \"value1\", :key2 => \"value2\"}\nputs \"1: %<key1>s 2: %<key2>s\" % {:key1 => \"value1\", :key2 => \"value2\"}\n String#% printf" }, { "answer_id": 13027855, "author": "Michael Kruglos", "author_id": 1767938, "author_profile": "https://Stackoverflow.com/users/1767938", "pm_score": 4, "selected": false, "text": "values = {:hello => 'world', :world => 'hello'}\nputs \"%{world} %{hello}\" % values\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
196,859
<p>I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button</p>
[ { "answer_id": 196916, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <script type=\"text/javascript\">\n function mkclr(cntl,clr) {\n document.getElementById(cntl).style.backgroundColor = clr;\n };\n </script>\n </head>\n <body>\n <form>\n <input type=\"textbox\" id=\"tb1\"></input>\n <input type=\"submit\" value=\"Go\"\n onClick=\"javascript:mkclr('tb1','red');\">\n </input>\n </form>\n </body>\n</html>\n" }, { "answer_id": 196987, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": false, "text": "<asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" ErrorMessage=\"\"\n ControlToValidate=\"TextBox1\" ClientValidationFunction=\"ValidateTextBox\"\n OnServerValidate=\"CustomValidator1_ServerValidate\"\n ValidateEmptyText=\"True\"></asp:CustomValidator>\n\n<asp:TextBox ID=\"TextBox1\" runat=\"server\"></asp:TextBox>\n\n<script src=\"jquery-1.2.6.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n function ValidateTextBox(source, args)\n {\n var is_valid = $(\"#TextBox1\").val() != \"\";\n $(\"#TextBox1\").css(\"background-color\", is_valid ? \"white\" : \"red\");\n args.IsValid = is_valid;\n }\n</script>\n protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)\n{\n bool is_valid = TextBox1.Text != \"\";\n TextBox1.BackColor = is_valid ? Color.White : Color.Red;\n args.IsValid = is_valid;\n}\n" }, { "answer_id": 2472593, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 5, "selected": false, "text": "function fnOnUpdateValidators()\n{\n for (var i = 0; i < Page_Validators.length; i++)\n {\n var val = Page_Validators[i];\n var ctrl = document.getElementById(val.controltovalidate);\n if (ctrl != null && ctrl.style != null)\n {\n if (!val.isvalid)\n ctrl.style.background = '#FFAAAA';\n else\n ctrl.style.backgroundColor = '';\n }\n }\n}\n Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, \"val\", \"fnOnUpdateValidators();\")\n Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), \"val\", \"fnOnUpdateValidators();\");\n" }, { "answer_id": 2529532, "author": "Steve Krile", "author_id": 303199, "author_profile": "https://Stackoverflow.com/users/303199", "pm_score": 2, "selected": false, "text": " function ValidateTextBox(source, args) {\n var cntrl_id = $(source).attr(\"controltovalidate\");\n var cntrl = $(\"#\" + cntrl_id);\n var is_valid = $(cntrl).val() != \"\";\n is_valid ? $(cntrl).removeClass(\"error\") : $(cntrl).addClass(\"error\");\n\n args.IsValid = is_valid;\n }\n" }, { "answer_id": 3157714, "author": "Lilja", "author_id": 303998, "author_profile": "https://Stackoverflow.com/users/303998", "pm_score": 1, "selected": false, "text": "protected void cvPhone_ServerValidate(object source, ServerValidateEventArgs args)\n{\n bool is_valid = !string.IsNullOrEmpty(args.Value);\n string control = ((CustomValidator)source).ControlToValidate;\n ((TextBox)this.Master.FindControl(\"ContentBody\").FindControl(control)).CssClass = is_valid ? string.Empty : \"inputError\";\n args.IsValid = is_valid;\n}\n" }, { "answer_id": 7110062, "author": "MJ Hufford", "author_id": 274449, "author_profile": "https://Stackoverflow.com/users/274449", "pm_score": 2, "selected": false, "text": "function validateFields() {\n try {\n var count = 0;\n var hasFocus = false;\n\n for (var i = 0; i < Page_Validators.length; i++) {\n var val = Page_Validators[i];\n var ctrl = document.getElementById(val.controltovalidate);\n\n validateField(ctrl, val);\n\n if (!val.isvalid) { count++; }\n if (!val.isvalid && hasFocus === false) {\n ctrl.focus(); hasFocus = true;\n }\n }\n\n if (count == 0) {\n hasFocus = false;\n }\n }\n catch (err) { }\n}\n\nfunction validateField(ctrl, val)\n{\n $(ctrl).blur(function () { validateField(ctrl, val); });\n\n if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null\n val.isvalid ? $(ctrl).removeClass(\"error\") : $(ctrl).addClass(\"error\");\n } \n\n if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox\n var rtxt = document.getElementById(val.controltovalidate + '_text');\n val.isvalid ? $(rtxt).removeClass(\"error\") : $(rtxt).addClass(\"error\");\n }\n}\n" }, { "answer_id": 8279074, "author": "Bala", "author_id": 1066980, "author_profile": "https://Stackoverflow.com/users/1066980", "pm_score": 1, "selected": false, "text": "$(document).ready(function() {\n HighlightControlToValidate();\n $('#<%=btnSave.ClientID %>').click(function() {\n if (typeof (Page_Validators) != \"undefined\") {\n for (var i = 0; i < Page_Validators.length; i++) {\n if (!Page_Validators[i].isvalid) {\n $('#' + Page_Validators[i].controltovalidate).css(\"background\", \"#f3d74f\");\n }\n else {\n $('#' + Page_Validators[i].controltovalidate).css(\"background\", \"white\");\n }\n }\n }\n });\n});\n" }, { "answer_id": 10829154, "author": "Thomas_King", "author_id": 1427732, "author_profile": "https://Stackoverflow.com/users/1427732", "pm_score": 2, "selected": false, "text": "<asp:CustomValidator ID=\"CustomValidatorMyTextBox\" runat=\"server\" ErrorMessage=\"\"\n Display=\"None\" ClientValidationFunction=\"ValidateInput\" \n ControlToValidate=\"MyTextBox\" ValidateEmptyText=\"true\" \n ValidationGroup=\"MyValidationGroup\">\n </asp:CustomValidator>\n <script type=\"text/javascript\">\n function ValidateInput(source, args)\n {\n var controlName = source.controltovalidate;\n var control = $('#' + controlName);\n if (control.is('input:text')) {\n if (control.val() == \"\") {\n control.addClass(\"validation\");\n args.IsValid = false;\n }\n else {\n control.removeClass(\"validation\");\n args.IsValid = true;\n }\n }\n else if (control.is('select')) {\n if (control.val() == \"-1\"[*] ) {\n control.addClass(\"validation\");\n args.IsValid = false;\n }\n else {\n control.removeClass(\"validation\");\n args.IsValid = true;\n }\n }\n }\n </script>\n .validation { border: solid 2px red; }\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />" }, { "answer_id": 11954218, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 4, "selected": false, "text": " /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).closest('.control-group').removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n $('#' + val.controltovalidate).closest('.control-group').addClass('error');\n }\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n" }, { "answer_id": 12859791, "author": "LarryDavid", "author_id": 942269, "author_profile": "https://Stackoverflow.com/users/942269", "pm_score": 2, "selected": false, "text": " /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).parents('.control-group:first').removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');\n var t = $('#' + val.controltovalidate).parents('.control-group:first');\n t.addClass('error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n" }, { "answer_id": 15200858, "author": "DevDave", "author_id": 896631, "author_profile": "https://Stackoverflow.com/users/896631", "pm_score": 0, "selected": false, "text": " function ValidateTextBox(source, args) {\n var controlId = document.getElementById(source.controltovalidate).id;\n var control = $(\"#\" + controlId);\n var value = control.val();\n var is_valid = value != \"\";\n is_valid ? control.removeClass(\"error\") : control.addClass(\"error\");\n args.IsValid = is_valid;\n }\n" }, { "answer_id": 15638922, "author": "Asim Khan", "author_id": 2211851, "author_profile": "https://Stackoverflow.com/users/2211851", "pm_score": 0, "selected": false, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Custemvalidatin.aspx.cs\" Inherits=\"AspDotNetPractice.Custemvalidatin\" %>\n\n<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n <script type=\"text/javascript\">\n function vali(source, args) {\n if (document.getElementById(source.controltovalidate).value.length > 0) {\n args.IsValid = true;\n document.getElementById(source.controltovalidate).style.borderColor = 'green';\n }\n else {\n args.IsValid = false;\n document.getElementById(source.controltovalidate).style.borderColor = 'red';\n }\n\n }\n </script>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:TextBox ID=\"TextBox1\" Style=\"border:1px solid gray; width:270px; height:24px ; border-radius:6px;\" runat=\"server\"></asp:TextBox>\n\n <asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" ControlToValidate=\"TextBox1\"\n ErrorMessage=\"Enter First Name\" SetFocusOnError=\"True\" Display=\"Dynamic\" ClientValidationFunction=\"vali\" \n ValidateEmptyText=\"True\" Font-Size=\"Small\" ForeColor=\"Red\">Enter First Name</asp:CustomValidator><br /><br /><br />\n\n <asp:TextBox ID=\"TextBox2\" Style=\"border:1px solid gray; width:270px; height:24px ; border-radius:6px;\" runat=\"server\"></asp:TextBox>\n\n <asp:CustomValidator ID=\"CustomValidator2\" runat=\"server\" ClientValidationFunction=\"vali\"\n ControlToValidate=\"TextBox2\" Display=\"Dynamic\" ErrorMessage=\"Enter Second Name\"\n SetFocusOnError=\"True\" ValidateEmptyText=\"True\" Font-Size=\"Small\" ForeColor=\"Red\">Enter Second Name</asp:CustomValidator><br />\n <br />\n <br />\n\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" />\n </div>\n </form>\n</body>\n</html>\n" }, { "answer_id": 22502337, "author": "Ben Croughs", "author_id": 3122378, "author_profile": "https://Stackoverflow.com/users/3122378", "pm_score": 1, "selected": false, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>\n\n<!DOCTYPE html>\n<!-- http://stackoverflow.com/questions/196859/change-text-box-color-using-required-field-validator-no-extender-controls-pleas -->\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n <script src=\"http://code.jquery.com/jquery-1.11.0.min.js\"></script>\n<script src=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\"></script>\n <script>\n /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');\n var t = $('#' + val.controltovalidate);\n t.addClass('error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n </script>\n <style>\n .error {\n border: 1px solid red;\n }\n </style>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n\n <asp:TextBox ID=\"TextBox1\" runat=\"server\" ></asp:TextBox>\n <asp:RequiredFieldValidator ID=\"RequiredFieldValidator1\" runat=\"server\" ControlToValidate=\"TextBox1\" ErrorMessage=\"RequiredFieldValidator\"></asp:RequiredFieldValidator>\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" />\n\n <br />\n <asp:TextBox ID=\"TextBox2\" runat=\"server\"></asp:TextBox>\n <asp:RegularExpressionValidator ID=\"RegularExpressionValidator1\" runat=\"server\" ControlToValidate=\"TextBox2\" ErrorMessage=\"RegularExpressionValidator\" ValidationExpression=\"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\"></asp:RegularExpressionValidator>\n <br />\n <asp:TextBox ID=\"TextBox3\" runat=\"server\"></asp:TextBox>\n <asp:RangeValidator ID=\"RangeValidator1\" runat=\"server\" ControlToValidate=\"TextBox3\" ErrorMessage=\"RangeValidator\" MaximumValue=\"100\" MinimumValue=\"0\"></asp:RangeValidator>\n\n </div>\n </form>\n</body>\n</html>\n" }, { "answer_id": 23952980, "author": "BigMan", "author_id": 1039083, "author_profile": "https://Stackoverflow.com/users/1039083", "pm_score": 0, "selected": false, "text": " <asp:TextBox ID=\"TextBox1\" runat=\"server\" ></asp:TextBox>\n <asp:CustomValidator runat=\"server\" ControlToValidate=\"TextBox1\" Display=\"Dynamic\" Text=\"TextBox1 Not Set\" ValidateEmptyText=\"true\" OnServerValidate=\"ServerValidate\" />\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Execute\" />\n protected void Execute(object sender, EventArgs e)\n{\n Page.Validate();\n if (Page.IsValid)\n {\n *some code*\n }\n}\n\nprotected void ServerValidate(object source, ServerValidateEventArgs args)\n{\n CustomValidator cval = source as CustomValidator;\n if (cval == null)\n {\n args.IsValid = false;\n return;\n }\n\n if (string.IsNullOrEmpty(args.Value))\n {\n args.IsValid = false;\n string _target = cval.ControlToValidate;\n TextBox tb = cval.Parent.FindControl(_target) as TextBox;\n tb.BorderColor = System.Drawing.Color.Red;\n }\n else\n {\n args.IsValid = true;\n }\n}\n" }, { "answer_id": 25602922, "author": "Majid Dehnamaki", "author_id": 3946856, "author_profile": "https://Stackoverflow.com/users/3946856", "pm_score": 2, "selected": false, "text": " .form-control\n {\n width: 100px;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n color: black;\n background-color: white;\n }\n .form-control-Error\n {\n width: 100px;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n color: #EBB8C4;\n background-color: #F9F2F4\n border: 1px solid #DB7791;\n border-radius: 4px;\n }\n <asp:TextBox ID=\"txtUserName\" runat=\"server\" CssClass=\"form-control\"></asp:TextBox>\n <asp:RequiredFieldValidatorrunat=\"server\"Display=\"Dynamic\" ErrorMessage=\"PLease Enter UserName\" ControlToValidate=\"txtUserName\"></asp:RequiredFieldValidator>\n <script type=\"text/javascript\">\n function WebForm_OnSubmit() {\n if (typeof (ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) {\n for (var i in Page_Validators) {\n try {\n var control = document.getElementById(Page_Validators[i].controltovalidate);\n if (!Page_Validators[i].isvalid) {\n control.className = \"form-control-Error\";\n } else {\n control.className = \"form-control\";\n }\n } catch (e) { }\n }\n return false;\n }\n return true;\n }\n</script>\n" }, { "answer_id": 25857988, "author": "user2979644", "author_id": 2979644, "author_profile": "https://Stackoverflow.com/users/2979644", "pm_score": 3, "selected": false, "text": "<script>\n /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n\n // Remove the error class on each control group before validating\n // Store a reference to the ClientValidate function\n var origValidate = Page_ClientValidate;\n // Override with our custom version\n Page_ClientValidate = function (validationGroup) {\n // Clear all the validation classes for this validation group\n for (var i = 0; i < Page_Validators.length; i++) {\n if ((typeof(Page_Validators[i].validationGroup) == 'undefined' && !validationGroup) ||\n Page_Validators[i].validationGroup == validationGroup) {\n $(\"#\" + Page_Validators[i].controltovalidate).parents('.form-group').each(function () {\n $(this).removeClass('has-error');\n });\n }\n }\n // Call the original function\n origValidate(validationGroup);\n };\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (!val.isvalid) {\n // Set css class for invalid controls\n var t = $('#' + val.controltovalidate).parents('.form-group:first');\n t.addClass('has-error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(function () {\n UpgradeASPNETValidation();\n });\n</script>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
196,876
<p>Just looking at ways of getting named constants in python.</p> <pre><code>class constant_list: (A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3) </code></pre> <p>Then of course you can refer to it like so: </p> <pre><code>constant_list.A_CONSTANT </code></pre> <p>I suppose you could use a dictionary, using strings: </p> <pre><code>constant_dic = { "A_CONSTANT" : 1, "B_CONSTANT" : 2, "C_CONSTANT" : 3,} </code></pre> <p>and refer to it like this:</p> <pre><code>constant_dic["A_CONSTANT"] </code></pre> <hr> <p>My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?</p> <p>Thanks in advance.</p>
[ { "answer_id": 196881, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "class Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n codes = Enumerate('FOO BAR BAZ')\n codes.BAZ from __future__ import generators\n\n def enumerate(iterable):\n number = 0\n for name in iterable:\n yield number, name\n number += 1\n" }, { "answer_id": 196888, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 2, "selected": false, "text": "constants = [\"A_CONSTANT\", \"B_CONSTANT\", \"C_CONSTANT\"]\nconstant_dic = dict([(c,i) for i, c in enumerate(constants)])\n" }, { "answer_id": 196906, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 1, "selected": false, "text": "class Enumeration(object):\n def __init__(self, possibilities):\n self.possibilities = set(possibilities.split())\n\n def all(self):\n return sorted(self.possibilities)\n\n def __getattr__(self, name):\n if name in self.possibilities:\n return name\n raise AttributeError(\"Invalid constant: %s\" % name)\n >>> enum = Enumeration(\"FOO BAR\")\n>>> print enum.all()\n['BAR', 'FOO']\n>>> print enum.FOO\nFOO\n>>> print enum.FOOBAR\nTraceback (most recent call last):\n File \"enum.py\", line 17, in <module>\n print enum.FOOBAR\n File \"enum.py\", line 11, in __getattr__\n raise AttributeError(\"Invalid constant: %s\" % name)\nAttributeError: Invalid constant: FOOBAR\n" }, { "answer_id": 198101, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "# this is enum.py\nclass EnumException( Exception ):\n pass\n\nclass Enum( object ):\n class __metaclass__( type ):\n def __setattr__( cls, name, value ):\n raise EnumException(\"Can't set Enum class attribute!\")\n def __delattr__( cls, name ):\n raise EnumException(\"Can't delete Enum class attribute!\")\n\n def __init__( self ):\n raise EnumException(\"Enum cannot be instantiated!\")\n # this is testenum.py\nfrom enum import *\n\nclass ExampleEnum( Enum ):\n A=1\n B=22\n C=333\n\nif __name__ == '__main__' :\n\n print \"ExampleEnum.A |%s|\" % ExampleEnum.A\n print \"ExampleEnum.B |%s|\" % ExampleEnum.B\n print \"ExampleEnum.C |%s|\" % ExampleEnum.C\n z = ExampleEnum.A\n if z == ExampleEnum.A:\n print \"z is A\"\n\n try:\n ExampleEnum.A = 4 \n print \"ExampleEnum.A |%s| FAIL!\" % ExampleEnum.A\n except EnumException:\n print \"Can't change Enum.A (pass...)\"\n\n try:\n del ExampleEnum.A\n except EnumException:\n print \"Can't delete Enum.A (pass...)\"\n\n try:\n bad = ExampleEnum()\n except EnumException:\n print \"Can't instantiate Enum (pass...)\"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
196,883
<p>I am having an ASP.net page in my page i am having this as my code behind files. on first access the page the page preinit, init, load methods are called. on postbacks the preinit, init, load methods are called.</p> <p>My question is LoadViewstate and control state events (Overridden methods) are not firing after postbacks also</p> <pre><code>protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); } protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); } protected override void LoadControlState(object savedState) { base.LoadControlState(savedState); } protected void Page_Init(object sender, EventArgs e) { } protected void Page_Load(object sender, EventArgs e) { // lblName.Text = ViewState["Test"].ToString(); } </code></pre>
[ { "answer_id": 196881, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "class Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n codes = Enumerate('FOO BAR BAZ')\n codes.BAZ from __future__ import generators\n\n def enumerate(iterable):\n number = 0\n for name in iterable:\n yield number, name\n number += 1\n" }, { "answer_id": 196888, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 2, "selected": false, "text": "constants = [\"A_CONSTANT\", \"B_CONSTANT\", \"C_CONSTANT\"]\nconstant_dic = dict([(c,i) for i, c in enumerate(constants)])\n" }, { "answer_id": 196906, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 1, "selected": false, "text": "class Enumeration(object):\n def __init__(self, possibilities):\n self.possibilities = set(possibilities.split())\n\n def all(self):\n return sorted(self.possibilities)\n\n def __getattr__(self, name):\n if name in self.possibilities:\n return name\n raise AttributeError(\"Invalid constant: %s\" % name)\n >>> enum = Enumeration(\"FOO BAR\")\n>>> print enum.all()\n['BAR', 'FOO']\n>>> print enum.FOO\nFOO\n>>> print enum.FOOBAR\nTraceback (most recent call last):\n File \"enum.py\", line 17, in <module>\n print enum.FOOBAR\n File \"enum.py\", line 11, in __getattr__\n raise AttributeError(\"Invalid constant: %s\" % name)\nAttributeError: Invalid constant: FOOBAR\n" }, { "answer_id": 198101, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "# this is enum.py\nclass EnumException( Exception ):\n pass\n\nclass Enum( object ):\n class __metaclass__( type ):\n def __setattr__( cls, name, value ):\n raise EnumException(\"Can't set Enum class attribute!\")\n def __delattr__( cls, name ):\n raise EnumException(\"Can't delete Enum class attribute!\")\n\n def __init__( self ):\n raise EnumException(\"Enum cannot be instantiated!\")\n # this is testenum.py\nfrom enum import *\n\nclass ExampleEnum( Enum ):\n A=1\n B=22\n C=333\n\nif __name__ == '__main__' :\n\n print \"ExampleEnum.A |%s|\" % ExampleEnum.A\n print \"ExampleEnum.B |%s|\" % ExampleEnum.B\n print \"ExampleEnum.C |%s|\" % ExampleEnum.C\n z = ExampleEnum.A\n if z == ExampleEnum.A:\n print \"z is A\"\n\n try:\n ExampleEnum.A = 4 \n print \"ExampleEnum.A |%s| FAIL!\" % ExampleEnum.A\n except EnumException:\n print \"Can't change Enum.A (pass...)\"\n\n try:\n del ExampleEnum.A\n except EnumException:\n print \"Can't delete Enum.A (pass...)\"\n\n try:\n bad = ExampleEnum()\n except EnumException:\n print \"Can't instantiate Enum (pass...)\"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
196,885
<p>How can I determine if I'm running on a 32bit or a 64bit version of matlab?</p> <p>I have some pre-compiled mex-files which need different path's depending on 32/64bit matlab.</p>
[ { "answer_id": 206927, "author": "Adrian", "author_id": 28406, "author_profile": "https://Stackoverflow.com/users/28406", "pm_score": 2, "selected": false, "text": "if regexp(computer,'..$','match','64'),\n % setup 64bit options\nelse,\n % 32bit options\nend\n" }, { "answer_id": 208589, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 3, "selected": false, "text": "mexext >> help mexext\n MEXEXT MEX filename extension for this platform, or all platforms. \n EXT = MEXEXT returns the MEX-file name extension for the current\n platform. \n\n ALLEXT = MEXEXT('all') returns a struct with fields 'arch' and 'ext' \n describing MEX-file name extensions for all platforms.\n\n There is a script named mexext.bat on Windows and mexext.sh on UNIX\n that is intended to be used outside MATLAB in makefiles or scripts. Use\n that script instead of explicitly specifying the MEX-file extension in\n a makefile or script. The script is located in $MATLAB\\bin.\n\n See also MEX, MEXDEBUG.\n" }, { "answer_id": 377623, "author": "peje", "author_id": 27331, "author_profile": "https://Stackoverflow.com/users/27331", "pm_score": 4, "selected": true, "text": "computer switch computer\n case 'GLNX86'\n display('32-bit stuff')\n case 'GLNXA64'\n display('64-bit stuff')\n otherwise\n display('Not supported')\nend\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27331/" ]
196,890
<p>I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues. </p> <p>Here are results of tests I ran:</p> <p>Drawing a 25x18 map with 32x32 pixel tiles on a JComponent<br> Image 1 = .bmp format, Image 2 = A .png format</p> <h2>Without -Dsun.java2d.opengl=true</h2> <p>120 FPS using .BMP image 1<BR> 13 FPS using .PNG image 2</p> <h2>With -Dsun.java2d.opengl=true</h2> <p>12 FPS using .BMP image 1<BR> 700 FPS using .PNG image 2</p> <p>Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!</p> <p>.BMP Image 1 is translated to an image type of TYPE_INT_RGB. .PNG Image 2 is translated to an image type of TYPE_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE_INT_ARGB, and draw Image 1 or Image 2 to this new image. </p> <p>Here are the results running with that:</p> <h2>Without -Dsun.java2d.opengl=true</h2> <p>120 FPS using .BMP image 1<BR> 120 FPS using .PNG image 2</p> <h2>With -Dsun.java2d.opengl=true</h2> <p>700 FPS using .BMP image 1<BR> 700 FPS using .PNG image 2</p> <p>My real question is, can I assume that TYPE_INT_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance? </p> <p>Thanks in advance...</p>
[ { "answer_id": 197060, "author": "Consty", "author_id": 1191472, "author_profile": "https://Stackoverflow.com/users/1191472", "pm_score": 7, "selected": true, "text": "private BufferedImage toCompatibleImage(BufferedImage image)\n{\n // obtain the current system graphical settings\n GraphicsConfiguration gfxConfig = GraphicsEnvironment.\n getLocalGraphicsEnvironment().getDefaultScreenDevice().\n getDefaultConfiguration();\n\n /*\n * if image is already compatible and optimized for current system \n * settings, simply return it\n */\n if (image.getColorModel().equals(gfxConfig.getColorModel()))\n return image;\n\n // image is not optimized, so create a new image that is\n BufferedImage newImage = gfxConfig.createCompatibleImage(\n image.getWidth(), image.getHeight(), image.getTransparency());\n\n // get the graphics context of the new image to draw the old image on\n Graphics2D g2d = newImage.createGraphics();\n\n // actually draw the image and dispose of context no longer needed\n g2d.drawImage(image, 0, 0, null);\n g2d.dispose();\n\n // return the new optimized image\n return newImage; \n}\n" }, { "answer_id": 35306754, "author": "Alex Byrth", "author_id": 4304439, "author_profile": "https://Stackoverflow.com/users/4304439", "pm_score": 3, "selected": false, "text": " /**\n* How to use MemoryImageSource to render images on JPanel\n* Example by A.Borges (2015)\n*/\npublic class MyCanvas extends JPanel implements Runnable {\n\npublic int pixel[];\npublic int width;\npublic int height;\nprivate Image imageBuffer; \nprivate MemoryImageSource mImageProducer; \nprivate ColorModel cm; \nprivate Thread thread;\n\n\npublic MyCanvas() {\n super(true);\n thread = new Thread(this, \"MyCanvas Thread\");\n}\n\n/**\n * Call it after been visible and after resizes.\n */\npublic void init(){ \n cm = getCompatibleColorModel();\n width = getWidth();\n height = getHeight();\n int screenSize = width * height;\n if(pixel == null || pixel.length < screenSize){\n pixel = new int[screenSize];\n } \n mImageProducer = new MemoryImageSource(width, height, cm, pixel,0, width);\n mImageProducer.setAnimated(true);\n mImageProducer.setFullBufferUpdates(true); \n imageBuffer = Toolkit.getDefaultToolkit().createImage(mImageProducer); \n if(thread.isInterrupted() || !thread.isAlive()){\n thread.start();\n }\n}\n/**\n* Do your draws in here !!\n* pixel is your canvas!\n*/\npublic /* abstract */ void render(){\n // rubisch draw\n int[] p = pixel; // this avoid crash when resizing\n if(p.length != width * height) return; \n for(int x=0; x < width; x++){\n for(int y=0; y<height; y++){\n int color = (((x + i) % 255) & 0xFF) << 16; //red\n color |= (((y + j) % 255) & 0xFF) << 8; //green\n color |= (((y/2 + x/2 - j) % 255) & 0xFF) ; //blue \n p[ x + y * width] = color;\n }\n } \n i += 1;\n j += 1; \n} \nprivate int i=1,j=256;\n\n@Override\npublic void run() {\n while (true) {\n // request a JPanel re-drawing\n repaint(); \n try {Thread.sleep(5);} catch (InterruptedException e) {}\n }\n}\n\n@Override\npublic void paintComponent(Graphics g) {\n super.paintComponent(g);\n // perform draws on pixels\n render();\n // ask ImageProducer to update image\n mImageProducer.newPixels(); \n // draw it on panel \n g.drawImage(this.imageBuffer, 0, 0, this); \n}\n\n/**\n * Overrides ImageObserver.imageUpdate.\n * Always return true, assuming that imageBuffer is ready to go when called\n */\n@Override\npublic boolean imageUpdate(Image image, int a, int b, int c, int d, int e) {\n return true;\n}\n}// end class\n /**\n * Get Best Color model available for current screen.\n * @return color model\n */\nprotected static ColorModel getCompatibleColorModel(){ \n GraphicsConfiguration gfx_config = GraphicsEnvironment.\n getLocalGraphicsEnvironment().getDefaultScreenDevice().\n getDefaultConfiguration(); \n return gfx_config.getColorModel();\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191472/" ]
196,897
<p>I noticed when a file is executed on Windows (.exe or .dll), it is locked and cannot be deleted, moved or modified.</p> <p>Linux, on the other hand, does not lock executing files and you <em>can</em> delete, move, or modify them.</p> <p>Why does Windows lock when Linux does not? Is there an advantage to locking?</p>
[ { "answer_id": 30273566, "author": "Thorsten Schöning", "author_id": 2055163, "author_profile": "https://Stackoverflow.com/users/2055163", "pm_score": 2, "selected": false, "text": "dwShareMode" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27332/" ]
196,925
<p>JavaScript doesn't seem to have a native <code>trim()</code> method. How can I trim white spaces at the start and end of a string with JavaScript?</p>
[ { "answer_id": 196926, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 5, "selected": false, "text": "return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');\n" }, { "answer_id": 196928, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "$j.trim(string)\n <script type=\"text/javascript\">$j = jQuery.noConflict();</script>\n" }, { "answer_id": 196935, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 3, "selected": false, "text": "return str.replace( /^\\s+|\\s+$/g, '' );\n" }, { "answer_id": 196939, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "str2 = str.replace(/^\\s+/,'');\n str2 = str.replace(/\\s+$/,'');\n str2 = str.replace(/^\\s+|\\s+$/g,'');\n" }, { "answer_id": 249399, "author": "Evan", "author_id": 6277, "author_profile": "https://Stackoverflow.com/users/6277", "pm_score": 0, "selected": false, "text": "jQuery.trim(string)\n" }, { "answer_id": 249412, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 5, "selected": false, "text": "string = $.trim(string);\n" }, { "answer_id": 249542, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 4, "selected": false, "text": "function( text ) { return (text || \"\").replace( /^(\\s|\\u00A0)+|(\\s|\\u00A0)+$/g, \"\" );}\n" }, { "answer_id": 364353, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 3, "selected": false, "text": "String.prototype.trim = function() {\n try {\n return this.replace(/^\\s+|\\s+$/g, \"\");\n } catch(e) {\n return this;\n }\n}\n\nvar s = \" hello \";\nalert(s.trim() == \"hello\"); // displays true\n" }, { "answer_id": 1593847, "author": "jamesmhaley", "author_id": 150939, "author_profile": "https://Stackoverflow.com/users/150939", "pm_score": 1, "selected": false, "text": " String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g,\"\");\n }\n" }, { "answer_id": 1593878, "author": "Ionuț G. Stan", "author_id": 58808, "author_profile": "https://Stackoverflow.com/users/58808", "pm_score": 3, "selected": false, "text": "// Licensed under BSD\nfunction myBestTrim( str ){\n var start = -1,\n end = str.length;\n while( str.charCodeAt(--end) < 33 );\n while( str.charCodeAt(++start) < 33 );\n return str.slice( start, end + 1 );\n};\n trim String.prototype.trim = String.prototype.trim || function () {\n var start = -1,\n end = this.length;\n\n while( this.charCodeAt(--end) < 33 );\n while( this.charCodeAt(++start) < 33 );\n\n return this.slice( start, end + 1 );\n};\n" }, { "answer_id": 3269946, "author": "Jet", "author_id": 348008, "author_profile": "https://Stackoverflow.com/users/348008", "pm_score": 0, "selected": false, "text": " function trim($) { \n return (typeof $ == \"function\" ? $() : $).replace(/[\\s]*/g,\"\")\n }\n\n code example: \n\n trim((function(){ return \"a b\"})) // ab\n\n trim(\" a b\") //ab\n" }, { "answer_id": 3270346, "author": "RaviRaj", "author_id": 266055, "author_profile": "https://Stackoverflow.com/users/266055", "pm_score": 0, "selected": false, "text": "function trim(str) {\n try {\n if (str && typeof(str) == 'string') {\n return str.replace(/^\\s*|\\s*$/g, \"\");\n } else {\n return '';\n }\n } catch (e) {\n return str;\n }\n}\n" }, { "answer_id": 12547889, "author": "Timo Kähkönen", "author_id": 1691517, "author_profile": "https://Stackoverflow.com/users/1691517", "pm_score": 2, "selected": false, "text": "function trim27(str) {\n var c;\n for (var i = 0; i < str.length; i++) {\n c = str.charCodeAt(i);\n if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)\n continue; else break;\n }\n for (var j = str.length - 1; j >= i; j--) {\n c = str.charCodeAt(j);\n if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12)\n continue; else break;\n }\n return str.substring(i, j + 1);\n}\n if (!String.prototype.trim || \"\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF\".trim() || navigator.userAgent.toString().toLowerCase().indexOf(\"chrome\") != -1)\n var mytrim = function(str) {\n var c;\n for (var i = 0; i < str.length; i++) {\n c = str.charCodeAt(i);\n if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)\n continue; else break;\n }\n for (var j = str.length - 1; j >= i; j--) {\n c = str.charCodeAt(j);\n if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12 || c == 11 || c == 160 || c == 5760 || c == 6158 || c == 8192 || c == 8193 || c == 8194 || c == 8195 || c == 8196 || c == 8197 || c == 8198 || c == 8199 || c == 8200 || c == 8201 || c == 8202 || c == 8232 || c == 8233 || c == 8239 || c == 8287 || c == 12288 || c == 65279)\n continue; else break;\n }\n return str.substring(i, j + 1);\n };\n else var mytrim = function(str) {\n return str.trim();\n }\n var foo = mytrim(\" \\n \\t Trimmed \\f \\n \"); // foo is now \"Trimmed\"\n" }, { "answer_id": 15939320, "author": "vapcguy", "author_id": 1181535, "author_profile": "https://Stackoverflow.com/users/1181535", "pm_score": 0, "selected": false, "text": "function Trim(obj) {\n var coll = \"\";\n var arrObj = obj.split(' ');\n\n for (var i=0;i<arrObj.length;i++) {\n if (arrObj[i] == \"\") {\n arrObj.splice(i,1); // removes array indices containing spaces\n }\n }\n //alert(arrObj.length); // should be equal to the number of words\n // Rebuilds with spaces in-between words, but without spaces at the end\n for (var i=0;i<arrObj.length;i++) {\n if (arrObj[i] != \"\" && i != arrObj.length-1)\n coll += arrObj[i] + \" \";\n if (arrObj[i] != \"\" && i == arrObj.length-1)\n coll += arrObj[i];\n }\n\n return coll;\n}\n" }, { "answer_id": 25974037, "author": "CodeChops", "author_id": 1325129, "author_profile": "https://Stackoverflow.com/users/1325129", "pm_score": 0, "selected": false, "text": "$(\"#start-date\").text().trim()\n" }, { "answer_id": 30898872, "author": "kiranvj", "author_id": 1188322, "author_profile": "https://Stackoverflow.com/users/1188322", "pm_score": 2, "selected": false, "text": "// Adding trim function to String object if its not there\nif(typeof String.prototype.trim !== 'function') {\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n }\n}\n var myString = \" some text \";\n\nalert(myString.trim());\n // Adding trim function to String object if its not there\nif(typeof String.prototype.trim !== 'function') {\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n }\n}\n\nvar str = \" some text \";\nconsole.log(str.trim());" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
196,930
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="noreferrer">pywin32</a> or <a href="http://www.wxpython.org/" rel="noreferrer">wxPython</a>?</p> <p>Essentially, I need a function that called will return True iff current OS is Vista:</p> <pre><code>&gt;&gt;&gt; isWindowsVista() True </code></pre>
[ { "answer_id": 196931, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 3, "selected": false, "text": "import sys\n\ndef isWindowsVista():\n '''Return True iff current OS is Windows Vista.'''\n if sys.platform != \"win32\":\n return False\n import win32api\n VER_NT_WORKSTATION = 1\n version = win32api.GetVersionEx(1)\n if not version or len(version) < 9:\n return False\n return ((version[0] == 6) and \n (version[1] == 0) and\n (version[8] == VER_NT_WORKSTATION))\n" }, { "answer_id": 196962, "author": "Thomas Hervé", "author_id": 25409, "author_profile": "https://Stackoverflow.com/users/25409", "pm_score": 3, "selected": false, "text": "def isVista():\n if getattr(sys, \"getwindowsversion\", None) is not None:\n return sys.getwindowsversion()[0] == 6\n else:\n return False\n" }, { "answer_id": 200148, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 6, "selected": true, "text": ">>> import platform\n>>> platform.win32_ver()\n('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')\n>>> platform.system()\n'Windows'\n>>> platform.version()\n'5.1.2600'\n>>> platform.release()\n'XP'\n" }, { "answer_id": 17010604, "author": "Deming", "author_id": 2092480, "author_profile": "https://Stackoverflow.com/users/2092480", "pm_score": 0, "selected": false, "text": "win_version = {4: \"NT\", 5: \"2K\", 6: \"XP\"}[os.sys.getwindowsversion()[0]]\nprint \"win_version=\", win_version\n" }, { "answer_id": 43156269, "author": "Boštjan Mejak", "author_id": 7771315, "author_profile": "https://Stackoverflow.com/users/7771315", "pm_score": 0, "selected": false, "text": "import platform\nif platform.release() == \"Vista\":\n # Do something.\n import platform\nif \"Vista\" in platform.release():\n # Do something.\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18745/" ]
196,936
<p>I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class:</p> <pre><code>public class MyClass{ public string Property1 { get; set; } public int Property2 { get; set; } public bool Property3 { get; set; } public static T DoStuff&lt;T&gt;(string name){ // get the data for the property from the external API // or if there's a problem return 'default(T)' } } </code></pre> <p>Now in my constructor I want something like this:</p> <pre><code>public MyClass(){ var properties = this.GetType().GetProperties(); foreach(PropertyInfo p in properties){ p.SetValue(this, DoStuff(p.Name), new object[0]); } } </code></pre> <p>So the above constructor will thrown an error because I'm not supplying the generic type.</p> <p>So how do I pass in the type of the property in?</p>
[ { "answer_id": 196945, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "var properties = this.GetType().GetProperties();\nforeach (PropertyInfo p in properties)\n{\n object value = typeof(MyClass)\n .GetMethod(\"DoStuff\")\n .MakeGenericMethod(p.PropertyType)\n .Invoke(null, new object[] { p.Name });\n p.SetValue(this, value, null);\n}\n static object DoStuff(string name, Type propertyType);\n... and then\nobject value = DoStuff(p.Name, p.PropertyType);\n" }, { "answer_id": 196947, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "public MyClass(){\n var properties = this.GetType().GetProperties();\n foreach(PropertyInfo p in properties){\n p.SetValue(this, DoStuff(p.Name), new object[0]);\n }\n}\n DoStuff MyClass DoStuff PropertyInfo.SetValue" }, { "answer_id": 197021, "author": "Gaspar Nagy", "author_id": 26530, "author_profile": "https://Stackoverflow.com/users/26530", "pm_score": 2, "selected": false, "text": "object defaultResult = type.IsValueType ? Activator.CreateInstance(type) : null\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11388/" ]
196,946
<p>I was trying the following example, but with external URLs: <a href="http://android-developers.blogspot.com/2008/09/using-webviews.html" rel="nofollow noreferrer">Using WebViews</a></p> <p>The example shows how to load an HTML file from assets folder (<code>file:// url</code>) and display it in a WebView. </p> <p>But when I try it with external URLs (like <a href="http://google.com" rel="nofollow noreferrer">http://google.com</a>), I am always getting a "Website Not Available" error. Android's built-in browser is able to access all external URLs. </p> <p>I suspect that it has something to do with permissions, but wasn't able to confirm it.</p>
[ { "answer_id": 198662, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 6, "selected": true, "text": "<uses-permission android:name=\"android.permission.INTERNET\"></uses-permission>\n" }, { "answer_id": 679774, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<uses-permission android:name=\"android.permission.INTERNET\" />\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18027/" ]
196,949
<p>I have an application that I have to run as Administrator.</p> <p>One small part of that application is to start other applications with Process.Start</p> <p>The started applications will also be run as administrators, but I'd rather see them run as the 'normal' user.</p> <p>How do I accomplish that?</p> <p>/johan/</p>
[ { "answer_id": 196959, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 3, "selected": false, "text": "//---------------------------------------------------------------------\n// This file is part of the Microsoft .NET Framework SDK Code Samples.\n// \n// Copyright (C) Microsoft Corporation. All rights reserved.\n// \n//This source code is intended only as a supplement to Microsoft\n//Development Tools and/or on-line documentation. See these other\n//materials for detailed information regarding Microsoft code samples.\n// \n//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY\n//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A\n//PARTICULAR PURPOSE.\n//---------------------------------------------------------------------\n\n/****************************************************************************\n* Main.cpp - Sample application for Task Scheduler V2 COMAPI * Component: Task Scheduler \n* Copyright (c) 2002 - 2003, Microsoft Corporation \n* This sample creates a task to that launches as the currently logged on deskup user. The task launches as soon as it is registered. *\n****************************************************************************/\n#include \"stdafx.h\"\n#include <windows.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <comdef.h>\n#include <comutil.h>\n//Include Task header files - Included in Windows Vista Beta-2 SDK from MSDN\n#include <taskschd.h>\n#include <conio.h>\n#include <iostream>\n#include <time.h>\n\nusing namespace std;\n\n#define CLEANUP \\\npRootFolder->Release();\\\n pTask->Release();\\\n CoUninitialize();\n\nHRESULT CreateMyTask(LPCWSTR, wstring);\n\nvoid __cdecl wmain(int argc, wchar_t** argv)\n{\nwstring wstrExecutablePath;\nWCHAR taskName[20];\nHRESULT result;\n\nif( argc < 2 )\n{\nprintf(\"\\nUsage: LaunchApp yourapp.exe\" );\nreturn;\n}\n\n// Pick random number for task name\nsrand((unsigned int) time(NULL));\nwsprintf((LPWSTR)taskName, L\"Launch %d\", rand());\n\nwstrExecutablePath = argv[1];\n\nresult = CreateMyTask(taskName, wstrExecutablePath);\nprintf(\"\\nReturn status:%d\\n\", result);\n\n}\nHRESULT CreateMyTask(LPCWSTR wszTaskName, wstring wstrExecutablePath)\n{\n // ------------------------------------------------------\n // Initialize COM.\nTASK_STATE taskState;\nint i;\n HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);\n if( FAILED(hr) )\n {\n printf(\"\\nCoInitializeEx failed: %x\", hr );\n return 1;\n }\n\n // Set general COM security levels.\n hr = CoInitializeSecurity(\n NULL,\n -1,\n NULL,\n NULL,\n RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n RPC_C_IMP_LEVEL_IMPERSONATE,\n NULL,\n 0,\n NULL);\n\n if( FAILED(hr) )\n {\n printf(\"\\nCoInitializeSecurity failed: %x\", hr );\n CoUninitialize();\n return 1;\n }\n\n // ------------------------------------------------------\n // Create an instance of the Task Service. \n ITaskService *pService = NULL;\n hr = CoCreateInstance( CLSID_TaskScheduler,\n NULL,\n CLSCTX_INPROC_SERVER,\n IID_ITaskService,\n (void**)&pService ); \n if (FAILED(hr))\n {\n printf(\"Failed to CoCreate an instance of the TaskService class: %x\", hr);\n CoUninitialize();\n return 1;\n }\n\n // Connect to the task service.\n hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());\n if( FAILED(hr) )\n {\n printf(\"ITaskService::Connect failed: %x\", hr );\n pService->Release();\n CoUninitialize();\n return 1;\n }\n\n // ------------------------------------------------------\n // Get the pointer to the root task folder. This folder will hold the\n // new task that is registered.\n ITaskFolder *pRootFolder = NULL;\n hr = pService->GetFolder( _bstr_t( L\"\\\\\") , &pRootFolder );\n if( FAILED(hr) )\n {\n printf(\"Cannot get Root Folder pointer: %x\", hr );\n pService->Release();\n CoUninitialize();\n return 1;\n }\n\n // Check if the same task already exists. If the same task exists, remove it.\n hr = pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );\n\n // Create the task builder object to create the task.\n ITaskDefinition *pTask = NULL;\n hr = pService->NewTask( 0, &pTask );\n\n pService->Release(); // COM clean up. Pointer is no longer used.\n if (FAILED(hr))\n {\n printf(\"Failed to CoCreate an instance of the TaskService class: %x\", hr);\n pRootFolder->Release();\n CoUninitialize();\n return 1;\n }\n\n\n // ------------------------------------------------------\n // Get the trigger collection to insert the registration trigger.\n ITriggerCollection *pTriggerCollection = NULL;\n hr = pTask->get_Triggers( &pTriggerCollection );\n if( FAILED(hr) )\n {\n printf(\"\\nCannot get trigger collection: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Add the registration trigger to the task.\n ITrigger *pTrigger = NULL;\n\n hr = pTriggerCollection->Create( TASK_TRIGGER_REGISTRATION, &pTrigger ); \n pTriggerCollection->Release(); // COM clean up. Pointer is no longer used.\n if( FAILED(hr) )\n {\n printf(\"\\nCannot add registration trigger to the Task %x\", hr );\n CLEANUP\n return 1;\n }\n pTrigger->Release();\n\n // ------------------------------------------------------\n // Add an Action to the task. \n IExecAction *pExecAction = NULL;\n IActionCollection *pActionCollection = NULL;\n\n // Get the task action collection pointer.\n hr = pTask->get_Actions( &pActionCollection );\n if( FAILED(hr) )\n {\n printf(\"\\nCannot get Task collection pointer: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Create the action, specifying that it is an executable action.\n IAction *pAction = NULL;\n hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );\n pActionCollection->Release(); // COM clean up. Pointer is no longer used.\n if( FAILED(hr) )\n {\n printf(\"\\npActionCollection->Create failed: %x\", hr );\n CLEANUP\n return 1;\n }\n\n hr = pAction->QueryInterface( IID_IExecAction, (void**) &pExecAction );\n pAction->Release();\n if( FAILED(hr) )\n {\n printf(\"\\npAction->QueryInterface failed: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Set the path of the executable to the user supplied executable.\n hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) ); \n\n if( FAILED(hr) )\n {\n printf(\"\\nCannot set path of executable: %x\", hr );\n pExecAction->Release();\n CLEANUP\n return 1;\n }\n hr = pExecAction->put_Arguments( _bstr_t( L\"\" ) ); \n\n if( FAILED(hr) )\n {\n printf(\"\\nCannot set arguments of executable: %x\", hr );\n pExecAction->Release();\n CLEANUP\n return 1;\n }\n\n // ------------------------------------------------------\n // Save the task in the root folder.\n IRegisteredTask *pRegisteredTask = NULL;\n hr = pRootFolder->RegisterTaskDefinition(\n _bstr_t( wszTaskName ),\n pTask,\n TASK_CREATE, \n_variant_t(_bstr_t( L\"S-1-5-32-545\")),//Well Known SID for \\\\Builtin\\Users group\n_variant_t(), \nTASK_LOGON_GROUP,\n _variant_t(L\"\"),\n &pRegisteredTask);\n if( FAILED(hr) )\n {\n printf(\"\\nError saving the Task : %x\", hr );\n CLEANUP\n return 1;\n }\n printf(\"\\n Success! Task successfully registered. \" );\n for (i=0; i<100; i++)//give 10 seconds for the task to start\n{\npRegisteredTask->get_State(&taskState);\nif (taskState == TASK_STATE_RUNNING)\n{\nprintf(\"\\nTask is running\\n\");\nbreak;\n}\nSleep(100);\n}\nif (i>= 100) printf(\"Task didn't start\\n\");\n\n //Delete the task when done\n hr = pRootFolder->DeleteTask(\n _bstr_t( wszTaskName ),\n NULL);\n if( FAILED(hr) )\n {\n printf(\"\\nError deleting the Task : %x\", hr );\n CLEANUP\n return 1;\n }\n\n printf(\"\\n Success! Task successfully deleted. \" );\n\n// Clean up.\n CLEANUP\n CoUninitialize();\n return 0;\n}\n" }, { "answer_id": 287072, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": true, "text": "CreateSaferProcess(@\"calc.exe\", \"\", SaferLevel.NormalUser);\n //http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx\npublic static void CreateSaferProcess(String fileName, String arguments, SaferLevel saferLevel)\n{\n IntPtr saferLevelHandle = IntPtr.Zero;\n\n //Create a SaferLevel handle to match what was requested\n if (!WinSafer.SaferCreateLevel(\n SaferLevelScope.User, \n saferLevel, \n SaferOpen.Open, \n out saferLevelHandle, \n IntPtr.Zero))\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n try\n {\n //Generate the access token to use, based on the safer level handle.\n IntPtr hToken = IntPtr.Zero;\n\n if (!WinSafer.SaferComputeTokenFromLevel(\n saferLevelHandle, // SAFER Level handle\n IntPtr.Zero, // NULL is current thread token.\n out hToken, // Target token\n SaferTokenBehaviour.Default, // No flags\n IntPtr.Zero)) // Reserved\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n try\n {\n //Now that we have a security token, we can lauch the process\n //using the standard CreateProcessAsUser API\n STARTUPINFO si = new STARTUPINFO();\n si.cb = Marshal.SizeOf(si);\n si.lpDesktop = String.Empty;\n\n PROCESS_INFORMATION pi = new PROCESS_INFORMATION();\n\n // Spin up the new process\n Boolean bResult = Windows.CreateProcessAsUser(\n hToken,\n fileName,\n arguments,\n IntPtr.Zero, //process attributes\n IntPtr.Zero, //thread attributes\n false, //inherit handles\n 0, //CREATE_NEW_CONSOLE\n IntPtr.Zero, //environment\n null, //current directory\n ref si, //startup info\n out pi); //process info\n\n if (!bResult)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\n if (pi.hProcess != IntPtr.Zero)\n Windows.CloseHandle(pi.hProcess);\n\n if (pi.hThread != IntPtr.Zero)\n Windows.CloseHandle(pi.hThread);\n }\n finally\n {\n if (hToken != IntPtr.Zero)\n Windows.CloseHandle(hToken);\n }\n }\n finally\n {\n WinSafer.SaferCloseLevel(saferLevelHandle);\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace PInvoke\n{\n public class WinSafer\n {\n /// <summary>\n /// The SaferCreateLevel function opens a SAFER_LEVEL_HANDLE.\n /// </summary>\n /// <param name=\"scopeId\">The scope of the level to be created.</param>\n /// <param name=\"levelId\">The level of the handle to be opened.</param>\n /// <param name=\"openFlags\">Must be SaferOpenFlags.Open</param>\n /// <param name=\"levelHandle\">The returned SAFER_LEVEL_HANDLE. When you have finished using the handle, release it by calling the SaferCloseLevel function.</param>\n /// <param name=\"reserved\">This parameter is reserved for future use. IntPtr.Zero</param>\n /// <returns></returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferCreateLevel(SaferLevelScope scopeId, SaferLevel levelId, SaferOpen openFlags,\n out IntPtr levelHandle, IntPtr reserved);\n\n /// <summary>\n /// The SaferComputeTokenFromLevel function restricts a token using restrictions specified by a SAFER_LEVEL_HANDLE.\n /// </summary>\n /// <param name=\"levelHandle\">SAFER_LEVEL_HANDLE that contains the restrictions to place on the input token. Do not pass handles with a LevelId of SAFER_LEVELID_FULLYTRUSTED or SAFER_LEVELID_DISALLOWED to this function. This is because SAFER_LEVELID_FULLYTRUSTED is unrestricted and SAFER_LEVELID_DISALLOWED does not contain a token.</param>\n /// <param name=\"inAccessToken\">Token to be restricted. If this parameter is NULL, the token of the current thread will be used. If the current thread does not contain a token, the token of the current process is used.</param>\n /// <param name=\"outAccessToken\">The resulting restricted token.</param>\n /// <param name=\"flags\">Specifies the behavior of the method.</param>\n /// <param name=\"lpReserved\">Reserved for future use. This parameter should be set to IntPtr.EmptyParam.</param>\n /// <returns></returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferComputeTokenFromLevel(IntPtr levelHandle, IntPtr inAccessToken,\n out IntPtr outAccessToken, SaferTokenBehaviour flags, IntPtr lpReserved);\n\n /// <summary>\n /// The SaferCloseLevel function closes a SAFER_LEVEL_HANDLE that was opened by using the SaferIdentifyLevel function or the SaferCreateLevel function.</summary>\n /// <param name=\"levelHandle\">The SAFER_LEVEL_HANDLE to be closed.</param>\n /// <returns>TRUE if the function succeeds; otherwise, FALSE. For extended error information, call GetLastWin32Error.</returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferCloseLevel(IntPtr levelHandle);\n } //class WinSafer\n\n /// <summary>\n /// Specifies the behaviour of the SaferComputeTokenFromLevel method\n /// </summary>\n public enum SaferTokenBehaviour : uint\n {\n /// <summary></summary>\n Default = 0x0,\n /// <summary>If the OutAccessToken parameter is not more restrictive than the InAccessToken parameter, the OutAccessToken parameter returns NULL.</summary>\n NullIfEqual = 0x1,\n /// <summary></summary>\n CompareOnly = 0x2,\n /// <summary></summary>\n MakeInert = 0x4,\n /// <summary></summary>\n WantFlags = 0x8\n }\n\n /// <summary>\n /// The level of the handle to be opened.\n /// </summary>\n public enum SaferLevel : uint\n {\n /// <summary>Software will not run, regardless of the user rights of the user.</summary>\n Disallowed = 0,\n /// <summary>Allows programs to execute with access only to resources granted to open well-known groups, blocking access to Administrator and Power User privileges and personally granted rights.</summary>\n Untrusted = 0x1000,\n /// <summary>Software cannot access certain resources, such as cryptographic keys and credentials, regardless of the user rights of the user.</summary>\n Constrained = 0x10000,\n /// <summary>Allows programs to execute as a user that does not have Administrator or Power User user rights. Software can access resources accessible by normal users.</summary>\n NormalUser = 0x20000,\n /// <summary>Software user rights are determined by the user rights of the user.</summary>\n FullyTrusted = 0x40000\n }\n\n /// <summary>\n /// The scope of the level to be created.\n /// </summary>\n public enum SaferLevelScope : uint\n {\n /// <summary>The created level is scoped by computer.</summary>\n Machine = 1,\n /// <summary>The created level is scoped by user.</summary>\n User = 2\n }\n\n public enum SaferOpen : uint\n {\n Open = 1\n }\n} //namespace PInvoke\n" }, { "answer_id": 34473238, "author": "magicandre1981", "author_id": 1466046, "author_profile": "https://Stackoverflow.com/users/1466046", "pm_score": 2, "selected": false, "text": "Task Scheduler Managed Wrapper td.Principal.RunLevel = TaskRunLevel.LUA; // Get the service on the local machine\nusing (var ts = new TaskService())\n{\n const string taskName = \"foo\";\n\n // Create a new task definition and assign properties\n var td = ts.NewTask();\n td.RegistrationInfo.Description = \"start foo.exe as limited user\";\n\n // Create an action that will launch foo.exe, with argument bar in workingdir C:\\\\\n td.Actions.Add(new ExecAction(\"C:\\\\foo.exe\", \"bar\", \"C:\\\\\"));\n\n td.Settings.Priority = ProcessPriorityClass.Normal;\n\n // run with limited token\n td.Principal.RunLevel = TaskRunLevel.LUA;\n\n td.Settings.AllowDemandStart = true;\n\n td.Settings.DisallowStartIfOnBatteries = false;\n\n td.Settings.StopIfGoingOnBatteries = false;\n\n // Register the task in the root folder\n var ret = ts.RootFolder.RegisterTaskDefinition(taskName, td);\n\n var fooTask = ts.FindTask(taskName, true);\n if (null != fooTask )\n {\n if (fooTask.Enabled)\n {\n fooTask.Run();\n\n Thread.Sleep(TimeSpan.FromSeconds(1));\n\n // find process and wait for Exit\n var processlist = Process.GetProcesses();\n\n foreach(var theprocess in processlist)\n {\n if (theprocess.ProcessName != \"foo\")\n continue;\n\n theprocess.WaitForExit();\n break;\n }\n }\n }\n\n // Remove the task we just created\n ts.RootFolder.DeleteTask(taskName);\n}\n" }, { "answer_id": 58579679, "author": "Paul", "author_id": 2604492, "author_profile": "https://Stackoverflow.com/users/2604492", "pm_score": 2, "selected": false, "text": "ExecuteProcessUnElevated // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace Microsoft.NodejsTools.SharedProject\n{\n /// <summary>\n /// Utility for accessing window IShell* interfaces in order to use them to launch a process unelevated\n /// </summary>\n internal class SystemUtility\n {\n /// <summary>\n /// We are elevated and should launch the process unelevated. We can't create the\n /// process directly without it becoming elevated. So to workaround this, we have\n /// explorer do the process creation (explorer is typically running unelevated).\n /// </summary>\n internal static void ExecuteProcessUnElevated(string process, string args, string currentDirectory = \"\")\n {\n var shellWindows = (IShellWindows)new CShellWindows();\n\n // Get the desktop window\n object loc = CSIDL_Desktop;\n object unused = new object();\n int hwnd;\n var serviceProvider = (IServiceProvider)shellWindows.FindWindowSW(ref loc, ref unused, SWC_DESKTOP, out hwnd, SWFO_NEEDDISPATCH);\n\n // Get the shell browser\n var serviceGuid = SID_STopLevelBrowser;\n var interfaceGuid = typeof(IShellBrowser).GUID;\n var shellBrowser = (IShellBrowser)serviceProvider.QueryService(ref serviceGuid, ref interfaceGuid);\n\n // Get the shell dispatch\n var dispatch = typeof(IDispatch).GUID;\n var folderView = (IShellFolderViewDual)shellBrowser.QueryActiveShellView().GetItemObject(SVGIO_BACKGROUND, ref dispatch);\n var shellDispatch = (IShellDispatch2)folderView.Application;\n\n // Use the dispatch (which is unelevated) to launch the process for us\n shellDispatch.ShellExecute(process, args, currentDirectory, string.Empty, SW_SHOWNORMAL);\n }\n\n /// <summary>\n /// Interop definitions\n /// </summary>\n private const int CSIDL_Desktop = 0;\n private const int SWC_DESKTOP = 8;\n private const int SWFO_NEEDDISPATCH = 1;\n private const int SW_SHOWNORMAL = 1;\n private const int SVGIO_BACKGROUND = 0;\n private readonly static Guid SID_STopLevelBrowser = new Guid(\"4C96BE40-915C-11CF-99D3-00AA004AE837\");\n\n [ComImport]\n [Guid(\"9BA05972-F6A8-11CF-A442-00A0C90A8F39\")]\n [ClassInterfaceAttribute(ClassInterfaceType.None)]\n private class CShellWindows\n {\n }\n\n [ComImport]\n [Guid(\"85CB6900-4D95-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellWindows\n {\n [return: MarshalAs(UnmanagedType.IDispatch)]\n object FindWindowSW([MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, int swClass, out int pHWND, int swfwOptions);\n }\n\n [ComImport]\n [Guid(\"6d5140c1-7436-11ce-8034-00aa006009fa\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IServiceProvider\n {\n [return: MarshalAs(UnmanagedType.Interface)]\n object QueryService(ref Guid guidService, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"000214E2-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellBrowser\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // InsertMenusSB\n void VTableGap04(); // SetMenuSB\n void VTableGap05(); // RemoveMenusSB\n void VTableGap06(); // SetStatusTextSB\n void VTableGap07(); // EnableModelessSB\n void VTableGap08(); // TranslateAcceleratorSB\n void VTableGap09(); // BrowseObject\n void VTableGap10(); // GetViewStateStream\n void VTableGap11(); // GetControlWindow\n void VTableGap12(); // SendControlMsg\n IShellView QueryActiveShellView();\n }\n\n [ComImport]\n [Guid(\"000214E3-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellView\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // TranslateAcceleratorA\n void VTableGap04(); // EnableModeless\n void VTableGap05(); // UIActivate\n void VTableGap06(); // Refresh\n void VTableGap07(); // CreateViewWindow\n void VTableGap08(); // DestroyViewWindow\n void VTableGap09(); // GetCurrentInfo\n void VTableGap10(); // AddPropertySheetPages\n void VTableGap11(); // SaveViewState\n void VTableGap12(); // SelectItem\n\n [return: MarshalAs(UnmanagedType.Interface)]\n object GetItemObject(UInt32 aspectOfView, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"00020400-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IDispatch\n {\n }\n\n [ComImport]\n [Guid(\"E7A1AF80-4D96-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellFolderViewDual\n {\n object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; }\n }\n\n [ComImport]\n [Guid(\"A4C6892C-3BA9-11D2-9DEA-00C04FB16162\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n public interface IShellDispatch2\n {\n void ShellExecute([MarshalAs(UnmanagedType.BStr)] string File, [MarshalAs(UnmanagedType.Struct)] object vArgs, [MarshalAs(UnmanagedType.Struct)] object vDir, [MarshalAs(UnmanagedType.Struct)] object vOperation, [MarshalAs(UnmanagedType.Struct)] object vShow);\n }\n }\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21761/" ]
196,960
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p> <pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) </code></pre> <p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p> <p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p> <p>Ideally I would just do</p> <pre><code>parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) </code></pre> <p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
[ { "answer_id": 196978, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 5, "selected": false, "text": "def func(one, two=\"value\"):\n y = one, two\n return y\nprint func.func_code.co_varnames[:func.func_code.co_argcount]\n co_varnames y def get_valid_args(func, args_dict):\n '''Return dictionary without invalid function arguments.'''\n validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]\n return dict((key, value) for key, value in args_dict.iteritems() \n if key in validArgs)\n >>> func(**get_valid_args(func, args))\n func_defaults def get_valid_kwargs(func, args_dict):\n validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]\n kwargsLen = len(func.func_defaults) # number of keyword arguments\n validKwargs = validArgs[-kwargsLen:] # because kwargs are last\n return dict((key, value) for key, value in args_dict.iteritems() \n if key in validKwargs)\n func(param1, param2, **get_valid_kwargs(func, kwargs_dict))\n func *args **kwargs" }, { "answer_id": 196997, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "argnames = example.func_code.co_varnames[:func.func_code.co_argcount]\nargs = dict((key, val) for key,val in d_args.iteritems() if key in argnames)\nexample(**args)\n" }, { "answer_id": 197053, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 8, "selected": true, "text": ">>> import inspect\n>>> def func(a,b,c=42, *args, **kwargs): pass\n>>> inspect.getargspec(func)\n(['a', 'b', 'c'], 'args', 'kwargs', (42,))\n def get_required_args(func):\n args, varargs, varkw, defaults = inspect.getargspec(func)\n if defaults:\n args = args[:-len(defaults)]\n return args # *args and **kwargs are not required, so ignore them.\n def missing_args(func, argdict):\n return set(get_required_args(func)).difference(argdict)\n def invalid_args(func, argdict):\n args, varargs, varkw, defaults = inspect.getargspec(func)\n if varkw: return set() # All accepted\n return set(argdict) - set(args)\n def is_callable_with_args(func, argdict):\n return not missing_args(func, argdict) and not invalid_args(func, argdict)\n kwargs" }, { "answer_id": 197101, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": ">>> import inspect\n>>> import fileinput\n>>> print(inspect.getfullargspec(fileinput.input))\nFullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],\nvarargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], \nkwdefaults=None, annotations={})\n" }, { "answer_id": 45373004, "author": "Dimitris Fasarakis Hilliard", "author_id": 4952130, "author_profile": "https://Stackoverflow.com/users/4952130", "pm_score": 4, "selected": false, "text": "inspect.signature def spam(a, b=1, *args, c=2, **kwargs):\n print(a, b, args, c, kwargs)\n from inspect import signature\nsig = signature(spam)\n >>> # positional or keyword\n>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]\n['a', 'b']\n>>> # keyword only\n>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]\n['c']\n p.VAR_POSITIONAL VAR_KEYWORD p.default p.empty" }, { "answer_id": 67854523, "author": "Sumit", "author_id": 15582748, "author_profile": "https://Stackoverflow.com/users/15582748", "pm_score": 2, "selected": false, "text": "myfun.__code__.co_varnames\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
196,966
<p>I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is. I want to do the following:</p> <pre><code>$().ready(function() { $('#searchHolder').customSearch('MyApp.Models.User'); }); </code></pre> <p>As long as I have implemented a specific interface on Models.User, jQuery will be able to talk to a reflection service to generically construct the relevant UI.</p> <p>Sounds fun, but it seems that I'm now calling the JavaScript from the View, which is in turn going to do some View-related activity to build the search UI, and then to do the search and interact with the user it's going to throw a bunch of Controller tasks in there.</p> <p>So where does this really fit? Is there a different way I can structure my jQuery plugin so that it conforms more to the idea of MVC? Does MVC work when it scales down to its own form <em>within</em> another MVC structure? Should I just ignore these issues for the sake of one plugin?</p>
[ { "answer_id": 200410, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 1, "selected": false, "text": "partials switch UpdatePanel" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
196,972
<p>Is there a simple way to convert a string to Title Case? E.g. <code>john smith</code> becomes <code>John Smith</code>. I'm not looking for something complicated like <a href="http://ejohn.org/blog/title-capitalization-in-javascript/" rel="noreferrer">John Resig's solution</a>, just (hopefully) some kind of one- or two-liner.</p>
[ { "answer_id": 196989, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "var toMatch = \"john w. smith\";\nvar result = toMatch.replace(/(\\w)(\\w*)/g, function (_, i, r) {\n return i.toUpperCase() + (r != null ? r : \"\");\n }\n)\n /([a-z])(\\w*)/g function toTitleCase(toTransform) {\n return toTransform.replace(/\\b([a-z])/g, function (_, initial) {\n return initial.toUpperCase();\n });\n}\n" }, { "answer_id": 196991, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 10, "selected": false, "text": "function toTitleCase(str) {\n return str.replace(\n /\\w\\S*/g,\n function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }\n );\n} <form>\n Input:\n <br /><textarea name=\"input\" onchange=\"form.output.value=toTitleCase(this.value)\" onkeyup=\"form.output.value=toTitleCase(this.value)\"></textarea>\n <br />Output:\n <br /><textarea name=\"output\" readonly onclick=\"select(this)\"></textarea>\n</form>" }, { "answer_id": 2195924, "author": "Lwangaman", "author_id": 265725, "author_profile": "https://Stackoverflow.com/users/265725", "pm_score": 4, "selected": false, "text": "function toProperCase(s)\n{\n return s.toLowerCase().replace( /\\b((m)(a?c))?(\\w)/g,\n function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });\n}\n" }, { "answer_id": 3054478, "author": "Talha Ashfaque", "author_id": 362193, "author_profile": "https://Stackoverflow.com/users/362193", "pm_score": 8, "selected": false, "text": "text-transform: capitalize;\n hello world Hello World HELLO WORLD HELLO WORLD emily-jane o'brien Emily-jane O'brien Maria von Trapp Maria Von Trapp" }, { "answer_id": 4171093, "author": "fncomp", "author_id": 455581, "author_profile": "https://Stackoverflow.com/users/455581", "pm_score": 4, "selected": false, "text": "/**\n * @param String str The text to be converted to titleCase.\n * @param Array glue the words to leave in lowercase. \n */\nvar titleCase = function(str, glue){\n glue = (glue) ? glue : ['of', 'for', 'and'];\n return str.replace(/(\\w)(\\w*)/g, function(_, i, r){\n var j = i.toUpperCase() + (r != null ? r : \"\");\n return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();\n });\n};\n var titleCase = function(str, glue){\n glue = !!glue ? glue : ['of', 'for', 'and', 'a'];\n var first = true;\n return str.replace(/(\\w)(\\w*)/g, function(_, i, r) {\n var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();\n var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();\n first = false;\n return result;\n });\n};\n" }, { "answer_id": 5574446, "author": "Tuan", "author_id": 360053, "author_profile": "https://Stackoverflow.com/users/360053", "pm_score": 8, "selected": false, "text": "String.prototype.toProperCase = function () {\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n};\n \"pascal\".toProperCase();\n" }, { "answer_id": 6475125, "author": "Geoffrey Booth", "author_id": 223225, "author_profile": "https://Stackoverflow.com/users/223225", "pm_score": 7, "selected": false, "text": "String.prototype.toTitleCase = function() {\n var i, j, str, lowers, uppers;\n str = this.replace(/([^\\W_]+[^\\s-]*) */g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n\n // Certain minor words should be left lowercase unless \n // they are the first or last words in the string\n lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', \n 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];\n for (i = 0, j = lowers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), \n function(txt) {\n return txt.toLowerCase();\n });\n\n // Certain words such as initialisms or acronyms should be left uppercase\n uppers = ['Id', 'Tv'];\n for (i = 0, j = uppers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), \n uppers[i].toUpperCase());\n\n return str;\n}\n \"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:\".toTitleCase();\n// Returns: \"To Login to This Site and Watch TV, Please Enter a Valid ID:\"\n" }, { "answer_id": 8564268, "author": "Mike", "author_id": 276939, "author_profile": "https://Stackoverflow.com/users/276939", "pm_score": 4, "selected": false, "text": "String.prototype.toProperCase = function() {\n var words = this.split(' ');\n var results = [];\n for (var i = 0; i < words.length; i++) {\n var letter = words[i].charAt(0).toUpperCase();\n results.push(letter + words[i].slice(1));\n }\n return results.join(' ');\n};\n\nconsole.log(\n 'john smith'.toProperCase()\n)" }, { "answer_id": 10625035, "author": "Maxi Baez", "author_id": 1202001, "author_profile": "https://Stackoverflow.com/users/1202001", "pm_score": 3, "selected": false, "text": "String.prototype.toProperCase = function(){\n return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, \n function($1){\n return $1.toUpperCase();\n }\n );\n};\n var str = 'john smith';\nstr.toProperCase();\n" }, { "answer_id": 12533554, "author": "Billy Moon", "author_id": 665261, "author_profile": "https://Stackoverflow.com/users/665261", "pm_score": 0, "selected": false, "text": "function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\\.?|via)$/i;return e.replace(/([^\\W_]+[^\\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==\":\"&&i.charAt(r-1).search(/[^\\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};\n\nconsole.log( toTitleCase( \"ignores mixed case words like iTunes, and allows AT&A and website.com/address etc...\" ) );\n" }, { "answer_id": 20763116, "author": "simo", "author_id": 1260020, "author_profile": "https://Stackoverflow.com/users/1260020", "pm_score": 5, "selected": false, "text": "var result =\n 'this is very interesting'.replace(/\\b[a-z]/g, (x) => x.toUpperCase())\n\nconsole.log(result) // This Is Very Interesting" }, { "answer_id": 22193094, "author": "a8m", "author_id": 2503796, "author_profile": "https://Stackoverflow.com/users/2503796", "pm_score": 7, "selected": false, "text": "const str = \"foo bar baz\";\nconst newStr = str.split(' ')\n .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())\n .join(' ');\nconsole.log(newStr);" }, { "answer_id": 24784109, "author": "lewax00", "author_id": 864070, "author_profile": "https://Stackoverflow.com/users/864070", "pm_score": 3, "selected": false, "text": "function toTitleCase(str)\n{\n return str.replace(/\\b\\w/g, function (txt) { return txt.toUpperCase(); });\n}\n" }, { "answer_id": 26128016, "author": "Asereware", "author_id": 1048751, "author_profile": "https://Stackoverflow.com/users/1048751", "pm_score": 2, "selected": false, "text": "\"SOFÍA vergara\".toLowerCase().replace(/\\b(\\s\\w|^\\w)/g, function (txt) { return txt.toUpperCase(); });" }, { "answer_id": 29760794, "author": "Spencer Shattuck", "author_id": 4806162, "author_profile": "https://Stackoverflow.com/users/4806162", "pm_score": 1, "selected": false, "text": "var myPoem = 'What is a jQuery but a misunderstood object?'\n//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?\n\n //code here\nvar capitalize = function(str) {\n var strArr = str.split(' ');\n var newArr = [];\n for (var i = 0; i < strArr.length; i++) {\n newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))\n };\n return newArr.join(' ') \n}\n\nvar fixedPoem = capitalize(myPoem);\nalert(fixedPoem);" }, { "answer_id": 30710880, "author": "vijayscode", "author_id": 4053617, "author_profile": "https://Stackoverflow.com/users/4053617", "pm_score": 0, "selected": false, "text": "function toTitleCase(str) {\n var strnew = \"\";\n var i = 0;\n\n for (i = 0; i < str.length; i++) {\n if (i == 0) {\n strnew = strnew + str[i].toUpperCase();\n } else if (i != 0 && str[i - 1] == \" \") {\n strnew = strnew + str[i].toUpperCase();\n } else {\n strnew = strnew + str[i];\n }\n }\n\n alert(strnew);\n}\n\ntoTitleCase(\"hello world how are u\");\n" }, { "answer_id": 31278078, "author": "aagamezl", "author_id": 4246683, "author_profile": "https://Stackoverflow.com/users/4246683", "pm_score": 0, "selected": false, "text": "var stringToConvert = 'john';\nstringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');\nconsole.log(stringToConvert);" }, { "answer_id": 31865052, "author": "dipole_moment", "author_id": 1869326, "author_profile": "https://Stackoverflow.com/users/1869326", "pm_score": 1, "selected": false, "text": "String.prototype.capitalize = function() {\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}\n" }, { "answer_id": 32485600, "author": "Rafael Sanches", "author_id": 410293, "author_profile": "https://Stackoverflow.com/users/410293", "pm_score": 1, "selected": false, "text": " var TITLE_CASE_LOWER_MAP = {\n 'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,\n 'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1\n };\n\n // LEAK/CACHE TODO: evaluate using LRU.\n var TITLE_CASE_CACHE = new Object();\n\n toTitleCase: function (title) {\n if (!title) return null;\n\n var result = TITLE_CASE_CACHE[title];\n if (result) {\n return result;\n }\n\n result = \"\";\n var split = title.toLowerCase().split(\" \");\n for (var i=0; i < split.length; i++) {\n\n if (i > 0) {\n result += \" \";\n }\n\n var word = split[i];\n if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {\n word = word.substr(0,1).toUpperCase() + word.substr(1);\n }\n\n result += word;\n }\n\n TITLE_CASE_CACHE[title] = result;\n\n return result;\n }," }, { "answer_id": 33815550, "author": "Jamesy Dimmick May", "author_id": 2677107, "author_profile": "https://Stackoverflow.com/users/2677107", "pm_score": 2, "selected": false, "text": "function titleCase(str) {\n return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');\n}\n" }, { "answer_id": 34251961, "author": "Pro N00P", "author_id": 5674751, "author_profile": "https://Stackoverflow.com/users/5674751", "pm_score": 0, "selected": false, "text": "function titleCase(str) {\n str = str.toLowerCase();\n\n var strArray = str.split(\" \");\n\n\n for(var i = 0; i < strArray.length; i++){\n strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);\n\n }\n\n var result = strArray.join(\" \");\n\n //Return the string\n return result;\n}\n" }, { "answer_id": 35236310, "author": "zurfyx", "author_id": 2013580, "author_profile": "https://Stackoverflow.com/users/2013580", "pm_score": 0, "selected": false, "text": "String.prototype.capitalize = function() {\n return this.toLowerCase().split(' ').map(capFirst).join(' ');\n function capFirst(str) {\n return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);\n }\n}\n \"hello world\".capitalize()\n" }, { "answer_id": 35681245, "author": "immazharkhan", "author_id": 4945514, "author_profile": "https://Stackoverflow.com/users/4945514", "pm_score": 4, "selected": false, "text": "function titleCase(str) {\n return str.split(' ').map(function(val){ \n return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();\n }).join(' ');\n}\n" }, { "answer_id": 36991252, "author": "Suryatapa", "author_id": 4978139, "author_profile": "https://Stackoverflow.com/users/4978139", "pm_score": 1, "selected": false, "text": " function titlecase(str){\n var arr=[]; \n var str1=str.split(' ');\n for (var i = 0; i < str1.length; i++) {\n var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);\n arr.push(upper);\n };\n return arr.join(' ');\n }\n titlecase('my name is suryatapa roy');\n" }, { "answer_id": 37931321, "author": "le_m", "author_id": 1647737, "author_profile": "https://Stackoverflow.com/users/1647737", "pm_score": 3, "selected": false, "text": "/\\S+/g function toTitleCase(str) {\n return str.replace(/\\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());\n}\n\nconsole.log(toTitleCase(\"a city named örebro\")); // A City Named Örebro" }, { "answer_id": 38640255, "author": "Scott", "author_id": 1655035, "author_profile": "https://Stackoverflow.com/users/1655035", "pm_score": 0, "selected": false, "text": "String.prototype.toTitleCase = function() {\n var str = this;\n if(!str.length) {\n return \"\";\n }\n str = str.split(\" \");\n for(var i = 0; i < str.length; i++) {\n str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');\n }\n return (str.length ? str.join(\" \") : str);\n};\n" }, { "answer_id": 40090269, "author": "Wayne Chiu", "author_id": 6778784, "author_profile": "https://Stackoverflow.com/users/6778784", "pm_score": 1, "selected": false, "text": "Title Case Function function toTitleCase(input){\n let output = input\n .split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']\n .map((letter) => {\n let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y\n let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou\n return firstLetter + restLetters // conbine together\n })\n .join(' ') //['How' 'Are' 'You'] => 'How Are You'\n return output\n}\n function toTitleCase(input){\n return input\n .split(' ')\n .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())\n .join(' ') \n}\n\ntoTitleCase('HoW ARe yoU') // reuturn 'How Are You'\n" }, { "answer_id": 40111894, "author": "KevBot", "author_id": 2056157, "author_profile": "https://Stackoverflow.com/users/2056157", "pm_score": 6, "selected": false, "text": "toLowerCase toUpperCase function titleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, s => s.toUpperCase());\n}\n\nconsole.log(titleCase('iron man'));\nconsole.log(titleCase('iNcrEdible hulK'));" }, { "answer_id": 40287630, "author": "hacklikecrack", "author_id": 1181545, "author_profile": "https://Stackoverflow.com/users/1181545", "pm_score": -1, "selected": false, "text": "const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');\n" }, { "answer_id": 40289152, "author": "jssridhar", "author_id": 1024119, "author_profile": "https://Stackoverflow.com/users/1024119", "pm_score": 4, "selected": false, "text": "str.split(' ')\n .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())\n .join(' ')\n str.split(' ').map(function (s) {\n return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();\n}).join(' ')\n" }, { "answer_id": 41088451, "author": "Ouatataz", "author_id": 6710722, "author_profile": "https://Stackoverflow.com/users/6710722", "pm_score": 3, "selected": false, "text": "String.prototype.titlecase = function(lang, withLowers = false) {\n var i, string, lowers, uppers;\n\n string = this.replace(/([^\\s:\\-'])([^\\s:\\-']*)/g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }).replace(/Mc(.)/g, function(match, next) {\n return 'Mc' + next.toUpperCase();\n });\n\n if (withLowers) {\n if (lang == 'EN') {\n lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];\n }\n else {\n lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];\n }\n for (i = 0; i < lowers.length; i++) {\n string = string.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), function(txt) {\n return txt.toLowerCase();\n });\n }\n }\n\n uppers = ['Id', 'R&d'];\n for (i = 0; i < uppers.length; i++) {\n string = string.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), uppers[i].toUpperCase());\n }\n\n return string;\n}\n" }, { "answer_id": 41378781, "author": "waqas", "author_id": 649388, "author_profile": "https://Stackoverflow.com/users/649388", "pm_score": 4, "selected": false, "text": "_.startCase('foo bar');\n// => 'Foo Bar'\n\n_.startCase('--foo-bar--');\n// => 'Foo Bar'\n \n_.startCase('fooBar');\n// => 'Foo Bar'\n \n_.startCase('__FOO_BAR__');\n// => 'FOO BAR'" }, { "answer_id": 44386787, "author": "Vikram", "author_id": 2025736, "author_profile": "https://Stackoverflow.com/users/2025736", "pm_score": 3, "selected": false, "text": "str.replace(/(^[a-z])|(\\s+[a-z])/g, txt => txt.toUpperCase());\n" }, { "answer_id": 44387386, "author": "lashja", "author_id": 6564610, "author_profile": "https://Stackoverflow.com/users/6564610", "pm_score": 2, "selected": false, "text": "function titleCase(str)\n{\n var words = str.split(\" \");\n for ( var i = 0; i < words.length; i++ )\n {\n var j = words[i].charAt(0).toUpperCase();\n words[i] = j + words[i].substr(1);\n }\n return words.join(\" \");\n}" }, { "answer_id": 44665163, "author": "chasnz", "author_id": 8191338, "author_profile": "https://Stackoverflow.com/users/8191338", "pm_score": 0, "selected": false, "text": "var stopWordsArray = new Array(\"a\", \"all\", \"am\", \"an\", \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\", \"can\", \"can't\", \"did\", \"didn't\", \"do\", \"does\", \"doesn't\", \"don't\", \"else\", \"for\", \"get\", \"gets\", \"go\", \"got\", \"had\", \"has\", \"he\", \"he's\", \"her\", \"here\", \"hers\", \"hi\", \"him\", \"his\", \"how\", \"i'd\", \"i'll\", \"i'm\", \"i've\", \"if\", \"in\", \"is\", \"isn't\", \"it\", \"it's\", \"its\", \"let\", \"let's\", \"may\", \"me\", \"my\", \"no\", \"of\", \"off\", \"on\", \"our\", \"ours\", \"she\", \"so\", \"than\", \"that\", \"that's\", \"thats\", \"the\", \"their\", \"theirs\", \"them\", \"then\", \"there\", \"there's\", \"these\", \"they\", \"they'd\", \"they'll\", \"they're\", \"they've\", \"this\", \"those\", \"to\", \"too\", \"try\", \"until\", \"us\", \"want\", \"wants\", \"was\", \"wasn't\", \"we\", \"we'd\", \"we'll\", \"we're\", \"we've\", \"well\", \"went\", \"were\", \"weren't\", \"what\", \"what's\", \"when\", \"where\", \"which\", \"who\", \"who's\", \"whose\", \"why\", \"will\", \"with\", \"won't\", \"would\", \"yes\", \"yet\", \"you\", \"you'd\", \"you'll\", \"you're\", \"you've\", \"your\");\n\n// Only significant words are transformed. Handles acronyms and punctuation\nString.prototype.toTitleCase = function() {\n var newSentence = true;\n return this.split(/\\s+/).map(function(word) {\n if (word == \"\") { return; }\n var canCapitalise = true;\n // Get the pos of the first alpha char (word might start with \" or ')\n var firstAlphaCharPos = word.search(/\\w/);\n // Check for uppercase char that is not the first char (might be acronym or all caps)\n if (word.search(/[A-Z]/) > 0) {\n canCapitalise = false;\n } else if (stopWordsArray.indexOf(word) != -1) {\n // Is a stop word and not a new sentence\n word.toLowerCase();\n if (!newSentence) {\n canCapitalise = false;\n }\n }\n // Is this the last word in a sentence?\n newSentence = (word.search(/[\\.!\\?:]['\"]?$/) > 0)? true : false;\n return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;\n }).join(' ');\n}\n\n// Pass a string using dot notation:\nalert(\"A critical examination of Plato's view of the human nature\".toTitleCase());\nvar str = \"Ten years on: a study into the effectiveness of NCEA in New Zealand schools\";\nstr.toTitleCase());\nstr = \"\\\"Where to from here?\\\" the effectivness of eLearning in childhood education\";\nalert(str.toTitleCase());\n\n/* Result:\nA Critical Examination of Plato's View of the Human Nature.\nTen Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.\n\"Where to From Here?\" The Effectivness of eLearning in Childhood Education. */\n" }, { "answer_id": 44770157, "author": "Covfefe", "author_id": 8217903, "author_profile": "https://Stackoverflow.com/users/8217903", "pm_score": 1, "selected": false, "text": "function Title_Case(phrase) \n{\n var revised = phrase.charAt(0).toUpperCase();\n\n for ( var i = 1; i < phrase.length; i++ ) {\n\n if (phrase.charAt(i - 1) == \" \") {\n revised += phrase.charAt(i).toUpperCase(); }\n else {\n revised += phrase.charAt(i).toLowerCase(); }\n\n }\n\nreturn revised;\n}\n" }, { "answer_id": 44962866, "author": "wondim", "author_id": 3674573, "author_profile": "https://Stackoverflow.com/users/3674573", "pm_score": 3, "selected": false, "text": "function format_str(str) {\n str = str.toLowerCase();\n return '<span style=\"text-transform: capitalize\">'+ str +'</span>';\n}\n" }, { "answer_id": 46501455, "author": "xGeo", "author_id": 7291240, "author_profile": "https://Stackoverflow.com/users/7291240", "pm_score": 4, "selected": false, "text": "string var words = str.split(' ');\n var capitalized = words.map(function(word) {\n return word.charAt(0).toUpperCase() + word.substring(1, word.length);\n});\n capitalized.join(\" \");\n function titleCase(str) {\n str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end\n var words = str.split(\" \");\n\n var capitalized = words.map(function(word) {\n return word.charAt(0).toUpperCase() + word.substring(1, word.length);\n });\n return capitalized.join(\" \");\n}\n\nconsole.log(titleCase(\"I'm a little tea pot\")); str = \"I'm a little/small tea pot\"; const capitalize = str => str.length\n ? str[0].toUpperCase() +\n str.slice(1).toLowerCase()\n : '';\n\nconst escape = str => str.replace(/./g, c => `\\\\${c}`);\nconst titleCase = (sentence, seps = ' _-/') => {\n let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');\n \n return sentence.replace(wordPattern, capitalize);\n};\nconsole.log( titleCase(\"I'm a little/small tea pot.\") ); function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();\n}\n\nfunction titleCase(str) {\n return str.replace(/[^\\ \\/\\-\\_]+/g, capitalize);\n}\n\nconsole.log(titleCase(\"I'm a little/small tea pot.\"));" }, { "answer_id": 46774740, "author": "dipole_moment", "author_id": 1869326, "author_profile": "https://Stackoverflow.com/users/1869326", "pm_score": 4, "selected": false, "text": "const toTitleCase = (str) => {\n const articles = ['a', 'an', 'the'];\n const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];\n const prepositions = [\n 'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',\n 'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'\n ];\n\n // The list of spacial characters can be tweaked here\n const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\\\]/gi, ' ').replace(/(\\s\\s+)/gi, ' ');\n const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);\n const normalizeStr = (str) => str.toLowerCase().trim();\n const shouldCapitalize = (word, fullWordList, posWithinStr) => {\n if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {\n return true;\n }\n\n return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));\n }\n\n str = replaceCharsWithSpace(str);\n str = normalizeStr(str);\n\n let words = str.split(' ');\n if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized\n words = words.map(w => capitalizeFirstLetter(w));\n }\n else {\n for (let i = 0; i < words.length; i++) {\n words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);\n }\n }\n\n return words.join(' ');\n}\n import { expect } from 'chai';\nimport { toTitleCase } from '../../src/lib/stringHelper';\n\ndescribe('toTitleCase', () => {\n it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){\n expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long\n expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long\n expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long\n });\n\n it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){\n expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');\n expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');\n expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');\n });\n\n it('Replace special characters with space', function(){\n expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');\n expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');\n });\n\n it('Trim whitespace at beginning and end', function(){\n expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');\n });\n\n it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){\n expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');\n expect(toTitleCase('the three Musketeers And plus ')).to.equal('The Three Musketeers and Plus');\n });\n});\n" }, { "answer_id": 46959528, "author": "Tom Kay", "author_id": 1073738, "author_profile": "https://Stackoverflow.com/users/1073738", "pm_score": 6, "selected": false, "text": "toLowerCase() function title(str) {\n return str.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\n}\n 'my string'.toTitle() String.prototype.toTitle = function() {\n return this.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\n}\n String.prototype.toTitle = function() {\n return this.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\n}\n\nconsole.log('all lower case ->','all lower case'.toTitle());\nconsole.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());\nconsole.log(\"I'm a little teapot ->\",\"I'm a little teapot\".toTitle());" }, { "answer_id": 49398245, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "[^\\s_\\-/]* . function toUpperCase(str) { return str.toUpperCase(); }\nfunction capitalizeWord(word) { return word.replace(/./, toUpperCase); }\nfunction capitalize(sentence) { return sentence.toLowerCase().replace(/[^\\s_\\-/]*/g, capitalizeWord); }\n\nconsole.log(capitalize(\"hello world\")); // Outputs: Hello World replace function capitalize(sentence) {\n return sentence.toLowerCase().replace(/[^\\s_\\-/]*/g, function (word) {\n return word.replace(/./, function (ch) { return ch.toUpperCase(); } );\n } );\n}\n\nconsole.log(capitalize(\"hello world\")); // Outputs: Hello World" }, { "answer_id": 51346019, "author": "bajran", "author_id": 7763149, "author_profile": "https://Stackoverflow.com/users/7763149", "pm_score": 1, "selected": false, "text": "this is a test This Is A Test function capitalize(str) {\n\n const word = [];\n\n for (let char of str.split(' ')) {\n word.push(char[0].toUpperCase() + char.slice(1))\n }\n\n return word.join(' ');\n\n}\n\nconsole.log(capitalize(\"this is a test\"));" }, { "answer_id": 52175696, "author": "Wayne Li", "author_id": 5894959, "author_profile": "https://Stackoverflow.com/users/5894959", "pm_score": 0, "selected": false, "text": "function titleCase(str) {\n const arr = str.split(\" \");\n const result = arr.reduce((acc, cur) => {\n const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();\n return acc += `${newStr} `\n },\"\")\n return result.slice(0, result.length-1);\n}" }, { "answer_id": 52344286, "author": "Muhammad Usman", "author_id": 6298042, "author_profile": "https://Stackoverflow.com/users/6298042", "pm_score": 0, "selected": false, "text": "formatName(name) {\n let nam = '';\n name.split(' ').map((word, index) => {\n if (index === 0) {\n nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');\n } else {\n nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');\n }\n });\n return nam;\n}\n" }, { "answer_id": 52952471, "author": "Mayur Nandane", "author_id": 5314943, "author_profile": "https://Stackoverflow.com/users/5314943", "pm_score": 0, "selected": false, "text": "ES-6 way to get title case of a word or entire line.\nex. input = 'hEllo' --> result = 'Hello'\nex. input = 'heLLo woRLd' --> result = 'Hello World'\n\nconst getTitleCase = (str) => {\n if(str.toLowerCase().indexOf(' ') > 0) {\n return str.toLowerCase().split(' ').map((word) => {\n return word.replace(word[0], word[0].toUpperCase());\n }).join(' ');\n }\n else {\n return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();\n }\n}\n" }, { "answer_id": 52988991, "author": "henrie", "author_id": 9602904, "author_profile": "https://Stackoverflow.com/users/9602904", "pm_score": 3, "selected": false, "text": "<span id='text'>JOHN SMITH</span>\n var str = document.getElementById('text').innerHtml;\nvar return_text = str.toLowerCase();\n #text{text-transform:capitalize;}\n" }, { "answer_id": 54104929, "author": "Siddharth Joshi", "author_id": 3401966, "author_profile": "https://Stackoverflow.com/users/3401966", "pm_score": 2, "selected": false, "text": "_.capitalize('FRED'); => 'Fred'\n" }, { "answer_id": 54527288, "author": "iMartin", "author_id": 1877349, "author_profile": "https://Stackoverflow.com/users/1877349", "pm_score": 1, "selected": false, "text": "'john smith'.replace(/(^\\w|\\s+\\w){1}/g, function(str){ return str.toUpperCase() } );\n" }, { "answer_id": 56699654, "author": "Proximo", "author_id": 111624, "author_profile": "https://Stackoverflow.com/users/111624", "pm_score": 3, "selected": false, "text": "\"john f. kennedy\".replace(/\\b\\S/g, t => t.toUpperCase())\n" }, { "answer_id": 57486489, "author": "Fouad Boukredine", "author_id": 7594095, "author_profile": "https://Stackoverflow.com/users/7594095", "pm_score": 2, "selected": false, "text": "String.prototype.capitalizeWords = function() {\n return this.split(\" \").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(\" \");\n};\n capitalizeWords() var myS = \"this actually works!\";\nmyS.capitalizeWords();\n\n>>> This Actually Works\n function capitalizeFirstLetter(word) {\n return word[0].toUpperCase() + word.slice(1).toLowerCase();\n}\nString.prototype.capitalizeAllWords = function() {\n var arr = this.split(\" \");\n for(var i = 0; i < arr.length; i++) {\n arr[i] = capitalizeFirstLetter(arr[i]);\n }\n return arr.join(\" \");\n};\n capitalizeWords() var myStr = \"this one works too!\";\nmyStr.capitalizeWords();\n\n>>> This One Works Too\n function capitalizeFirstLetter(word) {\n return word[0].toUpperCase() + word.slice(1).toLowerCase();\n}\nString.prototype.capitalizeWords = function() {\n return this.replace(/\\w\\S*/g, capitalizeFirstLetter);\n};\n capitalizeWords() var myString = \"yes and no\";\nmyString.capitalizeWords()\n\n>>> Yes And No\n" }, { "answer_id": 58451659, "author": "Avinash", "author_id": 2753071, "author_profile": "https://Stackoverflow.com/users/2753071", "pm_score": 1, "selected": false, "text": "import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';\nconst titleCase = string =>\n padEnd(\n words(string, /[^ ]+/g)\n .map(lowerCase)\n .map(capitalize)\n .join(' '),\n string.length,\n );\n" }, { "answer_id": 59478805, "author": "Neeraj Kumar", "author_id": 1555696, "author_profile": "https://Stackoverflow.com/users/1555696", "pm_score": 0, "selected": false, "text": "var toTitleCase = function (str) {\n str = str.toLowerCase().split(' ');\n for (var i = 0; i < str.length; i++) {\n str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);\n }\n return str.join(' ');\n};\n" }, { "answer_id": 61123252, "author": "Regular Jo", "author_id": 3917091, "author_profile": "https://Stackoverflow.com/users/3917091", "pm_score": 2, "selected": false, "text": "function camelCase(str) {\n return str.replace(/((?:^|\\.)\\w|\\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\\b)\\w)/g, function(character) {\n return character.toUpperCase();\n})}\n \nconsole.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));" }, { "answer_id": 61843287, "author": "mschwartz", "author_id": 11194082, "author_profile": "https://Stackoverflow.com/users/11194082", "pm_score": 2, "selected": false, "text": "str.slice(0, 1).toUpperCase() + str.slice(1, str.length)\n [...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')\n" }, { "answer_id": 61874826, "author": "kapil pandey", "author_id": 11693215, "author_profile": "https://Stackoverflow.com/users/11693215", "pm_score": 5, "selected": false, "text": "let str=\"john smith\"\nstr=str.split(\" \").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join(\"\").toLowerCase()).join(\" \")\nconsole.log(str)" }, { "answer_id": 64892968, "author": "its4zahoor", "author_id": 2013403, "author_profile": "https://Stackoverflow.com/users/2013403", "pm_score": 2, "selected": false, "text": "\\g \\b[a-zA-Z] .toUpperCase() const textString = \"Convert string to title case with Javascript.\";\nconst converted = textString.replace(/\\b[a-zA-Z]/g, (match) => match.toUpperCase());\nconsole.log(converted)" }, { "answer_id": 64909945, "author": "Hedley Smith", "author_id": 3320740, "author_profile": "https://Stackoverflow.com/users/3320740", "pm_score": 3, "selected": false, "text": "const titleCase = (str) => {\n return str.replace(/\\w\\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });\n}\n\nexport default titleCase;\n utilities import titleCase from './utilities/titleCase.js';\n\nconst string = 'my title & string';\n\nconsole.log(titleCase(string)); //-> 'My Title & String'\n" }, { "answer_id": 64910248, "author": "Ulysse BN", "author_id": 6320039, "author_profile": "https://Stackoverflow.com/users/6320039", "pm_score": 5, "selected": false, "text": "function titleize(str) {\n let upper = true\n let newStr = \"\"\n for (let i = 0, l = str.length; i < l; i++) {\n // Note that you can also check for all kinds of spaces with\n // str[i].match(/\\s/)\n if (str[i] == \" \") {\n upper = true\n newStr += str[i]\n continue\n }\n newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()\n upper = false\n }\n return newStr\n}\n// NOTE: you could beat that using charcode and string builder I guess.\n str = \"the QUICK BrOWn Fox jUMPS oVeR the LAzy doG\";\nfunction regex(str) {\n return str.replace(\n /\\w\\S*/g,\n function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }\n );\n}\n\nfunction split(str) {\n return str.\n split(' ').\n map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).\n join(' ');\n}\n\nfunction complete(str) {\n var i, j, str, lowers, uppers;\n str = str.replace(/([^\\W_]+[^\\s-]*) */g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n\n // Certain minor words should be left lowercase unless \n // they are the first or last words in the string\n lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', \n 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];\n for (i = 0, j = lowers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), \n function(txt) {\n return txt.toLowerCase();\n });\n\n // Certain words such as initialisms or acronyms should be left uppercase\n uppers = ['Id', 'Tv'];\n for (i = 0, j = uppers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), \n uppers[i].toUpperCase());\n\n return str;\n}\n\nfunction firstLetterOnly(str) {\n return str.replace(/\\b(\\S)/g, function(t) { return t.toUpperCase(); });\n}\n\nfunction forLoop(str) {\n let upper = true;\n let newStr = \"\";\n for (let i = 0, l = str.length; i < l; i++) {\n if (str[i] == \" \") {\n upper = true;\n newStr += \" \";\n continue;\n }\n newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();\n upper = false;\n }\n return newStr;\n}\n" }, { "answer_id": 65167625, "author": "Soham Patel", "author_id": 7370437, "author_profile": "https://Stackoverflow.com/users/7370437", "pm_score": 2, "selected": false, "text": "function toTitleCase(str) {\n return str.replace(\n /(\\w*\\W*|\\w*)\\s*/g,\n function(txt) {\n return(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())\n }\n ); \n} <form>\n Input:\n <br /><textarea name=\"input\" onchange=\"form.output.value=toTitleCase(this.value)\" onkeyup=\"form.output.value=toTitleCase(this.value)\"></textarea>\n <br />Output:\n <br /><textarea name=\"output\" readonly onclick=\"select(this)\"></textarea>\n</form>" }, { "answer_id": 67641990, "author": "PaperinFlames", "author_id": 13929460, "author_profile": "https://Stackoverflow.com/users/13929460", "pm_score": 2, "selected": false, "text": "let str = 'john smith';\nlet res = str.split(\" \");\nres.forEach((w, index) => {\n res[index] = w.charAt(0).toUpperCase().concat(w.slice(1, w.length))\n});\nres = res.join(\" \");\nconsole.log(res);" }, { "answer_id": 68236885, "author": "Max", "author_id": 14647822, "author_profile": "https://Stackoverflow.com/users/14647822", "pm_score": -1, "selected": false, "text": "function toTitleCase(string = '') {\n const regex = /^[a-z]{0,1}|\\s\\w/gi;\n\n string = string.toLowerCase();\n\n string.match(regex).forEach((char) => {\n string = string.replace(char, char.toUpperCase());\n });\n\n return string;\n}\n\nconst input = document.getElementById('fullname');\nconst button = document.getElementById('button');\nconst result = document.getElementById('result');\n\nbutton.addEventListener('click', () => {\n result.innerText = toTitleCase(input.value);\n}); <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Test</title>\n</head>\n<body>\n <input type=\"text\" id=\"fullname\">\n <button id=\"button\">click me</button>\n <p id=\"result\">Result here</p>\n <script src=\"./index.js\"></script>\n</body>\n</html>" }, { "answer_id": 68635466, "author": "Anshul", "author_id": 8671374, "author_profile": "https://Stackoverflow.com/users/8671374", "pm_score": -1, "selected": false, "text": "String.prototype.toTitleCase = function () { return this.valueOf().toLowerCase().replace(this.valueOf()[0], this.valueOf()[0].toUpperCase()); }\n\nconsole.log('laiLA'.toTitleCase());" }, { "answer_id": 70546786, "author": "o17t H1H' S'k", "author_id": 664456, "author_profile": "https://Stackoverflow.com/users/664456", "pm_score": 2, "selected": false, "text": "function toTitleCase(str) {\n return str.replace(/\\p{L}+('\\p{L}+)?/gu, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.slice(1)\n })\n}\n" }, { "answer_id": 70682133, "author": "Kerem", "author_id": 1421528, "author_profile": "https://Stackoverflow.com/users/1421528", "pm_score": 3, "selected": false, "text": "function toTitleCase(str) {\n return str.toLocaleLowerCase().replace(\n /(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|\\w)\\S*/g,\n (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),\n )\n}\n\nconsole.log(toTitleCase('İSMAİL HAKKI'))\nconsole.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))\nconsole.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))" }, { "answer_id": 70959264, "author": "rinogo", "author_id": 114558, "author_profile": "https://Stackoverflow.com/users/114558", "pm_score": 0, "selected": false, "text": "title-case npm install title-case --save\n import { titleCase } from \"title-case\";\n\ntitleCase(\"string\"); //=> \"String\"\ntitleCase(\"follow step-by-step instructions\"); //=> \"Follow Step-by-Step Instructions\"\n" }, { "answer_id": 72497564, "author": "Brendan Sluke", "author_id": 7660196, "author_profile": "https://Stackoverflow.com/users/7660196", "pm_score": 0, "selected": false, "text": "npm install title-case title-case import { titleCase } from \"title-case\";\n\ntitleCase(\"string\"); //=> \"String\"\ntitleCase(\"follow step-by-step instructions\"); //=> \"Follow Step-by-Step Instructions\"\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
196,976
<p>I have an old project that was built using visual studio 2003 and I recompiled it with vs2005 recently. However, during runtime, I get the following error:</p> <p>list iterator not incrementable</p> <p>I traced the program to this function:</p> <pre><code>void InputQueue::update() { list&lt;PCB&gt;::iterator iter; list&lt;PCB&gt;::iterator iterTemp; for(iter = begin(); iter != end(); iter++) { if(iter-&gt;arrivalTime == 0) { ReadyQueue::getInstance()-&gt;add(*iter); iterTemp = iter; iter++; erase(iterTemp); } } } </code></pre> <p>I'm not a C++ expert and this is as far as the VS debugger got me. Could somebody explain to me what the problem is?</p> <p>Thanks</p>
[ { "answer_id": 196988, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "iter->arrivalTime == 0 end()" }, { "answer_id": 196994, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": " for(iter = begin(); iter != end(); iter++) // ***\n {\n if(iter->arrivalTime == 0)\n { \n\n iter++; // ***\n\n }\n }\n end()" }, { "answer_id": 196996, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": false, "text": "while (iter != end())\n{\n if (iter->arrivalTime == 0)\n {\n ReadyQueue::getInstance()->add(*iter);\n iter = erase(iter);\n }\n else\n {\n ++iter;\n }\n}\n" }, { "answer_id": 197007, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "std::ist<PCB>" }, { "answer_id": 197153, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "std::remove_if ReadyQueue::getInstance()->add(subrange_begin, subrange_end)" }, { "answer_id": 19817468, "author": "suc", "author_id": 2730054, "author_profile": "https://Stackoverflow.com/users/2730054", "pm_score": 1, "selected": false, "text": " for (list<CMessage*>::iterator it=que.begin(); it!=que.end(); ++it)\n {\n if(m_type == (*it)->m_type)\n {\n delete *it;\n it=que.erase(it); //\"list.erase()\" will change the iterator!!!\n if(it==que.end()) break; //Check again!!!\n //still has side effect here. --it?\n }\n }\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
196,980
<p>The rich text editor must be implemented in Java, provide Swing support, and preferably be open source.</p> <p>I'm looking to integrate it into an existing Java/Swing application. </p> <p>Thanks.</p>
[ { "answer_id": 197036, "author": "dalyons", "author_id": 16925, "author_profile": "https://Stackoverflow.com/users/16925", "pm_score": 5, "selected": false, "text": "jpane.getSelectionStart() jpane.getSelectionEnd() history.push(jpane.getText()) jpane.setText(history.pop())" }, { "answer_id": 2736329, "author": "user328744", "author_id": 328744, "author_profile": "https://Stackoverflow.com/users/328744", "pm_score": 3, "selected": false, "text": "HTMLDocumentEditor StyledEditorKit" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27344/" ]
196,993
<p>i have a wordpress blog and want to give people the same user experience for adding comments that is in stackoverflow. There are a number of comments ajax plugins out there but i can't find a working one that allows you to inline on the main page, go in and add comments without first drilling down into a seperate single post page.</p> <p>Can anyone help here with either a wordpress plugin or php code to do this.</p>
[ { "answer_id": 207140, "author": "coderGeek", "author_id": 28426, "author_profile": "https://Stackoverflow.com/users/28426", "pm_score": 4, "selected": true, "text": "<?php the_content(''); ?>\n <?php ajax_comments_link(); ?>\n<?php ajax_comments_div(); ?>\n if ($comment_count == '1') {\n echo('<span id=\"show-inline-comments-'. $id .'\"> ');\n /* echo('<a href=\"javascript:;\" id=\"show-inline-comments-link-'. $id .'\" onmouseup=\"ajaxShowComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return false;\">show comment &raquo;</a>'); \n*/\n echo('</span>');\n echo('<span id=\"hide-inline-comments-'. $id .'\" style=\"display: none;\"> ');\n /* echo('<a href=\"#comments-'. $id .'\" onmouseup=\"ajaxHideComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return true;\">&laquo; hide comment</a>'); \n*/\n echo('</span>');\n} else if ($comment_count > '1') {\n echo('<span id=\"show-inline-comments-'. $id .'\"> ');\n /* echo('<a href=\"javascript:;\" id=\"show-inline-comments-link-'. $id .'\" onmouseup=\"ajaxShowComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return false;\">show comments &raquo;</a>'); \n*/\n echo('</span>');\n echo('<span id=\"hide-inline-comments-'. $id .'\" style=\"display: none;\"> ');\n /* echo('<a href=\"#comments-'. $id .'\" onmouseup=\"ajaxHideComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return true;\">&laquo; hide comments</a>'); \n*/\n echo('</span>');\n}\n" }, { "answer_id": 1082189, "author": "anshul", "author_id": 17674, "author_profile": "https://Stackoverflow.com/users/17674", "pm_score": 1, "selected": false, "text": "functions.php functions.php inc entry.php index.php <?php if (have_posts()) : ?> \n\n <?php while (have_posts()) : the_post(); ?> \n <?php /* your themes code must be here */ ?>\n\n <?php endwhile; ?> \n <?php if (have_posts()) : ?> \n\n <?php while (have_posts()) : the_post(); ?> \n <?php require dirname(__FILE__) . '/entry.php'; ?> \n\n <?php endwhile; ?> \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/196993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
197,009
<p>A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.</p> <p>Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists. </p> <pre><code> if os.path.isdir(checkout_dir): # working copy dir already exists return checkout_dir </code></pre> <p>So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.</p> <p>Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.</p> <pre><code>checked-out failed: svn: Working copy '/tmp/qm_23683' locked svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)** </code></pre> <p>So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?</p> <p>Thanks.</p>
[ { "answer_id": 199791, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 3, "selected": true, "text": "svn svn svn import os, errno\n\n# ...\n\ntry:\n os.mkdir(dirName)\nexcept OSError, e:\n if e.errno != errno.EEXIST: raise # some other error\n print 'Directory already exists.'\nelse:\n print 'Successfully created new directory.'\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
197,027
<p>I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.</p> <p>I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.</p> <p>Finally, how do I pass the selected id from the dropdown box back to my action in the controller?</p>
[ { "answer_id": 197549, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 1, "selected": false, "text": "<%= Html.DropDownList(\"Select One\", \"CategoryId\", ViewData.Model.Categories, \"Id\", \"Name\", ViewData.Model.SelectedCategoryId)) %>\n" }, { "answer_id": 476759, "author": "Konstantinos", "author_id": 17443, "author_profile": "https://Stackoverflow.com/users/17443", "pm_score": 3, "selected": true, "text": "//Lets assume you retrieve your product types somehow here\nViewData[\"ProductTypes\"] = new List<ProductType>();\n <%= Html.DropDownList(\"productType\",\n new SelectList((IEnumerable)ViewData[\"ProductTypes\"],\n \"TypeID\", \"Description\"))%>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2812/" ]
197,028
<p>neither</p> <pre><code>&lt;?php system('php file.php'); ?&gt; </code></pre> <p>nor</p> <pre><code>&lt;?php system('/usr/bin/php file.php'); ?&gt; </code></pre> <p>worked. Why?</p> <p>I tried with <code>-q</code>, with <code>!#/usr/bin/php</code> etc.</p>
[ { "answer_id": 197034, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 2, "selected": false, "text": "<?php system('/usr/bin/php -f file.php'); ?>\n" }, { "answer_id": 197038, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 1, "selected": false, "text": "Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.\n" }, { "answer_id": 197084, "author": "barredo", "author_id": 7398, "author_profile": "https://Stackoverflow.com/users/7398", "pm_score": 0, "selected": false, "text": "<?php\n$a = system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\nprint_r($a);\necho '-'; # for separation\nprint_r($b); ?>\n <?php echo 'hello world'; ?>\n" }, { "answer_id": 197085, "author": "olle", "author_id": 22422, "author_profile": "https://Stackoverflow.com/users/22422", "pm_score": 0, "selected": false, "text": "<?php\nerror_reporting(E_ALL);\nini_set(\"display_errors\", 1);\n$a = system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\nprint_r($a);\necho '-'; # for separation\nprint_r($b);\n" }, { "answer_id": 197256, "author": "barredo", "author_id": 7398, "author_profile": "https://Stackoverflow.com/users/7398", "pm_score": 0, "selected": false, "text": "system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\n ('/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\n" }, { "answer_id": 197276, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "$output = array();\n$returnCode = 0;\nexec('/usr/bin/php -f /Applications/MAMP/htdocs/a.php 2>&1', $output, $returnCode);\nprint_r($output);\n 2>&1 $output" }, { "answer_id": 197908, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 0, "selected": false, "text": "$fp = popen('/usr/bin/php -f file.php', 'r');\n\nif(false === $fp)\n{\n // something bad happened: error handle\n}\n\n$contents = '';\n\nwhile(false === feof($fp))\n{\n $contents .= fgets($fp);\n}\n\nfclose($fp); \necho $contents;\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7398/" ]
197,033
<p>Where is the location of my oracle event log (on a default Linux installation)?</p>
[ { "answer_id": 197108, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 5, "selected": true, "text": "select value from v$parameter where name = 'background_dump_dest'\n" }, { "answer_id": 197120, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 3, "selected": false, "text": "/usr/lib/oracle/xe/app/oracle/admin/XE/bdump\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27346/" ]
197,045
<p>Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?</p>
[ { "answer_id": 375202, "author": "Cameron Pope", "author_id": 1385388, "author_profile": "https://Stackoverflow.com/users/1385388", "pm_score": 9, "selected": true, "text": "columnDefinition @Column @Column(name=\"Price\", columnDefinition=\"Decimal(10,2) default '100.00'\")\n" }, { "answer_id": 1013520, "author": "Pablo Venturino", "author_id": 16732, "author_profile": "https://Stackoverflow.com/users/16732", "pm_score": 8, "selected": false, "text": "@Column(name=\"price\")\nprivate double price = 0.0;\n" }, { "answer_id": 2554796, "author": "asd", "author_id": 306202, "author_profile": "https://Stackoverflow.com/users/306202", "pm_score": 3, "selected": false, "text": "@Column(columnDefinition=\"tinyint(1) default 1\")\n @Column(name=\"price\") \nprivate double price = 0.0;\n" }, { "answer_id": 2622053, "author": "Marco", "author_id": 314510, "author_profile": "https://Stackoverflow.com/users/314510", "pm_score": 4, "selected": false, "text": "public class MyObject\n{\n int attrib = 0;\n\n /** Default is 0 */\n @Column ( nullable = true )\n public int getAttrib()\n\n /** Falls to default = 0 when null */\n public void setAttrib ( Integer attrib ) {\n this.attrib = attrib == null ? 0 : attrib;\n }\n}\n" }, { "answer_id": 3400418, "author": "Derek Mahar", "author_id": 107158, "author_profile": "https://Stackoverflow.com/users/107158", "pm_score": 1, "selected": false, "text": "save() update() Example" }, { "answer_id": 8585494, "author": "Lenik", "author_id": 217071, "author_profile": "https://Stackoverflow.com/users/217071", "pm_score": 3, "selected": false, "text": "@DefaultValue commit 34199cba96b6b1dc42d0d19c066bd4d119b553d5\nAuthor: Lenik <xjl at 99jsj.com>\nDate: Wed Dec 21 13:28:33 2011 +0800\n\n Add default-value ddl support with annotation @DefaultValue.\n\ndiff --git a/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java\nnew file mode 100644\nindex 0000000..b3e605e\n--- /dev/null\n+++ b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java\n@@ -0,0 +1,35 @@\n+package org.hibernate.annotations;\n+\n+import static java.lang.annotation.ElementType.FIELD;\n+import static java.lang.annotation.ElementType.METHOD;\n+import static java.lang.annotation.RetentionPolicy.RUNTIME;\n+\n+import java.lang.annotation.Retention;\n+\n+/**\n+ * Specify a default value for the column.\n+ *\n+ * This is used to generate the auto DDL.\n+ *\n+ * WARNING: This is not part of JPA 2.0 specification.\n+ *\n+ * @author 谢继雷\n+ */\n+@java.lang.annotation.Target({ FIELD, METHOD })\n+@Retention(RUNTIME)\n+public @interface DefaultValue {\n+\n+ /**\n+ * The default value sql fragment.\n+ *\n+ * For string values, you need to quote the value like 'foo'.\n+ *\n+ * Because different database implementation may use different \n+ * quoting format, so this is not portable. But for simple values\n+ * like number and strings, this is generally enough for use.\n+ */\n+ String value();\n+\n+}\ndiff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\nindex b289b1e..ac57f1a 100644\n--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\n+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\n@@ -29,6 +29,7 @@ import org.hibernate.AnnotationException;\n import org.hibernate.AssertionFailure;\n import org.hibernate.annotations.ColumnTransformer;\n import org.hibernate.annotations.ColumnTransformers;\n+import org.hibernate.annotations.DefaultValue;\n import org.hibernate.annotations.common.reflection.XProperty;\n import org.hibernate.cfg.annotations.Nullability;\n import org.hibernate.mapping.Column;\n@@ -65,6 +66,7 @@ public class Ejb3Column {\n private String propertyName;\n private boolean unique;\n private boolean nullable = true;\n+ private String defaultValue;\n private String formulaString;\n private Formula formula;\n private Table table;\n@@ -175,7 +177,15 @@ public class Ejb3Column {\n return mappingColumn.isNullable();\n }\n\n- public Ejb3Column() {\n+ public String getDefaultValue() {\n+ return defaultValue;\n+ }\n+\n+ public void setDefaultValue(String defaultValue) {\n+ this.defaultValue = defaultValue;\n+ }\n+\n+ public Ejb3Column() {\n }\n\n public void bind() {\n@@ -186,7 +196,7 @@ public class Ejb3Column {\n }\n else {\n initMappingColumn(\n- logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true\n+ logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, defaultValue, true\n );\n log.debug( \"Binding column: \" + toString());\n }\n@@ -201,6 +211,7 @@ public class Ejb3Column {\n boolean nullable,\n String sqlType,\n boolean unique,\n+ String defaultValue,\n boolean applyNamingStrategy) {\n if ( StringHelper.isNotEmpty( formulaString ) ) {\n this.formula = new Formula();\n@@ -217,6 +228,7 @@ public class Ejb3Column {\n this.mappingColumn.setNullable( nullable );\n this.mappingColumn.setSqlType( sqlType );\n this.mappingColumn.setUnique( unique );\n+ this.mappingColumn.setDefaultValue(defaultValue);\n\n if(writeExpression != null && !writeExpression.matches(\"[^?]*\\\\?[^?]*\")) {\n throw new AnnotationException(\n@@ -454,6 +466,11 @@ public class Ejb3Column {\n else {\n column.setLogicalColumnName( columnName );\n }\n+ DefaultValue _defaultValue = inferredData.getProperty().getAnnotation(DefaultValue.class);\n+ if (_defaultValue != null) {\n+ String defaultValue = _defaultValue.value();\n+ column.setDefaultValue(defaultValue);\n+ }\n\n column.setPropertyName(\n BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )\ndiff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\nindex e57636a..3d871f7 100644\n--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\n+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\n@@ -423,6 +424,7 @@ public class Ejb3JoinColumn extends Ejb3Column {\n getMappingColumn() != null ? getMappingColumn().isNullable() : false,\n referencedColumn.getSqlType(),\n getMappingColumn() != null ? getMappingColumn().isUnique() : false,\n+ null, // default-value\n false\n );\n linkWithValue( value );\n@@ -502,6 +504,7 @@ public class Ejb3JoinColumn extends Ejb3Column {\n getMappingColumn().isNullable(),\n column.getSqlType(),\n getMappingColumn().isUnique(),\n+ null, // default-value\n false //We do copy no strategy here\n );\n linkWithValue( value );\n" }, { "answer_id": 8750327, "author": "Tong", "author_id": 1133136, "author_profile": "https://Stackoverflow.com/users/1133136", "pm_score": 3, "selected": false, "text": "columnDefinition @Column(columnDefinition=\"TIMESTAMP DEFAULT CURRENT_TIMESTAMP\")\n\nprivate Date createdDate;\n" }, { "answer_id": 9191447, "author": "Gal Bracha", "author_id": 395804, "author_profile": "https://Stackoverflow.com/users/395804", "pm_score": 2, "selected": false, "text": "@Column(columnDefinition=\"double precision default '96'\")\n\nprivate Double grolsh;\n" }, { "answer_id": 13432234, "author": "Husin Wijaya", "author_id": 637042, "author_profile": "https://Stackoverflow.com/users/637042", "pm_score": 7, "selected": false, "text": "@PrePersist\nvoid preInsert() {\n if (this.createdTime == null)\n this.createdTime = new Date();\n}\n" }, { "answer_id": 35761040, "author": "Dave Anderson", "author_id": 6010634, "author_profile": "https://Stackoverflow.com/users/6010634", "pm_score": 1, "selected": false, "text": "getDate() insertable=false" }, { "answer_id": 36423172, "author": "Thomas Zhang", "author_id": 4250694, "author_profile": "https://Stackoverflow.com/users/4250694", "pm_score": 3, "selected": false, "text": " @PrePersist\n void preInsert() {\n PrePersistUtil.pre(this);\n }\n public class PrePersistUtil {\n\n private static SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n\n public static void pre(Object object){\n try {\n Field[] fields = object.getClass().getDeclaredFields();\n for(Field field : fields){\n field.setAccessible(true);\n if (field.getType().getName().equals(\"java.lang.Long\")\n && field.get(object) == null){\n field.set(object,0L);\n }else if (field.getType().getName().equals(\"java.lang.String\")\n && field.get(object) == null){\n field.set(object,\"\");\n }else if (field.getType().getName().equals(\"java.util.Date\")\n && field.get(object) == null){\n field.set(object,sdf.parse(\"1900-01-01\"));\n }else if (field.getType().getName().equals(\"java.lang.Double\")\n && field.get(object) == null){\n field.set(object,0.0d);\n }else if (field.getType().getName().equals(\"java.lang.Integer\")\n && field.get(object) == null){\n field.set(object,0);\n }else if (field.getType().getName().equals(\"java.lang.Float\")\n && field.get(object) == null){\n field.set(object,0.0f);\n }\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n }\n" }, { "answer_id": 42150940, "author": "Ondra Žižka", "author_id": 145989, "author_profile": "https://Stackoverflow.com/users/145989", "pm_score": 6, "selected": false, "text": "@Column(columnDefinition='...') @Column(length = 4096, nullable = false)\n@org.hibernate.annotations.ColumnDefault(\"\")\nprivate String description;\n @ColumnDefault DEFAULT" }, { "answer_id": 44791049, "author": "Appesh", "author_id": 2244734, "author_profile": "https://Stackoverflow.com/users/2244734", "pm_score": 3, "selected": false, "text": "@Column(columnDefinition='...') insertable = false columnDefinition='...' insertable = false" }, { "answer_id": 46688515, "author": "Mohammed Rafeeq", "author_id": 1752917, "author_profile": "https://Stackoverflow.com/users/1752917", "pm_score": 2, "selected": false, "text": "@PrePersist\nvoid preInsert() {\n if (this.dateOfConsent == null)\n this.dateOfConsent = LocalDateTime.now();\n if(this.consentExpiry==null)\n this.consentExpiry = this.dateOfConsent.plusMonths(3);\n}\n" }, { "answer_id": 69636978, "author": "Diego Macario", "author_id": 2101212, "author_profile": "https://Stackoverflow.com/users/2101212", "pm_score": 2, "selected": false, "text": "@DynamicInsert @DynamicUpdate" }, { "answer_id": 72163049, "author": "Akash Verma", "author_id": 4273204, "author_profile": "https://Stackoverflow.com/users/4273204", "pm_score": 0, "selected": false, "text": "@ColumnDefault(\"abcd\")\nvar name: String,\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
197,047
<p>What is the difference between <code>&lt;% %&gt;</code> and <code>&lt;%= %&gt;</code> in ASP.NET MVC? And when to use which?</p>
[ { "answer_id": 197055, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 3, "selected": false, "text": "protected string SayHello()\n{\n return \"Hello!\";\n}\n first: <%= SayHello() %>\nsecond: <% SayHello() %>\n first: Hello!\nsecond: \n" }, { "answer_id": 197090, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 6, "selected": true, "text": "<% <%@ <%$ <%= <%# <%-- <%:" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
197,048
<p>Now that <code>shared_ptr</code> is in tr1, what do you think should happen to the use of <code>std::auto_ptr</code>? They both have different use cases, but all use cases of <code>auto_ptr</code> can be solved with <code>shared_ptr</code>, too. Will you abandon <code>auto_ptr</code> or continue to use it in cases where you want to express explicitly that only one class has ownership at any given point?</p> <p>My take is that using <code>auto_ptr</code> can add clarity to code, precisely by adding nuance and an indication of the design of the code, but on the other hand, it add yet another subtle issue when training new programmers: they need to understand smart pointers and the fine details of how they work. When you use only one smart pointer everywhere, you can just lay down a rule 'wrap all pointers in <code>shared_ptr</code>' and be done with it.</p> <p>What's your take on this?</p>
[ { "answer_id": 197054, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "shared_ptr auto_ptr" }, { "answer_id": 197083, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "std::auto_ptr boost::scoped_ptr std::tr1::shared_ptr scoped_ptr" }, { "answer_id": 197104, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 4, "selected": false, "text": "shared_ptr shared_ptr std::auto_ptr boost::scoped_ptr std::unique_ptr std::shared_ptr std::auto_ptr" }, { "answer_id": 197105, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 5, "selected": false, "text": "auto_ptr<T> T auto_ptr<T> scoped_ptr<T> T" }, { "answer_id": 198063, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "std::auto_ptr auto_ptr auto_ptr boost::scoped_ptr scoped_ptr auto_ptr shared_ptr scoped_ptr scoped_ptr shared_ptr" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11449/" ]
197,057
<p>Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?</p>
[ { "answer_id": 197588, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "-cp tools.jar tools.jar import com.sun.source.util.Trees;\nimport javax.tools.JavaCompiler;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.ToolProvider;\n\npublic class JCTreeTest {\n private static final JavaCompiler javac\n = ToolProvider.getSystemJavaCompiler();\n\n public static void main(String[] args) {\n final StandardJavaFileManager jfm\n = javac.getStandardFileManager(null, null, null);\n final JavaCompiler.CompilationTask task\n = javac.getTask(null, jfm, null, null, null,\n jfm.getJavaFileObjects(args));\n final Trees trees = Trees.instance(task);\n // Do stuff with \"trees\"\n }\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15441/" ]
197,059
<p>What is the most efficient way of turning the list of values of a dictionary into an array?</p> <p>For example, if I have a <code>Dictionary</code> where <code>Key</code> is <code>String</code> and <code>Value</code> is <code>Foo</code>, I want to get <code>Foo[]</code></p> <p>I am using VS 2005, C# 2.0</p>
[ { "answer_id": 197062, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 8, "selected": true, "text": "// dict is Dictionary<string, Foo>\n\nFoo[] foos = new Foo[dict.Count];\ndict.Values.CopyTo(foos, 0);\n\n// or in C# 3.0:\nvar foos = dict.Values.ToArray();\n" }, { "answer_id": 197071, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 3, "selected": false, "text": "Foo[] arr = new Foo[dict.Count]; \ndict.Values.CopyTo(arr, 0);\n IEnumerable<Foo> foos = dict.Values;\n" }, { "answer_id": 9928420, "author": "Steztric", "author_id": 1069178, "author_profile": "https://Stackoverflow.com/users/1069178", "pm_score": 4, "selected": false, "text": "List<Foo> arr = new List<Foo>(dict.Values);\n Foo[] arr = (new List<Foo>(dict.Values)).ToArray();\n" }, { "answer_id": 15003916, "author": "Piotr Czyż", "author_id": 851516, "author_profile": "https://Stackoverflow.com/users/851516", "pm_score": 3, "selected": false, "text": "Dictionary<string, object> dict = new Dictionary<string, object>();\nvar arr = dict.Select(z => z.Value).ToArray();\n" }, { "answer_id": 50420276, "author": "Lior Kirshner", "author_id": 8960627, "author_profile": "https://Stackoverflow.com/users/8960627", "pm_score": 2, "selected": false, "text": "// convert the dictionary to an array of strings\nstring[] strArray = dict.Select(x => (\"Key: \" + x.Key + \", Value: \" + x.Value)).ToArray();\n\n// convert a string array to a single string\nstring result = String.Join(\", \", strArray);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
197,070
<p>Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?</p> <p>eg getting the AST for:</p> <hr> <h2>Class1.java</h2> <pre><code>package parseable; public class Class1 { /** * @param args */ public static void main(String[] args) { System.out.println("Hello world!"); } </code></pre> <p>}</p>
[ { "answer_id": 6565258, "author": "johncip", "author_id": 353434, "author_profile": "https://Stackoverflow.com/users/353434", "pm_score": 1, "selected": false, "text": "// get an ICompilationUnit by some means\n// you might drill down from an IJavaProject, for instance \nICompilationUnit iunit = ...\n\n// create a new parser for the latest Java Language Spec\nASTParser parser = ASTParser.newParser(AST.JLS3);\n\n// tell the parser you are going to pass it some code where the type level is a source file\n// you might also just want to parse a block, or a method (\"class body declaration\"), etc\nparser.setKind(ASTParser.K_COMPILATION_UNIT);\n\n// set the source to be parsed to the ICompilationUnit\n// we could also use a character array\nparser.setSource(iunit);\n\n// parse it.\n// the output will be a CompilationUnit (also an ASTNode)\n// the null is because we're not using a progress monitor\nCompilationUnit unit = (CompilationUnit) parser.createAST(null);\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15441/" ]
197,081
<p>How can I do the Ruby method <a href="http://www.ruby-doc.org/core/classes/Array.html#M002241" rel="noreferrer">"Flatten" Ruby Method</a> in C#. This method flattens a jagged array into a single-dimensional array.</p> <p>For example:</p> <pre><code>s = [ 1, 2, 3 ] #=&gt; [1, 2, 3] t = [ 4, 5, 6, [7, 8] ] #=&gt; [4, 5, 6, [7, 8]] a = [ s, t, 9, 10 ] #=&gt; [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] a.flatten #=&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 </code></pre>
[ { "answer_id": 197087, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 5, "selected": true, "text": "IEnumerable Flatten(IEnumerable array)\n{\n foreach(var item in array)\n {\n if(item is IEnumerable)\n {\n foreach(var subitem in Flatten((IEnumerable)item))\n {\n yield return subitem;\n }\n }\n else\n {\n yield return item;\n }\n }\n}\n public static IEnumerable Flatten(this IEnumerable array)\n foreach(var item in myArray.Flatten()) { ... }\n" }, { "answer_id": 200144, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 2, "selected": false, "text": "public static IEnumerable Flatten<T>(IEnumerable e)\n{\n if (e == null) yield break;\n foreach (var item in e)\n {\n if (item is T)\n yield return (T)item;\n else if (item is IEnumerable)\n {\n foreach (var subitem in Flatten<T>((IEnumerable)item))\n yield return subitem;\n }\n else\n yield return item;\n }\n}\n" }, { "answer_id": 70032423, "author": "had", "author_id": 1326212, "author_profile": "https://Stackoverflow.com/users/1326212", "pm_score": 0, "selected": false, "text": "var s = new[] { 1, 2, 3 };\nvar t = new[] { 4, 5, 6 };\nvar a = new[] { s, t, new[] {7, 8} };\n\na.SelectMany(e => e); \n// IEnumerable<int> {1,2,3,4,5,6,7,8}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4455/" ]
197,088
<p>In WPF, there are two ways to set the focus to an element.<br> You can either call the .Focus() method of the input element, or call Keyboard.Focus() with the input element as parameter.</p> <pre><code>// first way: item.Focus(); // alternate way: Keyboard.Focus(item); </code></pre> <p>What is the difference between these two? Are there special reasons to use one of them instead of the other in some cases?<br> So far I noticed no difference - what ever method I used, the item always got logical focus as well as keyboard focus.</p>
[ { "answer_id": 197309, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 0, "selected": false, "text": "DependencyObject focusScope = FocusManager.GetFocusScope(item);\nif (FocusManager.GetFocusedElement(focusScope) == null)\n{\n FocusManager.SetFocusedElement(focusScope, item);\n}\n" }, { "answer_id": 197582, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 6, "selected": true, "text": "item.Focus() Keyboard.Focus( this ) FocusManager UIElement UIElement3D public bool Focus()\n{\n if (Keyboard.Focus(this) == this)\n {\n return true;\n }\n if (this.Focusable && this.IsEnabled)\n {\n DependencyObject focusScope = FocusManager.GetFocusScope(this);\n if (FocusManager.GetFocusedElement(focusScope) == null)\n {\n FocusManager.SetFocusedElement(focusScope, this);\n }\n }\n return false;\n}\n ContentElement public bool Focus()\n{\n return (Keyboard.Focus(this) == this);\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
197,095
<p>The following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation:</p> <pre><code>&lt;StackPanel&gt; &lt;TextBlock x:Name="MyTextBlock"&gt;Foo Bar&lt;/TextBlock&gt; &lt;TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" /&gt; &lt;/StackPanel&gt; </code></pre> <p>The binding also uses the <a href="http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx" rel="noreferrer">StringFormat property introduced with .NET 3.5 SP1</a> which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas?</p>
[ { "answer_id": 197130, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 7, "selected": false, "text": "<TextBox ...>\n <TextBox.ToolTip>\n <ToolTip \n Content=\"{Binding ElementName=myTextBlock,Path=Text}\"\n ContentStringFormat=\"{}It is: {0}\"\n />\n </TextBox.ToolTip>\n</TextBox>\n" }, { "answer_id": 197370, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": -1, "selected": true, "text": "<StackPanel>\n <TextBox Text=\"{Binding Path=., StringFormat='The answer is: {0}'}\">\n <TextBox.DataContext>\n <sys:Int32>42</sys:Int32>\n </TextBox.DataContext>\n <TextBox.ToolTip>\n <ToolTip Content=\"{Binding}\" ContentStringFormat=\"{}The answer is: {0}\" />\n </TextBox.ToolTip>\n </TextBox>\n</StackPanel>\n" }, { "answer_id": 14034294, "author": "Athari", "author_id": 293099, "author_profile": "https://Stackoverflow.com/users/293099", "pm_score": 2, "selected": false, "text": "<TextBlock ToolTip=\"{Binding PrideLands.YearsTillSimbaReturns,\n Converter={StaticResource convStringFormat},\n ConverterParameter='Rejoice! Just {0} years left!'}\" Text=\"Hakuna Matata\"/>\n using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace TLKiaWOL\n{\n [ValueConversion (typeof(object), typeof(string))]\n public class StringFormatConverter : IValueConverter\n {\n public object Convert (object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (ReferenceEquals(value, DependencyProperty.UnsetValue))\n return DependencyProperty.UnsetValue;\n return string.Format(culture, (string)parameter, value);\n }\n\n public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n }\n}\n <conv:StringFormatConverter x:Key=\"convStringFormat\"/>\n" }, { "answer_id": 21096381, "author": "Lucas Locatelli", "author_id": 1575144, "author_profile": "https://Stackoverflow.com/users/1575144", "pm_score": 3, "selected": false, "text": "<StackPanel>\n <TextBlock x:Name=\"MyTextBlock\">Foo Bar</TextBlock>\n <TextBox Text=\"{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \\{0\\}'}\">\n <TextBox.ToolTip>\n <TextBlock>\n <TextBlock.Text>\n <Binding ElementName=MyTextBlock Path=\"Text\" StringFormat=\"It is: {0}\" />\n </TextBlock.Text>\n </TextBlock>\n </TextBox.ToolTip>\n </TextBox>\n</StackPanel>\n" }, { "answer_id": 25055900, "author": "MuiBienCarlota", "author_id": 231977, "author_profile": "https://Stackoverflow.com/users/231977", "pm_score": 5, "selected": false, "text": "<TextBox ToolTip=\"{Binding WhatEverYouWant StringFormat='It is: \\{0\\}'}\" />\n <TextBox Text=\"text\">\n <TextBox.ToolTip>\n <TextBlock Text=\"{Binding WhatEverYouWant StringFormat='It is: \\{0\\}'}\"/>\n </TextBox.ToolTip>\n</TextBox>\n" }, { "answer_id": 48195359, "author": "Сергей Игнахин", "author_id": 9200565, "author_profile": "https://Stackoverflow.com/users/9200565", "pm_score": 0, "selected": false, "text": "<StackPanel>\n <TextBlock x:Name=\"MyTextBlock\">Foo Bar</TextBlock>\n <TextBox Text=\"{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \\{0\\}'}\"\n ToolTip=\"{Binding Text, RelativeSource={RelativeSource Self}}\" />\n</StackPanel>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39/" ]
197,096
<p>In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?</p>
[ { "answer_id": 197138, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": " select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)\n case when SecondsColumn> (24*60*60) \n then \n cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))\n + 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108) \n else\n convert(varchar(8), dateadd(second, SecondsColumn, 0), 108) \n end\n" }, { "answer_id": 197143, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "select to_char(my_date - my_other_date, 'HH:MM:SS');\n" }, { "answer_id": 197151, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "DECLARE @DurationSeconds INT\n\n-- 25h 45m 14s\nSET @DurationSeconds = (25 * 3600) + (45 * 60) + (14)\n\nSELECT \n @DurationSeconds, \n @DurationSeconds / 3600 hours, \n @DurationSeconds % 3600 / 60 minutes,\n @DurationSeconds % (3600 / 60) seconds\n" }, { "answer_id": 9185734, "author": "grokster", "author_id": 502441, "author_profile": "https://Stackoverflow.com/users/502441", "pm_score": 0, "selected": false, "text": " -- 86,400 seconds in a day\n -- 3,600 seconds in an hour\n -- 60 seconds in a minute\n select duration, -- seconds\n trunc((duration)/86400) || ':' || -- dd\n trunc(mod(duration,86400)/3600) || ':' || -- hh\n trunc(mod(mod(duration,86400),3600)/60) || ':' || -- mm\n mod(mod(mod(duration,86400),3600),60) -- ss\n as human_readable\n from dual\n ;\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
197,097
<p>I'm having a bit of trouble with the UTL_MAIL package in Oracle 10g, and was wondering if anyone had any solutions?</p> <p>I connect to my DB as SYSMAN and load the following two scripts;</p> <p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\utlmail.sql</strong></p> <p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\prvtmail.plb</strong></p> <p>I set up the SMTP server;</p> <p><strong>ALTER SYSTEM SET smtp_out_server='mymailserver.fake:25' SCOPE=BOTH;</strong></p> <p>I grant the user the required permission;</p> <p><strong>GRANT execute ON utl_mail TO MYUSER;</strong></p> <p>But then if I connect to the "MYTABLESPACE" (where MYUSER exists), I get the following error if I make reference to UTL_MAIL.SEND;</p> <p><strong>PLS-00201: identifier 'UTL_MAIL.SEND' must be declared</strong></p> <p>If I prefix it with SYSMAN though (SYSMAN.UTL_MAIL.SEND), it works, but I don't want to do this as this procedure that contains this call has no knowledge of the tablespace which installed the scripts.</p> <p>Is there a way to install these scripts so that they are accessible universally, and do not require the SYSMAN prefix to execute?</p> <p>Cheers,</p> <p>Chris</p>
[ { "answer_id": 197103, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 2, "selected": false, "text": "CREATE PUBLIC SYNONYM UTL_MAIL FOR SYSMAN.UTL_MAIL;\n" }, { "answer_id": 197197, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 4, "selected": true, "text": "SELECT * FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' and table_name LIKE 'UTL%'\n" }, { "answer_id": 1728408, "author": "KkK", "author_id": 210337, "author_profile": "https://Stackoverflow.com/users/210337", "pm_score": 1, "selected": false, "text": "ALTER SYSTEM SET smtp_out_server='mymailserver.fake:25' SCOPE=BOTH; MYTABLESPACE as MYUSER" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827/" ]
197,099
<p>I'm trying to select data from a table defined similar to the following :</p> <pre><code>Column | Data Type ------------------------- Id | Int DataType | Int LoggedData | XML </code></pre> <p>but I only want to select those rows with a specific DataType value, and that contain a string (or evaluates a piece of XPath) in the LoggedData column.</p> <p>A quick Google search turned up nothing useful, and I am in a bit of a rush to get an answer... I'll carry on searching, but if anyone can help me out on this in the mean time, I'd really appreciate it.</p> <p><strong>EDIT</strong> _ Clarification</p> <p>So, what I'm after is something like this, but in the correct format...</p> <pre><code>select Id, LoggedData from myTable where DataType = 29 and LoggedData.query('RootNode/ns1:ChildNode[@value="searchterm"]'); </code></pre> <p>Still might not be clear...</p>
[ { "answer_id": 197106, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "SELECT\n Id, \n LoggedData \nFROM\n myTable \nWHERE\n DataType = 29 \n AND LoggedData.exist('RootNode/ns1:ChildNode[@value=\"searchterm\"]') = 1\n" }, { "answer_id": 199950, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 2, "selected": true, "text": "Select Id, LoggedData From myTable Where DataType = 29 And \nLoggedData.exist('RootNode/ns1:ChildNode[@value=sql:variable(\"@searchterm\")]')=1\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/377/" ]
197,111
<p>What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like:</p> <pre><code>SELECT afield1, afield2 FROM afile a WHERE 1 &lt; (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1); </code></pre> <p>But this is quite slow.</p>
[ { "answer_id": 197114, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "select afield1,count(afield1) from atable \ngroup by afield1 having count(afield1) > 1\n" }, { "answer_id": 197117, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": false, "text": "select afield1, afield2 from afile a\nwhere afield1 in\n( select afield1\n from afile\n group by afield1\n having count(*) > 1\n);\n" }, { "answer_id": 4753091, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 3, "selected": false, "text": "delete from MyTable where MyTableID in (\n select max(MyTableID)\n from MyTable\n group by Thing1, Thing2, Thing3\n having count(*) > 1\n)\n" }, { "answer_id": 12048993, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT a.id, a.dupeField1, a.dupeField2\nFROM TableX a\nJOIN TableX b\nON a.dupeField1 = b.dupeField2\nAND a.dupeField2 = b.dupeField2\nAND a.id != b.id\n COUNT(*)" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535708/" ]
197,112
<p>This <a href="http://my.php.net/static" rel="nofollow noreferrer">example</a> is from php.net:</p> <pre><code>&lt;?php function Test() { static $a = 0; echo $a; $a++; } ?&gt; </code></pre> <p>And this is my code:</p> <pre><code>function getNextQuestionID() { static $idx = 0; return $idx++; } </code></pre> <p>And I use it in JavaScript:</p> <pre><code>'quizID=' + "&lt;?php echo getNextQuestionID(); ?&gt;" </code></pre> <p>Returns 0 everytime. Why?</p>
[ { "answer_id": 197126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "echo getNextQuestionID() . \", \" getNextQuestionID() . \", \" getNextQuestionID();\n" }, { "answer_id": 197600, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 0, "selected": false, "text": "session_start();\nfunction getNextQuestionID()\n{\n if (!isset($_SESSION['qNo'])) {\n $_SESSION['qNo'] = 0;\n } else {\n $_SESSION['qNo']++;\n }\n\n return $_SESSION['qNo'];\n}\n" }, { "answer_id": 36086853, "author": "djot", "author_id": 1077754, "author_profile": "https://Stackoverflow.com/users/1077754", "pm_score": 0, "selected": false, "text": "function getNextQuestionID()\n{\n if (!isset($idx)) {\n static $idx = 0; // OR -1, if you want to start with 0 (ZERO);\n }\n $idx++;\n return $idx;\n}\n\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
197,121
<p>I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc:</p> <p>What's the best way to fill in the blanks?</p> <pre><code>void DeleteUnreferencedRecords(CAtlMap&lt;Record&gt;&amp; records) { for(____;____;____) { if( NotReferencedElsewhere(record) ) { // Delete record _______; } } } </code></pre>
[ { "answer_id": 197209, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 0, "selected": false, "text": "GetNext" }, { "answer_id": 198050, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "CAtlMap map" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ]
197,122
<p>I am fairly new to WPF. I want to develop a datagrid control which supports databinding.</p> <p>There is a lot of information available about databinding to existing controls, but I cannot find any information how to develop a control from scratch which supports databinding. </p> <p>I do not expect a simple answer to this question, a link to get me started would be nice.</p>
[ { "answer_id": 249080, "author": "Scott Weinstein", "author_id": 25201, "author_profile": "https://Stackoverflow.com/users/25201", "pm_score": 0, "selected": false, "text": "AffectsArrange List<string> INotifyCollectionChanged FirstName List<Person> DataTable" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10329/" ]
197,127
<p>How do I make my application always use English when displaying win32/.net exceptions messages?</p> <p>I got this message, it looks like someone used babelfish to translate it (it's Swedish): "System.ComponentModel.Win32Exception: Programmet kunde inte starta eftersom programmets sida-vid-sidakonfiguration är felaktig."</p> <p>Extremely unhelpful, and Google had a whopping 4 hits for it, none of them helpful. So I have to guess what the original message was and google that. (It's was: "The application has failed to start because its side-by-side configuration is incorrect.")</p> <p>This time it was fairly simple to find out what the original error message was, having the message in English from the start would of course save me time.</p> <p>So how do I do that?</p>
[ { "answer_id": 197141, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 4, "selected": true, "text": "Thread.CurrentThread.CurrentUICulture .CurrentCulture CultureInfo(\"en-US\")" }, { "answer_id": 197262, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<system.web>\n <globalization ... uiCulture=\"en-US\" ... />\n</system.web>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17413/" ]
197,135
<p>My application is implemented as a service (running under services.exe). I am adding a new feature which requires being notified when the user sends an SMS.</p> <p>I have tried using <code>IMAPIAdviseSink</code>, registering with both <code>IMAPISession</code> and <code>IMsgStore</code>, but I do not get any notifications.</p> <p>The other options I can see are to create a Short Message Service Provider or to implement the <code>IFormProviderEx</code> interface, but I am not sure about the impact this might have on SMS functionality and the user experience.</p> <p>Is there any way in which my application can reliably get notifications of SMSs being created in the Outbox?</p> <p>edit: The app is written in native C++. I've looked into RIL and several other APIs, but I can only find information about getting notified of incoming SMSs.</p> <p>OK, some more information: The same code for registering my <code>IMAPIAdviseSink</code> works in a stand alone app. It's only failing to get notifications in the service.</p> <p>Is there anyway to get notifications in my service? Or do I need a separate process to monitor SMS events and notify my service?</p> <p>Mark</p>
[ { "answer_id": 207796, "author": "Mark Cheeseborough", "author_id": 13570, "author_profile": "https://Stackoverflow.com/users/13570", "pm_score": 3, "selected": true, "text": "IMAPIAdviseSink" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13570/" ]
197,150
<p>I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.</p> <p>I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)</p>
[ { "answer_id": 197169, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 4, "selected": false, "text": "sed -ne '/LastHeaderLine/,$p' <inputfile\n perl -ne 'if ($flag) {print;} if (/LastHeaderFile/) {$flag=1;}' <inputfile\n" }, { "answer_id": 197175, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 4, "selected": false, "text": "awk 'NR == 1, /LastHeaderLine/ { next } { print }' myinputfile > myoutputfile\n" }, { "answer_id": 197185, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 5, "selected": false, "text": "sed -e '1,/LastHeaderLine/d'\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
197,162
<p>How does Windows with NTFS perform with large volumes of files and directories?</p> <p>Is there any guidance around limits of files or directories you can place in a single directory before you run into performance problems or other issues? </p> <p>E.g. is having a folder with 100,000 folders inside of it an OK thing to do?</p>
[ { "answer_id": 26205776, "author": "Spoc", "author_id": 3746069, "author_profile": "https://Stackoverflow.com/users/3746069", "pm_score": 5, "selected": false, "text": "(FOPS = File Operations per Second)\n(DOPS = Directory Operations per Second)\n\n#Files lg(#) FOPS FOPS2 DOPS DOPS2\n 10 1.00 16692 16692 16421 16312\n 100 2.00 16425 15943 15738 16031\n 120 2.08 15716 16024 15878 16122\n 130 2.11 15883 16124 14328 14347\n 160 2.20 15978 16184 11325 11128\n 200 2.30 16364 16052 9866 9678\n 210 2.32 16143 15977 9348 9547\n 220 2.34 16290 15909 9094 9038\n 230 2.36 16048 15930 9010 9094\n 240 2.38 15096 15725 8654 9143\n 250 2.40 15453 15548 8872 8472\n 260 2.41 14454 15053 8577 8720\n 300 2.48 12565 13245 8368 8361\n 400 2.60 11159 11462 7671 7574\n 500 2.70 10536 10560 7149 7331\n 1000 3.00 9092 9509 6569 6693\n 2000 3.30 8797 8810 6375 6292\n10000 4.00 8084 8228 6210 6194\n20000 4.30 8049 8343 5536 6100\n50000 4.70 7468 7607 5364 5365\n [TestCase(50000, false, Result = 50000)]\n[TestCase(50000, true, Result = 50000)]\npublic static int TestDirPerformance(int numFilesInDir, bool testDirs) {\n var files = new List<string>();\n var dir = Path.GetTempPath() + \"\\\\Sub\\\\\" + Guid.NewGuid() + \"\\\\\";\n Directory.CreateDirectory(dir);\n Console.WriteLine(\"prepare...\");\n const string FILE_NAME = \"\\\\file.txt\";\n for (int i = 0; i < numFilesInDir; i++) {\n string filename = dir + Guid.NewGuid();\n if (testDirs) {\n var dirName = filename + \"D\";\n Directory.CreateDirectory(dirName);\n using (File.Create(dirName + FILE_NAME)) { }\n } else {\n using (File.Create(filename)) { }\n }\n files.Add(filename);\n }\n //Adding 1000 Directories didn't change File Performance\n /*for (int i = 0; i < 1000; i++) {\n string filename = dir + Guid.NewGuid();\n Directory.CreateDirectory(filename + \"D\");\n }*/\n Console.WriteLine(\"measure...\");\n var r = new Random();\n var sw = new Stopwatch();\n sw.Start();\n int len = 0;\n int count = 0;\n while (sw.ElapsedMilliseconds < 5000) {\n string filename = files[r.Next(files.Count)];\n string text = File.ReadAllText(testDirs ? filename + \"D\" + FILE_NAME : filename);\n len += text.Length;\n count++;\n }\n Console.WriteLine(\"{0} File Ops/sec \", count / 5);\n return numFilesInDir; \n}\n" }, { "answer_id": 42791061, "author": "ximik", "author_id": 6166098, "author_profile": "https://Stackoverflow.com/users/6166098", "pm_score": 2, "selected": false, "text": "winhttrack" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11829/" ]
197,164
<p>In my views I use a helper that takes arbitrary HTML as a block:</p> <pre><code>&lt;% some_block_helper do %&gt; Some arbitrary HTML and ERB variables here. More HTML here. &lt;% end %&gt; </code></pre> <p>My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.</p>
[ { "answer_id": 249295, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 3, "selected": false, "text": "describe SomeHelper do\n it 'should do something' do\n helper.some_block_helper { the_block_code }.should XXXX\n end\nend\n" }, { "answer_id": 4311761, "author": "James Healy", "author_id": 127255, "author_profile": "https://Stackoverflow.com/users/127255", "pm_score": 1, "selected": false, "text": "describe SomeHelper do\n it 'should do something' do\n content = lambda { \"blah\" } \n result = helper.some_block_helper(&content)\n\n result.should include(\"blah\")\n result.should XXX\n end\nend\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21702/" ]
197,170
<p>When I <kbd>Alt</kbd>+<kbd>Tab</kbd> to my VM from my host the VM does not get keyboard input until I click inside it. This is causing me an issue as it looks like the VM has control of the input (as the cursor is flashing away). If while in this state, VMWare server has the focus rather then the application inside it, if you do <kbd>ctrl</kbd>+<kbd>Z</kbd> (normally for undo) it <strong>suspends</strong> the VM.</p> <p>This is driving me barmey. I have looked through all the options and preferences in VMWare Server and can't find anyway to disable this.</p> <p>Anyone know how to disable this?</p>
[ { "answer_id": 197186, "author": "Argalatyr", "author_id": 18484, "author_profile": "https://Stackoverflow.com/users/18484", "pm_score": 2, "selected": false, "text": "vmware.exe" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26792/" ]
197,171
<p>Not too long ago, I had a problem which required me to <a href="https://stackoverflow.com/questions/186237/program-only-crashes-as-release-build-how-to-debug">set WinDbg.exe as the default post-mortem debugger</a>. Now that I've fixed that and am back doing normal work, it would be really nice if I could set VS to be my default post-mortem debugger. How does one go about doing this?</p> <p>Also, how do I make VS attach to an already existing session? That is, I've got my VS project open in one window, and a command line open where I'm launching my program from. If the program crashes, how do I get VS to figure out to attach the debugger to the active line in the project that's already open?</p>
[ { "answer_id": 197208, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 4, "selected": true, "text": "1. Start Registry Editor and locate the following Registry subkey in the HKEY_LOCAL_MACHINE subtree:\n\n\\SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\AEDEBUG\n2. Select the Debugger value.\n3. On the Edit menu, click String.\n\n• To use the Windows debugger, type windbg -p %ld -e %ld.\n• To use Visual C++ 4.2 or earlier, type msvc -p %ld -e %ld.\n• To use Visual C++ 5.0 or later, type msdev.exe -p %ld -e %ld.\n• To use Dr. Watson, type drwtsn32.exe -p %ld -e %ld. You can also make Dr. Watson the default debugger by running this command:drwtsn32.exe -i.\n4. Choose OK and exit Registry Editor. \n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ]
197,190
<p>So, I understand <i>that</i> the following doesn't work, but <i>why</i> doesn't it work?</p> <pre><code>interface Adapter&lt;E&gt; {} class Adaptulator&lt;I&gt; { &lt;E, A extends I &amp; Adapter&lt;E&gt;&gt; void add(Class&lt;E&gt; extl, Class&lt;A&gt; intl) { addAdapterFactory(new AdapterFactory&lt;E, A&gt;(extl, intl)); } } </code></pre> <p>The <code>add()</code> method gives me a compile error, "Cannot specify any additional bound Adapter&lt;E&gt; when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.</p> <p>Clearly you're just Not Allowed to use the type parameter <code>I</code> there, before the <code>&amp;</code>, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that <code>I</code> isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.</p> <p>Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one <code>add()</code> method, so it's not like there's any ambiguity...</p> <p>Can someone demonstrate the problem for me?</p>
[ { "answer_id": 197391, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 6, "selected": true, "text": "max public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)\n public static Comparable max(Collection coll)\n max max public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)\n public static Object max(Collection coll)\n max" }, { "answer_id": 210992, "author": "Chris Povirk", "author_id": 28465, "author_profile": "https://Stackoverflow.com/users/28465", "pm_score": 4, "selected": false, "text": "holder.comparator Comparator<Integer> Comparator<String> Comparator Comparator<Integer> Comparator<String> <A extends I & Adapter<E>>" }, { "answer_id": 60572215, "author": "Ealrann", "author_id": 4030058, "author_profile": "https://Stackoverflow.com/users/4030058", "pm_score": 0, "selected": false, "text": " interface Adapter<E>\n {}\n\n interface Adaptulator<I>\n {\n void add(Container<?, ? extends I> container);\n }\n\n static final class Container<E, I extends Adapter<E>>\n {\n public final Class<E> extl;\n public final Class<I> intl;\n\n public Container(Class<E> extl, Class<I> intl)\n {\n this.extl = extl;\n this.intl = intl;\n }\n }\n Container<?, ? extends I> ? super A ? super I" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27358/" ]
197,199
<p>We're running a Rails site at <a href="http://hansard.millbanksystems.com" rel="nofollow noreferrer">http://hansard.millbanksystems.com</a>, on a dedicated Accelerator. We currently have Apache setup with mod-proxy-balancer, proxying to four mongrels running the application.</p> <p>Some requests are rather slow and in order to prevent the situation where other requests get queued up behind them, we're considering options for proxying that will direct requests to an idle mongrel if there is one.</p> <p>Options appear to include:</p> <ul> <li><p>recompiling mod_proxy_balancer for Apache as described at <a href="http://labs.reevoo.com/2008/7/30/fixing-uneven-load-balancing-between-apache-and-mongrel-for-ruby-on-rails-applications" rel="nofollow noreferrer">http://labs.reevoo.com/</a></p></li> <li><p>compiling nginx with the fair proxy balancer for Solaris</p></li> <li><p>compiling haproxy for Open Solaris (although this may not work well with SMF)</p></li> </ul> <p>Are these reasonable options? Have we missed anything obvious? We'd be very grateful for your advice.</p>
[ { "answer_id": 393331, "author": "James Brady", "author_id": 29903, "author_profile": "https://Stackoverflow.com/users/29903", "pm_score": 2, "selected": false, "text": "mod_proxy_balancer" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20035/" ]
197,211
<p>what is the best way to put a container class or a some other class inside a class as private or a public member?</p> <p>Requirements:</p> <p>1.Vector&lt; someclass> inside my class</p> <p>2.Add and count of vector is needed interface</p>
[ { "answer_id": 197250, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "vector class ContWrapper {\n std::vector<int> _ints;\npublic:\n class Action {\n public: \n virtual void accept( int i ) = 0;\n };\n void each_int( Action& a );\n};\n std::vector<T>" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
197,215
<p>Does anyone know of any reverse proxy solutions that allow the content/data of an HTTP response to be directly modified before being relayed to the requesting client?</p> <p>As an example:</p> <p>Proxy relays client request for pdf document to another server, response received by proxy, watermark added to pages of pdf, watermarked pdf is returned to client.</p> <p>Regards, Mike </p>
[ { "answer_id": 197272, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "mod_proxy mod_proxy_html" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27376/" ]
197,218
<p>I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:</p> <p><strong>system("date /T")</strong> (output is e.g. 13-Oct-08 which is date on my system in the format i have set) </p> <p>but this prints the date to the i/o console. </p> <p>How do i make take this date as returned by above system call and store it as a string value to a string defined in my code? Or </p> <p>Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?</p> <p>-AD</p>
[ { "answer_id": 197230, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "#include <windows.h>\n#include <iostream>\n\nint main() {\n\n SYSTEMTIME systmDateTime = {};\n ::GetLocalTime(&systmDateTime);\n\n wchar_t wszDate[64] = {};\n int const result = ::GetDateFormatW(\n LOCALE_USER_DEFAULT, DATE_SHORTDATE,\n &systmDateTime, 0, wszDate, _countof(wszDate));\n\n if (result) {\n std::wcout << wszDate;\n }\n}\n" }, { "answer_id": 197293, "author": "goldenmean", "author_id": 2759376, "author_profile": "https://Stackoverflow.com/users/2759376", "pm_score": 0, "selected": false, "text": "#include <time.h>\n#include <stdio.h>\n#include <sys/types.h>\n#include <sys/timeb.h>\n#include <string.h>\n int main()\n\n { \n\n char tmpbuf[128];\n\n time_t ltime;\n\n struct tm *today;\n\n _strdate( tmpbuf );\n printf(\"\\n before formatting date is %s\",tmpbuf); \n\n time(&ltime);\n today = localtime( &ltime );\n\n strftime(tmpbuf,128,\"%d-%m-%y\",today);\n printf( \"\\nafter formatting date is %s\\n\", tmpbuf );\n\n }\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
197,220
<p>I've got an ASP.NET 2.0 website that connects to a SQL database. I've upgraded the SQL server from 2000 to 2008 and since then, one page refuses to work. </p> <p>I've worked out the problem is that the call to SqlDataReader.HasRows is returning false even though the dataset is not empty and removing the check allows the loop through reader.Read() to access the expected data. </p> <pre><code> _connectionString = WebConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString; SqlConnection connection = new SqlConnection(_connectionString); SqlCommand command = new SqlCommand(searchtype, connection); SqlParameter _parSeachTerm = new SqlParameter("@searchterm", SqlDbType.VarChar, 255); _parSeachTerm.Value = searchterm; command.Parameters.Add(_parSeachTerm); command.CommandType = CommandType.StoredProcedure; try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) //this always returns false!? { while (reader.Read()) {... </code></pre> <p>Does anybody have any idea what's going on? There are similar code blocks on other pages where HasRows returns the correct value.</p> <p>EDIT- Just to clarify, the stored procedure DOES return results which I have confirmed because the loop runs through fine if I remove the HasRows check. Changing just the name of the SQL server in the connection string to an identical database running on SQL 2000 makes the problem go away. I've checked that NOCOUNT is off, so what else could make HasRows return false when that's not the case??</p> <p>EDIT2- Here's the SP</p> <pre><code>CREATE PROCEDURE StaffEnquirySurnameSearch @searchterm varchar(255) AS SELECT AD.Name, AD.Company, AD.telephoneNumber, AD.manager, CVS.Position, CVS.CompanyArea, CVS.Location, CVS.Title, AD.guid AS guid, AD.firstname, AD.surname FROM ADCVS AD LEFT OUTER JOIN CVS ON AD.Guid=CVS.Guid WHERE AD.SurName LIKE @searchterm ORDER BY AD.Surname, AD.Firstname GO </code></pre> <p>Many thanks in advance.</p>
[ { "answer_id": 197964, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "HasRows image/BLOB Stored Procedure" }, { "answer_id": 198127, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "\nusing (connection cnn = new Connection(...)\n{\nusing (SqlDataReader rdr = ....\n{\n//some code which deals with datareader\n}\n}\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27377/" ]
197,224
<p>I wanted to edit a log comment in the repository browser and received an error message that no pre-revprop-change hook exists for the repository. Besides having a scary name, what is a pre-revprop-change hook, and how do I create it?</p>
[ { "answer_id": 468475, "author": "patmortech", "author_id": 19090, "author_profile": "https://Stackoverflow.com/users/19090", "pm_score": 8, "selected": false, "text": "pre-revprop-change.bat \\hooks @ECHO OFF\n:: Set all parameters. Even though most are not used, in case you want to add\n:: changes that allow, for example, editing of the author or addition of log messages.\nset repository=%1\nset revision=%2\nset userName=%3\nset propertyName=%4\nset action=%5\n\n:: Only allow the log message to be changed, but not author, etc.\nif /I not \"%propertyName%\" == \"svn:log\" goto ERROR_PROPNAME\n\n:: Only allow modification of a log message, not addition or deletion.\nif /I not \"%action%\" == \"M\" goto ERROR_ACTION\n\n:: Make sure that the new svn:log message is not empty.\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (\nset bIsEmpty=false\n)\nif \"%bIsEmpty%\" == \"true\" goto ERROR_EMPTY\n\ngoto :eof\n\n:ERROR_EMPTY\necho Empty svn:log messages are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:log messages are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:log revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1\n" }, { "answer_id": 4876694, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 4, "selected": false, "text": "pre-revprop-change" }, { "answer_id": 13304738, "author": "yasin", "author_id": 995447, "author_profile": "https://Stackoverflow.com/users/995447", "pm_score": 3, "selected": false, "text": ":: Only allow editing of the same user.\nfor /f \"tokens=*\" %%a in ( \n'\"%VISUALSVN_SERVER%\\bin\\svnlook.exe\" author -r %revision% %repository%') do ( \nset orgAuthor=%%a\n)\nif /I not \"%userName%\" == \"%orgAuthor%\" goto ERROR_SAME_USER\n" }, { "answer_id": 20396766, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 3, "selected": false, "text": "pre-revprop-change svn:needs-lock svn:mime-type svn:log svn:date svn:date svn:author svn:log pre-revprop-change pre-revprop-change exit 0 pre-revprop-change svn:log # Store hook arguments into variables with mnemonic names\n$repos = $args[0]\n$rev = $args[1]\n$user = $args[2]\n$propname = $args[3]\n$action = $args[4]\n\n# Only allow changes to svn:log. The author, date and other revision\n# properties cannot be changed\nif ($propname -ne \"svn:log\")\n{\n [Console]::Error.WriteLine(\"Only changes to 'svn:log' revision properties are allowed.\")\n exit 1\n}\n\n# Only allow modifications to svn:log (no addition/overwrite or deletion)\nif ($action -ne \"M\")\n{\n [Console]::Error.WriteLine(\"Only modifications to 'svn:log' revision properties are allowed.\")\n exit 2\n}\n\n# Read from the standard input while the first non-white-space characters\n$datalines = ($input | where {$_.trim() -ne \"\"})\nif ($datalines.length -lt 25)\n{\n # Log message is empty. Show the error.\n [Console]::Error.WriteLine(\"Empty 'svn:log' properties are not allowed.\")\n exit 3\n}\n\nexit 0\n IF \"%3\" == \"svnmgr\" (goto :label1) else (echo \"Only the svnmgr user may change revision properties\" >&2 )\n\nexit 1\ngoto :eof\n\n:label1\nexit 0\n" }, { "answer_id": 25844525, "author": "Alois Heimer", "author_id": 2523663, "author_profile": "https://Stackoverflow.com/users/2523663", "pm_score": 5, "selected": false, "text": "pre-revprop-change.tmpl hooks pre-revprop-change www-data 0" }, { "answer_id": 64147889, "author": "Tom Andraszek", "author_id": 356052, "author_profile": "https://Stackoverflow.com/users/356052", "pm_score": 1, "selected": false, "text": "@ECHO OFF\n:: Set all parameters. Even though most are not used, in case you want to add\n:: changes that allow, for example, editing of the author or addition of log messages.\nset repository=%1\nset revision=%2\nset userName=%3\nset propertyName=%4\nset action=%5\n\n:: Only allow the author to be changed, but not message (\"svn:log\"), etc.\nif /I not \"%propertyName%\" == \"svn:author\" goto ERROR_PROPNAME\n\n:: Only allow modification of a log message, not addition or deletion.\nif /I not \"%action%\" == \"M\" goto ERROR_ACTION\n\n:: Make sure that the new svn:log message is not empty.\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (\nset bIsEmpty=false\n)\nif \"%bIsEmpty%\" == \"true\" goto ERROR_EMPTY\n\ngoto :eof\n\n:ERROR_EMPTY\necho Empty svn:author messages are not allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:author messages are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:author revision properties are allowed. >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1\n" }, { "answer_id": 66366955, "author": "Tobias Knauss", "author_id": 2505186, "author_profile": "https://Stackoverflow.com/users/2505186", "pm_score": 2, "selected": false, "text": "if \"%bIsEmpty%\" == \"true\" goto ERROR_EMPTY goto :eofbefore set outputFile=%repos%\\log-change-history.txt\n\necho User '%user%' changes log message in rev %rev% on %date% %time%.>>%outputFile%\necho ----- Old message: ----->>%outputFile%\nsvnlook propget --revprop %repos% svn:log -r %rev% >>%outputFile%\necho.>>%outputFile%\necho ----- New message: ----->>%outputFile%\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (echo %%g >>%outputFile%)\necho ---------->>%outputFile%\necho.>>%outputFile%\n log-change-history.txt" }, { "answer_id": 69664548, "author": "Ricardo Araos", "author_id": 3689426, "author_profile": "https://Stackoverflow.com/users/3689426", "pm_score": 0, "selected": false, "text": "pre-revprop-change.tmpl hooks pre-revprop-change name chmod 755 pre-revprop-change chcon -t httpd_exec_t pre-revprop-change\n svnrdump: E175008: Revprop change blocked by pre-revprop-change hook (exit code 255) with no output.\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
197,228
<p>I'm using the jquery library to load the content of an html file. Something like this:</p> <p>$("#Main").load("login.html")</p> <p>If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?</p>
[ { "answer_id": 197237, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 5, "selected": true, "text": "$(\"#someDivId\").ajaxComplete(function(request, settings){\n if (settings.status===404){\n //redirect here\n }\n});\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/197228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15928/" ]