qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
230,792
<p>I have noticed that regardless of a given script's execution time, every date() call will return the same timestamp regardless of where the function is called within the script. It looks like it just returns the time at which the script first started executing.</p> <p>For logging purposes, it would be extremely useful to be able to get incremental timestamps from within a script. Is this possible? Is there a way to do this that is relatively lightweight?</p> <p><strong>Edit:</strong> Would the example for the <a href="http://us.php.net/microtime" rel="nofollow noreferrer">microtime()</a> function suggests it might do this. Can anyone confirm?</p> <p><strong>Update:</strong> microtime() does work, but I cannot format it with the date() function because date() only accepts timestamps as integers (so no microseconds). How can I get a properly formatted date from the value returned by microtime() ?</p>
[ { "answer_id": 231010, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 2, "selected": false, "text": "<?php\n$time_start = time();\n\nsleep(2);\n\n$time_end = time();\n\nprint 'Start: ' . date(\"m/d/Y @ g:i:sA\", $time_start) . '<br>';\nprint 'End: ' . date(\"m/d/Y @ g:i:sA\", $time_end);\n?>\n Start: 10/23/2008 @ 3:12:23PM\nEnd: 10/23/2008 @ 3:12:25PM\n time()" }, { "answer_id": 231012, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "date() date('Y-m-d') date('Y-m-d', time()) date() function formatTime($microtime, $format)\n{\n list($timestamp, $fraction) = explode('.', $microtime);\n return date($format, (int)$timestamp) . '.' . $fraction;\n}\n $microtime float true microtime()" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
230,796
<p>I'm creating a table that looks something like this.</p> <pre><code>CREATE TABLE packages ( productCode char(2) , name nvarchar(100) , ... ) </code></pre> <p>How do I make sure the productCode is always one of two values <code>XJ</code> or <code>XD</code>?</p>
[ { "answer_id": 230819, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "ALTER TABLE packages\nADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))\n" }, { "answer_id": 230833, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 2, "selected": false, "text": "CREATE TABLE packages\n(\n productCode char(2)\n , name nvarchar(100) \n , ...\n ,CONSTRAINT productCode CHECK (productCode in ('XJ','XD') )\n)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ]
230,831
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Unbalanced_binary_tree.svg/251px-Unbalanced_binary_tree.svg.png" alt="alt text"></p> <p>The image above is from <a href="http://en.wikipedia.org/wiki/AVL_tree" rel="nofollow noreferrer">"Wikipedia's entry on AVL trees"</a> which Wikipedia indicates is unbalanced. How is this tree not balanced already? Here's a quote from the article:</p> <blockquote> <p>The balance factor of a node is the height of its right subtree minus the height of its left subtree and a node with balance factor 1, 0, or -1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.</p> </blockquote> <p>Both the left and right subtrees have a height of 4. The right subtree of the left tree has a height of 3 which is still only 1 less than 4. Can someone explain what I'm missing?</p>
[ { "answer_id": 230966, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": true, "text": "Root: 23\n(23) -> 14 & 67\n(14) -> 12 & 17\n(12) -> 9\n(17) -> 19\n(67) -> 50 & 72\n(50) -> 54\n(72) -> 76\n" }, { "answer_id": 23232436, "author": "par", "author_id": 312594, "author_profile": "https://Stackoverflow.com/users/312594", "pm_score": 2, "selected": false, "text": "h h = 1 + max( left.height, right.height ) abs( left.height - right.height ) > 1 - Node 12 is a leaf node so its height = 1+max(0,0) = 1\n- Node 14 has one child (12, on the left), so its height is = 1+max(1,0) = 2\n- Node 9 has one child (14, on the right), so its height is = 1+max(0,2) = 3\n - 9's left child is NULL, so 9.left.height = 0\n- 9's right child (14) has height 2, so 9.right.height = 2\n 9.unbalanced = abs( 9.left.height - 9.right.height ) > 1\n9.unbalanced = abs( 0 - 2 ) > 1\n9.unbalanced = abs( -2 ) > 1\n9.unbalanced = 2 > 1\n9.unbalanced = true\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/412/" ]
230,834
<p>This is a winforms application.</p> <p>In windows, I want the user to click and button, and then a popup should make the user select the path of where they want to save the file.</p>
[ { "answer_id": 230867, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": "StringBuilder.ToString() TextStream.Write()" }, { "answer_id": 230874, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 5, "selected": false, "text": "using (SaveFileDialog dialog = new SaveFileDialog()) {\n if (dialog.ShowDialog(this) == DialogResult.OK) {\n File.WriteAllText(dialog.FileName, yourStringBuilder.ToString());\n }\n}\n" }, { "answer_id": 230910, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2 {\npublic partial class Form1 : Form {\n\n StringBuilder sb = new StringBuilder();\n\n public Form1() {\n InitializeComponent();\n\n sb.Append(\"This is going \");\n sb.Append(\"to be saved to a text file\");\n }\n\n private void button1_Click(object sender, EventArgs e) {\n using (SaveFileDialog dlg = new SaveFileDialog()) {\n if (dlg.ShowDialog() == DialogResult.OK) {\n string fileName = dlg.FileName;\n SaveToFile(fileName);\n }\n }\n }\n\n private void SaveToFile(string fileName) {\n System.IO.TextWriter w = new System.IO.StreamWriter(fileName);\n w.Write(sb.ToString());\n w.Flush();\n w.Close();\n }\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
230,842
<p>The first one is definitely something that works, but which one below is the efficient way?</p> <pre><code>switch($type) { case 1: print 'success'; break; case 2: print 'success'; break; case 3: print 'success'; break; case 4: print 'success for type 4'; break; } </code></pre> <p>Since 1, 2 and 3 print do the same, can I do this?</p> <pre><code>switch($type) { case 1, 2, 3: print 'success'; break; case 4: print 'success for type 4'; break; } </code></pre> <p>or</p> <pre><code>switch($type) { case 1: case 2: case 3: print 'success'; break; case 4: print 'success for type 4'; break; } </code></pre>
[ { "answer_id": 230857, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 5, "selected": true, "text": " switch($type) \n {\n case 1:\n case 2:\n case 3:\n print 'success';\n break;\n case 4:\n print 'success for type 4';\n break;\n }\n" }, { "answer_id": 230858, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 2, "selected": false, "text": "<?php\nswitch ($i) {\ncase 0:\ncase 1:\ncase 2:\n echo \"i is less than 3 but not negative\";\n break;\ncase 3:\n echo \"i is 3\";\n}\n?>\n" }, { "answer_id": 231651, "author": "null", "author_id": 25411, "author_profile": "https://Stackoverflow.com/users/25411", "pm_score": 2, "selected": false, "text": "switch ($i) {\n case 0: //drop\n case 1: //drop\n case 2: //drop\n echo \"i is 0, 1, or 2\";\n break;\n // or you can line them up like this.\n case 3: case 4: case 5:\n echo \"i is 3, 4 or 5\";\n break;\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import commands commands.getoutput('server stop') </code></pre>
[ { "answer_id": 230855, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 0, "selected": false, "text": "commands.getoutput('server stop -p password')\n" }, { "answer_id": 230862, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 3, "selected": false, "text": "from subprocess import Popen, PIPE\n\nproc = Popen(['server', 'stop'], stdin=PIPE)\n\nproc.communicate('password')\n" }, { "answer_id": 230982, "author": "darrickc", "author_id": 7949, "author_profile": "https://Stackoverflow.com/users/7949", "pm_score": 0, "selected": false, "text": "import popen2\n\n(stdout, stdin) = popen2.popen2('server stop')\n\nstdin.write(\"password\")\n" }, { "answer_id": 321950, "author": "darrickc", "author_id": 7949, "author_profile": "https://Stackoverflow.com/users/7949", "pm_score": 1, "selected": false, "text": "import pexpect\nchild = pexpect.spawn('server stop')\nchild.expect_exact('Password:')\n\nchild.sendline('password')\n\nprint \"Stopping the servers...\"\n\nindex = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60)\nchild.expect(pexpect.EOF)\n" }, { "answer_id": 809168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "input= proc.communicate() from subprocess import Popen, PIPE\nproc = Popen(['server', 'stop'], stdin=PIPE)\nproc.communicate(input='password')\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7949/" ]
230,869
<p>I have this situation. I have a real stored in a varbinary field in a sql 2005 database. As I can't convert a varbinary to a real in sql 2005, I'm trying to do that in vb.net.</p> <p>That field gets stored as a byte() array in a DataTable.</p> <p>Now I would like to read that byte() into a double, or decimal variable. But I don't have much of a clue on how to do that...</p>
[ { "answer_id": 231295, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 1, "selected": false, "text": "'declare a test array\nDim testArray As Byte() = {0, 0, 0, 0}\n'wrap it into a memory stream\nDim memStream As MemoryStream = new MemoryStream(testArray)\n'wrap the stream in a binary reader\nDim bReader As BinaryReader = new BinaryReader(memStream)\n'read a 32bit integer from the stream using the reader\nDim count As Integer = bReader.ReadInt32()\n" }, { "answer_id": 657904, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Public Function GetDateFromBytes(ByRef value() As Byte, _\n ByRef startindex As Int32) As Date\n 'create a aray of Ints\n Dim IntValues() As Int32 = {BitConverter.ToInt32(value, startindex), _\n BitConverter.ToInt32(value, (startindex + 7)), _\n BitConverter.ToInt32(value, startindex + 15), _\n BitConverter.ToInt32(value, startindex + 31)}\n\n Return Date.FromBinary(New Decimal(IntValues))\n\nEnd Function\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
230,886
<p>I've seen this format used for comma-delimited lists in some C++ code (although this could apply to any language):</p> <pre><code>void function( int a , int b , int c ) </code></pre> <p>I was wondering why would someone use that over a more common format such as:</p> <pre><code>void function (int a, int b, int c ) </code></pre>
[ { "answer_id": 230915, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 1, "selected": false, "text": "std::cout << \"some info \"\n << \"some more info \" << 4\n + 5 << std::endl;\n std::vector<int> v = ...;\n std::vector<int> w = ...;\n for (std::vector<int>::iterator i = v.begin()\n , std::vector<int>::iterator j = w.begin()\n ; i != v.end() && j != w.end()\n ; ++i, ++j)\n std::cout << *i + *j << std::endl;\n" }, { "answer_id": 230922, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 5, "selected": true, "text": "SELECT field1\n , field2\n , field3\n-- , field4\n , field5\nFROM tablename\n" }, { "answer_id": 230926, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "void function (int a,\n int b,\n int c\n )\n" }, { "answer_id": 237945, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "function(\n int a,\n int b,\n// int c,\n int d\n )\n function (\n// int a\n , int b\n , int c\n , int d\n )\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
230,892
<p>I have quickly read (and will read with more care soon) the article of Scott Allen concerning the possibility to use an other provider of the default SQL Express or SQL Server database to use the "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a>" for ASP.NET.</p> <p>We will soon need to open a part of our project to some client via the web and I thought about using the "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a>" but our database is PostGreSql. </p> <p>Does any one have some experience with "<a href="http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx" rel="nofollow noreferrer">Membership and Role Providers</a> and an other database type (not SQL Server)? Is it worth it or it's a pain?</p>
[ { "answer_id": 230915, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 1, "selected": false, "text": "std::cout << \"some info \"\n << \"some more info \" << 4\n + 5 << std::endl;\n std::vector<int> v = ...;\n std::vector<int> w = ...;\n for (std::vector<int>::iterator i = v.begin()\n , std::vector<int>::iterator j = w.begin()\n ; i != v.end() && j != w.end()\n ; ++i, ++j)\n std::cout << *i + *j << std::endl;\n" }, { "answer_id": 230922, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 5, "selected": true, "text": "SELECT field1\n , field2\n , field3\n-- , field4\n , field5\nFROM tablename\n" }, { "answer_id": 230926, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "void function (int a,\n int b,\n int c\n )\n" }, { "answer_id": 237945, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "function(\n int a,\n int b,\n// int c,\n int d\n )\n function (\n// int a\n , int b\n , int c\n , int d\n )\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
230,893
<p>What is the fastest way to load data from flatfiles into a MySQL database, and then create the relations between the tables via foreign keys? </p> <p>For example... I have a flat file in the format: </p> <pre><code>[INDIVIDUAL] [POP] [MARKER] [GENOTYPE] "INDIVIDUAL1", "CEU", "rs55555","AA" "INDIVIDUAL1", "CEU", "rs535454","GA" "INDIVIDUAL1", "CEU", "rs555566","AT" "INDIVIDUAL1", "CEU", "rs12345","TT" ... "INDIVIDUAL2", "JPT", "rs55555","AT" </code></pre> <p>Which I need to load into four tables:</p> <pre><code>IND (id,fk_pop,name) POP (id,population) MARKER (id,rsid) GENOTYPE (id,fk_ind,fk_rsid,call) </code></pre> <p>Specifically, how does one populate the foreign keys in a way that scales? The figures are in the range of 1000+ individuals, each with 1 million+ genotypes.</p>
[ { "answer_id": 449373, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": " LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE POP FIELDS TERMINATED BY ','\n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, population, @rsid, @call);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE MARKER FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, @population, rsid, @call);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE IND FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (name, @population, @rsid, @call) \n SET fk_pop = (SELECT id FROM POP WHERE population = @population);\n LOAD DATA INFILE 'data.txt' IGNORE INTO TABLE GENOTYPE FIELDS TERMINATED BY ',' \n ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES \n (@name, @population, @rsid, call)\n SET fk_ind = (SELECT id FROM IND where name = @name),\n fk_rsid = (SELECT id FROM MARKER where rsid = @rsid);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30911/" ]
230,896
<p>I have a list of variable names, like this:</p> <pre><code>['foo', 'bar', 'baz'] </code></pre> <p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p> <p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?</p> <pre><code>{'foo': foo, 'bar': bar, 'baz': baz} </code></pre> <p>Now that I'm re-asking the question, I came up with:</p> <pre><code>d = {} for name in list_of_variable_names: d[name] = eval(name) </code></pre> <p>Can that be improved upon?</p> <p><strong>Update</strong>, responding to the question (in a comment) of why I'd want to do this:</p> <p>I often find myself using the % operator to strings with a dictionary of names and values to interpolate. Often the names in the string is just the names of local variables. So (with the answer below) I can do something like this:</p> <pre><code>message = '''Name: %(name)s ZIP: %(zip)s Dear %(name)s, ...''' % dict((x, locals()[x]) for x in ['name', 'zip']) </code></pre>
[ { "answer_id": 230907, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "[foo, bar, baz] foo a[0] a quux quux = a[0]\n eval() __dict__ import __main__\nd = dict((x, __main__.__dict__[x]) for x in list_of_variable_names)\n import __main__" }, { "answer_id": 230955, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 3, "selected": false, "text": "dict((name, eval(name)) for name in list_of_variable_names)\n dict((name, locals()[name]) for name in list_of_variable_names)\n" }, { "answer_id": 230976, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "eval dict((k,v) for (k,v) in globals().iteritems() if k in list_of_variable_names)\n dict((k,v) for (k,v) in vars().iteritems() if k in list_of_variable_names)\n" }, { "answer_id": 231368, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "locals() >>> name = 'foo'\n>>> zip = 123\n>>> unused = 'whoops!'\n>>> locals()\n{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}\n>>> '%(name)s %(zip)i' % locals()\n'foo 123'\n locals() >>> name = 'foo'\n>>> zip = 123\n>>> unused = 'whoops!'\n>>> f'{zip: >5} {name.upper()}'\n' 123 FOO'\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
230,925
<p>Visual Studio does it; Reflector does it; and now I want to as well :)</p> <p>I want to retrieve the XML documentation for some members in some framework assemblies (i.e. <code>mscorlib.dll</code>, <code>System.dll</code>, etc). I assume this would involve:</p> <ul> <li>finding the XML file for the assembly, </li> <li>navigating to the appropriately named child element, and </li> <li>retrieving the desired items (<code>&lt;summary&gt;</code>, <code>&lt;remarks&gt;</code>, etc)</li> </ul> <p><br/> Where are the XML files kept for framework assemblies? Any points on deciphering the XMLDOC naming scheme? Are there any libraries out there that will make this process easier?</p>
[ { "answer_id": 238058, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "static FileInfo GetXmlDocFile( Assembly assembly ) {\n string assemblyDirPath = Path.GetDirectoryName( assembly.Location );\n string fileName = Path.GetFileNameWithoutExtension( assembly.Location ) +\".xml\";\n\n return GetFallbackDirectories( CultureInfo.CurrentCulture )\n .Select( dirName => CombinePath( assemblyDirPath, dirName, fileName ) )\n .Select( filePath => new FileInfo( filePath ) )\n .Where( file => file.Exists )\n .First( );\n}\n\nstatic IEnumerable<string> GetFallbackDirectories( CultureInfo culture ) {\n return culture\n .Enumerate( c => c.Parent.Name != c.Name ? c.Parent : null )\n .Select( c => c.Name );\n}\n\nstatic IEnumerable<T> Enumerate<T>( this T start, Func<T, T> next ) {\n for( T item = start; !object.Equals( item, default(T) ); item = next( item ) )\n yield return item;\n}\n\nstatic string CombinePath( params string[] args ) {\n return args.Aggregate( Path.Combine );\n}\n static XElement GetDocMember( XElement docMembers, MemberInfo member ) {\n string memberId = GetMemberId( member );\n return docMembers.Elements( \"member\" )\n .Where( e => e.Attribute( \"name\" ).Value == memberId )\n .First( );\n}\n\nstatic string GetMemberId( MemberInfo member ) {\n char memberKindPrefix = GetMemberPrefix( member );\n string memberName = GetMemberFullName( member );\n return memberKindPrefix + \":\" + memberName;\n}\n\nstatic char GetMemberPrefix( MemberInfo member ) {\n return member.GetType( ).Name\n .Replace( \"Runtime\", \"\" )[0];\n}\n\nstatic string GetMemberFullName( MemberInfo member ) {\n string memberScope = \"\";\n if( member.DeclaringType != null )\n memberScope = GetMemberFullName( member.DeclaringType );\n else if( member is Type )\n memberScope = ((Type)member).Namespace;\n\n return memberScope + \".\" + member.Name;\n}\n Type type = typeof( string );\n\nvar file = GetXmlDocFile( type.Assembly );\nvar docXml = XDocument.Load( file.FullName );\nvar docMembers = docXml.Root.Element( \"members\" );\n\nvar member = type.GetProperty( \"Length\" );\nvar docMember = GetDocMember( docMembers, member );\n" }, { "answer_id": 1090388, "author": "Steve Guidi", "author_id": 131407, "author_profile": "https://Stackoverflow.com/users/131407", "pm_score": 2, "selected": false, "text": "System.Reflection MethodInfo PropertyInfo" }, { "answer_id": 16239988, "author": "giacomelli", "author_id": 956886, "author_profile": "https://Stackoverflow.com/users/956886", "pm_score": 2, "selected": false, "text": "// From method.\nvar methodInfo = typeof(Stub).GetMethod(\"MethodWithGenericParameter\");\nvar methodDoc = DocsService.GetXmlFromMember(methodInfo);\n" }, { "answer_id": 17053135, "author": "kzu", "author_id": 24684, "author_profile": "https://Stackoverflow.com/users/24684", "pm_score": 1, "selected": false, "text": "var members = Reader.Read(typeof(string).Assembly);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
230,927
<p>I'm looking for best practices for establishing connections between Oracle 8 and Visual Studio 2005 applications. The target would be a Windows Forms application written in C# that hits the database once a second to monitor tables looking for their last inserted record. I'm considering using "Application settings" to store the connection string there, but I'd love to hear from you guys. Thanks in advance!</p> <p>This is a very rudimentary draft:</p> <pre><code>using System.Data; using System.Data.OracleClient; try { StringBuilder str = new StringBuilder(); string ora = Properties.Settings.Default.OracleConnectionString; OracleConnection con = new OracleConnection(ora); OracleCommand cmd = new OracleCommand(); cmd.Connection = con; cmd.CommandText = "SELECT timestamp FROM jde_out WHERE rownum = 1"; cmd.CommandType = CommandType.Text; con.Open(); OracleDataReader rdr = cmd.ExecuteReader(); rdr.Read(); str.AppendLine(cmd.ExecuteScalar().ToString()); this.lblJDEtime.Text = str.ToString(); rdr.Close(); con.Close(); } catch (OracleException err) { MessageBox.Show("Exception caught:\n\n" + err.ToString()); } </code></pre> <p>I've just updated the code needed to perform the connection. Changed the Exception type to the more specific OracleException. Added the connection string via Properties.Settings.</p>
[ { "answer_id": 231073, "author": "Loscas", "author_id": 22706, "author_profile": "https://Stackoverflow.com/users/22706", "pm_score": 2, "selected": true, "text": "<?xml version='1.0' encoding='utf-8'?>\n <configuration>\n <connectionStrings>\n <clear />\n <add name=\"Name\" \n providerName=\"System.Data.ProviderName\" \n connectionString=\"Valid Connection String;\" />\n </connectionStrings>\n </configuration>\n" }, { "answer_id": 231493, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 2, "selected": false, "text": "<add key=\"ODP.NET.ConnectionString\" value=\"Password=abcdefg;Persist Security Info=True;User ID=abc123;Data Source=blah;\"/>\n" }, { "answer_id": 274583, "author": "Kevin P.", "author_id": 18542, "author_profile": "https://Stackoverflow.com/users/18542", "pm_score": 0, "selected": false, "text": "string connectionString = @\"\nSERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP\n(HOST=OracleHost)(PORT=OraclePort))\n(CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))\n;uid=UserID;pwd=Password;\";\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"My.Database.Connection\" value=\"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP\n (HOST=OracleHost)(PORT=OraclePort))\n (CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))\n ;uid=UserID;pwd=Password;\" />\n </appSettings>\n</configuration>\n connectionString = ConfigurationSettings.AppSettings[\"My.Database.Connection\"];\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
230,931
<p>As I've read somewhere it is advised to use !== and === instead.</p>
[ { "answer_id": 230944, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "5 == \"5\"\n 5 === \"5\"\n" }, { "answer_id": 230957, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 2, "selected": false, "text": "== != === !== == !=" }, { "answer_id": 230959, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 1, "selected": false, "text": "var int = 3; // Is typeof Number\nint = 'haha!'; // is typeof String\n" }, { "answer_id": 231113, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "=== !== == null undefined 0 \"\" [0] 0" }, { "answer_id": 231150, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "!myVar false === myVar\n'undefined' === typeof myVar\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
230,973
<p>I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:</p> <pre><code> List&lt;string&gt; myList = new List&lt;string&gt; {"aBc", "HELLO", "GoodBye"}; myList.ForEach(d=&gt;d.ToLower()); </code></pre> <p>I was hoping I could use it to convert all items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.</p> <p>So my question is whether there IS a way, using LINQ and Lambda expressions to easily iterate through and modify the contents of a list in a manner similar to this.</p> <p>Thanks, Max</p>
[ { "answer_id": 230991, "author": "marcumka", "author_id": 30761, "author_profile": "https://Stackoverflow.com/users/30761", "pm_score": 2, "selected": false, "text": "[TestMethod]\npublic void LinqStringTest()\n{\n List<string> myList = new List<string> { \"aBc\", \"HELLO\", \"GoodBye\" };\n myList = (from s in myList select s.ToLower()).ToList();\n Assert.AreEqual(myList[0], \"abc\");\n Assert.AreEqual(myList[1], \"hello\");\n Assert.AreEqual(myList[2], \"goodbye\");\n}\n" }, { "answer_id": 230995, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 6, "selected": false, "text": "List<string> lowerCase = myList.Select(x => x.ToLower()).ToList();\n" }, { "answer_id": 231016, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 2, "selected": false, "text": "ForEach Action<T> x x string" }, { "answer_id": 231019, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 9, "selected": true, "text": "myList = myList.ConvertAll(d => d.ToLower());\n ForEach ConvertAll" }, { "answer_id": 15266151, "author": "Uhlamurile", "author_id": 2082721, "author_profile": "https://Stackoverflow.com/users/2082721", "pm_score": -1, "selected": false, "text": "var _reps = new List(); // with variant data\n\n_reps.ConvertAll<string>(new Converter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains(\"invisible\"))\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29662/" ]
230,974
<p>I am attempting to disable SSL v2.0 protocol on IIS 7.</p> <p>The following article refers to IIS v6: <a href="http://support.microsoft.com/kb/187498" rel="noreferrer">http://support.microsoft.com/kb/187498</a></p> <p>It doesn't seem to apply because the only protocol listed in the registry is SSL 2.0 (not all the others) and the setting "DisabledByDefault=1" is already in there, which would seem to imply that it is disabled.</p> <p>However, the following article seems to suggest that it still applies and to turn off "DisabledByDefault" which seems strange. <a href="http://forums.iis.net/t/1151822.aspx" rel="noreferrer">http://forums.iis.net/t/1151822.aspx</a></p> <p>I only need to disable SSL v2.0, but I want to be relatively confident I am doing the right thing.</p>
[ { "answer_id": 5057027, "author": "Martin Buberl", "author_id": 135441, "author_profile": "https://Stackoverflow.com/users/135441", "pm_score": 5, "selected": false, "text": "HKey_Local_Machine\\System\\CurrentControlSet\\Control\\SecurityProviders \\SCHANNEL\\Protocols\\SSL 2.0" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
230,981
<p>I am working with some input that is in the possible forms</p> <pre><code>$1,200 20 cents/ inch $10 </code></pre> <p>Is there a way to parse these to numbers in VB? Also printing these numbers?</p> <p><strong>EDIT:</strong> Regular expressions would be great.</p> <p><strong>EDIT:</strong> VB 6 in particular</p>
[ { "answer_id": 231025, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": true, "text": "Dim oRE As Object\nSet oRE = New VBScript_RegExp.RegExp\noRe.Pattern = \"\\D\"\nstrTest = oRE.Replace(strTest, \"\")\n" }, { "answer_id": 231092, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 2, "selected": false, "text": "CLng() CDec() CLng(split(\"20 cents / inch\", \" \")(0))\n CDec" }, { "answer_id": 231717, "author": "SystemSmith", "author_id": 30987, "author_profile": "https://Stackoverflow.com/users/30987", "pm_score": 1, "selected": false, "text": "Function GetNumberFromString(s As String) As Currency\n12800 Const ProcID = \"GetNumberFromString\"\n12810 Dim c As String\n12820 Dim d As Integer\n12830 Dim Denominator As Double ' currency only handles 4 places\n12840 Dim HaveDec As Boolean\n12850 Dim HaveSlash As Boolean\n12860 Dim HaveSpace As Boolean\n12870 Dim i As Integer\n12880 Dim LenV As Integer\n12890 Dim NegMult As Integer\n12900 Dim Numerator As Currency\n12910 Dim TempVal As Currency\n12920 Dim v As String\n\n 'Provides the functionality of VAL, but handles commas, fractions\n ' also million and billion\n\n12930 On Error GoTo ErrLbl\n12940 oLog.LogProcEntry ModuleID, ProcID, \"v=\" & v\n\n12950 v = Trim(s)\n12960 LenV = Len(v)\n12970 If LenV = 0 Then\n12980 GetNumberFromString = 0\n12990 GoTo ExitProc\n13000 End If\n13010 TempVal = 0\n13020 d = 0\n13030 NegMult = 1\n '\n13040 For i = 1 To LenV\n13050 c = Mid(v, i, 1)\n13060 Select Case c\n Case \"0\" To \"9\"\n13070 If HaveSpace Then\n13080 If Not HaveSlash Then\n13090 Numerator = 10 * Numerator + Asc(c) - 48\n13100 Else\n13110 Denominator = 10 * Denominator + Asc(c) - 48\n13120 End If\n13130 ElseIf Not HaveDec Then\n13140 TempVal = 10 * TempVal + Asc(c) - 48\n13150 Else\n13160 TempVal = TempVal + ((Asc(c) - 48)) / (10 ^ d)\n13170 d = d + 1\n13180 End If\n13190 Case \",\", \"$\"\n ' do nothing\n13200 Case \"-\" 'let handle negatives ns 12/20/96\n13210 NegMult = -1 * NegMult\n13220 Case \"(\" 'let handle negatives mt 6/9/99\n13230 NegMult = -1 * NegMult\n13240 Case \".\"\n13250 HaveDec = True\n13260 d = 1\n13270 Case \" \"\n13280 HaveSpace = True\n13290 d = 1\n13300 Case \"/\"\n13310 HaveSlash = True\n13320 If Not HaveSpace Then\n13330 HaveSpace = True\n13340 Numerator = TempVal\n13350 TempVal = 0\n13360 End If\n13370 Case \"b\", \"B\"\n13380 If UCase(Mid(v, i, 7)) = \"BILLION\" Then\n13390 TempVal = TempVal * 1000000000#\n13400 Exit For\n13410 End If\n13420 Case \"m\", \"M\"\n13430 If UCase(Mid(v, i, 7)) = \"MILLION\" Then\n13440 TempVal = TempVal * 1000000#\n13450 Exit For\n13460 End If\n13470 Case Else\n ' ignore character/error\n13480 End Select\n13490 Next i\n\n13500 If HaveSlash And Denominator <> 0 Then\n13510 TempVal = TempVal + Numerator / Denominator\n13520 End If\n\n13530 GetNumberFromString = TempVal * NegMult\n\nExitProc:\n13540 oLog.LogProcExit ModuleID, ProcID\n13550 Exit Function\n\nErrLbl:\n13560 Debug.Print Err.Description, Err.Number\n13570 Debug.Assert False\n13580 ERHandler ModuleID, ProcID\n13590 Resume\nEnd Function\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
230,984
<p>Is there a compression API available for use on the iPhone? We're building some RESTful web services for our iPhone app to talk to, but we want to compress at least some of the conversations for efficiency.</p> <p>I don't care what the format (ZIP, LHA, whatever) is, and it does not need to be secure.</p> <p>Some respondents have pointed out that the server can compress its output, and the iPhone can consume that. The scenario we have is exactly the reverse. We'll be POSTing compressed content <strong>to</strong> the web service. We're not concerned with compression going the other way.</p>
[ { "answer_id": 234099, "author": "Brad Larson", "author_id": 19679, "author_profile": "https://Stackoverflow.com/users/19679", "pm_score": 6, "selected": false, "text": "@interface NSData (NSDataExtension)\n\n// Returns range [start, null byte), or (NSNotFound, 0).\n- (NSRange) rangeOfNullTerminatedBytesFrom:(int)start;\n\n// Canonical Base32 encoding/decoding.\n+ (NSData *) dataWithBase32String:(NSString *)base32;\n- (NSString *) base32String;\n\n// COBS is an encoding that eliminates 0x00.\n- (NSData *) encodeCOBS;\n- (NSData *) decodeCOBS;\n\n// ZLIB\n- (NSData *) zlibInflate;\n- (NSData *) zlibDeflate;\n\n// GZIP\n- (NSData *) gzipInflate;\n- (NSData *) gzipDeflate;\n\n//CRC32\n- (unsigned int)crc32;\n\n// Hash\n- (NSData*) md5Digest;\n- (NSString*) md5DigestString;\n- (NSData*) sha1Digest;\n- (NSString*) sha1DigestString;\n- (NSData*) ripemd160Digest;\n- (NSString*) ripemd160DigestString;\n\n@end\n #import \"NSData+CocoaDevUsersAdditions.h\"\n#include <zlib.h>\n#include <openssl/md5.h>\n#include <openssl/sha.h>\n#include <openssl/ripemd.h>\n\n\n@implementation NSData (NSDataExtension)\n\n// Returns range [start, null byte), or (NSNotFound, 0).\n- (NSRange) rangeOfNullTerminatedBytesFrom:(int)start\n{\n const Byte *pdata = [self bytes];\n int len = [self length];\n if (start < len)\n {\n const Byte *end = memchr (pdata + start, 0x00, len - start);\n if (end != NULL) return NSMakeRange (start, end - (pdata + start));\n }\n return NSMakeRange (NSNotFound, 0);\n}\n\n+ (NSData *) dataWithBase32String:(NSString *)encoded\n{\n /* First valid character that can be indexed in decode lookup table */\n static int charDigitsBase = '2';\n\n /* Lookup table used to decode() characters in encoded strings */\n static int charDigits[] =\n { 26,27,28,29,30,31,-1,-1,-1,-1,-1,-1,-1,-1 // 23456789:;<=>?\n ,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14 // @ABCDEFGHIJKLMNO\n ,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1 // PQRSTUVWXYZ[\\]^_\n ,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14 // `abcdefghijklmno\n ,15,16,17,18,19,20,21,22,23,24,25 // pqrstuvwxyz\n };\n\n if (! [encoded canBeConvertedToEncoding:NSASCIIStringEncoding]) return nil;\n const char *chars = [encoded cStringUsingEncoding:NSASCIIStringEncoding]; // avoids using characterAtIndex.\n int charsLen = [encoded lengthOfBytesUsingEncoding:NSASCIIStringEncoding];\n\n // Note that the code below could detect non canonical Base32 length within the loop. However canonical Base32 length can be tested before entering the loop.\n // A canonical Base32 length modulo 8 cannot be:\n // 1 (aborts discarding 5 bits at STEP n=0 which produces no byte),\n // 3 (aborts discarding 7 bits at STEP n=2 which produces no byte),\n // 6 (aborts discarding 6 bits at STEP n=1 which produces no byte).\n switch (charsLen & 7) { // test the length of last subblock\n case 1: // 5 bits in subblock: 0 useful bits but 5 discarded\n case 3: // 15 bits in subblock: 8 useful bits but 7 discarded\n case 6: // 30 bits in subblock: 24 useful bits but 6 discarded\n return nil; // non-canonical length\n }\n int charDigitsLen = sizeof(charDigits);\n int bytesLen = (charsLen * 5) >> 3;\n Byte bytes[bytesLen];\n int bytesOffset = 0, charsOffset = 0;\n // Also the code below does test that other discarded bits\n // (1 to 4 bits at end) are effectively 0.\n while (charsLen > 0)\n {\n int digit, lastDigit;\n // STEP n = 0: Read the 1st Char in a 8-Chars subblock\n // Leave 5 bits, asserting there's another encoding Char\n if ((digit = (int)chars[charsOffset] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n lastDigit = digit << 3;\n // STEP n = 5: Read the 2nd Char in a 8-Chars subblock\n // Insert 3 bits, leave 2 bits, possibly trailing if no more Char\n if ((digit = (int)chars[charsOffset + 1] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n bytes[bytesOffset] = (Byte)((digit >> 2) | lastDigit);\n lastDigit = (digit & 3) << 6;\n if (charsLen == 2) {\n if (lastDigit != 0) return nil; // non-canonical end\n break; // discard the 2 trailing null bits\n }\n // STEP n = 2: Read the 3rd Char in a 8-Chars subblock\n // Leave 7 bits, asserting there's another encoding Char\n if ((digit = (int)chars[charsOffset + 2] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n lastDigit |= (Byte)(digit << 1);\n // STEP n = 7: Read the 4th Char in a 8-chars Subblock\n // Insert 1 bit, leave 4 bits, possibly trailing if no more Char\n if ((digit = (int)chars[charsOffset + 3] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n bytes[bytesOffset + 1] = (Byte)((digit >> 4) | lastDigit);\n lastDigit = (Byte)((digit & 15) << 4);\n if (charsLen == 4) {\n if (lastDigit != 0) return nil; // non-canonical end\n break; // discard the 4 trailing null bits\n }\n // STEP n = 4: Read the 5th Char in a 8-Chars subblock\n // Insert 4 bits, leave 1 bit, possibly trailing if no more Char\n if ((digit = (int)chars[charsOffset + 4] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n bytes[bytesOffset + 2] = (Byte)((digit >> 1) | lastDigit);\n lastDigit = (Byte)((digit & 1) << 7);\n if (charsLen == 5) {\n if (lastDigit != 0) return nil; // non-canonical end\n break; // discard the 1 trailing null bit\n }\n // STEP n = 1: Read the 6th Char in a 8-Chars subblock\n // Leave 6 bits, asserting there's another encoding Char\n if ((digit = (int)chars[charsOffset + 5] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n lastDigit |= (Byte)(digit << 2);\n // STEP n = 6: Read the 7th Char in a 8-Chars subblock\n // Insert 2 bits, leave 3 bits, possibly trailing if no more Char\n if ((digit = (int)chars[charsOffset + 6] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n bytes[bytesOffset + 3] = (Byte)((digit >> 3) | lastDigit);\n lastDigit = (Byte)((digit & 7) << 5);\n if (charsLen == 7) {\n if (lastDigit != 0) return nil; // non-canonical end\n break; // discard the 3 trailing null bits\n }\n // STEP n = 3: Read the 8th Char in a 8-Chars subblock\n // Insert 5 bits, leave 0 bit, next encoding Char may not exist\n if ((digit = (int)chars[charsOffset + 7] - charDigitsBase) < 0 || digit >= charDigitsLen || (digit = charDigits[digit]) == -1)\n return nil; // invalid character\n bytes[bytesOffset + 4] = (Byte)(digit | lastDigit);\n //// This point is always reached for chars.length multiple of 8\n charsOffset += 8;\n bytesOffset += 5;\n charsLen -= 8;\n }\n // On loop exit, discard the n trailing null bits\n return [NSData dataWithBytes:bytes length:sizeof(bytes)];\n}\n\n- (NSString *) base32String\n{\n /* Lookup table used to canonically encode() groups of data bits */\n static char canonicalChars[] =\n { 'A','B','C','D','E','F','G','H','I','J','K','L','M' // 00..12\n ,'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' // 13..25\n ,'2','3','4','5','6','7' // 26..31\n };\n const Byte *bytes = [self bytes];\n int bytesOffset = 0, bytesLen = [self length];\n int charsOffset = 0, charsLen = ((bytesLen << 3) + 4) / 5;\n char chars[charsLen];\n while (bytesLen != 0) {\n int digit, lastDigit;\n // INVARIANTS FOR EACH STEP n in [0..5[; digit in [0..31[;\n // The remaining n bits are already aligned on top positions\n // of the 5 least bits of digit, the other bits are 0.\n ////// STEP n = 0: insert new 5 bits, leave 3 bits\n digit = bytes[bytesOffset] & 255;\n chars[charsOffset] = canonicalChars[digit >> 3];\n lastDigit = (digit & 7) << 2;\n if (bytesLen == 1) { // put the last 3 bits\n chars[charsOffset + 1] = canonicalChars[lastDigit];\n break;\n }\n ////// STEP n = 3: insert 2 new bits, then 5 bits, leave 1 bit\n digit = bytes[bytesOffset + 1] & 255;\n chars[charsOffset + 1] = canonicalChars[(digit >> 6) | lastDigit];\n chars[charsOffset + 2] = canonicalChars[(digit >> 1) & 31];\n lastDigit = (digit & 1) << 4;\n if (bytesLen == 2) { // put the last 1 bit\n chars[charsOffset + 3] = canonicalChars[lastDigit];\n break;\n }\n ////// STEP n = 1: insert 4 new bits, leave 4 bit\n digit = bytes[bytesOffset + 2] & 255;\n chars[charsOffset + 3] = canonicalChars[(digit >> 4) | lastDigit];\n lastDigit = (digit & 15) << 1;\n if (bytesLen == 3) { // put the last 1 bits\n chars[charsOffset + 4] = canonicalChars[lastDigit];\n break;\n }\n ////// STEP n = 4: insert 1 new bit, then 5 bits, leave 2 bits\n digit = bytes[bytesOffset + 3] & 255;\n chars[charsOffset + 4] = canonicalChars[(digit >> 7) | lastDigit];\n chars[charsOffset + 5] = canonicalChars[(digit >> 2) & 31];\n lastDigit = (digit & 3) << 3;\n if (bytesLen == 4) { // put the last 2 bits\n chars[charsOffset + 6] = canonicalChars[lastDigit];\n break;\n }\n ////// STEP n = 2: insert 3 new bits, then 5 bits, leave 0 bit\n digit = bytes[bytesOffset + 4] & 255;\n chars[charsOffset + 6] = canonicalChars[(digit >> 5) | lastDigit];\n chars[charsOffset + 7] = canonicalChars[digit & 31];\n //// This point is always reached for bytes.length multiple of 5\n bytesOffset += 5;\n charsOffset += 8;\n bytesLen -= 5;\n }\n return [NSString stringWithCString:chars length:sizeof(chars)];\n}\n\n#define FinishBlock(X) \\\n(*code_ptr = (X), \\\ncode_ptr = dst++, \\\ncode = 0x01)\n\n- (NSData *) encodeCOBS\n{\n if ([self length] == 0) return self;\n\n NSMutableData *encoded = [NSMutableData dataWithLength:([self length] + [self length] / 254 + 1)];\n unsigned char *dst = [encoded mutableBytes];\n const unsigned char *ptr = [self bytes];\n unsigned long length = [self length];\n const unsigned char *end = ptr + length;\n unsigned char *code_ptr = dst++;\n unsigned char code = 0x01;\n while (ptr < end)\n {\n if (*ptr == 0) FinishBlock(code);\n else\n {\n *dst++ = *ptr;\n code++;\n if (code == 0xFF) FinishBlock(code);\n }\n ptr++;\n }\n FinishBlock(code);\n\n [encoded setLength:((Byte *)dst - (Byte *)[encoded mutableBytes])];\n return [NSData dataWithData:encoded];\n}\n\n- (NSData *) decodeCOBS\n{\n if ([self length] == 0) return self;\n\n const Byte *ptr = [self bytes];\n unsigned length = [self length];\n NSMutableData *decoded = [NSMutableData dataWithLength:length];\n Byte *dst = [decoded mutableBytes];\n Byte *basedst = dst;\n\n const unsigned char *end = ptr + length;\n while (ptr < end)\n {\n int i, code = *ptr++;\n for (i=1; i<code; i++) *dst++ = *ptr++;\n if (code < 0xFF) *dst++ = 0;\n }\n\n [decoded setLength:(dst - basedst)];\n return [NSData dataWithData:decoded];\n}\n\n- (NSData *)zlibInflate\n{\n if ([self length] == 0) return self;\n\n unsigned full_length = [self length];\n unsigned half_length = [self length] / 2;\n\n NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];\n BOOL done = NO;\n int status;\n\n z_stream strm;\n strm.next_in = (Bytef *)[self bytes];\n strm.avail_in = [self length];\n strm.total_out = 0;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n\n if (inflateInit (&strm) != Z_OK) return nil;\n\n while (!done)\n {\n // Make sure we have enough room and reset the lengths.\n if (strm.total_out >= [decompressed length])\n [decompressed increaseLengthBy: half_length];\n strm.next_out = [decompressed mutableBytes] + strm.total_out;\n strm.avail_out = [decompressed length] - strm.total_out;\n\n // Inflate another chunk.\n status = inflate (&strm, Z_SYNC_FLUSH);\n if (status == Z_STREAM_END) done = YES;\n else if (status != Z_OK) break;\n }\n if (inflateEnd (&strm) != Z_OK) return nil;\n\n // Set real length.\n if (done)\n {\n [decompressed setLength: strm.total_out];\n return [NSData dataWithData: decompressed];\n }\n else return nil;\n}\n\n- (NSData *)zlibDeflate\n{\n if ([self length] == 0) return self;\n\n z_stream strm;\n\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.total_out = 0;\n strm.next_in=(Bytef *)[self bytes];\n strm.avail_in = [self length];\n\n // Compresssion Levels:\n // Z_NO_COMPRESSION\n // Z_BEST_SPEED\n // Z_BEST_COMPRESSION\n // Z_DEFAULT_COMPRESSION\n\n if (deflateInit(&strm, Z_DEFAULT_COMPRESSION) != Z_OK) return nil;\n\n NSMutableData *compressed = [NSMutableData dataWithLength:16384]; // 16K chuncks for expansion\n\n do {\n\n if (strm.total_out >= [compressed length])\n [compressed increaseLengthBy: 16384];\n\n strm.next_out = [compressed mutableBytes] + strm.total_out;\n strm.avail_out = [compressed length] - strm.total_out;\n\n deflate(&strm, Z_FINISH);\n\n } while (strm.avail_out == 0);\n\n deflateEnd(&strm);\n\n [compressed setLength: strm.total_out];\n return [NSData dataWithData: compressed];\n}\n\n- (NSData *)gzipInflate\n{\n if ([self length] == 0) return self;\n\n unsigned full_length = [self length];\n unsigned half_length = [self length] / 2;\n\n NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];\n BOOL done = NO;\n int status;\n\n z_stream strm;\n strm.next_in = (Bytef *)[self bytes];\n strm.avail_in = [self length];\n strm.total_out = 0;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n\n if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;\n while (!done)\n {\n // Make sure we have enough room and reset the lengths.\n if (strm.total_out >= [decompressed length])\n [decompressed increaseLengthBy: half_length];\n strm.next_out = [decompressed mutableBytes] + strm.total_out;\n strm.avail_out = [decompressed length] - strm.total_out;\n\n // Inflate another chunk.\n status = inflate (&strm, Z_SYNC_FLUSH);\n if (status == Z_STREAM_END) done = YES;\n else if (status != Z_OK) break;\n }\n if (inflateEnd (&strm) != Z_OK) return nil;\n\n // Set real length.\n if (done)\n {\n [decompressed setLength: strm.total_out];\n return [NSData dataWithData: decompressed];\n }\n else return nil;\n}\n\n- (NSData *)gzipDeflate\n{\n if ([self length] == 0) return self;\n\n z_stream strm;\n\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.total_out = 0;\n strm.next_in=(Bytef *)[self bytes];\n strm.avail_in = [self length];\n\n // Compresssion Levels:\n // Z_NO_COMPRESSION\n // Z_BEST_SPEED\n // Z_BEST_COMPRESSION\n // Z_DEFAULT_COMPRESSION\n\n if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;\n\n NSMutableData *compressed = [NSMutableData dataWithLength:16384]; // 16K chunks for expansion\n\n do {\n\n if (strm.total_out >= [compressed length])\n [compressed increaseLengthBy: 16384];\n\n strm.next_out = [compressed mutableBytes] + strm.total_out;\n strm.avail_out = [compressed length] - strm.total_out;\n\n deflate(&strm, Z_FINISH);\n\n } while (strm.avail_out == 0);\n\n deflateEnd(&strm);\n\n [compressed setLength: strm.total_out];\n return [NSData dataWithData:compressed];\n}\n\n// --------------------------------CRC32-------------------------------\nstatic const unsigned long crc32table[] =\n{\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d\n};\n\n- (unsigned int)crc32\n{\n unsigned int crcval;\n unsigned int x, y;\n const void *bytes;\n unsigned int max;\n\n bytes = [self bytes];\n max = [self length];\n crcval = 0xffffffff;\n for (x = 0, y = max; x < y; x++) {\n crcval = ((crcval >> 8) & 0x00ffffff) ^ crc32table[(crcval ^ (*((unsigned char *)bytes + x))) & 0xff];\n }\n\n return crcval ^ 0xffffffff;\n}\n\n// Hash function, by [[DamienBob]]\n\n#define HEComputeDigest(method) \\\nmethod##_CTX ctx; \\\nunsigned char digest[method##_DIGEST_LENGTH]; \\\nmethod##_Init(&ctx); \\\nmethod##_Update(&ctx, [self bytes], [self length]); \\\nmethod##_Final(digest, &ctx);\n\n#define HEComputeDigestNSData(method) \\\nHEComputeDigest(method) \\\nreturn [NSData dataWithBytes:digest length:method##_DIGEST_LENGTH];\n\n#define HEComputeDigestNSString(method) \\\nstatic char __HEHexDigits[] = \"0123456789abcdef\"; \\\nunsigned char digestString[2*method##_DIGEST_LENGTH];\\\nunsigned int i; \\\nHEComputeDigest(method) \\\nfor(i=0; i<method##_DIGEST_LENGTH; i++) { \\\n digestString[2*i] = __HEHexDigits[digest[i] >> 4]; \\\n digestString[2*i+1] = __HEHexDigits[digest[i] & 0x0f];\\\n} \\\nreturn [NSString stringWithCString:(char *)digestString length:2*method##_DIGEST_LENGTH];\n\n#define SHA1_CTX SHA_CTX\n#define SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH\n\n- (NSData*) md5Digest\n{\n HEComputeDigestNSData(MD5);\n}\n\n- (NSString*) md5DigestString\n{\n HEComputeDigestNSString(MD5);\n}\n\n- (NSData*) sha1Digest\n{\n HEComputeDigestNSData(SHA1);\n}\n\n- (NSString*) sha1DigestString\n{\n HEComputeDigestNSString(SHA1);\n}\n\n- (NSData*) ripemd160Digest\n{\n HEComputeDigestNSData(RIPEMD160);\n}\n\n- (NSString*) ripemd160DigestString\n{\n HEComputeDigestNSString(RIPEMD160);\n}\n\n@end\n" }, { "answer_id": 2996757, "author": "Yogan", "author_id": 270088, "author_profile": "https://Stackoverflow.com/users/270088", "pm_score": 2, "selected": false, "text": "#import \"zlib.h\"\n\n\nint datal = [zipedData length];\nBytef *buffer[uncompressedSize];\nBytef *dataa[datal];\n\n[zipedData getBytes:dataa];\n\nLong *ld;\n\nuLong sl = datal;\n*ld = uncompressedSize;\nif(uncompress(buffer, ld, dataa, sl) == Z_OK)\n{\nNSData *uncompressedData = [NSData dataWithBytes:buffer length:uncompressedSize];\nNSString *txtFile = [[NSString alloc] initWithData:uncompressedData encoding:NSUTF8StringEncoding];\n}\n" }, { "answer_id": 38888360, "author": "James C", "author_id": 1024845, "author_profile": "https://Stackoverflow.com/users/1024845", "pm_score": 3, "selected": false, "text": "@import Compression;\n\nNSData *theData = [NSData dataWithContentsOfFile:[<some file> path]];\nsize_t theDataSize = [theData length];\nconst uint8_t *buf = (const uint8_t *)[theData bytes];\nuint8_t *destBuf = malloc(sizeof(uint8_t) * theDataSize);\nsize_t compressedSize = compression_encode_buffer(destBuf, theDataSize, buf, theDataSize, NULL, COMPRESSION_LZFSE);\nself.<NSData item> = [NSData dataWithBytes:destBuf length:compressedSize];\n\nNSLog(@\"originalsize:%zu compressed:%zu\", theDataSize, compressedSize);\nfree(destBuf);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/230984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
231,023
<p>I'd like to align label/value pairs in the center using CSS without using absolute positioning or tables (see screen shot). In that screen shot I positioned the value (ie. $4,500/wk) absolute and then floated the label right up against it. But absolute doesn't work so well in IE and I've heard it's not a good technique.</p> <p>But how can I acheive this effect where the labels are all justified right without absolute?</p> <p><a href="http://www.amherstparents.org/files/shot.jpg" rel="nofollow noreferrer">alt text http://www.amherstparents.org/files/shot.jpg</a></p>
[ { "answer_id": 231056, "author": "Rahul", "author_id": 16308, "author_profile": "https://Stackoverflow.com/users/16308", "pm_score": 2, "selected": false, "text": "<dl>\n<dt>Cost:</dt>\n<dd>$4,500/wk</dd>\n<dt>Sleeps:</dt>\n<dd>1</dd>\n</dl>\n dl { width: 200px; }\ndt { width: 100px; text-align: right; float: left; clear: both; }\ndd { width: 100px; margin: 0; float: left; }\n" }, { "answer_id": 231078, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 2, "selected": false, "text": ".label {\n min-width: 20%;\n text-align: right;\n float: left;\n}\n <div class=\"pair\">\n <div class=\"label\">Cost</div>\n <div class=\"value\">$4,500/wk</div>\n</div>\n<div class=\"pair\">\n <div class=\"label\">Sleeps</div>\n <div class=\"value\">1</div>\n</div>\n<div class=\"pair\">\n <div class=\"label\">Bedrooms</div>\n <div class=\"value\">9</div>\n</div>\n" }, { "answer_id": 231164, "author": "Mike", "author_id": 25371, "author_profile": "https://Stackoverflow.com/users/25371", "pm_score": 2, "selected": false, "text": "#list { width: 450px; }\n#left { float: left; background: lightgreen; }\n#right { float: right; background: lightblue; }\ndl { width: 225px; }\ndt { width: 100px; text-align: right; float: left; clear: both; }\ndd { width: 100px; margin: 0; float: left; padding-left: 5px; }\n <div id=\"list\">\n <dl id=\"left\">\n <dt>Cost:</dt>\n <dd>$4,500/wk</dd>\n <dt>Sleeps:</dt>\n <dd>1</dd>\n <dt>Bedrooms:</dt>\n <dd>9</dd>\n <dt>Baths:</dt>\n <dd>6</dd>\n </dl>\n <dl id=\"right\">\n <dt>Pets:</dt>\n <dd>No</dd>\n <dt>Smoking:</dt>\n <dd>No</dd>\n <dt>Pool:</dt>\n <dd>No</dd>\n <dt>Waterfront:</dt>\n <dd>No</dd>\n </dl>\n</div>\n" }, { "answer_id": 231311, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 4, "selected": true, "text": "<style>\n dl\n {\n float:left;\n width:100%;\n }\n dt,\n dd\n {\n float:left;\n width:24%;\n margin:0;\n padding:0;\n }\n dt\n {\n text-align:right;\n padding-right:.33em;\n }\n dd\n {\n text-align:left;\n }\n</style>\n<dl>\n <dt>Cost:</dt>\n <dd>$4,500/wk</dd>\n <dt>Pets:</dt>\n <dd>No</dd>\n <dt>Sleeps:</dt>\n <dd>1</dd>\n <dt>Smoking:</dt>\n <dd>No</dd>\n</dl>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6957/" ]
231,027
<p>I make a request to an xml web service, and get back a response. This response, being a stream, is then saved to a string. The problem is, the response is full of tags, CDATA, etc (as you would expect). There is no line breaking either, as to be expected.</p> <p>I want to take this string, which represents an xml document, and strip it of all its tags but keep the actual values, and also, make sure that each record is in one line, so:</p> <pre><code>&lt;Record&gt; &lt;name&gt;adam&lt;/name&gt; &lt;telephoneno&gt;000&lt;/telephonenumber&gt; &lt;/Record&gt; &lt;Record&gt; &lt;name&gt;mike&lt;/name&gt; &lt;telephoneno&gt;001&lt;/telephonenumber&gt; &lt;/Record&gt; </code></pre> <p>Will be transformed to:</p> <pre><code>adam 000 mike 001 </code></pre> <p>Headings is an easy issue, but how could I achieve this? I've tried datatables and datasets but I don't think they have great support for achieving what I am trying to do.</p>
[ { "answer_id": 231041, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"style.xsl\"?>\n<Records>\n <Record>\n <name>adam</name>\n <telephonenumber>000</telephonenumber>\n </Record>\n <Record>\n <name>mike</name>\n <telephonenumber>001</telephonenumber>\n </Record>\n</Records>\n <xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"text\" omit-xml-declaration=\"yes\" indent=\"no\"/>\n <xsl:template match=\"Record\">\n <xsl:value-of select=\"name\"/><xsl:text> </xsl:text><xsl:value-of select=\"telephonenumber\"/>\n </xsl:template>\n</xsl:stylesheet>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,029
<p>I am trying to include a value from a database table within the value element of an input field.<br> This is what I have, but it is not working:</p> <pre><code>?&gt;&lt;input type="text" size="10" value="&lt;?= date("Y-m-d", strtotime($rowupd['upcoming_event_featured_date'])) ?&gt;" name="upcoming_event_featured_date" id="keys"/&gt;&lt;?php </code></pre> <p>I have done this before, but I usually print it out like this:</p> <pre><code>print '&lt;input type="text" size="10" value="'.date("Y-m-d", strtotime($rowupd['upcoming_event_featured_date'])).'" name="upcoming_event_featured_date" id="keys"/&gt;'; </code></pre> <p>What is the appropriate way of doing this without using <code>print ''</code>?</p>
[ { "answer_id": 231037, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 1, "selected": false, "text": "ini_set('short_open_tag', true);\n" }, { "answer_id": 231058, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 0, "selected": false, "text": "[...] ?><input \n type=\"text\" \n size=\"10\" \n value=\"<?php echo date(\"Y-m-d\", strtotime($rowupd['upcoming_event_featured_date'])) ?>\" \n name=\"upcoming_event_featured_date\" \n id=\"keys\"/>\n<?php [...]\n short_open_tag" }, { "answer_id": 231085, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 3, "selected": true, "text": "?>\n<input type=\"text\" size=\"10\" value=\"<?php\necho(date(\"Y-m-d\", strtotime($rowupd['upcoming_event_featured_date'])));\n?>\"name=\"upcoming_event_featured_date\" id=\"keys\"/><?php\n ; echo()" }, { "answer_id": 234908, "author": "Zac", "author_id": 5630, "author_profile": "https://Stackoverflow.com/users/5630", "pm_score": 2, "selected": false, "text": "short_open_tag <?= $featured_date = date(\"Y-m-d\",strtotime($rowupd['featured_date']));\n\n?><input type=\"text\" value=\"<?=$featured_date?>\" name=\"featured_date\" /><?php\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
231,034
<p>I'm using Visual Studio 2008 Team Development Edition and my Project properties page will not display. I right-clicked the project name and selected "Properties" and no page displayed as it normally would. Also, when I double-click the Settings.settings the normal Settings GUI does not display. I only see the XML in the Settings.settings file. Please Help. Thanks.</p>
[ { "answer_id": 27580436, "author": "slavash", "author_id": 4380689, "author_profile": "https://Stackoverflow.com/users/4380689", "pm_score": 2, "selected": false, "text": "devenv.exe /resetskippkgs\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27852/" ]
231,051
<p>After reading <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip130.html?page=2" rel="noreferrer">this old article</a> measuring the memory consumption of several object types, I was amazed to see how much memory <code>String</code>s use in Java:</p> <pre><code>length: 0, {class java.lang.String} size = 40 bytes length: 7, {class java.lang.String} size = 56 bytes </code></pre> <p>While the article has some tips to minimize this, I did not find them entirely satisfying. It seems to be wasteful to use <code>char[]</code> for storing the data. The obvious improvement for most western languages would be to use <code>byte[]</code> and an encoding like UTF-8 instead, as you only need a single byte to store the most frequent characters then instead of two bytes.</p> <p>Of course one could use <code>String.getBytes(&quot;UTF-8&quot;)</code> and <code>new String(bytes, &quot;UTF-8&quot;)</code>. Even the overhead of the String instance itself would be gone. But then there you lose very handy methods like <code>equals()</code>, <code>hashCode()</code>, <code>length()</code>, ...</p> <p>Sun has a <a href="http://www.freepatentsonline.com/6751790.html" rel="noreferrer">patent</a> on <code>byte[]</code> representation of Strings, as far as I can tell.</p> <blockquote> <p><strong>Frameworks for efficient representation of string objects in Java programming environments</strong><br /> ... The techniques can be implemented to create Java string objects as arrays of one-byte characters when it is appropriate ...</p> </blockquote> <p>But I failed to find an API for that patent.</p> <p>Why do I care?<br /> In most cases I don't. But I worked on applications with huge caches, containing lots of Strings, which would have benefitted from using the memory more efficiently.</p> <p>Does anybody know of such an API? Or is there another way to keep your memory footprint for Strings small, even at the cost of CPU performance or uglier API?</p> <p>Please don't repeat the suggestions from the above article:</p> <ul> <li>own variant of <code>String.intern()</code> (possibly with <code>SoftReferences</code>)</li> <li>storing a single <code>char[]</code> and exploiting the current <code>String.subString(.)</code> implementation to avoid data copying (nasty)</li> </ul> <p><strong>Update</strong></p> <p>I ran the code from the article on Sun's current JVM (1.6.0_10). It yielded the same results as in 2002.</p>
[ { "answer_id": 231352, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 0, "selected": false, "text": "String.intern" }, { "answer_id": 3323724, "author": "J. Dimeo", "author_id": 198371, "author_profile": "https://Stackoverflow.com/users/198371", "pm_score": 1, "selected": false, "text": "long long (char) 0 TLongHashSet long int int int long int" }, { "answer_id": 4402560, "author": "haylem", "author_id": 453590, "author_profile": "https://Stackoverflow.com/users/453590", "pm_score": 5, "selected": false, "text": "-XX:+UseCompressedStrings\n -XX byte[] char[] String LiteStrings byte[] String String StringBuffer StringBuilder" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21368/" ]
231,052
<p>I have a page where a few textboxes cannot be empty before clicking a Save button. </p> <pre><code>&lt;TextBox... &lt;TextBox.Text&gt; &lt;Binding Path ="LastName" UpdateSourceTrigger="PropertyChanged"&gt; &lt;Binding.ValidationRules&gt; &lt;local:StringRequiredValidationRule /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; </code></pre> <p>My rule works, I have a red border around my textbox until I enter a value. I now want to add this validation rule to my other text boxes.</p> <p>How do I disable the Save button until the page has no validation errors? I'm not sure what to check.</p>
[ { "answer_id": 808190, "author": "Christoph", "author_id": 98795, "author_profile": "https://Stackoverflow.com/users/98795", "pm_score": 4, "selected": false, "text": "this.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(OnErrorEvent)); \n private int errorCount;\nprivate void OnErrorEvent(object sender, RoutedEventArgs e)\n{\n var validationEventArgs = e as ValidationErrorEventArgs;\n if (validationEventArgs == null)\n throw new Exception(\"Unexpected event args\");\n switch(validationEventArgs.Action)\n {\n case ValidationErrorEventAction.Added:\n {\n errorCount++; break;\n }\n case ValidationErrorEventAction.Removed:\n {\n errorCount--; break;\n }\n default:\n {\n throw new Exception(\"Unknown action\");\n }\n }\n Save.IsEnabled = errorCount == 0;\n}\n" }, { "answer_id": 7512442, "author": "Nihal", "author_id": 958741, "author_profile": "https://Stackoverflow.com/users/958741", "pm_score": 2, "selected": false, "text": "int count = 0;\n\nprivate void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)\n{\n if (e.Action == ValidationErrorEventAction.Added)\n {\n button1.IsEnabled = false;\n count++;\n }\n if (e.Action == ValidationErrorEventAction.Removed)\n { \n count--;\n if (count == 0) button1.IsEnabled = true;\n }\n}\n" }, { "answer_id": 8157748, "author": "andrey.tsykunov", "author_id": 108317, "author_profile": "https://Stackoverflow.com/users/108317", "pm_score": 2, "selected": false, "text": " public static void AddErrorHandler(DependencyObject element, Action<bool> setHasValidationErrors)\n {\n var errors = new List<Tuple<object, ValidationError>>();\n\n RoutedEventHandler sourceUnloaded = null;\n\n sourceUnloaded = (sender, args) =>\n {\n if (sender is FrameworkElement)\n ((FrameworkElement) sender).Unloaded -= sourceUnloaded;\n else\n ((FrameworkContentElement) sender).Unloaded -= sourceUnloaded;\n\n foreach (var error in errors.Where(err => err.Item1 == sender).ToArray())\n errors.Remove(error);\n\n setHasValidationErrors(errors.Any());\n };\n\n EventHandler<ValidationErrorEventArgs> errorHandler = (_, args) =>\n {\n if (args.Action == ValidationErrorEventAction.Added)\n {\n errors.Add(new Tuple<object, ValidationError>(args.OriginalSource, args.Error));\n\n if (args.OriginalSource is FrameworkElement)\n ((FrameworkElement)args.OriginalSource).Unloaded += sourceUnloaded;\n else if (args.OriginalSource is FrameworkContentElement)\n ((FrameworkContentElement)args.OriginalSource).Unloaded += sourceUnloaded;\n }\n else\n {\n var error = errors\n .FirstOrDefault(err => err.Item1 == args.OriginalSource && err.Item2 == args.Error);\n\n if (error != null) \n errors.Remove(error);\n }\n\n setHasValidationErrors(errors.Any());\n };\n\n\n System.Windows.Controls.Validation.AddErrorHandler(element, errorHandler);\n } \n" }, { "answer_id": 14030269, "author": "Bilal", "author_id": 1928121, "author_profile": "https://Stackoverflow.com/users/1928121", "pm_score": 2, "selected": false, "text": " BindingExpression bexp = this.TextBox1.GetBindingExpression(TextBox.TextProperty);\nbexp.UpdateSource(); // this to refresh the binding and see if any error exist \nbool hasError = bexp.HasError; // this is boolean property indique if there is error \n\nMessageBox.Show(hasError.ToString());\n" }, { "answer_id": 26485326, "author": "Alexander Sirotkin", "author_id": 4165577, "author_profile": "https://Stackoverflow.com/users/4165577", "pm_score": 1, "selected": false, "text": " public bool IsValid\n {\n get\n {\n if (this.FloorPlanName.IsEmpty())\n return false;\n return true;\n }\n }\n <Button Margin=\"4,0,0,0\" Style=\"{StaticResource McVMStdButton_Ok}\" Click=\"btnDialogOk_Click\" IsEnabled=\"{Binding IsValid}\"/>\n public string this[string columnName]{\n get\n {\n switch (columnName)\n {\n case \"FloorPlanName\":\n if (this.FloorPlanName.IsEmpty())\n {\n OnPropertyChanged(\"IsValid\");\n return \"Floor plan name cant be empty\";\n }\n break;\n }\n }\n}\n" }, { "answer_id": 34953774, "author": "Kabua", "author_id": 1067299, "author_profile": "https://Stackoverflow.com/users/1067299", "pm_score": 1, "selected": false, "text": "TextBox Uri Okay CommandBindings.Add(new CommandBinding(AppCommands.Okay,\n (sender, args) => DialogResult = true,\n (sender, args) => args.CanExecute = !(bool) _uriTextBoxControl.GetValue(Validation.HasErrorProperty)));\n" }, { "answer_id": 57160112, "author": "Gregor A. Lamche", "author_id": 460732, "author_profile": "https://Stackoverflow.com/users/460732", "pm_score": 2, "selected": false, "text": "<TextBox.Text Validation.Error=\"handleValidationError\">\n <Binding Path =\"LastName\" \n UpdateSourceTrigger=\"PropertyChanged\"\n NotifyOnValidationError=\"True\">\n <Binding.ValidationRules>\n <local:StringRequiredValidationRule />\n </Binding.ValidationRules> \n </Binding>\n</TextBox.Text>\n<Button IsEnabled=\"{Binding HasNoValidationErrors}\"/>\n private int _numberOfValidationErrors;\npublic bool HasNoValidationErrors => _numberOfValidationErrors = 0;\n\nprivate void handleValidationError(object sender, ValidationErrorEventArgs e)\n{\n if (e.Action == ValidationErrorEventAction.Added)\n _numberOfValidationErrors++;\n else\n _numberOfValidationErrors--;\n}\n" }, { "answer_id": 59771649, "author": "David Shader", "author_id": 10641390, "author_profile": "https://Stackoverflow.com/users/10641390", "pm_score": 0, "selected": false, "text": "<Button Content=\"<NameThisButton>\" Click=\"<MethodToCallOnClick>\" >\n <Button.Style>\n <Style TargetType=\"{x:Type Button}\">\n <Setter Property=\"IsEnabled\" Value=\"false\" />\n <Style.Triggers>\n <MultiDataTrigger>\n <MultiDataTrigger.Conditions> \n <Condition Binding=\"{Binding ElementName=<TextBoxName>, Path=(Validation.HasError)}\" Value=\"false\" />\n <Condition Binding=\"{Binding ElementName=<TextBoxName>, Path=(Validation.HasError)}\" Value=\"false\" />\n </MultiDataTrigger.Conditions>\n <Setter Property=\"IsEnabled\" Value=\"true\" />\n </MultiDataTrigger>\n </Style.Triggers>\n </Style>\n </Button.Style>\n </Button>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
231,057
<p>Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?</p> <pre><code>echo ceil(31497230840470473074370324734723042.6); // Expected result 31497230840470473074370324734723043 // Prints &lt;garbage&gt; </code></pre>
[ { "answer_id": 231171, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "$x = '31497230840470473074370324734723042.9';\n\nbcscale(100);\nvar_dump(bcFloor($x));\nvar_dump(bcCeil($x));\nvar_dump(bcRound($x));\n\nfunction bcFloor($x)\n{\n $result = bcmul($x, '1', 0);\n if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))\n $result = bcsub($result, 1, 0);\n\n return $result;\n}\n\nfunction bcCeil($x)\n{\n $floor = bcFloor($x);\n return bcadd($floor, ceil(bcsub($x, $floor)), 0);\n}\n\nfunction bcRound($x)\n{\n $floor = bcFloor($x);\n return bcadd($floor, round(bcsub($x, $floor)), 0);\n}\n" }, { "answer_id": 1653830, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "function bcceil($number)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, 1, 0);\n }\n\n return bcsub($number, 0, 0);\n}\n\nfunction bcfloor($number)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, 0, 0);\n }\n\n return bcsub($number, 1, 0);\n}\n\nfunction bcround($number, $precision = 0)\n{\n if ($number[0] != '-')\n {\n return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n }\n\n return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n}\n assert(bcceil('4.3') == ceil('4.3')); // true\nassert(bcceil('9.999') == ceil('9.999')); // true\nassert(bcceil('-3.14') == ceil('-3.14')); // true\n\nassert(bcfloor('4.3') == floor('4.3')); // true\nassert(bcfloor('9.999') == floor('9.999')); // true\nassert(bcfloor('-3.14') == floor('-3.14')); // true\n\nassert(bcround('3.4', 0) == number_format('3.4', 0)); // true\nassert(bcround('3.5', 0) == number_format('3.5', 0)); // true\nassert(bcround('3.6', 0) == number_format('3.6', 0)); // true\nassert(bcround('1.95583', 2) == number_format('1.95583', 2)); // true\nassert(bcround('5.045', 2) == number_format('5.045', 2)); // true\nassert(bcround('5.055', 2) == number_format('5.055', 2)); // true\nassert(bcround('9.999', 2) == number_format('9.999', 2)); // true\n" }, { "answer_id": 55606171, "author": "Theodore R. Smith", "author_id": 430062, "author_profile": "https://Stackoverflow.com/users/430062", "pm_score": 0, "selected": false, "text": "/**\n * Based off of https://stackoverflow.com/a/1653826/430062\n * Thanks, [Alix Axel](https://stackoverflow.com/users/89771/alix-axel)!\n *\n * @param $number\n * @param int $precision\n * @return string\n */\nfunction bcround($number, $precision = BCMathCalcStrategy::PRECISION)\n{\n if (strpos($number, '.') !== false) {\n if ($number[0] != '-') return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);\n }\n\n // Pad it out to the desired precision.\n return number_format($number, $precision);\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13211/" ]
231,062
<p>I'm building up a library of filters for a validation class in PHP, some of them using regular expressions. I have a lot of filters in mind, but I also don't want to potentially miss any. What do you most often use regular expressions to check? What are some of the not-so-common things that you've had to check that would still be useful in a library? Note: I'm not looking for the actual regex code, just what you use it for.</p>
[ { "answer_id": 231101, "author": "tom.dietrich", "author_id": 15769, "author_profile": "https://Stackoverflow.com/users/15769", "pm_score": 1, "selected": false, "text": " '[\\s]*--\n ((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,255})\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
231,069
<p>I want to write a default structure, N times, to a file, using fwrite.</p> <pre><code>typedef struct foo_s { uint32 A; uint32 B; char desc[100]; }foo_t; void init_file(FILE *fp, int N) { foo_t foo_struct = {0}; foo_struct.A = -1; foo_struct.B = 1; fwrite(&amp;foo_struct, sizeof(foo_struct), N, fp); } </code></pre> <p>The above code does not write foo_struct N times to the file stream fp.</p> <p>Instead it writes N*sizeof(foo_struct) bytes starting from &amp;foo_struct to fp. </p> <p>Can anyone tell how to achieve the same with a single fwrite?</p>
[ { "answer_id": 231084, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": true, "text": "int i;\nfor (i = 0; i < N; ++i)\n fwrite(&foo_struct, sizeof(foo_struct), 1, fp);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
231,089
<p>Is there any point to freeing memory in an atexit() function?</p> <p>I have a global variable that gets malloc'ed after startup. I could write an atexit() function to free it, but isn't the system going to reclaim all that memory when the program exits anyway?</p> <p>Is there any benefit to being tidy and actively cleaning it up myself?</p>
[ { "answer_id": 242317, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 4, "selected": false, "text": "malloc() free() free() free() free() malloc() free()" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
231,098
<p>I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:</p> <pre><code>for( ushort i = 0; i &lt; UInt16.MaxValue; i++ ) { // do something } </code></pre> <p>The problem is that the loop will quit when i == 0xFFFF and not "do something". If I change the 'for' statement to "for(ushort i = 0; i &lt;= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.</p> <p>I could make 'i' an int and cast it or assign it to a ushort variable in the loop.</p> <p>Any suggestions?</p>
[ { "answer_id": 231112, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "do...while ushort i = 0;\ndo\n{\n // do something\n} while(i++ < UInt16.MaxValue);\n" }, { "answer_id": 231114, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "ushort i = 0;\ndo\n{\ni++;\n...\n} while(i!=UInt16.MaxValue);\n" }, { "answer_id": 231188, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 3, "selected": false, "text": "UInt16.MaxValue 0xffff 0x10000 do while ushort i = 0;\ndo {\n ...\n} while (++i != 0);\n" }, { "answer_id": 231252, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 1, "selected": false, "text": "for(int i = 0;i<=0xFFFF;i++)\n{\n //do whatever\n}\n" }, { "answer_id": 231332, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 1, "selected": false, "text": "0xffff 1 0xffff 0" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9516/" ]
231,121
<p>As a counterpart to <a href="https://stackoverflow.com/questions/215470/c-coding-guideline-102">C++ Coding Guideline 102</a>, which of the <a href="http://www.gotw.ca/publications/c++cs.htm" rel="nofollow noreferrer">101 guidelines of Sutter &amp; Alexandrescu</a> do you violate or ignore most often, and why?</p>
[ { "answer_id": 231713, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "uint64_t i = getIEEEbitpatternByMeansRelevantToTheQuestion();\ndouble d;\nmemcpy(&d, &i, 8);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
231,125
<p>I remember reading at one point that indexing a field with low cardinality (a low number of distinct values) is not really worth doing. I admit I don't know enough about how indexes work to understand why that is.</p> <p>So what if I have a table with 100 million rows in it, and I am selecting records where a bit field is 1? And let's say that at any point in time, there are only a handful of records where the bit field is 1 (as opposed to 0). Is it worth indexing that bit field or not? Why?</p> <p>Of course I can just test it and check the execution plan, and I will do that, but I'm also curious about the theory behind it. When does cardinality matter and when does it not?</p>
[ { "answer_id": 231366, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 1, "selected": false, "text": "tinyint CREATE INDEX IX_Users_IsActiveUsername ON Users\n(\n IsActive,\n Username\n)\n SELECT TOP 1 Username \nFROM Users\nWHERE IsActive = 0\n SELECT TOP 1 * \nFROM Users\nWHERE IsActive = 0\n SELECT TOP 1 Username \nFROM Users\nWHERE IsActive = 0\n SELECT TOP 1 * \nFROM Users\nWHERE IsActive = 0\n" }, { "answer_id": 18969193, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 5, "selected": false, "text": "create index [IX_foobar] on dbo.Foobar (FooID) where yourBitColumn = 1\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
231,126
<p>I'm terribly new to SQL, and cannot seem to get the desired information out, after trying a few different google searches, and reading through some SQL tutorials.</p> <p>I think it involves some sort of joins, but cannot get them straight.</p> <p>Given the following sample tables:</p> <p>Table 1(Activity This is updated every time a change is made to a task, could be manytimes per day):</p> <pre><code>ID Who What When 001 John Created 2008-10-01&lt;br&gt; 001 Bill Closed 2008-10-02&lt;br&gt; 001 John Updated 2008-10-03&lt;br&gt; 002 Bill Created 2008-10-04&lt;br&gt; 002 John Updated 2008-10-05&lt;br&gt; 002 Bill Closed 2008-10-06&lt;br&gt; </code></pre> <p>Table 2(Tasks - This is the main task tracking table):</p> <pre><code>ID Created Status 001 2008-10-01 Closed 002 2008-10-04 Closed </code></pre> <p>Table 3(Comments):</p> <pre><code>ID When Comment&lt;br 001 2008-10-01 "I'm creating a new task" 001 2008-10-02 "I have completed the task" 001 2008-10-03 "Nice job" 002 2008-10-04 "I'm creating a second task" 002 2008-10-05 "This task looks too easy" 002 2008-10-06 "I have completed this easy task" </code></pre> <p>What SQL (mySQL if it makes any difference) query would I use to find out who had done something on a task that had been closed?</p> <p>The results would be something like:</p> <pre><code>Who What ID When Comment Bill Updated 002 2008-10-03 "Nice job" </code></pre> <p>Meaning that Bill changed task 002 after it was closed, and added the comment "Nice Job"</p> <p>Any help would be much appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 231139, "author": "Totty", "author_id": 30838, "author_profile": "https://Stackoverflow.com/users/30838", "pm_score": 2, "selected": false, "text": "SELECT Activity.Who, Activity.What, Comments.When, Comments.Comment FROM Activity JOIN Comments ON Activity.ID = Comments.ID JOIN Tasks ON Comments.ID = Tasks.ID WHERE Tasks.Status = 'Closed'\n" }, { "answer_id": 231387, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "SELECT a1.Who, a1.What, a1.ID, c.When, c.Comment\nFROM Activity AS a1\n JOIN Activity AS a2 ON (a1.ID = a2.ID AND a1.When > a2.When)\n JOIN Comments AS c ON (a1.ID = c.ID AND a.When = c.When);\nWHERE a2.What = 'Closed';\n CREATE TABLE Tasks (\n Task_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Created DATE NOT NULL,\n Status VARCHAR(10)\n) TYPE=InnoDB;\n\nCREATE TABLE Activity (\n Activity_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Task_ID INT NOT NULL REFERENCES Tasks,\n Who VARCHAR(10) NOT NULL,\n What VARCHAR(10) NOT NULL,\n When DATE NOT NULL\n) TYPE=InnoDB;\n\nCREATE TABLE Comments (\n Comment_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n Activity_ID INT NOT NULL REFERENCES Activity,\n Who VARCHAR(10) NOT NULL,\n When DATE NOT NULL,\n Comment VARCHAR(100) NOT NULL\n) TYPE=InnoDB;\n SELECT c.Who, a1.What, a1.Task_ID, c.When, c.Comment\nFROM Activity AS a1\n JOIN Activity AS a2 ON (a1.Task_ID = a2.Task_ID AND a1.When > a2.When)\n JOIN Comments AS c ON (a1.Activity_ID = c.Activity_ID);\nWHERE a2.What = 'Closed';\n TYPE=InnoDB" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30939/" ]
231,128
<p>Just about every piece of example code everywhere omits error handling (because it "confuses the issue" that the example code is addressing). My programming knowledge comes primarily from books and web sites, and you seldom see any error handling in use at all there, let alone good stuff.</p> <p>Where are some places to see good examples of C++ error handling code? Specific books, specific open-source projects (preferably with the files and functions to look at), and specific web pages or sites will all be gratefully accepted.</p>
[ { "answer_id": 231302, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "int DoA() \n{\n if (location == hellInAHandcart)\n return ERROR;\n else\n RETURN OK;\n}\n\nint DoB()\n{\n int err = DoA();\n if (err != OK)\n return err;\n else\n return DoSomethingElse1();\n}\n\nint DoC()\n{\n int err = DoB();\n if (err != OK)\n //Handle My error here in whatever way...\n}\n void DoA() \n{\n if (location == hellInAHandcart)\n throw Exception(\"Gone To Hell in a Handcart\");\n}\n\nvoid DoB()\n{\n DoA();\n DoSomethingElse1();\n}\n\nvoid DoC()\n{\n try\n {\n DoB();\n }\n catch (Exception &E)\n {\n // Handle My error here in whatever way...\n }\n}\n" }, { "answer_id": 740229, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 4, "selected": false, "text": "Exception NetException SMTPException SMTPException Exception SMTPException std::exception DoC DoA DoA DoB" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
231,132
<p>I'm trying to get Wininet to ignore Internet Explorer's "Work Offline" mode, for both HTTP and FTP.</p> <p>So I'm trying to use <code>InternetSetOption()</code> with <code>INTERNET_OPTION_IGNORE_OFFLINE</code>. The documentation says "This is used by <code>InternetQueryOption</code> and <code>InternetSetOption</code> with a request handle." However, you can't get a request handle because if IE is in Work Offline mode then <code>InternetConnect()</code> will always return a null handle. Without a connection handle you can't get a request handle. So I tried using it with an <code>InternetOpen()</code> handle and a <code>NULL</code> handle. Both failed with <code>ERROR_INTERNET_INCORRECT_HANDLE_TYPE</code>.</p> <p>Is there a way to get this option to work? I found a reference on an MS newsgroup from 2003 that <code>INTERNET_OPEN_TYPE_PRECONFIG</code> is "broken". 5 years later with IE8 beta 2 and they still haven't fixed it? Or am I doing it wrong.</p> <p><strong>Edit</strong><br/> I wasn't quite correct. <code>InternetConnect()</code> always returns null if you are on "Work Offline" mode and using FTP, but it returns a valid handle if you are using Http. However, it still doesn't work even with a request handle.</p> <p>If I am set to "Work Offline" and I call</p> <pre><code>BOOL a = TRUE; ::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, &amp;a, sizeof(BOOL)); </code></pre> <p>on the handle from </p> <pre><code>HINTERNET hData = HttpOpenRequest(hInternet, L"POST", path, NULL, NULL, NULL, flags, 0 ); </code></pre> <p>the <code>InternetSetOption()</code> call succeeds.<br> However, the call to <code>HttpSendRequest()</code> still fails with error code 2 (file not found), same as it does if I don't set the option.<br> Same thing if I call</p> <pre><code>::InternetSetOption(hData, INTERNET_OPTION_IGNORE_OFFLINE, 0, 0); </code></pre>
[ { "answer_id": 471159, "author": "michael", "author_id": 31207, "author_profile": "https://Stackoverflow.com/users/31207", "pm_score": 0, "selected": false, "text": "GET POST" }, { "answer_id": 5739763, "author": "Rick Strahl", "author_id": 11197, "author_profile": "https://Stackoverflow.com/users/11197", "pm_score": 1, "selected": false, "text": "INTERNET_OPTION_IGNORE_OFFLINE" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24267/" ]
231,146
<p>I'm trying to change user input in wildcard form <code>("*word*")</code> to a regular expression format. To that end, I'm using the code below to strip off the <code>'*'</code> at the beginning and end of the input so that I can add the regular expression characters on either end:</p> <pre><code>string::iterator iter_begin = expressionBuilder.begin(); string::iterator iter_end = expressionBuilder.end(); iter_end--; if ((char)*iter_begin == '*' &amp;&amp; (char)*iter_end == '*') { expressionBuilder.erase(iter_begin); expressionBuilder.erase(iter_end); expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b"; } </code></pre> <p>However, the call to <code>"expressionBuilder.erase(iter_end)"</code> does <em>not</em> erase the trailing <code>'*'</code> from the input string so I wind up with an incorrect regular expression. What am I doing wrong here? <code>"(char)*iter_end == '*'"</code> must be true for the code inside the if statment to run (which it does), so why doesn't the same iterator work when passed to erase()?</p>
[ { "answer_id": 231173, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "expressionBuilder.erase(iter_end);\nexpressionBuilder.erase(iter_begin);\n erase()" }, { "answer_id": 231183, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 1, "selected": false, "text": "iter_end-- *iter_begin == '*' find() '*' rbegin() base() std::string rfind() find_last_of() '*' replace() '*'" }, { "answer_id": 231419, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "// using the reverse iterator rbegin() is a nice easy way \n// to get the last character of a string\n\nif ( (expressionBuilder.size() >= 2) &&\n (*expressionBuilder.begin() == '*') &&\n (*expressionBuilder.rbegin() == '*') ) {\n\n expressionBuilder.erase(expressionBuilder.begin());\n\n // can't nicely use rbegin() here because erase() wont take a reverse\n // iterator, and converting reverse iterators to regular iterators\n // results in rather ugly, non-intuitive code\n expressionBuilder.erase(expressionBuilder.end() - 1); // note - not invalid since we're getting it anew\n\n expressionBuilder = \"\\\\b\\\\w*\" + expressionBuilder + \"\\\\w*\\\\b\";\n}\n expressionBuilder \"\" \"*\" \"**\"" }, { "answer_id": 232383, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\nusing namespace std;\n\nstring stripStar(const string& s) {\n return string(s.begin() + 1, s.end() - 1);\n}\n\nint main() {\n cout << stripStar(\"*word*\") << \"\\n\";\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1544/" ]
231,159
<p>I remember from C days that we were encouraged to use</p> <pre><code>i &gt; -1 </code></pre> <p>instead of</p> <pre><code>i &gt;= 0 </code></pre> <p>because of performance.</p> <p>Does this still apply in the C# .NET world? What are the performance implications of using one over the other with today's compilers? i.e. Is the compiler clever enough to optimize these for you?</p> <p>(As an aside try and type the question "use >= or >" into the question field on Stack Overflow and see what happens.)</p>
[ { "answer_id": 231179, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 7, "selected": true, "text": " ;; if (i > -1) {\n cmp eax, -1\n jle else\nthen:\n ...\nelse:\n\n ;; if (i >= 0) {\n cmp eax, 0\n jl else\nthen:\n ...\nelse:\n // if (i >= 0) { (assuming i is in register %t0)\n\n stl $t1, $0, $t0 // in C: t1 = (0 < t0)\n beq $t1, $0, else // jump if t1 == 0, that is if t0 >= 0\n nop\nthen:\n ...\nelse:\n\n// if (i > -1) { (assuming i is in register %t0)\n\n addi $t2, $0, -1 // in C: t2 = -1\n stl $t1, $t2, $t0 // in C: t1 = (t2 < t0) = (-1 < t0)\n bne $t1, $0, else // jump if t1 != 0, that is if t0 > -1\n nop\nthen:\n ...\nelse:\n" }, { "answer_id": 231233, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "< <=" }, { "answer_id": 231237, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "> >= if (length >= str.size())\n if (length > str.size() - 1)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
231,175
<p>Where can I find comprehensive documentation for MOQ? I'm just starting with mocking and am having difficulty getting my head around it. I've read through all the links at <a href="http://code.google.com/p/moq/wiki/QuickStart" rel="noreferrer">http://code.google.com/p/moq/wiki/QuickStart</a> but can't seem to find a tutorial or gentle introduction.</p> <p>I have also looked briefly at Rhino Mocks but found it very confusing.</p> <hr> <p>Yes - I read Stephen Walthers article - very helpful. I also went through the links. I can't seem to watch the video at <strike><a href="http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq" rel="noreferrer">http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq</a></strike> <sup>[broken link]</sup></p> <p>Specifically I am trying to determine whether an event was raised from the mocked class. I can't get the example for events on the QuickStarts page to compile. On the google groups, Daniel explained that CreateEventHandler can only handle an event of type <code>EventHandler&lt;TEventArgs&gt;</code>, but even then I can't get the code to compile.</p> <p>More specifically I have a class that implements <code>INotifyChanged</code>. </p> <pre><code>public class Entity : INotifyChanged { public event PropertyChangingEventHandler PropertyChanging; public int Id { get {return _id;} set { _id = value; OnPropertyChanged("Id"); } } protected void OnPropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } etc ..... } </code></pre> <p>How do I mock the class to test whether the <code>PropertyChanged</code> event was fired? I can't rewrite the event to <code>public event EventHandler&lt;PropertyChangedEventArgs&gt;</code> becuase I get this error:</p> <blockquote> <p>Error 1 'CoreServices.Notifier' does not implement interface member System.ComponentModel.INotifyPropertyChanged.PropertyChanged'. 'CoreServices.Notifier.PropertyChanged' cannot implement 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' because it does not have the matching return type of 'System.ComponentModel.PropertyChangedEventHandler'.</p> </blockquote>
[ { "answer_id": 8546583, "author": "TrueWill", "author_id": 161457, "author_profile": "https://Stackoverflow.com/users/161457", "pm_score": 1, "selected": false, "text": "Id const int ExpectedId = 123;\nmockEntity.VerifySet(x => x.Id = ExpectedId);\n public interface IKeyedEntity\n{\n int Id { get; set; }\n}\n Entity INotifyChanged Entity" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30046/" ]
231,189
<p>What tool or method do you recommend to find and replace values in your code? If code is on Linux/Unix, are find and grep the best method?</p>
[ { "answer_id": 231241, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 4, "selected": true, "text": "$ perl -i -p -e's/\\bthisword\\b/thatword/g' $(find . -name *.html)\n" }, { "answer_id": 231290, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "find grep sed awk groovy python perl find | sed cygwin" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26180/" ]
231,191
<p>Ok simple question. I have a JSF application, containing a login page. The problem is if the user loads the login page, leaves it for a while, then tries to login the session expires and a ViewExpiredException is thrown. I could redirect back to the login when this happens, but that isn't very smooth. How can I allow this flow to properly login without an additional attempt?</p>
[ { "answer_id": 232829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<meta http-equiv=\"refresh\" content=\"5\"/>" }, { "answer_id": 265908, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 0, "selected": false, "text": "<%@ page session=\"false\" %>" }, { "answer_id": 894798, "author": "mtpettyp", "author_id": 98632, "author_profile": "https://Stackoverflow.com/users/98632", "pm_score": 4, "selected": true, "text": "<f:view> <f:view transient=\"true\">\n Your regular content\n</f:view>\n public class LoginViewHandler extends FaceletViewHandler\n{\n public LoginViewHandler( ViewHandler viewHandler )\n {\n super( viewHandler );\n }\n\n @Override\n public UIViewRoot restoreView( FacesContext ctx, String viewId )\n {\n UIViewRoot viewRoot = super.restoreView( ctx, viewId );\n\n if ( viewRoot == null && viewId.equals( \"/login.xhtml\" ) )\n {\n // Work around Facelet issue\n initialize( ctx );\n\n viewRoot = super.createView( ctx, viewId );\n ctx.setViewRoot( viewRoot );\n\n try\n {\n buildView( ctx, viewRoot );\n }\n catch ( IOException e )\n {\n log.log( Level.SEVERE, \"Error building view\", e ); \n }\n }\n\n return viewRoot;\n }\n}\n <application>\n <!-- snip -->\n <view-handler>my.package.LoginViewHandler</view-handler>\n</application>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17614/" ]
231,198
<p>The following code compiles correctly under VC++ 8 on XPSP3, but running it causes a runtime error. </p> <p>My header looks like:</p> <pre><code>#include &lt;stdexcept&gt; #include &lt;iterator&gt; #include &lt;list&gt; template&lt;typename T&gt; class test_generator { public: typedef T result_type; //constructor test_generator() { std::generate_n( std::back_inserter( tests ), 100, rand ); value = tests.begin(); } result_type operator()( void ) { if( value == tests.end() ) { throw std::logic_error( "" ); } return *value++; } private: std::list&lt;T&gt; tests; typename std::list&lt;T&gt;::iterator value; }; </code></pre> <p>My implementation looks like:</p> <pre><code>#include &lt;functional&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;deque&gt; #include "test.h" int main() { test_generator&lt;double&gt; test; std::deque&lt;double&gt; tests; std::generate_n( std::back_inserter( tests ), 10, test ); return 0; } </code></pre> <p>This compiles fine, it generates an exception (not the logic_error exception defined in the header).</p> <p>If I change the implementation to use a function instead of a functor, it works:</p> <pre><code>int main() { std::deque&lt;int&gt; tests; std::generate_n( std::back_inserter( tests ), 10, rand ); return 0; } </code></pre> <p>What's wrong with using a functor here?</p>
[ { "answer_id": 231270, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "return *value++ operator()" }, { "answer_id": 231319, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": true, "text": "test_generator value tests test_generator std::generate_n test value tests test_generator value operator()" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
231,206
<p>What's everyone take on tieing code enum's to row ID's in a database table? I'm really looking for a cleaner alternative. What if for example your static rows in a given table are ID's 1,2,3, and then that table gets filled with user transactional data using ID's 4-100, and then you later want to add a new row ID which in your local production database is row ID 4, but when that row goes to a customers database it will have to be 101...well that kinda breaks everything.</p> <p>So how do you handle static locked rows in a table that also gets filled with transactional data?</p> <p>Thanks, MeshMan</p>
[ { "answer_id": 231240, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "[Enum].Parse(System.Type, Value)\n" }, { "answer_id": 11615617, "author": "GenericJoe", "author_id": 1391644, "author_profile": "https://Stackoverflow.com/users/1391644", "pm_score": 1, "selected": false, "text": "name PK_ID | CODE | Other Data ' Get the string name of an enum\n[Enum].GetName(GetType(SortDirection), SortDirection.Ascending)\n\n' Get the enum value from its string name\nCType([Enum].Parse(GetType(SortDirection), \"Ascending\"), SortDirection)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30943/" ]
231,211
<p>Here are two different questions but I think they are related.</p> <ol> <li><p>When using Git, how do I find which changes I have committed locally, but haven't yet pushed to a remote branch? I'm looking for something similar to the Mercurial command <code>hg outgoing</code>.</p></li> <li><p>When using Git, how do I find what changes a remote branch has prior to doing a pull? I'm looking for something similar to the Mercurial command <code>hg incoming</code>.</p></li> </ol> <p>For the second: is there a way to see what is available and then cherry-pick the changes I want to pull?</p>
[ { "answer_id": 231379, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 8, "selected": true, "text": "git fetch hg pull hg fetch master origin git fetch origin/master git log master origin/master git log master..origin/master hg incoming/outgoing" }, { "answer_id": 6122592, "author": "robinst", "author_id": 305973, "author_profile": "https://Stackoverflow.com/users/305973", "pm_score": 5, "selected": false, "text": "git log --branches --not --remotes=origin\n outgoing incoming git log --remotes=origin --not --branches\n" }, { "answer_id": 6389348, "author": "Richard Hansen", "author_id": 712605, "author_profile": "https://Stackoverflow.com/users/712605", "pm_score": 7, "selected": false, "text": "@{u} @{upstream} hg incoming git log ..@{u}\n hg outgoing git log @{u}..\n incoming outgoing git config --global alias.incoming '!git remote update -p; git log ..@{u}'\ngit config --global alias.outgoing 'log @{u}..'\n" }, { "answer_id": 8017264, "author": "stepancheg", "author_id": 15018, "author_profile": "https://Stackoverflow.com/users/15018", "pm_score": 1, "selected": false, "text": "hg outgoing" }, { "answer_id": 20471036, "author": "prayagupa", "author_id": 432903, "author_profile": "https://Stackoverflow.com/users/432903", "pm_score": 1, "selected": false, "text": "$ git fetch && git log ..origin/master --stat\nOR\n$ git fetch && git log ..origin/master --patch\n $ git fetch && git log origin/master.. --stat\nOR\n$ git fetch && git log origin/master.. --patch\n" }, { "answer_id": 21260969, "author": "chris", "author_id": 476803, "author_profile": "https://Stackoverflow.com/users/476803", "pm_score": 3, "selected": false, "text": "$ git fetch --dry-run\n hg incoming $ git push --dry-run\n hg outgoing" }, { "answer_id": 24615473, "author": "pierce.jason", "author_id": 3148228, "author_profile": "https://Stackoverflow.com/users/3148228", "pm_score": 0, "selected": false, "text": "git push --dry-run git diff 5905..4878 # Gives full code changes in diff style\n\ngit log --online 5905..4878 # Displays each commit's comment\n" }, { "answer_id": 64259748, "author": "gospes", "author_id": 2250406, "author_profile": "https://Stackoverflow.com/users/2250406", "pm_score": 0, "selected": false, "text": "git fetch-diff git-fetch-diff #!/bin/bash\n\nset -e\n\n# get hashes before fetch\nold_hashes=$(git log --all --no-color --pretty=format:\"%H\")\n\n# perform the fetch\ngit fetch\n\n# get hashes after fetch\nnew_hashes=$(git log --all --no-color --pretty=format:\"%H\")\n\n# get the difference\nadded_hashes=$(comm -1 -3 <(echo \"$old_hashes\") <(echo \"$new_hashes\"))\n\n# print added hashes\n[ ! -z \"$added_hashes\" ] && echo \"$added_hashes\" | git log --stdin --no-walk --oneline\n git log --pretty=<format> --graph git log --max-count=<count>" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
231,214
<p>I am on the way to build an ASP.NET MVC application with the latest beta release and I wonder if it is possible to change the default project Layout of</p> <p>/Views/Home/Index.aspx /Views/Home/About.aspx</p> <p>to</p> <p>/Blog/Views/Home/Index.aspx /Blog/Views/Home/About.aspx</p> <p>/Forum/Views/Home/Index.aspx /Forum/Views/Home/About.aspx</p> <p>The goal is to get some separation between "applications" within one single Web project, something like Thomas Owens asked already here: <a href="https://stackoverflow.com/questions/178398/under-an-mvc-framework-which-directory-structure-would-be-expected-by-other-dev">Under an MVC framework, which directory structure would be expected by other developers?</a> </p> <p>Of course this should include the Controllers as well, not only the Views.</p>
[ { "answer_id": 231565, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 1, "selected": false, "text": "routes.MapRoute(\"Default\",\n \"{applicationName}/{controller}/{action}/{id})\",\n null, null);\n protected override System.Type GetControllerType(string controllerName)\n {\n string applicationName;\n if (RequestContext != null && \n RequestContext.RouteData.Values.TryGetValue(\n \"applicationName\", out applicationName)) {\n // return controller type using app name to \n // look up namespace and controllerName argument\n return ...\n }\n\n // if no match, maybe it's a different controller/route\n return base.GetControllerType(controllerName);\n }\n private void Application_Start(object sender, EventArgs e)\n {\n RegisterRoutes(RouteTable.Routes);\n ControllerBuilder.Current.SetControllerFactory(\n MyApp.MyControllerFactory());\n }\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,226
<pre><code> include('adodb5/adodb.inc.php'); $myServer = "localhost"; $myUser = "root"; $myPass = "root"; $myDB = "database"; //create an instance of the ADO connection object $conn = new COM("ADODB.Connection") or die("Cannot start ADO"); //define connection string, specify database driver $connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB; $conn-&gt;open($connStr); //Open the connection to the database </code></pre> <p>This is the first time I have come across the ADODB library and it supposedly is going to help me switch over from MySQL to Microsoft SQL Server. Does anyone know why i am getting this error or if there is a simpler way that does not involve playing around with the php.ini file?</p>
[ { "answer_id": 234072, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "include('adodb5/adodb.inc.php');\n\n$myServer = \"localhost\";\n$myUser = \"root\";\n$myPass = \"root\";\n$myDB = \"database\";\n\n\n$db = ADONewConnection('odbc_mssql');\n$dsn = \"Driver={SQL Server};Server={{$myServer}};Database={{$myDB}};\";\n$db->Connect($dsn,$myUser,$myPass) or die($db->ErrorMsg()); \n\nif (!$rs = $db->Execute('select * from table')) die($db->ErrorMsg());\n\nwhile (!$rs->EOF) {\n print_r($rs->fields);\n $rs->MoveNext();\n}\n\n$rs->Close(); \n" }, { "answer_id": 24908244, "author": "snowflake", "author_id": 223073, "author_profile": "https://Stackoverflow.com/users/223073", "pm_score": 2, "selected": false, "text": "new COM(\"ADODB.Connection\") \n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,229
<p>I have source in a bunch of subdirectories like:</p> <pre><code>src/widgets/apple.cpp src/widgets/knob.cpp src/tests/blend.cpp src/ui/flash.cpp </code></pre> <p>In the root of the project I want to generate a single Makefile using a rule like:</p> <pre><code>%.o: %.cpp $(CC) -c $&lt; build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o $(LD) build/widgets/apple.o .... build/ui/flash.o -o build/test.exe </code></pre> <p>When I try this it does not find a rule for build/widgets/apple.o. Can I change something so that the %.o: %.cpp is used when it needs to make build/widgets/apple.o ?</p>
[ { "answer_id": 231418, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 7, "selected": true, "text": "%.o: %.cpp\n ...\n VPATH = src/widgets\n\nBUILDDIR = build/widgets\n\n$(BUILDDIR)/%.o: %.cpp\n ...\n $(BUILDDIR)/%.o: %.cpp\n $(CC) $< -o $@\n build/widgets/%.o: %.cpp\n ....\n\nbuild/ui/%.o: %.cpp\n ....\n\nbuild/tests/%.o: %.cpp\n ....\n define cc-command\n$(CC) $(CFLAGS) $< -o $@\nendef\n build1/foo.o build1/bar.o: %.o: %.cpp\n $(cc-command)\n\nbuild2/frotz.o build2/fie.o: %.o: %.cpp\n $(cc-command)\n" }, { "answer_id": 1427198, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "$@ #####################\n# rules to build the object files\n$(OBJDIR_1)/%.o: %.c\n @$(ECHO) \"$< -> $@\"\n @test -d $(OBJDIR_1) || mkdir -pm 775 $(OBJDIR_1)\n @test -d $(@D) || mkdir -pm 775 $(@D)\n @-$(RM) $@\n $(CC) $(CFLAGS) $(CFLAGS_1) $(ALL_FLAGS) $(ALL_DEFINES) $(ALL_INCLUDEDIRS:%=-I%) -c $< -o $@\n $(OBJDIR_1) widget/apple.cpp\ntests/blend.cpp\n objs/widget/apple.o\nobjs/tests/blend.o\n" }, { "answer_id": 2484343, "author": "Manzill0", "author_id": 298128, "author_profile": "https://Stackoverflow.com/users/298128", "pm_score": 6, "selected": false, "text": "CC := g++\nLD := g++\n\nMODULES := widgets test ui\nSRC_DIR := $(addprefix src/,$(MODULES))\nBUILD_DIR := $(addprefix build/,$(MODULES))\n\nSRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))\nOBJ := $(patsubst src/%.cpp,build/%.o,$(SRC))\nINCLUDES := $(addprefix -I,$(SRC_DIR))\n\nvpath %.cpp $(SRC_DIR)\n\ndefine make-goal\n$1/%.o: %.cpp\n $(CC) $(INCLUDES) -c $$< -o $$@\nendef\n\n.PHONY: all checkdirs clean\n\nall: checkdirs build/test.exe\n\nbuild/test.exe: $(OBJ)\n $(LD) $^ -o $@\n\n\ncheckdirs: $(BUILD_DIR)\n\n$(BUILD_DIR):\n @mkdir -p $@\n\nclean:\n @rm -rf $(BUILD_DIR)\n\n$(foreach bdir,$(BUILD_DIR),$(eval $(call make-goal,$(bdir))))\n make-goal" }, { "answer_id": 17783161, "author": "iLya", "author_id": 2594223, "author_profile": "https://Stackoverflow.com/users/2594223", "pm_score": 3, "selected": false, "text": "PRG := prog-name\n\nOPTIMIZE := -O2 -fomit-frame-pointer\n\nCFLAGS += -finline-functions-called-once\nLDFLAGS += -Wl,--gc-section,--reduce-memory-overheads,--relax\n\n\n.DEFAULT_GOAL := hex\n\nOBJDIR := obj\n\nMK_DIRS := $(OBJDIR)\n\n\nSRCDIR := .\ninclude makef.mk\n\nSRCDIR := crc\nCFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE\nASFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE\ninclude makef.mk\n\n################################################################\n\nCC := avr-gcc -mmcu=$(MCU_TARGET) -I.\nOBJCOPY := avr-objcopy\nOBJDUMP := avr-objdump\n\nC_FLAGS := $(CFLAGS) $(REGS) $(OPTIMIZE)\nCPP_FLAGS := $(CPPFLAGS) $(REGS) $(OPTIMIZE)\nAS_FLAGS := $(ASFLAGS)\nLD_FLAGS := $(LDFLAGS) -Wl,-Map,$(OBJDIR)/$(PRG).map\n\n\nC_OBJS := $(C_SRC:%.c=$(OBJDIR)/%.o)\nCPP_OBJS := $(CPP_SRC:%.cpp=$(OBJDIR)/%.o)\nAS_OBJS := $(AS_SRC:%.S=$(OBJDIR)/%.o)\n\nC_DEPS := $(C_OBJS:%=%.d)\nCPP_DEPS := $(CPP_OBJS:%=%.d)\nAS_DEPS := $(AS_OBJS:%=%.d)\n\nOBJS := $(C_OBJS) $(CPP_OBJS) $(AS_OBJS)\nDEPS := $(C_DEPS) $(CPP_DEPS) $(AS_DEPS)\n\n\nhex: $(PRG).hex\nlst: $(PRG).lst\n\n\n$(OBJDIR)/$(PRG).elf : $(OBJS)\n $(CC) $(C_FLAGS) $(LD_FLAGS) $^ -o $@\n\n%.lst: $(OBJDIR)/%.elf\n -@rm $@ 2> /dev/nul\n $(OBJDUMP) -h -s -S $< > $@\n\n%.hex: $(OBJDIR)/%.elf\n -@rm $@ 2> /dev/nul\n $(OBJCOPY) -j .text -j .data -O ihex $< $@\n\n\n$(C_OBJS) : $(OBJDIR)/%.o : %.c Makefile\n $(CC) -MMD -MF $@.p.d -c $(C_FLAGS) $(C_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < $@.p.d > $@.d\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < $@.p.d >> $@.d\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < $@.p.d >> $@.d\n -@rm -f $@.p.d\n\n$(CPP_OBJS) : $(OBJDIR)/%.o : %.cpp Makefile\n $(CC) -MMD -MF $@.p.d -c $(CPP_FLAGS) $(CPP_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < $@.p.d > $@.d\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < $@.p.d >> $@.d\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < $@.p.d >> $@.d\n -@rm -f $@.p.d\n\n$(AS_OBJS) : $(OBJDIR)/%.o : %.S Makefile\n $(CC) -MMD -MF $@.p.d -c $(AS_FLAGS) $(AS_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < $@.p.d > $@.d\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < $@.p.d >> $@.d\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < $@.p.d >> $@.d\n -@rm -f $@.p.d\n\n\nclean:\n -@rm -rf $(OBJDIR)/$(PRG).elf\n -@rm -rf $(PRG).lst $(OBJDIR)/$(PRG).map\n -@rm -rf $(PRG).hex $(PRG).bin $(PRG).srec\n -@rm -rf $(PRG)_eeprom.hex $(PRG)_eeprom.bin $(PRG)_eeprom.srec\n -@rm -rf $(MK_DIRS:%=%/*.o) $(MK_DIRS:%=%/*.o.d)\n -@rm -f tags cscope.out\n\n# -rm -rf $(OBJDIR)/*\n# -rm -rf $(OBJDIR)\n# -rm $(PRG)\n\n\ntag: tags\ntags: $(SRC_FILES)\n if [ -e tags ] ; then ctags -u $? ; else ctags $^ ; fi\n cscope -U -b $^\n\n\n# include dep. files\nifneq \"$(MAKECMDGOALS)\" \"clean\"\n-include $(DEPS)\nendif\n\n\n# Create directory\n$(shell mkdir $(MK_DIRS) 2>/dev/null)\n SAVE_C_SRC := $(C_SRC)\nSAVE_CPP_SRC := $(CPP_SRC)\nSAVE_AS_SRC := $(AS_SRC)\n\nC_SRC :=\nCPP_SRC :=\nAS_SRC :=\n\n\ninclude $(SRCDIR)/files.mk\nMK_DIRS += $(OBJDIR)/$(SRCDIR)\n\n\nclear_name = $(subst /,_,$(1))\n\n\ndefine rename_var\n$(2)_$(call clear_name,$(SRCDIR))_$(call clear_name,$(1)) := \\\n $($(subst _,,$(2))_$(call clear_name,$(SRCDIR))) $($(call clear_name,$(1)))\n$(call clear_name,$(1)) :=\nendef\n\n\ndefine proc_lang\n\nORIGIN_SRC_FILES := $($(1)_SRC)\n\nifneq ($(strip $($(1)_ONLY_FILES)),)\n$(1)_SRC := $(filter $($(1)_ONLY_FILES),$($(1)_SRC))\nelse\n\nifneq ($(strip $(ONLY_FILES)),)\n$(1)_SRC := $(filter $(ONLY_FILES),$($(1)_SRC))\nelse\n$(1)_SRC := $(filter-out $(EXCLUDE_FILES),$($(1)_SRC))\nendif\n\nendif\n\n$(1)_ONLY_FILES :=\n$(foreach name,$($(1)_SRC),$(eval $(call rename_var,$(name),$(1)_FLAGS)))\n$(foreach name,$(ORIGIN_SRC_FILES),$(eval $(call clear_name,$(name)) :=))\n\nendef\n\n\n$(foreach lang,C CPP AS, $(eval $(call proc_lang,$(lang))))\n\n\nEXCLUDE_FILES :=\nONLY_FILES :=\n\n\nSAVE_C_SRC += $(C_SRC:%=$(SRCDIR)/%)\nSAVE_CPP_SRC += $(CPP_SRC:%=$(SRCDIR)/%)\nSAVE_AS_SRC += $(AS_SRC:%=$(SRCDIR)/%)\n\nC_SRC := $(SAVE_C_SRC)\nCPP_SRC := $(SAVE_CPP_SRC)\nAS_SRC := $(SAVE_AS_SRC)\n C_SRC := main.c\nCPP_SRC :=\nAS_SRC := timer.S\n\nmain.c += -DDEBUG\n C_SRC := byte-modbus-crc.c byte-crc8.c\nAS_SRC := modbus-crc.S crc8.S modbus-crc-table.S crc8-table.S\n\nbyte-modbus-crc.c += --std=gnu99\nbyte-crc8.c += --std=gnu99\n" }, { "answer_id": 21355129, "author": "Amaury Bouchard", "author_id": 3235911, "author_profile": "https://Stackoverflow.com/users/3235911", "pm_score": 2, "selected": false, "text": "src/lib.c\nsrc/aa/a1.c\nsrc/aa/a2.c\nsrc/bb/b1.c\nsrc/cc/c1.c\n src/ # make -> compile the shared library \"libfoo.so\"\n# make clean -> remove the library file and all object files (.o)\n# make all -> clean and compile\nSONAME = libfoo.so\nSRC = lib.c \\\n aa/a1.c \\\n aa/a2.c \\\n bb/b1.c \\\n cc/c1.c\n# compilation options\nCFLAGS = -O2 -g -W -Wall -Wno-unused-parameter -Wbad-function-cast -fPIC\n# linking options\nLDFLAGS = -shared -Wl,-soname,$(SONAME)\n\n# how to compile individual object files\nOBJS = $(SRC:.c=.o)\n.c.o:\n $(CC) $(CFLAGS) -c $< -o $@\n\n.PHONY: all clean\n\n# library compilation\n$(SONAME): $(OBJS) $(SRC)\n $(CC) $(OBJS) $(LDFLAGS) -o $(SONAME)\n\n# cleaning rule\nclean:\n rm -f $(OBJS) $(SONAME) *~\n\n# additional rule\nall: clean lib\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7743/" ]
231,250
<p>How would you write a non-recursive algorithm to compute <code>n!</code>?</p>
[ { "answer_id": 231255, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "public double factorial(int n) {\n double result = 1;\n for(double i = 2; i<=n; ++i) {\n result *= i;\n }\n return result;\n}\n" }, { "answer_id": 231263, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "long fact(int n) {\n long x = 1;\n for(int i = 1; i <= n; i++) {\n x *= i;\n }\n return x;\n}\n" }, { "answer_id": 231264, "author": "MrDatabase", "author_id": 22471, "author_profile": "https://Stackoverflow.com/users/22471", "pm_score": -1, "selected": false, "text": "int fact(int n){\n int r = 1;\n for(int i = 1; i <= n; i++) r *= i;\n return r;\n}\n" }, { "answer_id": 231268, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "total = 1\nFor i = 1 To n\n total *= i\nNext\n" }, { "answer_id": 231269, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 1, "selected": false, "text": "fac = 1 ; \nfor( i = 1 ; i <= n ; i++){\n fac = fac * i ;\n}\n" }, { "answer_id": 231272, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 2, "selected": false, "text": "int total = 1\nloop while n > 1\n total = total * n\n n--\nend while\n" }, { "answer_id": 231273, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": false, "text": "ans = 1\nfor i = n down to 2\n ans = ans * i\nnext\n" }, { "answer_id": 231276, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "public int factorialNonRecurse(int n) {\n int product = 1;\n\n for (int i = 2; i <= n; i++) {\n product *= i;\n }\n\n return product;\n}\n" }, { "answer_id": 231331, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 5, "selected": false, "text": "public int factorial(int n) {\n int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, \n 362880, 3628800, 39916800, 479001600};\n return fact[n];\n}\n" }, { "answer_id": 231458, "author": "David Frenkel", "author_id": 28747, "author_profile": "https://Stackoverflow.com/users/28747", "pm_score": 0, "selected": false, "text": "#define int MAX_PRECALCFACTORIAL = 13;\n\npublic double factorial(int n) {\n ASSERT(n>0);\n int[MAX_PRECALCFACTORIAL] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, \n 362880, 3628800, 39916800, 479001600};\n if(n < MAX_PRECALCFACTORIAL)\n return (double)fact[n];\n\n //else we are at least n big\n double total = (float)fact[MAX_PRECALCFACTORIAL-1]\n for(int i = MAX_PRECALCFACTORIAL; i <= n; i++)\n {\n total *= (double)i; //cost of incrimenting a double often equal or more than casting\n }\n return total;\n\n}\n" }, { "answer_id": 231569, "author": "PhirePhly", "author_id": 20082, "author_profile": "https://Stackoverflow.com/users/20082", "pm_score": 2, "selected": false, "text": "int factorial(int i) {\n static int factorials[] = {1, 1, 2, 6, 24, 120, 720, \n 5040, 40320, 362880, 3628800, 39916800, 479001600};\n if (i<0 || i>12) {\n fprintf(stderr, \"Factorial input out of range\\n\");\n exit(EXIT_FAILURE); // You could also return an error code here\n }\n return factorials[i];\n} \n" }, { "answer_id": 232070, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": " C++ C#\n---------------------\nIterative 1.0 1.6\nLookup .28 1.1\nRecursive 2.4 2.6\n C++ C#\n---------------------\nIterative 1.0 2.9\nLookup .16 .53\nRecursive 1.9 3.9\n" }, { "answer_id": 297903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "long fact(int n)\n{\n long fact=1;\n while(n>1)\n fact*=n--;\n return fact;\n}\n\nlong fact(int n)\n{\n for(long fact=1;n>1;n--)\n fact*=n;\n return fact;\n}\n" }, { "answer_id": 480011, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "//Note: many compilers have an upper limit on the number of recursive templates allowed.\n\ntemplate <int N>\nstruct Factorial \n{\n enum { value = N * Factorial<N - 1>::value };\n};\n\ntemplate <>\nstruct Factorial<0> \n{\n enum { value = 1 };\n};\n\n// Factorial<4>::value == 24\n// Factorial<0>::value == 1\nvoid foo()\n{\n int x = Factorial<4>::value; // == 24\n int y = Factorial<0>::value; // == 1\n}\n" }, { "answer_id": 481729, "author": "dangerouslyfacetious", "author_id": 56815, "author_profile": "https://Stackoverflow.com/users/56815", "pm_score": 2, "selected": false, "text": "def fact(n): return (reduce(lambda x, y: x * y, xrange(1, n+1)))\n" }, { "answer_id": 11887670, "author": "nyanshak", "author_id": 1587737, "author_profile": "https://Stackoverflow.com/users/1587737", "pm_score": 0, "selected": false, "text": "int answer = 1;\nfor (int i = 1; i <= n; i++){\n answer *= i;\n}\n factorial x =\n tailFact x 1\n where tailFact 0 a = a\n tailFact n a = tailFact (n - 1) (n * a)\n" }, { "answer_id": 13034901, "author": "Matt", "author_id": 833083, "author_profile": "https://Stackoverflow.com/users/833083", "pm_score": -1, "selected": false, "text": "var fc = []\nfunction factorial( n ) {\n return fc[ n ] || ( ( n - 1 && n != 0 ) && \n ( fc[ n ] = n * factorial( n - 1 ) ) ) || 1;\n}\n" }, { "answer_id": 35744745, "author": "Developer Marius Žilėnas", "author_id": 1737819, "author_profile": "https://Stackoverflow.com/users/1737819", "pm_score": 0, "selected": false, "text": "/** \n * Non recursive factorial. Iterator version,\n */\npackage factiterator;\n\nimport java.math.BigInteger;\nimport java.util.Iterator;\n\npublic class FactIterator\n{ \n public static void main(String[] args)\n {\n Iterable<BigInteger> fact = new Iterable<BigInteger>()\n {\n @Override\n public Iterator<BigInteger> iterator()\n {\n return new Iterator<BigInteger>()\n {\n BigInteger i = BigInteger.ONE;\n BigInteger total = BigInteger.ONE;\n\n @Override\n public boolean hasNext()\n {\n return true;\n }\n\n @Override\n public BigInteger next()\n { \n total = total.multiply(i);\n i = i.add(BigInteger.ONE);\n return total;\n }\n\n @Override\n public void remove()\n {\n throw new UnsupportedOperationException();\n }\n };\n }\n };\n int i = 1;\n for (BigInteger f : fact)\n {\n System.out.format(\"%d! is %s%n\", i++, f);\n }\n }\n}\n" }, { "answer_id": 56945554, "author": "Wael Assaf", "author_id": 6241797, "author_profile": "https://Stackoverflow.com/users/6241797", "pm_score": 1, "selected": false, "text": "int fac(int num) {\n int f = 1;\n for (int i = num; i > 0; i--)\n f *= i;\n return f;\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,257
<p>Let's say you have a dynamic language (similar to common scripting languages) and want to write a compiler for it. Is it good idea to reserve some bits of a machine word for something like type tags? Especially for microcontrollers and similar devices, is it a good idea?</p> <p>I can think of some advantages like reduced storage for type information, somewhat easier memory management (maybe even gc) and easier debugging. But would these justify the overhead on common arithmetic operations or other operations which needs the full word? Note that a bytecode VM will be much worse in this regard since there is much more performance overhead. So don't suggest it ;)</p> <p>It is not like some would write a numerical intense code for a microcontroller-class hardware anyway but still...</p>
[ { "answer_id": 231360, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 0, "selected": false, "text": "list array" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7988/" ]
231,288
<p>I have started using Jython as it seems to be a excellent language, and has proved to be so far.</p> <p>I am using dom4j to manipulate and retrieve data from the DOM of a bunch of HTML files I have on disk. I have wrote the below script to check threw the DOM using Xpath for <strong>H1</strong> tags and grab text, if a <strong>H1</strong> tag is not present in the DOM it then searches for the <strong>title</strong> tag and grabs the text from that.</p> <p>I am very new to Jython but I am sure there is way to perform the required task a lot more graceful than the below method, If I am right in thinking this, is there someone that can show me a better way to do it?</p> <pre><code>elemHolder = dom.createXPath('//xhtml:h1') elemHolder.setNamespaceURIs(map) elem = elemHolder.selectSingleNode(dom) if elem != None: h1 = elem.getText() else: elemHolder = dom.createXPath('//xhtml:title') elemHolder.setNamespaceURIs(map) elem = elemHolder.selectSingleNode(dom) if elem != None: title = elem.getText() else: title = "Page does not contain a H1 or title tag" </code></pre> <p>If anyone could help it would be great. Cheers</p>
[ { "answer_id": 231335, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "for path in ('//xhtml:h1', '//xhtml:title'):\n elemHolder = dom.createXPath(path)\n elemHolder.namespaceURIs = map\n elem = elemHolder.selectSingleNode(dom)\n if elem is not None:\n return (elem.localName, elem.text)\n\nreturn (None, \"Page does not contain h1 or title tag\")\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30786/" ]
231,321
<p>I cant' figure out how to reference the current instance object defined by the XAML file in the XAML file.</p> <p>I have a converter that I want to send in the current instance as the parameter object.</p> <pre><code>{Binding Path=&lt;bindingObject&gt;, Converter={x:Static namespace:Converter.Instance}, ConverterParameter=this} </code></pre> <p>In this code this is converted to a string instead of a reference to the current instance object.</p> <p>Thanks</p> <p>John</p>
[ { "answer_id": 231446, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "RelativeSource Self" }, { "answer_id": 231500, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<Button Content=\"{Binding }\" />\n<Button Content=\"{Binding Path=/}\" />\n<Button Content=\"{Binding Path=/Description}\" /> \n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9331/" ]
231,323
<p>Anyone know off the top of their heads how to convert a System.Xml.XmlNode to System.Xml.Linq.XNode?</p>
[ { "answer_id": 231412, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 5, "selected": true, "text": "XmlNode myNode;\nXNode translatedNode = XDocument.Parse(myNode.OuterXml);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21909/" ]
231,327
<p>I want to use the <a href="http://simplehtmldom.sourceforge.net/manual_api.htm" rel="noreferrer">php simple HTML DOM parser</a> to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?</p> <p>I guess im wondering why I use this, and what does it do as I have never come across a callback function before!</p>
[ { "answer_id": 231339, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 6, "selected": true, "text": "<?php\n\nfunction thisFuncTakesACallback($callbackFunc)\n{\n echo \"I'm going to call $callbackFunc!<br />\";\n $callbackFunc();\n}\n\nfunction thisFuncGetsCalled()\n{\n echo \"I'm a callback function!<br />\";\n}\n\nthisFuncTakesACallback( 'thisFuncGetsCalled' );\n?>\n" }, { "answer_id": 231347, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "$html = file_get_html('http://example.com');\n$html->set_callback('make_bold');\n$html->find('#title'); // returns an array\n\nfunction make_bold($results) {\n// make the first result bold\n return '<b>'.$results[0].'</b>';\n}\n make_bold()" }, { "answer_id": 231874, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "$fn = 'foo'; // => foo()\n$fn = array($obj, 'foo'); // => $obj->foo()\n$fn = array('Foo', 'bar'); // => Foo::bar()\n is_callable call_user_func" }, { "answer_id": 45677437, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function iWillReturnCallback($callBackHere){\n return $callBackHere;\n}\n\nfunction iAmCallBack(){\n echo \"I am returned with the help of another function\";\n}\n\niWillReturnCallback(iAmCallBack());\n\n//--Output -> I am returned with the help of another function\n" }, { "answer_id": 47279271, "author": "Deepak Bawa", "author_id": 4520304, "author_profile": "https://Stackoverflow.com/users/4520304", "pm_score": 0, "selected": false, "text": "PHP 5.3 function doIt($callback) { $callback(); }\n\ndoIt(function() {\n // this will be done\n});\n PHP" }, { "answer_id": 70610212, "author": "MaXi32", "author_id": 841677, "author_profile": "https://Stackoverflow.com/users/841677", "pm_score": 0, "selected": false, "text": "secretCode() helper service <?php\n \n // $call parameter can be anything\n function callBackServiceCenter($call)\n {\n echo \"[callBackServiceCenter]: Hey, this is callBackServiceCenter function <br>We have received your command to call your requested function and we are now calling it for you! <br />\";\n // Below is the part where it will call our secretCode()'s function\n $call();\n // And we can print other things after the secretCode()'s function has been executed:\n echo \"[callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day!<br />\";\n }\n \n function secretCode()\n {\n echo \"[secretCode]: Hey, this is secretCode function. Your secret code is 12345<br />\";\n }\n \n callBackServiceCenter( 'secretCode' );\n?>\n [callBackServiceCenter]: Hey, this is callBackServiceCenter function\nWe have received your command to call your requested function and we are now calling it for you!\n[secretCode]: Hey, this is secretCode function. Your secret code is 12345\n[callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day!\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
231,340
<p>In a project I am working on, Apache is set up to only forward requests that come in as /prefix/* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix? </p> <p>I have the routes set up for forward to the correct controller action by doing this:</p> <pre><code>map.connect 'sfc/:controller/:action' </code></pre> <p>but that doesn't seem to affect the way that the url writer generates the URLs.</p> <p>Any ideas?</p>
[ { "answer_id": 231417, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 2, "selected": false, "text": "RAILS_RELATIVE_URL_ROOT" }, { "answer_id": 231752, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 1, "selected": false, "text": "map.connect ':controller/:action', :path_prefix => 'sfc'\n" }, { "answer_id": 235311, "author": "Matt Burke", "author_id": 29691, "author_profile": "https://Stackoverflow.com/users/29691", "pm_score": 2, "selected": false, "text": "map.connect \"sfc/:controller/:action\"\nmap.connect \":controller/:action/:id\"\n url_for(:controller => 'x', :action => 'y', :id => 3) \"/x/y/3\" map.connect \"sfc/:controller/:action\"\nmap.connect \"sfc/:controller/:action/:id\"\n \"/sfc/x/y/3\"" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
231,344
<p>I am using the ASP.Net plugin and control provided by <a href="http://recaptcha.net" rel="noreferrer">reCAPTCHA</a>. I can successfully get the control to work if the submit button on the web form is not in a validationgroup. There is no validationgroup attribute for the reCAPTCHA control. </p> <p>Has anybody had any success with this or any solutions to get the reCAPTCHA control to work when there is a validationgroup on the web form?</p>
[ { "answer_id": 352439, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 3, "selected": true, "text": "ValidationGroup ValidationGroup BaseValidator IValidator BaseValidator WebControl BaseValidator ValidationGroup" }, { "answer_id": 4380268, "author": "Remotec", "author_id": 169640, "author_profile": "https://Stackoverflow.com/users/169640", "pm_score": 2, "selected": false, "text": "recaptcha.Validate();\n" }, { "answer_id": 12283328, "author": "James Law", "author_id": 1138519, "author_profile": "https://Stackoverflow.com/users/1138519", "pm_score": 3, "selected": false, "text": "<recaptcha:RecaptchaControl ID=\"RecaptchaControl\" runat=\"server\" />\n\n<asp:CustomValidator ID=\"RecaptchaValidator\" runat=\"server\" OnServerValidate=\"RecaptchaValidator_ServerValidate\" ErrorMessage=\"Recaptcha input invalid.\" ValidationGroup=\"SomeValidationGroup\" />\n protected void RecaptchaValidator_ServerValidate(object sender, ServerValidateEventArgs e)\n{\n this.RecaptchaControl.Validate();\n e.IsValid = this.RecaptchaControl.IsValid;\n}\n" }, { "answer_id": 14568588, "author": "dvdmn", "author_id": 770446, "author_profile": "https://Stackoverflow.com/users/770446", "pm_score": 1, "selected": false, "text": "protected void button_onclick(object sender, EventArgs e){\n recaptcha.Validate();\n if(!Page.IsValid && recaptcha.IsValid){\n lblError.Text = \"Please check your captcha entry\";\n } else {\n //do your thing\n }\n}\n" }, { "answer_id": 15827198, "author": "Clarice Bouwer", "author_id": 849986, "author_profile": "https://Stackoverflow.com/users/849986", "pm_score": 1, "selected": false, "text": "<asp:CustomValidator ID=\"reqRecaptcha\" runat=\"server\" ClientValidationFunction=\"validateRecaptcha\" Text=\"Required\"></asp:CustomValidator>\n ID recaptcha_response_field function validateRecaptcha(sender, args) {\n args.IsValid = isFieldValid(\"input[id$='recaptcha_response_field']\");\n }\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24522/" ]
231,355
<p>Hi guys I wrote this code and i have two errors.</p> <ol> <li>Invalid rank specifier: expected ',' or ']' </li> <li>Cannot apply indexing with [] to an expression of type 'int'</li> </ol> <p>Can you help please?</p> <pre><code> static void Main(string[] args) { ArrayList numbers = new ArrayList(); foreach (int number in new int[12] {10,9,8,7,6,5,4,3,2,1}) //error No.1 { numbers.Add(number); } numbers.Insert(numbers.Count - 1, 75); numbers.Remove(7); numbers.RemoveAt(6); for(int i=0; i&lt;numbers.Count; i++) { int number = (int) number[i]; // error No.2 Console.WriteLine(number); } } </code></pre>
[ { "answer_id": 231380, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": "foreach (int number in new int[] {10,9,8,7,6,5,4,3,2,1})\n int number = (int)numbers[i];\n number numbers" }, { "answer_id": 231385, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 0, "selected": false, "text": "new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };\n for (int i = 10; i > 0; i-- )\n{\n numbers.Add(i);\n}\n IEnumerable<int> numbers = Enumerable.Range(1, 10).Reverse();\n" }, { "answer_id": 231399, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": true, "text": "using System;\nusing System.Collections;\n\nnamespace ConsoleApplication3\n{\n class Program\n {\n static void Main(string[] args)\n {\n ArrayList numbers = new ArrayList();\n foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })\n {\n numbers.Add(number);\n }\n numbers.Insert(numbers.Count - 1, 75);\n numbers.Remove(7);\n numbers.RemoveAt(6);\n for (int i = 0; i < numbers.Count; i++)\n {\n int number = (int)numbers[i];\n Console.WriteLine(number);\n }\n }\n }\n}\n" }, { "answer_id": 231405, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": " for (int x = 10; x > 0; --x)\n {\n numbers.Add(number);\n }\n foreach for" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30858/" ]
231,358
<p>I'm using NuSOAP on PHP 5.2.6 and I'm seeing that the max message size is only 1000 bytes (which makes it tough to do anything meaningful). Is this set in the endpoint's WSDL or is this something I can configure in NuSOAP?</p>
[ { "answer_id": 232885, "author": "Dan Soap", "author_id": 25253, "author_profile": "https://Stackoverflow.com/users/25253", "pm_score": 2, "selected": false, "text": "max_input_time (defaults to 60)\n" }, { "answer_id": 3926436, "author": "Daniel Alvarez Arribas", "author_id": 474829, "author_profile": "https://Stackoverflow.com/users/474829", "pm_score": 4, "selected": true, "text": "$this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));\n\n// send\n$return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);\n getHTTPBody() $soapmsg substr() $soapmsg" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
231,362
<p>For some weeks now I simply can't run gem install in windows. It sticks on this line:</p> <pre><code>C:\Windows\System32&gt;gem install rails --version 2.1.2 Bulk updating Gem source index for: http://gems.rubyforge.org/ </code></pre> <p>Any ideas what it could be?</p>
[ { "answer_id": 231670, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": true, "text": "gem install rails.gem" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
231,364
<p>I am currently building a small website where the content of the main div is being filled through an Ajax call. I basically have a php script that returns the content like this:</p> <p>(simplified php script...)</p> <pre><code> if(isset($_POST["id_tuto"])){ PrintHtml($_POST["id_tuto"]); } function PrintHtml($id) { switch($id) { case [...]: echo "THIS IS MY HTML CONTENT"; break; [...] } } </code></pre> <p>The web page then gets the text from that echo command and replaces the inner html of the content div.</p> <p>My question is this : What is the best way to echo that html content? there is a lot of content each time since it's a step by step tutorial. Each string will be about 50-80 lines of HTML code. Is there a way to put that html content in a separate html file and echo that file or...?</p> <p>Thanks a lot!!</p>
[ { "answer_id": 231430, "author": "defrex", "author_id": 6007, "author_profile": "https://Stackoverflow.com/users/6007", "pm_score": 3, "selected": true, "text": "<?php\n function PrintHtml($id) {\n switch($id) {\n case [...]:\n?>\n <h1>Tut page 1</h1>\n <p>this is html content.</p>\n<?php\n break;\n [...]\n }\n }\n?>\n <?php\n function PrintHtml($id) {\n switch($id) {\n case [...]:\n include 'section1.php';\n break;\n [...]\n }\n }\n?>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ]
231,371
<p>Which are the most advanced frameworks and tools there are available for python for practicing Behavior Driven Development? Especially finding similar tools as rspec and mocha for ruby would be great.</p>
[ { "answer_id": 2999652, "author": "Douglas Camata", "author_id": 361638, "author_profile": "https://Stackoverflow.com/users/361638", "pm_score": 5, "selected": false, "text": "pip install specloud\n pip install ludibrio\n pip install pycukes\n" }, { "answer_id": 11279439, "author": "mdwhatcott", "author_id": 605022, "author_profile": "https://Stackoverflow.com/users/605022", "pm_score": 3, "selected": false, "text": "from pyspecs import given, when, then, and_, the, this\n\nwith given.two_operands:\n a = 2\n b = 3\n\n with when.supplied_to_the_add_function:\n total = a + b\n\n with then.the_total_should_be_mathmatically_correct:\n the(total).should.equal(5)\n\n with and_.the_total_should_be_greater_than_either_operand:\n the(total).should.be_greater_than(a)\n the(total).should.be_greater_than(b)\n\n with when.supplied_to_the_subtract_function:\n difference = b - a\n\n with then.the_difference_should_be_mathmatically_correct:\n the(difference).should.equal(1)\n # run_pyspecs.py\n\n | • given two operands \n | • when supplied to the add function \n | • then the total should be mathmatically correct \n | • and the total should be greater than either operand \n | • when supplied to the subtract function \n | • then the difference should be mathmatically correct \n\n(ok) 6 passed (6 steps, 1 scenarios in 0.0002 seconds)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30958/" ]
231,377
<p>I would like to use JavaScript to manipulate hidden input fields in a JSF/Facelets page. When the page loads, I need to set a hidden field to the color depth of the client.</p> <p>From my Facelet:</p> <pre><code>&lt;body onload="setColorDepth(document.getElementById(?????);"&gt; &lt;h:form&gt; &lt;h:inputHidden value="#{login.colorDepth}" id="colorDepth" /&gt; &lt;/h:form&gt; </code></pre> <p>When JSF processes the page, it is of course changing the IDs of the elements. What's the best way to reference these elements from my JavaScript code?</p>
[ { "answer_id": 231393, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "<body onload=\"setColorDepth(document.getElementById('myForm:colorDepth');\">\n\n<h:form id=\"myForm\">\n <h:inputHidden value=\"#{login.colorDepth}\" id=\"colorDepth\" />\n</h:form>\n <body onload=\"setColorDepth(document.getElementById(document.forms[0].id + ':colorDepth');\">\n" }, { "answer_id": 266112, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function findElement(elementId) {\n if(document.getElementById(elementId)) return elementId;\n for(var i = 0; i < document.forms.length; i++) {\n if(document.getElementById(document.forms[i].id + ':' + elementId)) {\n return document.forms[i].id + ':' + elementId;\n }\n }\n return null;\n }\n\n\n <body onload=\"setColorDepth(findElement('colorDepth'));\">\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27515/" ]
231,381
<p>Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower?</p> <p>I am trying to submit this to <a href="http://www.spoj.pl/" rel="nofollow noreferrer">SPOJ</a> and it tells me that my time limit exceeded... </p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; using namespace std; int main() { int testCases, first, second, counter = 0; bool isPrime = true; stringstream out; cin &gt;&gt; testCases; for (int i = 0; i &lt; testCases; i++) { // get the next two numbers cin &gt;&gt; first &gt;&gt; second; if (first%2 == 0) first++; // find the prime numbers between the two given numbers for (int j = first; j &lt;= second; j+=2) { // go through and check if j is prime for (int k = 2; k &lt; j; k++) { if (j%k == 0) { isPrime = false; break; } } if (isPrime) { out &lt;&lt; j &lt;&lt; "\n"; } isPrime = true; } out &lt;&lt; "\n"; } cout &lt;&lt; out.str(); return 0; } </code></pre> <p>EDIT: The program is supposed to generate prime numbers between the numbers specified in the input. (See here for more details: <a href="http://www.spoj.pl/problems/PRIME1/" rel="nofollow noreferrer">Prime Generator Problem</a> )</p> <p>-Tomek</p>
[ { "answer_id": 231400, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "<= (sqrt(num))" }, { "answer_id": 231421, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 0, "selected": false, "text": "for (int k = 2; k < j; k++) {\n if (j%k == 0) {\n isPrime = false;\n break;\n }\n}\n for(int k = 3; k <= j/2; k+=2 )\n{\n if( j % k == 0 )\n break;\n}\n" }, { "answer_id": 235517, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\ntemplate<typename T = int, typename M = map<T, T> >\nclass prime_iterator {\n public:\n prime_iterator() : current(2), skips() { skips[4] = 2; }\n T operator*() { return current; }\n prime_iterator &operator++() {\n typename M::iterator i;\n while ((i = skips.find(++current)) != skips.end()) {\n T skip = i->second, next = current + skip;\n skips.erase(i);\n for (typename M::iterator j = skips.find(next);\n j != skips.end(); j = skips.find(next += skip)) {}\n skips[next] = skip;\n }\n skips[current * current] = current;\n return *this;\n }\n private:\n T current;\n M skips;\n};\n\nint main() {\n prime_iterator<int> primes;\n for (; *primes < 1000; ++primes)\n cout << *primes << endl;\n return 0;\n}\n" }, { "answer_id": 1081800, "author": "dpetek", "author_id": 80204, "author_profile": "https://Stackoverflow.com/users/80204", "pm_score": 2, "selected": false, "text": "for(int k=1;k<sqrt(n);++k)\n for (int k=1;k*k < n;++k)\n int sq = sqrt ( n );\nfor (int k=1;k<sq;++k)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
231,390
<p>I've been trying to install <a href="http://thoughtbot.com/projects/shoulda" rel="nofollow noreferrer">Shoulda</a></p> <pre><code>script/plugin install git://github.com/thoughtbot/shoulda.git </code></pre> <p>but all I get is:</p> <pre><code>removing: C:/Documents and Settings/Danny/My Documents/Projects/Ruby On Rails/_ProjectName_/vendor/plugins/shoulda/.git &gt; </code></pre> <p>And the <code>vender/plugins</code> directory is empty. I have Rails 2.1.1 installed as a gem and have verified that 2.1.1 is loaded (using a puts inserted into config/boot.rb). Any ideas about what's going on?</p> <p>(this is on a windows box)</p>
[ { "answer_id": 3067200, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 0, "selected": false, "text": "--- reporting.rb.orig 2010-06-11 01:00:24.739991600 -0400\n+++ reporting.rb 2010-06-18 00:16:39.517649400 -0400\n@@ -35,7 +35,7 @@\n # puts 'But this will'\n def silence_stream(stream)\n old_stream = stream.dup\n- stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')\n+ stream.reopen(RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'NUL:' : '/dev/null')\n stream.sync = true\n yield\n ensure\n@@ -56,4 +56,4 @@\n raise unless exception_classes.any? { |cls| e.kind_of?(cls) }\n end\n end\n-end\n\\ No newline at end of file\n+end\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216/" ]
231,407
<p>I'm looking for a GWT common purpose paging widget. So far I have found <a href="http://gwt-widget.sourceforge.net/" rel="nofollow noreferrer">GWT widget library</a> and the <a href="http://code.google.com/p/google-web-toolkit-incubator/w/list" rel="nofollow noreferrer">Google Incubator widgets</a>. Is there any other free (possibly open source) widget library implementing a paging behavior.</p>
[ { "answer_id": 4300686, "author": "Robin", "author_id": 416740, "author_profile": "https://Stackoverflow.com/users/416740", "pm_score": 0, "selected": false, "text": "CellTable AsyncDataProvider" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6482/" ]
231,438
<p>Does anybody have an implementation of <a href="http://en.wikipedia.org/wiki/Cuckoo_hashing" rel="noreferrer">Cuckoo hashing</a> in C? If there was an Open Source, non GPL version it would be perfect!</p> <p>Since Adam mentioned it in his comment, anyone knows why it is not much used? Is it just a matter of implementation or the good theoretical properties do not materialize in practice?</p>
[ { "answer_id": 232624, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 1, "selected": false, "text": "void * struct node {\n void *key;\n void *value;\n struct node *left;\n struct node *right;\n}\n struct slot {\n void *key;\n void *value;\n}\n" }, { "answer_id": 239964, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 1, "selected": false, "text": "+--+--+\n| | | 2 slots\n+--+--+\n\n+--+--+--+\n| | | | 3 slots\n+--+--+--+ \n\n+--+--+--+--+\n| | | | | 4 slots\n+--+--+--+--+\n\n+--+--+--+--+--+--+\n| | | | | | | 6 slots\n+--+--+--+--+--+--+\n\n+--+--+--+--+--+--+--+--+\n| | | | | | | | | 8 slots\n+--+--+--+--+--+--+--+--+\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16827/" ]
231,439
<p>Is there any easy way to create an acronym from a string?</p> <pre><code>First_name Middle_name Last_name =&gt; FML first_name middle_name last_name =&gt; FML First_name-Middle_name Last_name =&gt; F-ML first_name-middle_name last_name =&gt; F-ML </code></pre>
[ { "answer_id": 231473, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "Tokenize the string on whitespace.\nFor each token1,\n Tokenize on dash.\n For each token2\n Take token2[0] and capitalize\n if not first token2, prepend with dash\n Concatenate to result2\n Concatenate to result\n" }, { "answer_id": 231566, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 2, "selected": true, "text": "\"First_name-Middle_nameLast_name\".gsub('-', ' - ').gsub(/\\B[A-Z]+/, ' \\&').split(' ').map { |s| s[0..0] }.join.upcase => \"F-ML\" gsub" }, { "answer_id": 231572, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "var testStrings = [\n'First_name Middle_name Last_name',\n'first_name middle_name last_name',\n'First_name-Middle_name Last_name',\n'first_name-middle_name last_name'\n];\nvar re = /\\b(\\w)\\w*\\b(-?)\\s*/g;\nvar mr;\nfor (var i = 0, l = testStrings.length; i < l; i++)\n{\n var name = testStrings[i];\n var abbr = name.replace(re, function (match, ini, dash)\n {\n return ini.toUpperCase() + dash;\n });\n alert(abbr);\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
231,478
<p>I have a site, foo.com, that makes ajax requests to bar.foo.com. Will this work.</p> <p>Also, if foo is a secure connection, https, does bar.foo.com need to be https too? Can these two sites use different certificates?</p>
[ { "answer_id": 231706, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": false, "text": "document.domain window.name https:// src https://foo.com http://bar.foo.com https://foo.com/someurl http://bar.foo.com/someurl https https src" }, { "answer_id": 14816153, "author": "Yogi", "author_id": 1995680, "author_profile": "https://Stackoverflow.com/users/1995680", "pm_score": 0, "selected": false, "text": "someFunction(\"{...}\");\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,491
<p>Is there an elegant way to create and initialize a <code>const std::vector&lt;const T&gt;</code> like <code>const T a[] = { ... }</code> to a fixed (and small) number of values?<br> I need to call a function frequently which expects a <code>vector&lt;T&gt;</code>, but these values will never change in my case.</p> <p>In principle I thought of something like</p> <pre><code>namespace { const std::vector&lt;const T&gt; v(??); } </code></pre> <p>since v won't be used outside of this compilation unit.</p>
[ { "answer_id": 231495, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 7, "selected": true, "text": "vector<int> luggage_combo = { 1, 2, 3, 4, 5 };\n #include <boost/assign/std/vector.hpp>\nusing namespace boost::assign; // bring 'operator+=()' into scope\n\nvector<int> v;\nv += 1,2,3,4,5;\n" }, { "answer_id": 231524, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": false, "text": "vector<InputIterator>(InputIterator, InputIterator) const T ra[3] = {t1, t2, t3};\nconst vector<const T> v(ra, ra+3);\n const_cast const_cast const_cast vector<T> const vector<const T> vector<const T> vector<T> T** const T *const *" }, { "answer_id": 231531, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 4, "selected": false, "text": "const int MyInts[] = {\n1, 2, 3, 4, 5};\n\nconst size_t NumMyInts = sizeof(MyInts)/sizeof(MyInts[0]);\n const int* myInt = std::find( &MyInts[0], &MyInts[NumMyInts], 3);\n" }, { "answer_id": 231546, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 0, "selected": false, "text": "push_back() std::vector< X* > v;\nv.reserve(num_elems);\nX* p = v.begin();\nfor (int count = 0; count < num_elems; count++)\n p[count] = some_source[count];\n push_back() v.begin()" }, { "answer_id": 231584, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 3, "selected": false, "text": "namespace {\n const T s_actual_array[] = { ... };\n const std::vector<const T> s_blah(s_actual_array,\n s_actual_array + (sizeof(s_actual_array) / sizeof(s_actual_array[0])));\n}\n" }, { "answer_id": 231619, "author": "Peter", "author_id": 22517, "author_profile": "https://Stackoverflow.com/users/22517", "pm_score": 0, "selected": false, "text": "vector<T> vec(num_items, item);\n vector<T> vec(num_items);\nvec[0] = 15;\nvec[1] = 5;\n...\n" }, { "answer_id": 254143, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 4, "selected": false, "text": "list_of() #include <iostream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\ntemplate <typename T>\nstruct vlist_of : public vector<T> {\n vlist_of(const T& t) {\n (*this)(t);\n }\n vlist_of& operator()(const T& t) {\n this->push_back(t);\n return *this;\n }\n};\n\nint main() {\n const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);\n copy(v.begin(), v.end(), ostream_iterator<int>(cout, \"\\n\"));\n}\n #include <iostream>\n #include <vector>\n #include <utility>\n #include <ostream>\n using namespace std;\n\n template <typename T>\n struct vlist_of : public vector<T> {\n vlist_of(T&& t) {\n (*this)(move(t));\n }\n vlist_of& operator()(T&& t) {\n this->push_back(move(t));\n return *this;\n }\n };\n\n int main() {\n const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);\n for (const auto& i: v) {\n cout << i << endl;\n }\n }\n operator=(vlist_of&&) vlist_of #include <iostream>\n#include <vector>\n#include <utility>\nusing namespace std;\n\ntemplate <typename T>\nclass vlist_of {\n public:\n vlist_of(T&& r) {\n (*this)(move(r));\n }\n vlist_of& operator()(T&& r) {\n v.push_back(move(r));\n return *this;\n }\n vector<T>&& operator()() {\n return move(v);\n }\n private:\n vector<T> v;\n \n};\n\nint main() {\n const auto v = vlist_of<int>(1)(2)(3)(4)(5)();\n for (const auto& i : v) {\n cout << i << endl;\n }\n \n}\n" }, { "answer_id": 5939934, "author": "tjohns20", "author_id": 223380, "author_profile": "https://Stackoverflow.com/users/223380", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass vector_init\n{\npublic:\n vector_init(const T& val)\n {\n vec.push_back(val);\n }\n inline vector_init& operator()(T val)\n {\n vec.push_back(val);\n return *this;\n }\n inline std::vector<T> end()\n {\n return vec;\n }\nprivate:\n std::vector<T> vec;\n};\n std::vector<int> testVec = vector_init<int>(1)(2)(3)(4)(5).end();\n" }, { "answer_id": 10446388, "author": "opal", "author_id": 267118, "author_profile": "https://Stackoverflow.com/users/267118", "pm_score": 3, "selected": false, "text": "int ar[]={1,2,3,4,5,6};\nconst int TotalItems = sizeof(ar)/sizeof(ar[0]);\nstd::vector<int> v(ar, ar+TotalItems);\n" }, { "answer_id": 21124823, "author": "Kevin", "author_id": 3195914, "author_profile": "https://Stackoverflow.com/users/3195914", "pm_score": 2, "selected": false, "text": "vector<int> initVector(void)\n{\n vector<int> initializer;\n initializer.push_back(10);\n initializer.push_back(13);\n initializer.push_back(3);\n return intializer;\n}\n\nint main()\n{\n const vector<int> a = initVector();\n return 0;\n}\n vector<int> & initVector(void)\n{\n static vector<int> initializer;\n if(initializer.empty())\n {\n initializer.push_back(10);\n initializer.push_back(13);\n initializer.push_back(3);\n }\n return intializer;\n}\n\nint main()\n{\n const vector<int> & a = initVector();\n return 0;\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26613/" ]
231,512
<p>I am using RedCloth with Rails 2.1.1. The Textile <code>&lt;del&gt;</code> tag markup format (i.e. -delete-) was not translating at all. Tried a few choice options.</p> <pre><code>&gt; x=RedCloth.new('foobar -blah-') =&gt; "foobar -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar &lt;del&gt;blah&lt;/del&gt;&lt;/p&gt;" # WORKED! &gt; x=RedCloth.new('foobar * -blah-') =&gt; "foobar * -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar * &lt;del&gt;blah&lt;/del&gt;&lt;/p&gt;" # WORKED! &gt; x=RedCloth.new("foobar\n* -blah-") =&gt; "foobar\n* -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar&lt;/p&gt;\n&lt;ul&gt;\n\t&lt;li&gt;-blah-&lt;/li&gt;\n&lt;/ul&gt;" # DID NOT WORK! </code></pre> <p>It appears to me that newlines are the culprit in throwing RedCloth up-in-arms. Any solutions to getting RedCloth to properly recognize '-delete-'? I have tried RedCloth 4.0.1, 4.0.3, and 4.0.4.</p>
[ { "answer_id": 231660, "author": "Michael Sepcot", "author_id": 6033, "author_profile": "https://Stackoverflow.com/users/6033", "pm_score": 2, "selected": false, "text": ">> RedCloth.new(\"foobar\\n* [-blah-]\").to_html\n=> \"<p>foobar</p>\\n<ul>\\n\\t<li><del>blah</del></li>\\n</ul>\"\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14895/" ]
231,525
<p>We're all familiar with the horror that is C# event declaration. To ensure thread-safety, <a href="http://blogs.msdn.com/brada/archive/2005/01/14/353132.aspx" rel="noreferrer">the standard is to write something like this</a>:</p> <pre><code>public event EventHandler SomethingHappened; protected virtual void OnSomethingHappened(EventArgs e) { var handler = SomethingHappened; if (handler != null) handler(this, e); } </code></pre> <p>Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it:</p> <pre><code>static public class EventExtensions { static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e) { var handler = @event; if (handler != null) handler(sender, e); } static public void RaiseEvent&lt;T&gt;(this EventHandler&lt;T&gt; @event, object sender, T e) where T : EventArgs { var handler = @event; if (handler != null) handler(sender, e); } } </code></pre> <p>With these extension methods in place, all you need to declare and raise an event is something like this:</p> <pre><code>public event EventHandler SomethingHappened; void SomeMethod() { this.SomethingHappened.RaiseEvent(this, EventArgs.Empty); } </code></pre> <p>My question: Is this a good idea? Are we missing anything by not having the standard On method? (One thing I notice is that it doesn't work with events that have explicit add/remove code.)</p>
[ { "answer_id": 231536, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "public event EventHandler SomethingHappened = delegate {};\n static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)\n{\n if (@event != null)\n @event(sender, e);\n}\n\nstatic public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)\n where T : EventArgs\n{\n if (@event != null)\n @event(sender, e);\n}\n" }, { "answer_id": 231548, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "public event EventHandler SomethingHappened = delegate{};\n" }, { "answer_id": 32015254, "author": "Bob Sammers", "author_id": 305237, "author_profile": "https://Stackoverflow.com/users/305237", "pm_score": 4, "selected": false, "text": "SomethingHappened?.Invoke(this, e);\n Invoke() SomethingHappened" }, { "answer_id": 57095184, "author": "Bill Tarbell", "author_id": 1721136, "author_profile": "https://Stackoverflow.com/users/1721136", "pm_score": 0, "selected": false, "text": " public static class EventHandlerExtensions\n {\n private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n\n public static void Taskify(this EventHandler theEvent, object sender, EventArgs args)\n {\n Invoke(theEvent, sender, args, true);\n }\n\n public static void Taskify<T>(this EventHandler<T> theEvent, object sender, T args)\n {\n Invoke(theEvent, sender, args, true);\n }\n\n public static void InvokeSafely(this EventHandler theEvent, object sender, EventArgs args)\n {\n Invoke(theEvent, sender, args, false);\n }\n\n public static void InvokeSafely<T>(this EventHandler<T> theEvent, object sender, T args)\n {\n Invoke(theEvent, sender, args, false);\n }\n\n private static void Invoke(this EventHandler theEvent, object sender, EventArgs args, bool taskify)\n {\n if (theEvent == null)\n return;\n\n foreach (EventHandler handler in theEvent.GetInvocationList())\n {\n var action = new Action(() =>\n {\n try\n {\n handler(sender, args);\n }\n catch (Exception ex)\n {\n _log.Error(ex);\n }\n });\n\n if (taskify)\n Task.Run(action);\n else\n action();\n }\n }\n\n private static void Invoke<T>(this EventHandler<T> theEvent, object sender, T args, bool taskify)\n {\n if (theEvent == null)\n return;\n\n foreach (EventHandler<T> handler in theEvent.GetInvocationList())\n {\n var action = new Action(() =>\n {\n try\n {\n handler(sender, args);\n }\n catch (Exception ex)\n {\n _log.Error(ex);\n }\n });\n\n if (taskify)\n Task.Run(action);\n else\n action();\n }\n }\n }\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
231,538
<p>So I have a snazzy custom route for login</p> <pre><code># routes.rb map.login '/login', :controller =&gt; 'sessions', :action =&gt; 'new' </code></pre> <p>Visit www.asite.com/login and you're there. As is custom with failed login, however, we'll do the following in our action. Note what happens on failed login.</p> <pre><code> # sessions_controller.rb def create self.current_user = User.authenticate(params[:email], params[:password]) if logged_in? # some work and redirect the user else flash.now[:warning] = "The email and/or password you entered is invalid." render :action =&gt; 'new' end end </code></pre> <p>This is very typical. Simply render the new action and prompt for login again. Unfortunately you also get with it an ugly URL: www.asite.com/session. Ick! Is it possible to get rendering to respect the original URL?</p>
[ { "answer_id": 231625, "author": "Michael Sepcot", "author_id": 6033, "author_profile": "https://Stackoverflow.com/users/6033", "pm_score": 0, "selected": false, "text": "render :action => 'new' redirect_to login_path" }, { "answer_id": 232888, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 3, "selected": false, "text": "/login /sessions else\n flash[:warning] = \"The email and/or password you entered is invalid.\"\n redirect_to login_path\n end\n map.login '/login',\n :controller => 'sessions', :action => 'new', \n :conditions => {:method => :get}\n\nmap.login_submit '/login',\n :controller => 'sessions', :action => 'create', \n :conditions => {:method => :post}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14895/" ]
231,550
<p>I'd like to use the <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler" rel="nofollow noreferrer">Rhino JavaScript</a> compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?</p> <p>Ideally it would have some way to resolve dependencies among JavaScript or Java classes.</p>
[ { "answer_id": 231750, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 4, "selected": true, "text": "<java fork=\"yes\" \n classpathref=\"build.path\" \n classname=\"org.mozilla.javascript.tools.jsc.Main\" \n failonerror=\"true\">\n <arg value=\"-debug\"/>\n ...\n <arg value=\"file.js\"/> \n</java>\n" }, { "answer_id": 1140411, "author": "Joseph Montanez", "author_id": 134617, "author_profile": "https://Stackoverflow.com/users/134617", "pm_score": 3, "selected": false, "text": "<project>\n<target name=\"compile\">\n <mkdir dir=\"build/classes\"/>\n <java fork=\"yes\" \n classpath=\"js.jar\" \n classname=\"org.mozilla.javascript.tools.jsc.Main\" \n failonerror=\"true\">\n <arg value=\"-nosource\"/>\n <arg value=\"-opt\"/>\n <arg value=\"9\"/>\n <arg value=\"-version\"/>\n <arg value=\"170\"/>\n <arg value=\"src/SwingApplication.js\"/>\n </java>\n <move todir=\"build/classes\">\n <fileset dir=\"src\">\n <include name=\"**/*.class\"/>\n </fileset>\n </move>\n</target>\n<target name=\"jar\">\n <mkdir dir=\"build/jar\"/>\n <jar destfile=\"build/jar/SwingApplication.jar\" basedir=\"build/classes\">\n <zipfileset src=\"js.jar\" includes=\"**/*.class\"/>\n <manifest>\n <attribute name=\"Main-Class\" value=\"SwingApplication\"/>\n </manifest>\n </jar>\n</target>\n<target name=\"run\">\n <exec executable=\"java\">\n <arg valUe=\"-jar\"/>\n <arg value=\"build/jar/SwingApplication.jar\"/>\n </exec>\n</target>\n</project>\n" }, { "answer_id": 3567406, "author": "jbeard4", "author_id": 366856, "author_profile": "https://Stackoverflow.com/users/366856", "pm_score": 3, "selected": false, "text": "<target name=\"compile-single-js\">\n <mkdir dir=\"${build-js}\"/>\n\n <java classname=\"org.mozilla.javascript.tools.shell.Main\">\n <classpath>\n <path refid=\"rhino-classpath\"/>\n <path refid=\"closure-classpath\"/>\n </classpath>\n <arg value=\"${js-build-script}\"/>\n <arg value=\"${js-build-dir}\"/>\n <arg value=\"name=${build-js-main-rhino-frontend-module}\"/> \n <arg value=\"out=${build-js-main}\"/>\n <arg value=\"baseUrl=.\"/>\n <arg value=\"includeRequire=true\"/>\n <arg value=\"inlineText=true\"/> \n <arg value=\"optimize=none\"/>\n </java>\n</target>\n\n<target name=\"compile-single-class\" depends=\"compile-single-js\">\n <mkdir dir=\"${build-class}\"/>\n\n <!-- TODO: set -opt -->\n <java classname=\"org.mozilla.javascript.tools.jsc.Main\">\n <classpath>\n <path refid=\"rhino-classpath\"/>\n </classpath>\n <arg value=\"-o\"/>\n <arg value=\"${build-class-main-name}.class\"/>\n <arg value=\"${build-js-main}\"/>\n </java>\n <move file=\"${build-js}/${build-class-main-name}.class\" todir=\"${build-class}\"/>\n</target>\n\n<target name=\"jar-single-class\" depends=\"compile-single-class\">\n <mkdir dir=\"${build-jar}\"/>\n\n <jar destfile=\"${build-jar-main}\"\n basedir=\"${build-class}\"\n includes=\"${build-class-main-name}.class\">\n <manifest>\n <attribute name=\"Main-Class\" value=\"${build-class-main-name}\" />\n </manifest>\n </jar>\n</target>\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28604/" ]
231,553
<p>As an amateur software developer (I'm still in academia) I've written a few schemas for XML documents. I routinely run into design flubs that cause ugly-looking XML documents because I'm not entirely certain what the semantics of XML exactly are.</p> <p>My assumptions:</p> <pre><code>&lt;property&gt; value &lt;/property&gt; </code></pre> <p>property = value</p> <pre><code>&lt;property attribute=&quot;attval&quot;&gt; value &lt;/property&gt; </code></pre> <p>A property with a special descriptor, the attribute.</p> <pre><code>&lt;parent&gt; &lt;child&gt; value &lt;/child&gt; &lt;/parent&gt; </code></pre> <p>The parent has a characteristic &quot;child&quot; which has the value &quot;value.&quot;</p> <pre><code>&lt;tag /&gt; </code></pre> <p>&quot;Tag&quot; is a flag or it directly translates to text. I'm not sure on this one.</p> <pre><code>&lt;parent&gt; &lt;child /&gt; &lt;/parent&gt; </code></pre> <p>&quot;child&quot; describes &quot;parent.&quot; &quot;child&quot; is a flag or boolean. I'm not sure on this one, either.</p> <p>Ambiguity arises if you want to do something like representing cartesian coordinates:</p> <pre><code>&lt;coordinate x=&quot;0&quot; y=&quot;1&quot; /&gt; &lt;coordinate&gt; 0,1 &lt;/coordinate&gt; &lt;coordinate&gt; &lt;x&gt; 0 &lt;/x&gt; &lt;y&gt; 1 &lt;/y&gt; &lt;/coordinate&gt; </code></pre> <p>Which one of these options is most correct? I would lean towards the third based upon my current conception of XML schema design, but I really don't know.</p> <p>What are some resources that succinctly describe how to effectively design xml schemas?</p>
[ { "answer_id": 231586, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "<coordinate x=\"\" y=\"\"/> http://company.com/2008/12/something/somethingelse/\nurn:company-com:2008-12:something:somethingelse\n\nhttp://company.com/v1/something/somethingelse/\nurn:company-com:v1:something:somethingelse\n" }, { "answer_id": 231595, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<coordinate>\n <x>0</x>\n <y>1</y>\n</coordinate>\n" }, { "answer_id": 231629, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 1, "selected": false, "text": "<coordinate type=\"cartesian\">\n <ordinate name=\"x\">0</ordinate>\n <ordinate name=\"y\">1</ordinate>\n</coordinate>\n <coordinate>\n <x>0</x>\n <y>1</y>\n</coordinate>\n" }, { "answer_id": 231684, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 5, "selected": false, "text": "<coordinate x=\"0\" y=\"1\" /> <coordinate> <x>0</x> <y>1</y> </coordinate> <coordinate> 0,1 </coordinate>" }, { "answer_id": 232314, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 4, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<xs:schema targetNamespace=\"TargetNamespace\" xmlns:TN=\"TargetNamespace\" \n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \n elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\"/> \n<xs:element name=\"BookInformation\" type=\"BookInformationType\"/> \n <xs:complexType name=\"BookInformationType\"/> \n <xs:sequence> \n <xs:element ref=\"Title\"/> \n <xs:element ref=\"ISBN\"/> \n <xs:element ref=\"Publisher\"/> \n <xs:element ref=\"PeopleInvolved\" maxOccurs=\"unbounded\"/> \n </xs:sequence> \n </xs:complexType> \n <xs:complexType name=\"PeopleInvolvedType\"> \n <xs:sequence> \n <xs:element name=\"Author\"/> \n </xs:sequence> \n </xs:complexType> \n <xs:element name=\"Title\"/> \n <xs:element name=\"ISBN\"/> \n <xs:element name=\"Publisher\"/> \n <xs:element name=\"PeopleInvolved\" type=\"PeopleInvolvedType\"/> \n</xs:schema>\n CREATE XML SCHEMA COLLECTION\n SELECT xml_schema_namespace function\n" }, { "answer_id": 292815, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 1, "selected": false, "text": "<coordinate> <x> 0 </x> <y> 1 </y> </coordinate> Coordinate x y" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29119/" ]
231,592
<p>I have some char() fields in a DBF table that were left encrypted by a past developer in the project. </p> <p>However, I know the plaintext result of the decryption of several records. How can I determine the function/algorithm/scheme to decrypt the original data? These are some sample fields:</p> <p>For cryptext:</p> <pre><code>b5 01 02 c1 e3 0d 0a </code></pre> <p>plaintext should be:</p> <pre><code>3543921 or 3.543.921 </code></pre> <p>And for cryptext:</p> <pre><code>41 c3 c5 07 17 0d 0a </code></pre> <p>plaintext should be</p> <pre><code>1851154 or 1.851.154 </code></pre> <p>I believe <code>0d 0a</code> is just padding. Was from data gathered in win-1252 encoding (dunno if matters)</p> <p><strong>EDIT:</strong> It's for the sake of curiosity and learning. I want to be able to undestand the encryption used(seems a simple one, although is binary data) to recover the value of the fields for the tuples whose plaintext I don't know.</p> <p><strong>EDIT 2:</strong> Added a couple samples.</p>
[ { "answer_id": 231611, "author": "Sergey", "author_id": 29363, "author_profile": "https://Stackoverflow.com/users/29363", "pm_score": 3, "selected": true, "text": "for (i in originalString) {\nnewString[i] = originalString[i] ^ CRYPT_BYTE;\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861/" ]
231,607
<p>Suppose you have the canonical Customer domain object. You have three different screens on which Customer is displayed: External Admin, Internal Admin, and Update Account.</p> <p>Suppose further that each screen displays only a subset of all of the data contained in the Customer object. </p> <p>The problem is: when the UI passes data back from each screen (e.g. through a DTO), it contains only that subset of a full Customer domain object. So when you send that DTO to the Customer Factory to re-create the Customer object, you have only part of the Customer.</p> <p>Then you send this Customer to your Customer Repository to save it, and a bunch of data will get wiped out because it isn't there. Tragedy ensues.</p> <p>So the question is: how would you deal with this problem?</p> <p>Some of my ideas:</p> <ul> <li><p>include an argument to the Repository indicating which part of the Customer to update, and ignore others</p></li> <li><p>when you load the Customer, keep it in static memory, or in the session, or wherever, and then when you receive one of the DTOs from the UI, update only the parts relevant to the DTO</p></li> </ul> <p>IMO, both of these are kludges. Are there any other better ideas?</p> <p>@chadmyers: Here is the problem.</p> <p>Entity has properties A, B, C, and D.</p> <p>DTO #1 contains properties for B and C.</p> <p>DTO #2 contains properties for C and D.</p> <p>UI asks for DTO #1, you load entity from the repository, convert it into DTO #1, filling in only B and C, and give it to the UI.</p> <p>Now UI updates B and sends the DTO back. You recreate the entity and it has only B and C filled in because that is all that is contained in the DTO.</p> <p>Now you want to save the entity, which has only B and C filled in, with A and D null/blank. The repository has no way of knowing if it should update A and D in persistence as blanks, or whether it should ignore them.</p>
[ { "answer_id": 904930, "author": "5x1llz", "author_id": 96074, "author_profile": "https://Stackoverflow.com/users/96074", "pm_score": 1, "selected": false, "text": "dtoUser.MapFrom<In,Out>(Entity)\nor\ndtoAdmin.MapFrom<In,Out>(Entity)\n entity.Foo = dtoUser.Foo\nor\nentity.Bar = dtoAdmin.Bar\n\nentityRepsotiry.Save(entity) <-- do not pass DTO.\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10759/" ]
231,630
<p>I want to override the default CreateObject() function in VBScript with my own.</p> <p>Basically this example in VB6:</p> <p><a href="http://www.darinhiggins.com/the-vb6-createobject-function/" rel="nofollow noreferrer">http://www.darinhiggins.com/the-vb6-createobject-function/</a></p> <p>I cannot figure out is this line:</p> <pre><code> Set CreateObject = VBA.CreateObject(Class$, ServerName$) </code></pre> <p>How do I refer to "VBA" in VBSript?</p>
[ { "answer_id": 231701, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "Function CreateObject(className, serverName)\n '---- override the CreateObject\n ' function in order to register what\n ' object is being created in any error message\n ' that's generated\n Dim source, descr, errNum\n\n WScript.echo \"In custom CreateObject\"\n If Len(serverName) > 0 Then\n Set CreateObject = WScript.CreateObject(className, serverName)\n Else\n Set CreateObject = WScript.CreateObject(className)\n End If\n\nEnd Function\n\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\", \"\")\npath = fso.GetAbsolutePathName(\".\")\n\nWScript.echo path\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
231,637
<p>I need to match (case insensitive) "abcd" and an optional trademark symbol</p> <p>Regex: <code>/abcd(™)?/gi</code></p> <p>See example:</p> <pre><code>preg_match("/abcd(™)?/gi","AbCd™ U9+",$matches); print_r($matches); </code></pre> <p>When I run this, <code>$matches</code> isn't populated with anything... Not even created as an empty array. Any ideas?</p>
[ { "answer_id": 231656, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "\\x99" }, { "answer_id": 231659, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "\\x99 \\xe2\\x84\\xa2" }, { "answer_id": 231697, "author": "Ken Sykora", "author_id": 53001, "author_profile": "https://Stackoverflow.com/users/53001", "pm_score": 2, "selected": false, "text": "/abcd(\\xe2\\x84\\xa2)?/i\n /g \\xe2\\x84\\xa2" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53001/" ]
231,647
<p>How do you set the timeout for blocking operations on a Ruby socket?</p>
[ { "answer_id": 231662, "author": "readonly", "author_id": 4883, "author_profile": "https://Stackoverflow.com/users/4883", "pm_score": 5, "selected": true, "text": "require 'timeout'\n ...\nbegin \n timeout(5) do\n message, client_address = some_socket.recvfrom(1024)\n end\nrescue Timeout::Error\n puts \"Timed out!\"\nend\n" }, { "answer_id": 232761, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 4, "selected": false, "text": "IO.select(read_array\n[, write_array\n[, error_array\n[, timeout]]] ) => array or nil\n require 'socket'\n\nstrmSock1 = TCPSocket::new( \"www.dn.se\", 80 )\nstrmSock2 = TCPSocket::new( \"www.svd.se\", 80 )\n# Block until one or more events are received\n#result = select( [strmSock1, strmSock2, STDIN], nil, nil )\ntimeout=5\n\ntimeout=100\nresult = select( [strmSock1, strmSock2], nil, nil,timeout )\nputs result.inspect\nif result\n\n for inp in result[0]\n if inp == strmSock1 then\n # data avail on strmSock1\n puts \"data avail on strmSock1\"\n elsif inp == strmSock2 then\n # data avail on strmSock2\n puts \"data avail on strmSock2\"\n elsif inp == STDIN\n # data avail on STDIN\n puts \"data avail on STDIN\"\n end\n end\nend\n" }, { "answer_id": 2791280, "author": "Pete Brumm", "author_id": 335770, "author_profile": "https://Stackoverflow.com/users/335770", "pm_score": 3, "selected": false, "text": "def self.open(host, port, timeout=10)\n addr = Socket.getaddrinfo(host, nil)\n sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)\n\n begin\n sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))\n rescue Errno::EINPROGRESS\n resp = IO.select([sock],nil, nil, timeout.to_i)\n if resp.nil?\n raise Errno::ECONNREFUSED\n end\n begin\n sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))\n rescue Errno::EISCONN\n end\n end\n sock\nend\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
231,649
<p>With common lisp and I am assuming the introspection properties. How can I add code to common lisp code that will tell me when a function is called and when has finished executing. I want to take any lisp code and this particular modification to the code. I figure with lisp's AST analysis, this should be possible.</p>
[ { "answer_id": 232638, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 4, "selected": true, "text": "(trace function) [CL_USER]>\n(defun fac (n)\n \"Naïve factorial implementation\"\n (if (< 1 n)\n (* n (fac (- n 1)))\n 1))\nFAC\n[CL_USER]> (trace fac)\n;; Tracing function FAC.\n(FAC)\n[CL_USER]> (fac 5)\n1. Trace: (FAC '5)\n2. Trace: (FAC '4)\n3. Trace: (FAC '3)\n4. Trace: (FAC '2)\n5. Trace: (FAC '1)\n5. Trace: FAC ==> 1\n4. Trace: FAC ==> 2\n3. Trace: FAC ==> 6\n2. Trace: FAC ==> 24\n1. Trace: FAC ==> 120\n120\n[CL_USER]> \n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
231,666
<p>I wonder if anyone could suggest the best way of looping through all the <code>&lt;option&gt;</code> s in a <code>&lt;select&gt;</code> element with jQuery, and building an array.</p> <p>Eg.</p> <p>Instead of the following, whereby a string ins passed to the autoCompleteArray(),</p> <pre><code>$("#CityLocal").autocompleteArray( [ "Aberdeen", "Ada", "Adamsville", "Zoar" //and a million other cities... ], { delay:10, minChars:1, matchSubset:1, onItemSelect:selectItem, onFindValue:findValue, autoFill:true, maxItemsToShow:10 } ); </code></pre> <p>...I need to loop through all the <code>&lt;options&gt;</code> in a <code>&lt;select&gt;</code> and push them into an array, and just pass that array variable to the function instead of a long string.</p> <p>Eg,</p> <pre><code>$("#CityLocal").autocompleteArray( [ MyBigArrayOfOptions ], { delay:10, minChars:1, matchSubset:1, onItemSelect:selectItem, onFindValue:findValue, autoFill:true, maxItemsToShow:10 } ); </code></pre> <p>I'd be grateful if you could suggest how to push stuff into an array in the correct format. I've pretty much sussed the looping part from another post on this site.</p> <p>Thanks.</p>
[ { "answer_id": 231699, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 4, "selected": true, "text": "$(document).ready(function(){\n // array of option elements' values\n var optionValues = [];\n // array of option elements' text\n var optionTexts = [];\n\n // iterate through all option elements\n $('#sel > option').each(function() {\n // get value/text and push it into respective array\n optionValues.push($(this).val());\n optionTexts.push($(this).text());\n });\n\n // test with alert\n alert(optionValues);\n alert(optionTexts);\n});\n select" }, { "answer_id": 231772, "author": "Matt Ephraim", "author_id": 22291, "author_profile": "https://Stackoverflow.com/users/22291", "pm_score": 3, "selected": false, "text": "<select> var values = jQuery.map(jQuery(\"#select\")[0].options, function(option)\n {\n return option.value;\n });\n\nvar texts = jQuery.map(jQuery(\"#select\")[0].options, function(option)\n {\n return option.innerHTML;\n });\n" }, { "answer_id": 232195, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 2, "selected": false, "text": "$(\"#CityLocal\").autocompleteArray(\n MyBigArrayOfOptions,\n {\n delay:10,\n minChars:1,\n matchSubset:1,\n onItemSelect:selectItem,\n onFindValue:findValue,\n autoFill:true,\n maxItemsToShow:10\n }\n );\n" }, { "answer_id": 232259, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 2, "selected": false, "text": "myFunction($(\"#my-select option\"));\n myFunction($(\"option\", theSelect));\n $(\"#CityLocal\").autocompleteArray(\n $(\"option\", theSelect),\n {\n delay:10,\n minChars:1,\n matchSubset:1,\n onItemSelect:selectItem,\n onFindValue:findValue,\n autoFill:true,\n maxItemsToShow:10\n }\n);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
231,677
<p>Given this in a grails action:</p> <pre><code>def xml = { rss(version: '2.0') { ... } } render(contentType: 'application/rss+xml', xml) </code></pre> <p>I see this:</p> <pre><code>&lt;rss&gt;&lt;channel&gt;&lt;title&gt;&lt;/title&gt;&lt;description&gt;&lt;/description&gt;&lt;link&gt;&lt;/link&gt;&lt;item&gt;&lt;/item&gt;&lt;/channel&gt;&lt;/rss&gt; </code></pre> <p>Is there an easy way to pretty print the XML? Something built into the render method, perhaps?</p>
[ { "answer_id": 232101, "author": "seansand", "author_id": 9452, "author_profile": "https://Stackoverflow.com/users/9452", "pm_score": 4, "selected": false, "text": "def xml = \"<rss><channel><title></title><description>\" +\n \"</description><link></link><item></item></channel></rss>\"\n\ndef stringWriter = new StringWriter()\ndef node = new XmlParser().parseText(xml);\nnew XmlNodePrinter(new PrintWriter(stringWriter)).print(node)\n\nprintln stringWriter.toString()\n <rss>\n <channel>\n <title/>\n <description/>\n <link/>\n <item/>\n </channel>\n</rss>\n" }, { "answer_id": 3459944, "author": "Eric Levine", "author_id": 3767, "author_profile": "https://Stackoverflow.com/users/3767", "pm_score": 3, "selected": true, "text": " grails.converters.default.pretty.print (Boolean)\n //Whether the default output of the Converters is pretty-printed ( default: false )\n" }, { "answer_id": 6326835, "author": "Captian Trips", "author_id": 2133630, "author_profile": "https://Stackoverflow.com/users/2133630", "pm_score": 2, "selected": false, "text": "def writer = new StringWriter()\ndef xml = new MarkupBuilder (writer)\n\nxml.rss(version: '2.0') {\n ...\n }\n}\n\nrender(contentType: 'application/rss+xml', writer.toString())\n" }, { "answer_id": 9507445, "author": "Fabien Barbier", "author_id": 103832, "author_profile": "https://Stackoverflow.com/users/103832", "pm_score": 2, "selected": false, "text": "def xml = \"<rss><channel><title></title><description>\" +\n \"</description><link></link><item></item></channel></rss>\"\n\nprintln XmlUtil.serialize(xml)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
231,679
<p>To add a svg graphics in html page, it is common to use object tag to wrap it like this:</p> <pre><code>&lt;object id="svgid" data="mysvg.svg" type="image/svg+xml" wmode="transparent" width="100" height="100"&gt; this browser is not able to show SVG: &lt;a linkindex="3" href="http://getfirefox.com"&gt;http://getfirefox.com&lt;/a&gt; is free and does it! If you use Internet Explorer, you can also get a plugin: &lt;a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html"&gt; http://www.adobe.com/svg/viewer/install/main.html&lt;/a&gt; &lt;/object&gt; </code></pre> <p>If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?</p>
[ { "answer_id": 233819, "author": "Jon Cram", "author_id": 5343, "author_profile": "https://Stackoverflow.com/users/5343", "pm_score": 3, "selected": false, "text": "object width height" }, { "answer_id": 1577890, "author": "codedread", "author_id": 67838, "author_profile": "https://Stackoverflow.com/users/67838", "pm_score": 3, "selected": false, "text": "var obj = document.getElementById(\"myobj\"); // reference to the object tag\nvar svgdoc = obj.contentDocument; // reference to the SVG document\nvar svgelem = svgdoc.documentElement; // reference to the SVG element\n svgelem.getAttribute(\"width\")\nsvgelem.getAttribute(\"height\")\n" }, { "answer_id": 3951992, "author": "Xaxis", "author_id": 441047, "author_profile": "https://Stackoverflow.com/users/441047", "pm_score": -1, "selected": false, "text": "var filesize = function(url, requestHandler) {\n var requestObj = new XMLHttpRequest(); \n requestObj.open('head', address, true); \n requestObj.onreadystatechange = callback;\n requestObj.send(null); \n};\n var requestHandler = function(result) {\n if (this.readyState === 1) {\n this.abort();\n }\n return this.getResponseHeader(\"Content-length\");\n};\n\nvar size = fileSize(\"http://whatever.org/someSVGFile.svg\", requestHandler);\nalert(size); \n" }, { "answer_id": 52411649, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 1, "selected": false, "text": "async/await async function getImage(url) {\n return new Promise((resolve, reject) => {\n let img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n let img = await getImage(\"yourimage.svg\");\nlet w = img.width;\nlet h = img.height; \n async function getImage(url) {\n return new Promise((resolve, reject) => {\n let img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nasync function start() {\n // here is example url with embeded svg but you can use any url\n let svgURL = \"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='120' width='220'%3E%3Cellipse cx='110' cy='60' rx='100' ry='50' stroke='black' stroke-width='3' fill='red' /%3E%3C/svg%3E\";\n \n let img = await getImage(svgURL);\n let w = img.width;\n let h = img.height; \n \n // print\n console.log({w,h});\n pic.src = svgURL;\n}\n\nstart(); <img id=\"pic\">" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
231,690
<p>When creating web parts for Sharepoint, is it better to create an actual web part, or is using and ASP.NET User Control (.ascx) just as good?</p> <p>I already know how to create the user controls that I need, so it seems like the extra effort of creating a web part is just unnecessary leg work.</p> <p>What are the advantages of using a web part over just creating and ASP.NET user control?</p>
[ { "answer_id": 232185, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 3, "selected": false, "text": "CreateChildControls()" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
231,693
<p>I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.</p> <p>Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?</p>
[ { "answer_id": 231779, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": true, "text": "myVars = new LoadVars();\nmyVars.username = username.text;\nmyVars.password = pwd.text;\nmyVars.onLoad = function(success) {\n trace(\"yay!\");\n else {\n trace(\"try again\"); \n }\n}\nmyVars.sendAndLoad(\"login.php\", myVars, \"POST\");\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2715/" ]
231,695
<p>I need to store several date values in a database field. These values will be tied to a "User" such that each user will have their own unique set of these several date values.</p> <p>I could use a one-to-many relationship here but each user will have exactly 4 date values tied to them so I feel that a one-to-many table would be overkill (in many ways e.g. speed) but if I needed to query against them I would need those 4 values to be in different fields e.g. MyDate1 MyDate2 ... etc. but then the SQL command to fetch it out would have to check for 4 values each time.</p> <p>So the one-to-many relationship would probably be the best solution, but is there a better/cleaner/faster/whatever another way around? Am I designing it correctly?</p> <p>The platform is MS SQL 2005 but solution on any platform will do, I'm mostly looking for proper db designing techniques.</p> <p><strong>EDIT:</strong> The 4 fields represent 4 instances of the same thing.</p>
[ { "answer_id": 231711, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 3, "selected": true, "text": "SELECT * FROM MyTable WHERE 'DateLiteral' IN (MyDate1, MyDate2, MyDate3, MyDate4);\n SELECT * FROM MyTable WHERE date_trunc('hour', 'DateLiteral') \nIN (date_trunc('hour', MyDate1), date_trunc('hour', MyDate2), date_trunc('hour', MyDate3), date_trunc('hour', MyDate4));\n" }, { "answer_id": 231828, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": " CREATE TABLE ThisManyDates (n INT PRIMARY KEY);\n INSERT INTO ThisManyDates VALUES (1), (2), (3), (4);\n\n CREATE TABLE UserDates (\n User_ID INT REFERENCES Users,\n n INT REFERENCES ThisManyDates,\n Date_Value DATE NOT NULL,\n PRIMARY KEY (User_ID, n)\n );\n" }, { "answer_id": 232007, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "alter table t1 add MyDate[4] date;\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055/" ]
231,716
<p>I have a table in an MS SQL Server db. I want to create a script that will put the table and all records into another db. So I right-click the table in Management Studio and select Create-To new query editor... but all I get is the table structure. </p> <p>How exactly do I get the values too?</p>
[ { "answer_id": 231754, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "INSERT INTO [destinationdb].[dbo].[destinationtable] SELECT * \nFROM [originaldb].[dbo].[originaltable]\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
231,739
<p>Im adding textboxes (not a fixed number of textboxes) dynamically to a form on ASP.NET page, how do i read back data from these textboxes?</p>
[ { "answer_id": 231759, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "ctl00$cphBody$[ControlID]\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24958/" ]
231,741
<p>Looking for free/opensource code or description of algorithms to code (simple) and decode (hard) the 2D barcode <a href="http://en.wikipedia.org/wiki/QR_Code" rel="noreferrer">QR code</a>.</p> <p>It doesn't seem like a trivial problem, but it's so popular in Japan that there must be something already available...</p>
[ { "answer_id": 6575376, "author": "Adriano Petrich", "author_id": 326220, "author_profile": "https://Stackoverflow.com/users/326220", "pm_score": 2, "selected": false, "text": "#!/usr/bin/python\n\nfrom sys import argv\nimport zbar\nimport Image\n\n\n# create a reader\nscanner = zbar.ImageScanner()\n\n# configure the reader\nscanner.parse_config('enable')\n\n# obtain image data \npil = Image.open(\"base.png\").convert('L')\nwidth, height = pil.size\nraw = pil.tostring()\n\n# wrap image data\nimage = zbar.Image(width, height, 'Y800', raw)\n\n# scan the image for barcodes\nscanner.scan(image)\n\n# extract results\nfor symbol in image:\n # do something useful with results\n print 'decoded', symbol.type, 'symbol', '\"%s\"' % symbol.data\n\n# clean up\ndel(image)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
231,746
<p>Use case: 3rd party application wants to programatically monitor a text file being generated by another program. Text file contains data you want to analyze as it's being updated.</p> <p>I'm finding a lot of answers to this question wrapped around FileSystemWatcher but let's say you are writing an application for a Windows machine and can't guarantee .NET is installed. </p> <p>Are there any libraries out there available for this, or am I just going to have to roll my own solution then?</p> <p>Thanks.</p>
[ { "answer_id": 231858, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "struct __stat64 fileinfo;\n\nif(-1 != _stat64(filename, &fileinfo)\n return fileinfo.st_mtime;\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
231,760
<p>This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a <code>_t</code> mean? Such as</p> <pre><code>int_t anInt; </code></pre> <p>I see it a lot in C code meant to deal closely with hardware—I can't help but think that they're related.</p>
[ { "answer_id": 231765, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": false, "text": "size_t" }, { "answer_id": 231789, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 6, "selected": false, "text": "typedef \ntypedef struct {\n char* model;\n int year;\n...\n} car_t;\n" }, { "answer_id": 231791, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "int_t int int_t" }, { "answer_id": 231807, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 9, "selected": true, "text": "_t size_t wchar_t off_t ptrdiff_t uintptr_t intmax_t int8_t uint_least16_t uint_fast32_t <stdint.h> <inttypes.h> <stdint.h> <inttypes.h> printf() scanf() _t" }, { "answer_id": 231818, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 4, "selected": false, "text": "_t _t i j k BYTE WORD DWORD int_t int int" }, { "answer_id": 233105, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 3, "selected": false, "text": "typedef unsigned long dc_uint32_t;\n" }, { "answer_id": 12727104, "author": "Benoit", "author_id": 1439701, "author_profile": "https://Stackoverflow.com/users/1439701", "pm_score": 6, "selected": false, "text": "_t _t _t foo_t foo_t _t _t" }, { "answer_id": 51279858, "author": "Jayhello", "author_id": 6329006, "author_profile": "https://Stackoverflow.com/users/6329006", "pm_score": 2, "selected": false, "text": "typedef unsigned char uint8_t;\ntypedef unsigned short int uint16_t;\n#ifndef __uint32_t_defined\ntypedef unsigned int uint32_t;\n# define __uint32_t_defined\n#endif\n#if __WORDSIZE == 64\ntypedef unsigned long int uint64_t;\n#else\n__extension__\ntypedef unsigned long long int uint64_t;\n#endif\n _t" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26237/" ]
231,764
<p>This is one of those meta-programming questions that may or may not belong on SO, but here goes...</p> <p>Have any other programmers out there noticed that their ability to communicate with people (technical or otherwise) almost disappears during and after a period of intense programming?</p> <p>I normally think of myself as a relatively good communicator. However, last night after staying late to work on some relatively challenging programming tasks, I found even ordering a takeaway meal was very difficult: my words got tied up before they left my mouth. This is not the first time this has happened ... </p> <p>Has anyone else experienced this phenomenon? Is there a name for it?</p>
[ { "answer_id": 231842, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "SYN\n ACK\n NACK\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26331/" ]
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: yield self._leftchild if self._rightchild and distance + max_dist &gt;= self._median: yield self._rightchild </code></pre> <p>And this is the caller:</p> <pre><code>result, candidates = [], [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance &lt;= max_dist and distance &gt;= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result </code></pre> <p>What happens when the method <code>_get_child_candidates</code> is called? Is a list returned? A single element? Is it called again? When will subsequent calls stop?</p> <hr /> <sub> 1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: <a href="https://well-adjusted.de/~jrspieker/mspace/" rel="noreferrer">Module mspace</a>.</sub>
[ { "answer_id": 231778, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 9, "selected": false, "text": "yield return yield get_child_candidates list.extend" }, { "answer_id": 231801, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 9, "selected": false, "text": "next() def some_function():\n for i in xrange(4):\n yield i\n\nfor i in some_function():\n print i\n class it:\n def __init__(self):\n # Start at -1 so that we get 0 when we add 1 below.\n self.count = -1\n\n # The __iter__ method will be called once by the 'for' loop.\n # The rest of the magic happens on the object returned by this method.\n # In this case it is the object itself.\n def __iter__(self):\n return self\n\n # The next method will be called repeatedly by the 'for' loop\n # until it raises StopIteration.\n def next(self):\n self.count += 1\n if self.count < 4:\n return self.count\n else:\n # A StopIteration exception is raised\n # to signal that the iterator is done.\n # This is caught implicitly by the 'for' loop.\n raise StopIteration\n\ndef some_func():\n return it()\n\nfor i in some_func():\n print i\n for iterator = some_func()\ntry:\n while 1:\n print iterator.next()\nexcept StopIteration:\n pass\n" }, { "answer_id": 231855, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 15, "selected": true, "text": "yield >>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3\n mylist >>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4\n for... in... lists strings >>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n () [] for i in mygenerator yield return >>> def create_generator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = create_generator() # create a generator\n>>> print(mygenerator) # mygenerator is an object!\n<generator object create_generator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n yield for for yield yield \"if/else\" # Here you create the method of the node object that will return the generator\ndef _get_child_candidates(self, distance, min_dist, max_dist):\n\n # Here is the code that will be called each time you use the generator object:\n\n # If there is still a child of the node object on its left\n # AND if the distance is ok, return the next child\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n\n # If there is still a child of the node object on its right\n # AND if the distance is ok, return the next child\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild\n\n # If the function arrives here, the generator will be considered empty\n # there are no more than two values: the left and the right children\n # Create an empty list and a list with the current object reference\nresult, candidates = list(), [self]\n\n# Loop on candidates (they contain only one element at the beginning)\nwhile candidates:\n\n # Get the last candidate and remove it from the list\n node = candidates.pop()\n\n # Get the distance between obj and the candidate\n distance = node._get_dist(obj)\n\n # If the distance is ok, then you can fill in the result\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n\n # Add the children of the candidate to the candidate's list\n # so the loop will keep running until it has looked\n # at all the children of the children of the children, etc. of the candidate\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\n\nreturn result\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) while extend() >>> a = [1, 2]\n>>> b = [3, 4]\n>>> a.extend(b)\n>>> print(a)\n[1, 2, 3, 4]\n >>> class Bank(): # Let's create a bank, building ATMs\n... crisis = False\n... def create_atm(self):\n... while not self.crisis:\n... yield \"$100\"\n>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\n>>> corner_street_atm = hsbc.create_atm()\n>>> print(corner_street_atm.next())\n$100\n>>> print(corner_street_atm.next())\n$100\n>>> print([corner_street_atm.next() for cash in range(5)])\n['$100', '$100', '$100', '$100', '$100']\n>>> hsbc.crisis = True # Crisis is coming, no more money!\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\n>>> print(wall_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\n>>> for cash in brand_new_atm:\n... print cash\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n...\n print(corner_street_atm.__next__()) print(next(corner_street_atm)) Map / Zip import itertools >>> horses = [1, 2, 3, 4]\n>>> races = itertools.permutations(horses)\n>>> print(races)\n<itertools.permutations object at 0xb754f1dc>\n>>> print(list(itertools.permutations(horses)))\n[(1, 2, 3, 4),\n (1, 2, 4, 3),\n (1, 3, 2, 4),\n (1, 3, 4, 2),\n (1, 4, 2, 3),\n (1, 4, 3, 2),\n (2, 1, 3, 4),\n (2, 1, 4, 3),\n (2, 3, 1, 4),\n (2, 3, 4, 1),\n (2, 4, 1, 3),\n (2, 4, 3, 1),\n (3, 1, 2, 4),\n (3, 1, 4, 2),\n (3, 2, 1, 4),\n (3, 2, 4, 1),\n (3, 4, 1, 2),\n (3, 4, 2, 1),\n (4, 1, 2, 3),\n (4, 1, 3, 2),\n (4, 2, 1, 3),\n (4, 2, 3, 1),\n (4, 3, 1, 2),\n (4, 3, 2, 1)]\n __iter__() __next__() for" }, { "answer_id": 232111, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 8, "selected": false, "text": "def yield next(generator) .next .__next__ next() len() .__len__ StopIteration return yield next() yield next() for for item in sequence:\n sequence def yield" }, { "answer_id": 232853, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 8, "selected": false, "text": "def fib():\n last, cur = 0, 1\n while True: \n yield cur\n last, cur = cur, last + cur\n for f in fib():\n if some_condition: break\n coolfuncs(f);\n" }, { "answer_id": 237028, "author": "user28409", "author_id": 28409, "author_profile": "https://Stackoverflow.com/users/28409", "pm_score": 11, "selected": false, "text": "yield yield result = [] yield expr result.append(expr) return result yield yield for x in mylist:\n ...loop body...\n mylist iter(mylist) next() __next__() next() next() x StopIteration next() otherlist.extend(mylist) otherlist mylist __iter__() next() __iter__() next() __iter__() self __iter__() for next() yield def f123():\n yield 1\n yield 2\n yield 3\n\nfor item in f123():\n print item\n yield return f123() f123() f123() for yield yield StopIteration __iter__() next() for next() __next__() next()" }, { "answer_id": 6400990, "author": "ninjagecko", "author_id": 711085, "author_profile": "https://Stackoverflow.com/users/711085", "pm_score": 9, "selected": false, "text": "yield yield return list set range yield generator = myYieldingFunction(...) # basically a list (but lazy)\nx = list(generator) # evaluate every element into a list\n\n generator\n v\n[x[0], ..., ???]\n\n generator\n v\n[x[0], x[1], ..., ???]\n\n generator\n v\n[x[0], x[1], x[2], ..., ???]\n\n StopIteration exception\n[x[0], x[1], x[2]] done\n yield next() StopIteration makeRange range makeRange(n) def makeRange(n):\n # return 0,1,2,...,n-1\n i = 0\n while i < n:\n yield i\n i += 1\n\n>>> makeRange(5)\n<generator object makeRange at 0x19e4aa0>\n list() >>> list(makeRange(5))\n[0, 1, 2, 3, 4]\n # return a list # # return a generator\ndef makeRange(n): # def makeRange(n):\n \"\"\"return [0,1,2,...,n-1]\"\"\" # \"\"\"return 0,1,2,...,n-1\"\"\"\n TO_RETURN = [] # \n i = 0 # i = 0\n while i < n: # while i < n:\n TO_RETURN += [i] # yield i\n i += 1 # i += 1\n return TO_RETURN # \n\n>>> makeRange(5)\n[0, 1, 2, 3, 4]\n # < ITERABLE >\n>>> [x+10 for x in makeRange(5)]\n[10, 11, 12, 13, 14]\n itertools chain.from_iterable chain itertools.count() def enumerate(iterable): zip(count(), iterable) yield list(makeRange(5)) >>> x=iter(range(5))\n>>> next(x) # calls x.__next__(); x.next() is deprecated\n0\n>>> next(x)\n1\n>>> next(x)\n2\n>>> next(x)\n3\n>>> next(x)\n4\n>>> next(x)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nStopIteration\n next() .__next__() next() def interactiveProcedure():\n userResponse = yield makeQuestionWebpage()\n print('user response:', userResponse)\n yield 'success'\n\ncoroutine = interactiveProcedure()\nwebFormData = next(coroutine) # same as .send(None)\nuserResponse = serveWebForm(webFormData)\n\n# ...at some point later on web form submit...\n\nsuccessStatus = coroutine.send(userResponse)\n yield nextInput = yield nextOutput yield next [1,2,3] [1,2,3].__iter__() > x = myRange(5)\n> list(x)\n[0, 1, 2, 3, 4]\n> list(x)\n[]\n myRange(...) x = list(myRange(5)) itertools.tee" }, { "answer_id": 12716515, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 7, "selected": false, "text": "from itertools import islice\n\ndef fib_gen():\n a, b = 1, 1\n while True:\n yield a\n a, b = b, a + b\n\nassert [1, 1, 2, 3, 5] == list(islice(fib_gen(), 5))\n def ftake(fnext, last):\n return [fnext() for _ in xrange(last)]\n\ndef fib_gen2():\n #funky scope due to python2.x workaround\n #for python 3.x use nonlocal\n def _():\n _.a, _.b = _.b, _.a + _.b\n return _.a\n _.a, _.b = 0, 1\n return _\n\nassert [1,1,2,3,5] == ftake(fib_gen2(), 5)\n class fib_gen3:\n def __init__(self):\n self.a, self.b = 1, 1\n\n def __call__(self):\n r = self.a\n self.a, self.b = self.b, self.a + self.b\n return r\n\nassert [1,1,2,3,5] == ftake(fib_gen3(), 5)\n" }, { "answer_id": 14352675, "author": "RBansal", "author_id": 1776798, "author_profile": "https://Stackoverflow.com/users/1776798", "pm_score": 8, "selected": false, "text": "def get_odd_numbers(i):\n return range(1, i, 2)\ndef yield_odd_numbers(i):\n for x in range(1, i, 2):\n yield x\nfoo = get_odd_numbers(10)\nbar = yield_odd_numbers(10)\nfoo\n[1, 3, 5, 7, 9]\nbar\n<generator object yield_odd_numbers at 0x1029c6f50>\nbar.next()\n1\nbar.next()\n3\nbar.next()\n5\n foo bar for" }, { "answer_id": 14404292, "author": "Daniel", "author_id": 1531346, "author_profile": "https://Stackoverflow.com/users/1531346", "pm_score": 8, "selected": false, "text": ">>> def f():\n... yield 1\n... yield 2\n... yield 3\n... \n>>> g = f()\n>>> for i in g:\n... print(i)\n... \n1\n2\n3\n>>> for i in g:\n... print(i)\n... \n>>> # Note that this time nothing was printed\n" }, { "answer_id": 14554322, "author": "johnzachary", "author_id": 479213, "author_profile": "https://Stackoverflow.com/users/479213", "pm_score": 7, "selected": false, "text": "yield (yield) send() (yield) yield" }, { "answer_id": 15814755, "author": "aestrivex", "author_id": 2040716, "author_profile": "https://Stackoverflow.com/users/2040716", "pm_score": 8, "selected": false, "text": "yield call/cc def save_file(filename):\n def write_file_continuation():\n write_stuff_to_file(filename)\n\n check_if_file_exists_and_user_wants_to_overwrite(write_file_continuation)\n def f():\n while True:\n yield 4\n for x in collection: do_something(x) yield next class Generator():\n def __init__(self,iterable,generatorfun):\n self.next_continuation = lambda:generatorfun(iterable)\n\n def next(self):\n value, next_continuation = self.next_continuation()\n self.next_continuation = next_continuation\n return value\n yield def generatorfun(iterable):\n if len(iterable) == 0:\n raise StopIteration\n else:\n return (iterable[0], lambda:generatorfun(iterable[1:]))\n yield" }, { "answer_id": 17113322, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 6, "selected": false, "text": "yield yield next() yield yield next() def normalFunction():\n return\n if False:\n pass\n\ndef yielderFunction():\n return\n if False:\n yield 12\n yield >>> yielderFunction()\n<generator object yielderFunction at 0x07742D28>\n yielderFunction() yielder >>> gen = yielderFunction()\n>>> dir(gen)\n['__class__',\n ...\n '__iter__', #Returns gen itself, to make it work uniformly with containers\n ... #when given to a for loop. (Containers return an iterator instead.)\n 'close',\n 'gi_code',\n 'gi_frame',\n 'gi_running',\n 'next', #The method that runs the function's body.\n 'send',\n 'throw']\n gi_code gi_frame dir(..)" }, { "answer_id": 18365578, "author": "alinsoar", "author_id": 1419272, "author_profile": "https://Stackoverflow.com/users/1419272", "pm_score": 7, "selected": false, "text": "Welcome to Racket v6.5.0.3.\n\n-> (define gen\n (lambda (l)\n (define yield\n (lambda ()\n (if (null? l)\n 'END\n (let ((v (car l)))\n (set! l (cdr l))\n v))))\n (lambda(m)\n (case m\n ('yield (yield))\n ('init (lambda (data)\n (set! l data)\n 'OK))))))\n-> (define stream (gen '(1 2 3)))\n-> (stream 'yield)\n1\n-> (stream 'yield)\n2\n-> (stream 'yield)\n3\n-> (stream 'yield)\n'END\n-> ((stream 'init) '(a b))\n'OK\n-> (stream 'yield)\n'a\n-> (stream 'yield)\n'b\n-> (stream 'yield)\n'END\n-> (stream 'yield)\n'END\n->\n" }, { "answer_id": 20704301, "author": "Engin OZTURK", "author_id": 1077381, "author_profile": "https://Stackoverflow.com/users/1077381", "pm_score": 7, "selected": false, "text": "def isPrimeNumber(n):\n print \"isPrimeNumber({}) call\".format(n)\n if n==1:\n return False\n for x in range(2,n):\n if n % x == 0:\n return False\n return True\n\ndef primes (n=1):\n while(True):\n print \"loop step ---------------- {}\".format(n)\n if isPrimeNumber(n): yield n\n n += 1\n\nfor n in primes():\n if n> 10:break\n print \"wiriting result {}\".format(n)\n loop step ---------------- 1\nisPrimeNumber(1) call\nloop step ---------------- 2\nisPrimeNumber(2) call\nloop step ---------------- 3\nisPrimeNumber(3) call\nwiriting result 3\nloop step ---------------- 4\nisPrimeNumber(4) call\nloop step ---------------- 5\nisPrimeNumber(5) call\nwiriting result 5\nloop step ---------------- 6\nisPrimeNumber(6) call\nloop step ---------------- 7\nisPrimeNumber(7) call\nwiriting result 7\nloop step ---------------- 8\nisPrimeNumber(8) call\nloop step ---------------- 9\nisPrimeNumber(9) call\nloop step ---------------- 10\nisPrimeNumber(10) call\nloop step ---------------- 11\nisPrimeNumber(11) call\n yield" }, { "answer_id": 21541902, "author": "Mike McKerns", "author_id": 2379433, "author_profile": "https://Stackoverflow.com/users/2379433", "pm_score": 7, "selected": false, "text": "yield yield yield yield yield yield next send next yield yield next yield send send yield yield next >>> def coroutine():\n... i = -1\n... while True:\n... i += 1\n... val = (yield i)\n... print(\"Received %s\" % val)\n...\n>>> sequence = coroutine()\n>>> sequence.next()\n0\n>>> sequence.next()\nReceived None\n1\n>>> sequence.send('hello')\nReceived hello\n2\n>>> sequence.close()\n" }, { "answer_id": 24944096, "author": "Sławomir Lenart", "author_id": 1416144, "author_profile": "https://Stackoverflow.com/users/1416144", "pm_score": 7, "selected": false, "text": "yield yield from <expr>\n async def new_coroutine(data):\n ...\n await blocking_action()\n yield" }, { "answer_id": 30341713, "author": "Will Dereham", "author_id": 4884103, "author_profile": "https://Stackoverflow.com/users/4884103", "pm_score": 6, "selected": false, "text": "yield yield list(generator())" }, { "answer_id": 31042491, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 9, "selected": false, "text": "yield yield yield from return yield yield yield __iter__ __next__ Iterator collections def func():\n yield 'I am'\n yield 'a generator!'\n >>> type(func) # A function with yield is still a function\n<type 'function'>\n>>> gen = func()\n>>> type(gen) # but it returns a generator\n<type 'generator'>\n>>> hasattr(gen, '__iter__') # that's an iterable\nTrue\n>>> hasattr(gen, '__next__') # and with .__next__\nTrue # implements the iterator protocol.\n from types import GeneratorType\nfrom collections.abc import Iterator\n\n>>> issubclass(GeneratorType, Iterator)\nTrue\n >>> isinstance(gen, GeneratorType)\nTrue\n>>> isinstance(gen, Iterator)\nTrue\n Iterator >>> list(gen)\n['I am', 'a generator!']\n>>> list(gen)\n[]\n >>> list(func())\n['I am', 'a generator!']\n def func(an_iterable):\n for item in an_iterable:\n yield item\n yield from def func(an_iterable):\n yield from an_iterable\n yield from yield received def bank_account(deposited, interest_rate):\n while True:\n calculated_interest = interest_rate * deposited \n received = yield calculated_interest\n if received:\n deposited += received\n\n\n>>> my_account = bank_account(1000, .05)\n next next __next__ >>> first_year_interest = next(my_account)\n>>> first_year_interest\n50.0\n None next >>> next_year_interest = my_account.send(first_year_interest + 1000)\n>>> next_year_interest\n102.5\n yield from yield from \ndef money_manager(expected_rate):\n # must receive deposited value from .send():\n under_management = yield # yield None to start.\n while True:\n try:\n additional_investment = yield expected_rate * under_management \n if additional_investment:\n under_management += additional_investment\n except GeneratorExit:\n '''TODO: write function to send unclaimed funds to state'''\n raise\n finally:\n '''TODO: write function to mail tax info to client'''\n \n\ndef investment_account(deposited, manager):\n '''very simple model of an investment account that delegates to a manager'''\n # must queue up manager:\n next(manager) # <- same as manager.send(None)\n # This is where we send the initial deposit to the manager:\n manager.send(deposited)\n try:\n yield from manager\n except GeneratorExit:\n return manager.close() # delegate?\n my_manager = money_manager(.06)\nmy_account = investment_account(1000, my_manager)\nfirst_year_return = next(my_account) # -> 60.0\n next_year_return = my_account.send(first_year_return + 1000)\nnext_year_return # 123.6\n yield from close GeneratorExit __del__ GeneratorExit my_account.close()\n import sys\ntry:\n raise ValueError\nexcept:\n my_manager.throw(*sys.exc_info())\n Traceback (most recent call last):\n File \"<stdin>\", line 4, in <module>\n File \"<stdin>\", line 6, in money_manager\n File \"<stdin>\", line 2, in <module>\nValueError\n yield yield __iter__ .__next__ for StopIteration StopIteration yield .next next next(obj) yield yield yield from yield expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |\n ('=' (yield_expr|testlist_star_expr))*)\n...\nyield_expr: 'yield' [yield_arg]\nyield_arg: 'from' test | testlist\n yield return return StopIteration StopIteration StopIteration.value return expression_list return StopIteration expression_list return range Iterator __iter__ yield yield" }, { "answer_id": 31692481, "author": "Mangu Singh Rajpurohit", "author_id": 2393267, "author_profile": "https://Stackoverflow.com/users/2393267", "pm_score": 6, "selected": false, "text": "yield yield def getNextLines():\n while con.isOpen():\n yield con.read()\n for line in getNextLines():\n doSomeThing(line)\n for def simpleYield():\n yield \"first time\"\n yield \"second time\"\n yield \"third time\"\n yield \"Now some useful value {}\".format(12)\n\nfor i in simpleYield():\n print i\n \"first time\"\n\"second time\"\n\"third time\"\n\"Now some useful value 12\"\n" }, { "answer_id": 32331953, "author": "Kaleem Ullah", "author_id": 2046817, "author_profile": "https://Stackoverflow.com/users/2046817", "pm_score": 6, "selected": false, "text": "return yield yield yield" }, { "answer_id": 33788856, "author": "Bahtiyar Özdere", "author_id": 5069117, "author_profile": "https://Stackoverflow.com/users/5069117", "pm_score": 6, "selected": false, "text": "yield yield return +=" }, { "answer_id": 35526740, "author": "Dimitris Fasarakis Hilliard", "author_id": 4952130, "author_profile": "https://Stackoverflow.com/users/4952130", "pm_score": 6, "selected": false, "text": "yield def fib(limit=50):\n a, b = 0, 1\n for i in range(limit):\n yield b\n a, b = b, a+b\n >>> fib()\n<generator object fib at 0x7fa38394e3b8>\n yield next next() .next __next__ >>> g = fib()\n>>> next(g)\n1\n>>> next(g)\n1\n>>> next(g)\n2\n>>> next(g)\n3\n>>> next(g)\n5\n fib for list tuple results = []\nfor i in fib(30): # consumes fib\n results.append(i) \n# can also be accomplished with\nresults = list(fib(30)) # consumes fib\n tuple >>> tuple(fib(5)) # consumes fib\n(1, 1, 2, 3, 5)\n fib f = fib()\n yield yield yield print print \"text\" def yielder(value):\n \"\"\" This is an infinite generator. Only use next on it \"\"\" \n while 1:\n print(\"I'm going to generate the value for you\")\n print(\"Then I'll pause for a while\")\n yield value\n print(\"Let's go through it again.\")\n >>> gen = yielder(\"Hello, yield!\")\n next >>> next(gen) # runs until it finds a yield\nI'm going to generate the value for you\nThen I'll pause for a while\n'Hello, yield!'\n yield next >>> next(gen) # continues from yield and runs again\nLet's go through it again.\nI'm going to generate the value for you\nThen I'll pause for a while\n'Hello, yield!'\n yield value yield while" }, { "answer_id": 36214653, "author": "smwikipedia", "author_id": 264052, "author_profile": "https://Stackoverflow.com/users/264052", "pm_score": 6, "selected": false, "text": "yield return generator function generator yield StopIteration generator functional programming perspective generator iterator data metadata the logic how the data is computed as a class iterator __next__() __iter__() as a function generator function generator object IS-A" }, { "answer_id": 36220775, "author": "Bob Stein", "author_id": 673991, "author_profile": "https://Stackoverflow.com/users/673991", "pm_score": 8, "selected": false, "text": "def square_list(n):\n the_list = [] # Replace\n for x in range(n):\n y = x * x\n the_list.append(y) # these\n return the_list # lines\n def square_yield(n):\n for x in range(n):\n y = x * x\n yield y # with this one.\n yield yield >>> for square in square_list(4):\n... print(square)\n...\n0\n1\n4\n9\n>>> for square in square_yield(4):\n... print(square)\n...\n0\n1\n4\n9\n next() return >>> def squares_all_of_them():\n... x = 0\n... while True:\n... yield x * x\n... x += 1\n...\n>>> squares = squares_all_of_them()\n>>> for _ in range(4):\n... print(next(squares))\n...\n0\n1\n4\n9\n list() >>> list(square_yield(4))\n[0, 1, 4, 9]\n yield" }, { "answer_id": 37964180, "author": "Christophe Roussy", "author_id": 657427, "author_profile": "https://Stackoverflow.com/users/657427", "pm_score": 6, "selected": false, "text": "next() next() next yield" }, { "answer_id": 39425637, "author": "Tom Fuller", "author_id": 5177604, "author_profile": "https://Stackoverflow.com/users/5177604", "pm_score": 6, "selected": false, "text": "return yield yield yield import random\n\ndef return_dates():\n dates = [] # With 'return' you need to create a list then return it\n for i in range(5):\n date = random.choice([\"1st\", \"2nd\", \"3rd\", \"4th\", \"5th\", \"6th\", \"7th\", \"8th\", \"9th\", \"10th\"])\n dates.append(date)\n return dates\n def yield_dates():\n for i in range(5):\n date = random.choice([\"1st\", \"2nd\", \"3rd\", \"4th\", \"5th\", \"6th\", \"7th\", \"8th\", \"9th\", \"10th\"])\n yield date # 'yield' makes a generator automatically which works\n # in a similar way. This is much more efficient.\n dates_list = return_dates()\nprint(dates_list)\nfor i in dates_list:\n print(i)\n\ndates_generator = yield_dates()\nprint(dates_generator)\nfor i in dates_generator:\n print(i)\n yield return_dates() yield_dates()" }, { "answer_id": 40022748, "author": "redbandit", "author_id": 3104473, "author_profile": "https://Stackoverflow.com/users/3104473", "pm_score": 6, "selected": false, "text": "yield generator generator yield yield def simple_generator():\n yield 'one'\n yield 'two'\n yield 'three'\n\nfor i in simple_generator():\n print i\n one\ntwo\nthree\n range def myRangeNaive(i):\n n = 0\n range = []\n while n < i:\n range.append(n)\n n = n + 1\n return range\n for i in myRangeNaive(10):\n print i\n def myRangeSmart(i):\n n = 0\n while n < i:\n yield n\n n = n + 1\n return\n\nfor i in myRangeSmart(10):\n print i\n next() next()" }, { "answer_id": 41426583, "author": "Gavriel Cohen", "author_id": 5770004, "author_profile": "https://Stackoverflow.com/users/5770004", "pm_score": 6, "selected": false, "text": "yield def f123():\n for _ in range(4):\n yield 1\n yield 2\n\n\nfor i in f123():\n print (i)\n 1 2 1 2 1 2 1 2\n" }, { "answer_id": 43698502, "author": "Ahmad Ismail", "author_id": 1772898, "author_profile": "https://Stackoverflow.com/users/1772898", "pm_score": 5, "selected": false, "text": "primes(n = 1) yield expression def isprime(n):\n if n == 1:\n return False\n for x in range(2, n):\n if n % x == 0:\n return False\n else:\n return True\n\ndef primes(n = 1):\n while(True):\n if isprime(n): yield n\n n += 1 \n\nfor n in primes():\n if n > 100: break\n print(n)\n isprime(n) n += 1 \n" }, { "answer_id": 46543549, "author": "Chen A.", "author_id": 840582, "author_profile": "https://Stackoverflow.com/users/840582", "pm_score": 5, "selected": false, "text": " 5\n / \\\n 3 6\n / \\ \\\n1 4 8\n class Node(object):\n..\ndef __iter__(self):\n if self.has_left_child():\n for child in self.left:\n yield child\n\n yield self.val\n\n if self.has_right_child():\n for child in self.right:\n yield child\n Tree __iter__ def __iter__(self):\n\n class EmptyIter():\n def next(self):\n raise StopIteration\n\n if self.root:\n return self.root.__iter__()\n return EmptyIter()\n while candidates for element in tree it = iter(TreeObj) # returns iter(self.root) which calls self.root.__iter__()\nfor element in it: \n .. process element .. \n Node.__iter__ for for for child in self.left self.left iterator it3 yield self.value next(it3) StopIteration it1 it2 next(it2) StopIteration it2 next(it2) yield child self.val self" }, { "answer_id": 47285378, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 7, "selected": false, "text": "return return yield return return def num_list(n):\n for i in range(n):\n return i\n In [5]: num_list(3)\nOut[5]: 0\n return yield return yield In [10]: def num_list(n):\n ...: for i in range(n):\n ...: yield i\n ...:\n\nIn [11]: num_list(3)\nOut[11]: <generator object num_list at 0x10327c990>\n\nIn [12]: list(num_list(3))\nOut[12]: [0, 1, 2]\n return yield return return one of them yield return all of them iterable yield return In [15]: def num_list(n):\n ...: result = []\n ...: for i in range(n):\n ...: result.append(i)\n ...: return result\n\nIn [16]: num_list(3)\nOut[16]: [0, 1, 2]\n yield return yield yield generator Out[11]: <generator object num_list at 0x10327c990> return yield list generator" }, { "answer_id": 52244968, "author": "Andy Jazz", "author_id": 6599590, "author_profile": "https://Stackoverflow.com/users/6599590", "pm_score": 5, "selected": false, "text": "generators iterators yield return yield state number generator def getPrimes(number):\n while True:\n if isPrime(number):\n number = yield number # a miracle occurs here\n number += 1\n\ndef printSuccessivePrimes(iterations, base=10):\n primeGenerator = getPrimes(base)\n primeGenerator.send(None)\n for power in range(iterations):\n print(primeGenerator.send(base ** power))\n" }, { "answer_id": 54826880, "author": "thavan", "author_id": 323000, "author_profile": "https://Stackoverflow.com/users/323000", "pm_score": 5, "selected": false, "text": "yield In [4]: def make_cake(numbers):\n ...: for i in range(numbers):\n ...: yield 'Cake {}'.format(i)\n ...:\n\nIn [5]: factory = make_cake(5)\n factory make_function yield In [7]: next(factory)\nOut[7]: 'Cake 0'\n\nIn [8]: next(factory)\nOut[8]: 'Cake 1'\n\nIn [9]: next(factory)\nOut[9]: 'Cake 2'\n\nIn [10]: next(factory)\nOut[10]: 'Cake 3'\n\nIn [11]: next(factory)\nOut[11]: 'Cake 4'\n In [12]: next(factory)\n---------------------------------------------------------------------------\nStopIteration Traceback (most recent call last)\n<ipython-input-12-0f5c45da9774> in <module>\n----> 1 next(factory)\n\nStopIteration:\n make_cake In [13]: factory = make_cake(3)\n\nIn [14]: for cake in factory:\n ...: print(cake)\n ...:\nCake 0\nCake 1\nCake 2\n In [22]: import random\n\nIn [23]: import string\n\nIn [24]: def random_password_generator():\n ...: while True:\n ...: yield ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n ...:\n\nIn [25]: rpg = random_password_generator()\n\nIn [26]: for i in range(3):\n ...: print(next(rpg))\n ...:\nFXpUBhhH\nDdUDHoHn\ndvtebEqG\n\nIn [27]: next(rpg)\nOut[27]: 'mJbYRMNo'\n rpg" }, { "answer_id": 55314423, "author": "Dr Rafael", "author_id": 4946896, "author_profile": "https://Stackoverflow.com/users/4946896", "pm_score": 6, "selected": false, "text": "barcode_generator def barcode_generator():\n serial_number = 10000 # Initial barcode\n while True:\n yield serial_number\n serial_number += 1\n\n\nbarcode = barcode_generator()\nwhile True:\n number_of_lightbulbs_to_generate = int(input(\"How many lightbulbs to generate? \"))\n barcodes = [next(barcode) for _ in range(number_of_lightbulbs_to_generate)]\n print(barcodes)\n\n # function_to_create_the_next_batch_of_lightbulbs(barcodes)\n\n produce_more = input(\"Produce more? [Y/n]: \")\n if produce_more == \"n\":\n break\n next(barcode) next() next for barcode in barcode_generator():\n print(barcode)\n" }, { "answer_id": 59785342, "author": "Swati Srivastava", "author_id": 9851541, "author_profile": "https://Stackoverflow.com/users/9851541", "pm_score": 4, "selected": false, "text": "def fun():\n yield 1\n yield 2\n yield 3\n def caller():\n print ('First value printing')\n print (fun())\n print ('Second value printing')\n print (fun())\n print ('Third value printing')\n print (fun())\n First value printing\n1\nSecond value printing\n2\nThird value printing\n3\n" }, { "answer_id": 63533381, "author": "Aaron_ab", "author_id": 6221828, "author_profile": "https://Stackoverflow.com/users/6221828", "pm_score": 4, "selected": false, "text": "yield generator yield def translator():\n # load all the words in English language and the translation to 'other lang'\n my_words_dict = {'hello': 'hello in other language', 'dog': 'dog in other language'}\n\n while True:\n word = (yield)\n yield my_words_dict.get(word, 'Unknown word...')\n my_words_translator = translator()\n\nnext(my_words_translator)\nprint(my_words_translator.send('dog'))\n\nnext(my_words_translator)\nprint(my_words_translator.send('cat'))\n dog in other language\nUnknown word...\n send (yield)" }, { "answer_id": 67970221, "author": "Siva Sankar", "author_id": 11282077, "author_profile": "https://Stackoverflow.com/users/11282077", "pm_score": 2, "selected": false, "text": "names = ['Sam', 'Sarah', 'Thomas', 'James']\n\n\n# Using function\ndef greet(name) :\n return f'Hi, my name is {name}.'\n \nfor each_name in names:\n print(greet(each_name))\n\n# Output: \n>>>Hi, my name is Sam.\n>>>Hi, my name is Sarah.\n>>>Hi, my name is Thomas.\n>>>Hi, my name is James.\n\n\n# using generator\ndef greetings(names) :\n for each_name in names:\n yield f'Hi, my name is {each_name}.'\n \nfor greet_name in greetings(names):\n print (greet_name)\n\n# Output: \n>>>Hi, my name is Sam.\n>>>Hi, my name is Sarah.\n>>>Hi, my name is Thomas.\n>>>Hi, my name is James.\n def function():\n yield 1 # return this first\n yield 2 # start continue from here (yield don't execute above code once executed)\n yield 3 # give this at last (yield don't execute above code once executed)\n\nfor processed_data in function(): \n print(processed_data)\n \n#Output:\n\n>>>1\n>>>2\n>>>3\n" }, { "answer_id": 67976136, "author": "Mayank Maheshwari", "author_id": 10251555, "author_profile": "https://Stackoverflow.com/users/10251555", "pm_score": 3, "selected": false, "text": "arr=[]\nif 2>0:\n arr.append(2)\n\ndef func():\n if 2>0:\n yield 2\n" }, { "answer_id": 69427199, "author": "ToTamire", "author_id": 15964568, "author_profile": "https://Stackoverflow.com/users/15964568", "pm_score": 3, "selected": false, "text": "yield yield yield yield yield def my_range(n):\n my_list = []\n i = 0\n while i < n:\n my_list.append(i)\n i += 1\n return my_list\n\n@profile\ndef function():\n my_sum = 0\n my_values = my_range(1000000)\n for my_value in my_values:\n my_sum += my_value\n\nfunction()\n Total time: 1.07901 s\nTimer unit: 1e-06 s\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 9 @profile\n 10 def function():\n 11 1 1.1 1.1 0.0 my_sum = 0\n 12 1 494875.0 494875.0 45.9 my_values = my_range(1000000)\n 13 1000001 262842.1 0.3 24.4 for my_value in my_values:\n 14 1000000 321289.8 0.3 29.8 my_sum += my_value\n\n\n\nLine # Mem usage Increment Occurences Line Contents\n============================================================\n 9 40.168 MiB 40.168 MiB 1 @profile\n 10 def function():\n 11 40.168 MiB 0.000 MiB 1 my_sum = 0\n 12 78.914 MiB 38.746 MiB 1 my_values = my_range(1000000)\n 13 78.941 MiB 0.012 MiB 1000001 for my_value in my_values:\n 14 78.941 MiB 0.016 MiB 1000000 my_sum += my_value\n def my_range(n):\n i = 0\n while i < n:\n yield i\n i += 1\n\n@profile\ndef function():\n my_sum = 0\n \n for my_value in my_range(1000000):\n my_sum += my_value\n\nfunction()\n Total time: 1.24841 s\nTimer unit: 1e-06 s\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 7 @profile\n 8 def function():\n 9 1 1.1 1.1 0.0 my_sum = 0\n 10\n 11 1000001 895617.3 0.9 71.7 for my_value in my_range(1000000):\n 12 1000000 352793.7 0.4 28.3 my_sum += my_value\n\n\n\nLine # Mem usage Increment Occurences Line Contents\n============================================================\n 7 40.168 MiB 40.168 MiB 1 @profile\n 8 def function():\n 9 40.168 MiB 0.000 MiB 1 my_sum = 0\n 10\n 11 40.203 MiB 0.016 MiB 1000001 for my_value in my_range(1000000):\n 12 40.203 MiB 0.020 MiB 1000000 my_sum += my_value\n" }, { "answer_id": 69893671, "author": "Ted Shaneyfelt", "author_id": 14751543, "author_profile": "https://Stackoverflow.com/users/14751543", "pm_score": 3, "selected": false, "text": ">>> def foo():\n yield 100\n yield 20\n yield 3\n\n \n>>> for i in foo(): print(i)\n\n100\n20\n3\n>>> \n" }, { "answer_id": 70233705, "author": "michalmonday", "author_id": 4620679, "author_profile": "https://Stackoverflow.com/users/4620679", "pm_score": 2, "selected": false, "text": "import time\n\ndef get_gen():\n for i in range(10):\n yield i\n time.sleep(1)\n\ndef get_list():\n ret = []\n for i in range(10):\n ret.append(i)\n time.sleep(1)\n return ret\n\n\nstart_time = time.time()\nprint('get_gen iteration (individual results come immediately)')\nfor i in get_gen():\n print(f'result arrived after: {time.time() - start_time:.0f} seconds')\nprint()\n\nstart_time = time.time()\nprint('get_list iteration (results come all at once)') \nfor i in get_list():\n print(f'result arrived after: {time.time() - start_time:.0f} seconds')\n\n get_gen iteration (individual results come immediately)\nresult arrived after: 0 seconds\nresult arrived after: 1 seconds\nresult arrived after: 2 seconds\nresult arrived after: 3 seconds\nresult arrived after: 4 seconds\nresult arrived after: 5 seconds\nresult arrived after: 6 seconds\nresult arrived after: 7 seconds\nresult arrived after: 8 seconds\nresult arrived after: 9 seconds\n\nget_list iteration (results come all at once)\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\n" }, { "answer_id": 70516941, "author": "Conjure.Li", "author_id": 15642146, "author_profile": "https://Stackoverflow.com/users/15642146", "pm_score": 2, "selected": false, "text": ">>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3 \n >>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4 \n >>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4 \n >>> def createGenerator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = createGenerator() \n>>> print(mygenerator) \n<generator object createGenerator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4 \n" }, { "answer_id": 70521893, "author": "yash bhangare", "author_id": 13388767, "author_profile": "https://Stackoverflow.com/users/13388767", "pm_score": 4, "selected": false, "text": "yield yield def counter():\n x=2\n while x < 5:\n yield x\n x += 1\n \nprint(\"Initial value of x: \", counter()) \n\nfor y in counter():\n print(y)\n Initial value of x: <generator object counter at 0x7f0263020ac0>\n2\n3\n4\n" }, { "answer_id": 70617027, "author": "Vinod Srivastav", "author_id": 3057246, "author_profile": "https://Stackoverflow.com/users/3057246", "pm_score": 2, "selected": false, "text": "yield # example A\ndef getNumber():\n for r in range(1,10):\n return r\n return yield # example B\ndef getNumber():\n for r in range(1,10):\n yield r\n \ng = getNumber() #instance\nprint(next(g)) #will print 1\nprint(next(g)) #will print 2\nprint(next(g)) #will print 3\n\n# so to assign it to a variables\nv = getNumber()\nv1 = next(v) #v1 will have 1\nv2 = next(v) #v2 will have 2\nv3 = next(v) #v3 will have 3\n" }, { "answer_id": 72334132, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 2, "selected": false, "text": "yield return yield next(g) return print() yield def f(n):\n for x in range(n):\n print(x)\n print(x * 10)\n >>> f(3)\n0\n0\n1\n10\n2\n2\n yield print def f(n):\n for x in range(n):\n yield x\n yield x * 10\n >>> list(f(3))\n[0, 0, 1, 10, 2, 20]\n >>> s = [10, 20, 30] # The list is the \"iterable\"\n>>> it = iter(s) # This is the \"iterator\"\n>>> next(it) # Gets values out of an iterator\n10\n>>> next(it)\n20\n>>> next(it)\n30\n>>> next(it)\nTraceback (most recent call last):\n ...\nStopIteration\n >>> for x in s:\n... print(x)\n... \n10\n20\n30\n print yield" }, { "answer_id": 73457837, "author": "Shisui Otsutsuki", "author_id": 16360640, "author_profile": "https://Stackoverflow.com/users/16360640", "pm_score": 1, "selected": false, "text": "yield generator" }, { "answer_id": 74055463, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": 2, "selected": false, "text": "yield for for i, row in df.iterrows(): #from the panda package for reading excel \n if row = blank: # pseudo code, check if row is non-blank...\n continue\n if past_last_row: # pseudo code, check for end of input data\n break\n #### above is boring stuff, below is what we actually want to do with the data ###\n f(row)\n g(row) for f(row) g(row) yield def valid_rows():\n for i, row in df.iterrows(): # iterate over each row of spreadsheet\n if row == blank: # pseudo code, check if row is non-blank...\n continue\n if past_last_row: # pseudo code, check for end of input data\n break\n yield i, row\n for return for for i, row in valid_rows():\n f(row)\n\nfor i, row in valid_rows():\n g(row)\n\nnr_valid_rows = len(list(valid_rows()))\n" }, { "answer_id": 74338534, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 2, "selected": false, "text": "yield from yield from test() 'One' 'Two' ['Three', 'Four'] test() test() test() def test():\n yield 'One' # Stop, return 'One' and resume \n yield 'Two' # Stop, return 'Two' and resume\n yield from ['Three', 'Four'] # Stop and return ['Three', 'Four'] \n test() 'One' 'Two' 'Three' 'Four' for x in test():\n print(x)\n x = test()\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x))\n x = test()\nprint(x.__next__())\nprint(x.__next__())\nprint(x.__next__())\nprint(x.__next__())\n $ python yield_test.py\nOne\nTwo\nThree\nFour\n return yield return def test():\n yield 'One' \n yield 'Two'\n yield from ['Three', 'Four']\n return 'Five' # 'Five' cannot be got\n\nx = test()\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x)) # Here\n 'Five' $ python yield_test.py \nOne\nTwo\nThree\nFour\nTraceback (most recent call last):\n File \"C:\\Users\\kai\\yield_test.py\", line 12, in <module>\n print(next(x))\n ^^^^^^^\nStopIteration: Five\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
231,821
<p>I am working on a VB.NET WinForms app that was "upgraded" by Visual Studio (originally 1.0 or 1.1) from VB6 code (which was itself upgraded from VB5). Except for the few new forms I've created since taking over maintenance of this app, all of the forms in the application have a method called DefInstance which allows you to grab an in-memory copy of the form if there is one. What I can't figure out is why: when would I ever need to reference a form object in memory when it's not immediately in scope where I'm working. To my mind this violates all kinds of sound programming principles and seems like an invitation for memory leaks or worse.</p> <p>The questions: (1) is this DefInstance thing an merely unfortunate remnant of the VB6 heritage of this app, and (2) should I make a point of removing DefInstance methods throughout the application?</p>
[ { "answer_id": 231852, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 1, "selected": false, "text": "Private Sub Command_Click()\n Call DoStuff\nEnd Sub\n\nPrivate Sub DoStuff()\n Form1.myTextbox.Text = \"Bad Idea\"\nEnd Sub\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3799/" ]
231,827
<p>I'm designing a multi-tiered database driven web application – SQL relational database, Java for the middle service tier, web for the UI. The language doesn't really matter.</p> <p>The middle service tier performs the actual querying of the database. The UI simply asks for certain data and has no concept that it's backed by a database.</p> <p>The question is how to handle large data sets? The UI asks for data but the results might be huge, possibly too big to fit in memory. For example, a street sign application might have a service layer of:</p> <pre><code>StreetSign getStreetSign(int identifier) Collection&lt;StreetSign&gt; getStreetSigns(Street street) Collection&lt;StreetSign&gt; getStreetSigns(LatLonBox box) </code></pre> <p>The UI layer asks to get all street signs meeting some criteria. Depending on the criteria, the result set might be huge. The UI layer might divide the results into separate pages (for a browser) or just present them all (serving up to Goolge Earth). The potentially huge result set could be a performance and resource problem (out of memory).</p> <p>One solution is not to return fully loaded objects (StreetSign objects). Rather return some sort of result set or iterator that lazily loads each individual object.</p> <p>Another solution is to change the service API to return a subset of the requested data:</p> <pre><code>Collection&lt;StreetSign&gt; getStreetSigns(LatLonBox box, int pageNumber, int resultsPerPage) </code></pre> <p>Of course the UI can still request a huge result set:</p> <pre><code>getStreetSigns(box, 1, 1000000000) </code></pre> <p>I'm curious what is the standard industry design pattern for this scenario?</p>
[ { "answer_id": 231864, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 0, "selected": false, "text": "public interface Pageable\n{\n public void setStartIndex( int index );\n public int getStartIndex();\n public int getRowsPerPage() throws Exception;\n public void setRowsPerPage( int rowsPerPage );\n}\n" }, { "answer_id": 231961, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE GetPagedStreetSigns\n(\n @Page int = 1,\n @PageSize int = 10\n)\nAS\n SET NOCOUNT ON\n\n -- This memory-variable table will control paging\n DECLARE @TempTable TABLE (RowNumber int identity, StreetSignId int)\n\n INSERT INTO @TempTable\n (\n StreetSignId\n )\n SELECT [Id]\n FROM StreetSign\n ORDER BY [Id]\n\n -- select only those rows belonging to the requested page\n SELECT SS.*\n FROM StreetSign SS\n INNER JOIN @TempTable TT ON TT.StreetSignId = SS.[Id]\n WHERE TT.RowNumber BETWEEN ((@Page - 1) * @PageSize + 1) \n AND (@Page * @PageSize)\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
231,838
<p>Alright, so I have a query that looks like this:</p> <pre><code>SELECT `orders`.*, GROUP_CONCAT( CONCAT( `menu_items`.`name`, ' ($', FORMAT(`menu_items`.`price`,2), ')' ) SEPARATOR '&lt;br&gt;' ) as `items`, SUM(`menu_items`.`price`) as `additional`, `children`.`first_name`, `children`.`last_name`, `organizations`.`base_price` FROM `orders`, `order_items`, `menu_items`, `children`, `organizations` WHERE `order_items`.`menu_item_id` = `menu_items`.`id` AND `order_items`.`order_id` = `orders`.`id` AND `orders`.`added_by` = {$user_id} AND `orders`.`date` &gt; '{$cutoff}' AND `children`.`id` = `orders`.`child_id` AND `organizations`.`id` = `children`.`organization_id` GROUP BY `orders`.`id` </code></pre> <p>I know it's a monstrosity and that some people will die before not using explicit joins. Ignoring that, however, what I wish to do is to only use the <code>CONCAT</code> inside the <code>GROUP_CONCAT</code> if the <code>menu_items.price</code> is greater than 0, otherwise only return <code>menu_items.name</code>. I have had, however, no success trying to throw an <code>IF</code> in there. I've read the manual but all the ways that I've tried aren't working and I'm pretty sure I'm missing something on the whole conditional statements thing.</p>
[ { "answer_id": 231846, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 4, "selected": true, "text": "CASE WHEN 'menu_items'.'price' = 0 THEN 'menu.items'.'name' ELSE CONCAT (etc) END \n CONCAT" }, { "answer_id": 231956, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "GROUP_CONCAT(\n CONCAT(\n `menu_items`.`name`, \n IF(`menu_items`.`price` > 0, -- <condition>\n CONCAT(' ($', FORMAT(`menu_items`.`price`,2), ')'), -- <true-expr>\n '' -- <false-expr>\n )\n )\n SEPARATOR '<br>'\n) as `items`,\n IF() IF( <condition>, <true-expr>, <false-expr> )\n <condition> <true-expr> <false-expr>" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16417/" ]
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
[ { "answer_id": 231857, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 3, "selected": false, "text": "class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n some_function = None\n class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n def some_function(self):\n raise NotImplementedError(\"function some_function not implemented\")\n" }, { "answer_id": 231871, "author": "kurosch", "author_id": 30153, "author_profile": "https://Stackoverflow.com/users/30153", "pm_score": 6, "selected": true, "text": ">>> class Foo( object ):\n... def foo( self ):\n... print 'FOO!'\n... \n>>> class Bar( Foo ):\n... def foo( self ):\n... raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n... \n>>> b = Bar()\n>>> b.foo()\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n File \"<interactive input>\", line 3, in foo\nAttributeError: 'Bar' object has no attribute 'foo'\n" }, { "answer_id": 235657, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 4, "selected": false, "text": "b.foo AttributeError import doctest\n\nclass Foo(object):\n \"\"\"\n >>> Foo().foo()\n foo\n \"\"\"\n def foo(self): print 'foo'\n def fu(self): print 'fu'\n\nclass Bar(object):\n \"\"\"\n >>> b = Bar()\n >>> b.foo()\n Traceback (most recent call last):\n ...\n AttributeError\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n def __init__(self): self._wrapped = Foo()\n\n def __getattr__(self, attr_name):\n if attr_name == 'foo': raise AttributeError\n return getattr(self._wrapped, attr_name)\n\nclass Baz(Foo):\n \"\"\"\n >>> b = Baz()\n >>> b.foo() # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AttributeError...\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n foo = property()\n\nif __name__ == '__main__':\n doctest.testmod()\n" }, { "answer_id": 23126120, "author": "Joey Nelson", "author_id": 2600246, "author_profile": "https://Stackoverflow.com/users/2600246", "pm_score": 1, "selected": false, "text": "class Deck(list):\n...\n@staticmethod\n def disabledmethods():\n raise Exception('Function Disabled')\n def pop(self): Deck.disabledmethods()\n def sort(self): Deck.disabledmethods()\n def reverse(self): Deck.disabledmethods()\n def __setitem__(self, loc, val): Deck.disabledmethods()\n" }, { "answer_id": 23126260, "author": "John Damen", "author_id": 2829389, "author_profile": "https://Stackoverflow.com/users/2829389", "pm_score": 4, "selected": false, "text": "class Foo( object ):\n def foo( self ):\n print 'FOO!'\n\nclass Bar( Foo ):\n @property\n def foo( self ):\n raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n\nb = Bar()\nb.foo\n AttributeError" }, { "answer_id": 56771281, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "@property\ndef private(self):\n raise AttributeError\n\nclass A:\n def __init__(self):\n pass\n def hello(self):\n print(\"Hello World\")\n\nclass B(A):\n hello = private # that short, really\n def hi(self):\n A.hello(self)\n\nobj = A()\nobj.hello()\nobj = B()\nobj.hi() # works\nobj.hello() # raises AttributeError\n" }, { "answer_id": 63585320, "author": "Gordon Wrigley", "author_id": 10471, "author_profile": "https://Stackoverflow.com/users/10471", "pm_score": 1, "selected": false, "text": " class NotHereDescriptor:\n def __get__(self, obj, type=None):\n raise AttributeError\n \n class Bar:\n foo = NotHereDescriptor()\n hasattr(Bar, 'foo') False dir(Bar)" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17523/" ]
231,848
<p>The follow code (running in ASP.Net 2.0) displays the contents of the requested URL <strong>twice</strong>. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.</p> <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/xml"; request.ContentLength = postDataBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postDataBytes, 0, postDataBytes.Length); requestStream.Close(); // get response and write to console response = (HttpWebResponse) request.GetResponse(); StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); try { Response.Write(responseReader.ReadToEnd()); } finally { responseReader.Close(); } response.Close(); </code></pre>
[ { "answer_id": 231857, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 3, "selected": false, "text": "class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n some_function = None\n class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n def some_function(self):\n raise NotImplementedError(\"function some_function not implemented\")\n" }, { "answer_id": 231871, "author": "kurosch", "author_id": 30153, "author_profile": "https://Stackoverflow.com/users/30153", "pm_score": 6, "selected": true, "text": ">>> class Foo( object ):\n... def foo( self ):\n... print 'FOO!'\n... \n>>> class Bar( Foo ):\n... def foo( self ):\n... raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n... \n>>> b = Bar()\n>>> b.foo()\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n File \"<interactive input>\", line 3, in foo\nAttributeError: 'Bar' object has no attribute 'foo'\n" }, { "answer_id": 235657, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 4, "selected": false, "text": "b.foo AttributeError import doctest\n\nclass Foo(object):\n \"\"\"\n >>> Foo().foo()\n foo\n \"\"\"\n def foo(self): print 'foo'\n def fu(self): print 'fu'\n\nclass Bar(object):\n \"\"\"\n >>> b = Bar()\n >>> b.foo()\n Traceback (most recent call last):\n ...\n AttributeError\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n def __init__(self): self._wrapped = Foo()\n\n def __getattr__(self, attr_name):\n if attr_name == 'foo': raise AttributeError\n return getattr(self._wrapped, attr_name)\n\nclass Baz(Foo):\n \"\"\"\n >>> b = Baz()\n >>> b.foo() # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AttributeError...\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n foo = property()\n\nif __name__ == '__main__':\n doctest.testmod()\n" }, { "answer_id": 23126120, "author": "Joey Nelson", "author_id": 2600246, "author_profile": "https://Stackoverflow.com/users/2600246", "pm_score": 1, "selected": false, "text": "class Deck(list):\n...\n@staticmethod\n def disabledmethods():\n raise Exception('Function Disabled')\n def pop(self): Deck.disabledmethods()\n def sort(self): Deck.disabledmethods()\n def reverse(self): Deck.disabledmethods()\n def __setitem__(self, loc, val): Deck.disabledmethods()\n" }, { "answer_id": 23126260, "author": "John Damen", "author_id": 2829389, "author_profile": "https://Stackoverflow.com/users/2829389", "pm_score": 4, "selected": false, "text": "class Foo( object ):\n def foo( self ):\n print 'FOO!'\n\nclass Bar( Foo ):\n @property\n def foo( self ):\n raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n\nb = Bar()\nb.foo\n AttributeError" }, { "answer_id": 56771281, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "@property\ndef private(self):\n raise AttributeError\n\nclass A:\n def __init__(self):\n pass\n def hello(self):\n print(\"Hello World\")\n\nclass B(A):\n hello = private # that short, really\n def hi(self):\n A.hello(self)\n\nobj = A()\nobj.hello()\nobj = B()\nobj.hi() # works\nobj.hello() # raises AttributeError\n" }, { "answer_id": 63585320, "author": "Gordon Wrigley", "author_id": 10471, "author_profile": "https://Stackoverflow.com/users/10471", "pm_score": 1, "selected": false, "text": " class NotHereDescriptor:\n def __get__(self, obj, type=None):\n raise AttributeError\n \n class Bar:\n foo = NotHereDescriptor()\n hasattr(Bar, 'foo') False dir(Bar)" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30996/" ]
231,862
<p>I'm working with a MySQL query that writes into an outfile. I run this query once every day or two and so I want to be able to remove the outfile without having to resort to su or sudo. The only way I can think of making that happen is to have the outfile written as owned by someone other than the mysql user. Is this possible?</p> <p>Edit: I am not redirecting output to a file, I am using the INTO OUTFILE part of a select query to output to a file.</p> <p>If it helps:<pre> mysql --version mysql Ver 14.12 Distrib 5.0.32, for pc-linux-gnu (x86_64) using readline 5.2 </pre></p>
[ { "answer_id": 232254, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 3, "selected": false, "text": "mysql db_schema -e 'SELECT col,... FROM table' > /tmp/outfile.txt\n" }, { "answer_id": 3028580, "author": "coder5", "author_id": 365212, "author_profile": "https://Stackoverflow.com/users/365212", "pm_score": 1, "selected": false, "text": "sudo gedit /etc/apparmor.d/usr.sbin.mysqld\n /var/www/codeigniter/assets/download/* w,\n sudo service mysql restart\n SELECT INTO OUTFILE" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447/" ]
231,868
<p>I'm getting a strange error from <code>g++</code> 3.3 in the following code:</p> <pre><code>#include &lt;bitset&gt; #include &lt;string&gt; using namespace std; template &lt;int N, int M&gt; bitset&lt;N&gt; slice_bitset(const bitset&lt;M&gt; &amp;original, size_t start) { string str = original.to_string&lt;char, char_traits&lt;char&gt;, allocator&lt;char&gt; &gt;(); string newstr = str.substr(start, N); return bitset&lt;N&gt;(newstr); } int main() { bitset&lt;128&gt; test; bitset&lt;12&gt; result = slice_bitset&lt;12, 128&gt;(test, 0); return 0; } </code></pre> <p>The error is as follows:</p> <pre> In function `std::bitset slice_bitset(const std::bitset&, unsigned int)': syntax error before `,' token `char_traits' specified as declarator-id two or more data types in declaration of `char_traits' `allocator' specified as declarator-id two or more data types in declaration of `allocator' syntax error before `>' token </pre> <p>It has to be something really silly, but I've already told it to my rubber duck and a friend to no avail.</p> <p>Thanks, Lazyweb.</p>
[ { "answer_id": 231904, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 3, "selected": false, "text": "original.to_string();\n original.template to_string<char, char_traits<char>, allocator<char> >();\n" }, { "answer_id": 231922, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 2, "selected": false, "text": "#include <bitset>\n#include <string>\n\nusing namespace std;\n\ntemplate <int N, int M> \nbitset<N> slice_bitset(const bitset<M> &original, size_t start) \n{ \n string str = original.to_string();\n string newstr = str.substr(start, N); \n return bitset<N>(newstr);\n}\n\nint main() \n{ \n return 0; \n}\n" }, { "answer_id": 239654, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 4, "selected": true, "text": "template <typename T>\nclass B;\n\ntemplate <typename T>\nvoid foo (B<T> & b) {\n // Use 'b' here, even though 'B' not defined\n}\n\ntemplate <typename T>\nclass B\n{\n // Define 'B' here.\n};\n typename template <typename T>\nvoid foo (B<T> & b)\n{\n typename B<T>::X t1; // 'X' is a type - this declares t1\n B<T>::Y * t1; // 'Y' is an object - this is multiplication\n}\n X < template <typename T>\nvoid foo (B<T> & b)\n{\n b.template bar<int> (0); // 'bar' is a template, '<' is start of arg list\n b.Y < 10; // 'Y' is an object, '<' is less than operator\n}\n template < int> template <typename T>\nclass B\n{\n template <typename S>\n void a();\n};\n\ntemplate <typename T>\nvoid foo (B<T> & b)\n{\n b.a < 10; // 'B<int>::a' is a member object\n}\n\ntemplate <>\nclass B<int>\n{\n int a;\n};\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
231,870
<p>I have a separate partition on my disk formatted with FAT32. When I hibernate windows, I want to be able to load another OS, create/modify files that are on that partition, then bring Windows out of hibernation and be able to see the changes that I've made.</p> <p>I know what you're going to type, "Well, you're not supposed to do that!" and then link me to some specs about how what I'm trying to do is wrong/impossible/going to break EVERYTHING. However, I'm sure there's some way I can get around that. :)</p> <p>I don't need the FAT32 partition in Windows, except to read the files that were written there, then I'm done - so whatever the solution is, it's acceptable for the disk to be completely inaccessible for a period of time. Unfortunately, I can't take the entire physical disk offline because it is just a partition of the same physical device that windows is installed on -- just the partition.</p> <p>These are the things I've tried so far...</p> <ol> <li>Google it. I got at least one "this is NEVER going to happen" answer. Unacceptable! :)</li> <li>Unmount the disk before hibernating. Mount after coming out of hibernation. This seems to have no effect. Windows still thinks the FAT is the same as it was before, so whatever data I wrote to disk is lost, and any files I resized are corrupted. If any of the file was cached, it's even worse.</li> <li>Use DeviceIoControl to call IOCTL_DISK_UPDATE_PROPERTIES to try and refresh the disk (but the partition table hasn't changed, so this doesn't really do anything).</li> </ol> <p>Is there any way to invalidate the disk/volume read cache to force windows to go back to the disk? </p> <p>I thought about opening the partition and reading/writing directly by using libfat and bypassing the cache or something is overkill.</p>
[ { "answer_id": 254756, "author": "Nick", "author_id": 30425, "author_profile": "https://Stackoverflow.com/users/30425", "pm_score": 3, "selected": false, "text": "volumeHandle = CreateFile(volumePath,\n GENERIC_READ|GENERIC_WRITE, \n FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,\n OPEN_EXISTING, \n FILE_ATTRIBUTE_NORMAL,\n 0 );\nFlushFileBuffers( volumeHandle );\nDeviceIoControl( volumeHandle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL ) ;\nDeviceIoControl( volumeHandle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL );\n//Keep the handle open here.\n//System hibernates.\n DeviceIoControl( volumeHandle, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL )\nCloseHandle(volumeHandle)\n" }, { "answer_id": 5894535, "author": "Raymond", "author_id": 739462, "author_profile": "https://Stackoverflow.com/users/739462", "pm_score": 1, "selected": false, "text": "\nDISKPART\n  SELECT G\n  REMOVE\n  ASSIGN LETTER=G\nEXIT" }, { "answer_id": 16381001, "author": "Papou", "author_id": 2144456, "author_profile": "https://Stackoverflow.com/users/2144456", "pm_score": 0, "selected": false, "text": "sync; echo 3 > /proc/sys/vm/drop_caches" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30425/" ]
231,885
<p>I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence frequency may be indicative of a race condition, but I don't know why one would cause an exception in this case. Here is the code in question:</p> <pre><code>MyClass::Dostuff() { static map&#60;char, int&#62; mappedChars; if (mappedChars.empty()) { for (char c = '0'; c &#60;= '9'; ++c) { mappedChars[c] = c - '0'; } } // More code here, but mappedChars in not changed. } </code></pre> <p>The exception is thrown in the map's operator[] implementation, on the very first call to the operator[] (Using the VS2005 implementation of STL.)</p> <pre><code> mapped_type& operator[](const key_type& _Keyval) { iterator _Where = this->lower_bound(_Keyval); //exception thrown on the first line // More code here } </code></pre> <p>I already tried freezing threads in operator[] and trying to get them to all run through it at the same time, but I was unable to reproduce the exception using that methodology.</p> <p>Can you think of any reason why that would throw, and only some of the time? </p> <p>(Yes, I know STL is not thread-safe and I'll need to make changes here. I am mostly curious as to WHY I'm seeing the behavior I described above.)</p> <p>As requested, here some further details about the exception:<br> Unhandled exception at 0x00639a1c (app.exe) in app15-51-02-0944_2008-10-23.mdmp: 0xC0000005: Access violation reading location 0x00000004.</p> <p>Thanks to everyone suggesting solutions to multithreading issues, but this isn't what this question is meant to address. Yes, I understand the presented code is not protected correctly and is overkill in what it's trying to accomplish. I already have the fix for it implemented. I'm just trying to get a better understanding of why this exception was thrown to begin with.</p>
[ { "answer_id": 231895, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 2, "selected": false, "text": "DoStuff if (mappedChars.empty())\n empty() static mappedChars" }, { "answer_id": 231921, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 4, "selected": true, "text": "static x y;\n004113ED mov eax,dword ptr [$S1 (418164h)] \n004113F2 and eax,1 \n004113F5 jne wmain+6Ch (41141Ch) \n004113F7 mov eax,dword ptr [$S1 (418164h)] \n004113FC or eax,1 \n004113FF mov dword ptr [$S1 (418164h)],eax \n00411404 mov dword ptr [ebp-4],0 \n0041140B mov ecx,offset y (418160h) \n00411410 call x::x (4111A4h) \n00411415 mov dword ptr [ebp-4],0FFFFFFFFh\n" }, { "answer_id": 232491, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "operator[] 0..9 operator[] int" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22724/" ]
231,886
<p>This may seem like a somewhat contrived example, but I'm left scratching my head.</p> <p>Ok, I have a console app that instantiates a WindowsForm and calls a method called DoSomeWork() on the form.</p> <pre><code>class Program { static void Main(string[] args) { Form1 form = new Form1(); form.DoSomeWork(); } } </code></pre> <p>Form1 looks like this...</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void DoSomeWork() { OuterClass outerClass = new OuterClass(); outerClass.DoSomeWork(); } } </code></pre> <p>Outer class, in turn, looks like this...</p> <pre><code>public class OuterClass { public void DoSomeWork() { InnerClass innerClass = new InnerClass(); innerClass.DoSomeWork(); } } </code></pre> <p>And finally InnerClass looks like this...</p> <pre><code>public class InnerClass { private BackgroundWorker _backgroundWorker = new BackgroundWorker(); public InnerClass() { _backgroundWorker.WorkerReportsProgress = true; _backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork); _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged); } void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { int i = 0; //I've placed a break point here. But it's never hit } void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; worker.ReportProgress(42); } public void DoSomeWork() { _backgroundWorker.RunWorkerAsync(); } } </code></pre> <p>For a reason unknown (to me), the BacgroundWorker in InnerClass never seems to fire the <strong>ProgressChanged</strong> event. If I replace </p> <pre><code>Form1 form = new Form1(); </code></pre> <p>with </p> <pre><code>OuterClass outerClass = new OuterClass() </code></pre> <p>in class Program, it works fine. So why is that my events don't fire when I'm calling the same methods through a Form?</p> <p>Thanks!</p> <p>EDIT: I seemed to be throwing people off by leaving the ProgressChanged event handler as throwing a NotImplementedException, so I've removed it for clarity.</p>
[ { "answer_id": 231894, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "throw NotImplementedException();" }, { "answer_id": 232073, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 4, "selected": true, "text": "static void Main(string[] args)\n{\n Application.Run(new Form1()); \n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6419/" ]