qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
130,803
<p>I'm not that up on VB.NET, the application I'm working on was not written by myself.<br> It works fine through the IDE but once I run it from the exe it gives me the above error.</p> <p>Any clues?</p> <p>This is really hacking me off!</p>
[ { "answer_id": 130831, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 3, "selected": false, "text": "Debugger.Break()\n" }, { "answer_id": 6346654, "author": "Michael Eakins", "author_id": 437301, "author_profile": "https://Stackoverflow.com/users/437301", "pm_score": 0, "selected": false, "text": "stop" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17579/" ]
130,829
<p>I have 3 points in a 3D space of which I know the exact locations. Suppose they are: <code>(x0,y0,z0)</code>, <code>(x1,y1,z1)</code> and <code>(x2,y2,z2)</code>.</p> <p>Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example <code>(x0,y0,z0)</code> will be <code>(x0',y0')</code>, and <code>(x1,y1,z1)</code> will be <code>(x1',y1')</code> and <code>(x2,y2,z2)</code> will be <code>(x2',y2')</code> from the camera's point of view.</p> <p>What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.</p>
[ { "answer_id": 130909, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "a*x0+b*y0+c*z0 = x0'\na*x1+b*y1+c*z1 = x1'\na*x2+b*y2+c*z2 = x2'\n\nd*x0+e*y0+f*z0 = y0'\nd*x1+e*y1+f*z1 = y1'\nd*x2+e*y2+f*z2 = y2'\n ( a, b, c, d ) ( xt )\n( x, y, z, 1 ) ( e, f, g, h ) = ( yt )\n ( i, j, k, l ) ( zt )\n\n( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt;\n a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1\na*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
130,837
<p>I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:</p> <ol> <li>No directories. JUST the file name.</li> <li>File name needs to be all lowercase.</li> <li>Whitespaces need to be replaced with underscores.</li> </ol> <p>Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).</p>
[ { "answer_id": 130845, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 2, "selected": false, "text": "([0-9a-z_-]+[\\.][0-9a-z_-]{1,3})$\n" }, { "answer_id": 139301, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "var parts= path.split('\\\\');\nparts= parts[parts.length-1].split('/');\nvar filename= parts[parts.length-1].toLowerCase();\nfilename= filename.replace(new RegExp('[^a-z0-9]+', 'g'), '_');\nif (filename=='') filename= '_'\n" }, { "answer_id": 147271, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": true, "text": "var a = \"c:\\\\some\\\\path\\\\to\\\\a\\\\file\\\\with Whitespace.TXT\";\na = a.replace(/^.*[\\\\\\/]([^\\\\\\/]*)$/i,\"$1\");\na = a.replace(/\\s/g,\"_\");\na = a.toLowerCase();\nalert(a);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
130,843
<p>Using Prototype 1.6's "new Element(...)" I am trying to create a &lt;table&gt; element with both a &lt;thead&gt; and &lt;tbody&gt; but nothing happens in IE6.</p> <pre><code>var tableProto = new Element('table').update('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Situation Task&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;td&gt;c&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;'); </code></pre> <p>I'm then trying to inject copies of it like this:</p> <pre><code>$$('div.question').each(function(o) { Element.insert(o, { after:$(tableProto.cloneNode(true)) }); }); </code></pre> <p>My current workaround is to create a &lt;div&gt; instead of a &lt;table&gt; element, and then "update" it with all of the table HTML.</p> <p>How does one successfully do this?</p>
[ { "answer_id": 131460, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "var tableProto = new Element('table', { class:'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>');\n var tableProto = new Element('table', { 'class':'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>');\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
130,877
<p>What function will let us know whether a date in VBA is in DST or not?</p>
[ { "answer_id": 130879, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 4, "selected": true, "text": "Public Function NDow(Y As Integer, M As Integer, _\n N As Integer, DOW As Integer) As Date \n\n' Returns Date of Nth Day of the Week in Month \n\nNDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _\n (DOW + 1) Mod 8)) + ((N - 1) * 7)) \n\nEnd Function \n" }, { "answer_id": 34357342, "author": "Pieter Heemeryck", "author_id": 2568944, "author_profile": "https://Stackoverflow.com/users/2568944", "pm_score": 2, "selected": false, "text": "Dim dates As String\ndates = \"A1:A20\"\n\nFor Each c In Worksheets(\"Sheet1\").Range(dates).Cells\n If (IsDateWithinDST(c.Value)) Then\n c.Value = DateAdd(\"h\", 1, c.Value)\n End If\nNext\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
130,878
<p>What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.</p> <h2>Code with Global</h2> <pre><code>$conn = new PDO(...); function getSomething() { global $conn; . . . } </code></pre> <h2>Code with Singleton</h2> <pre><code>class DB_Instance { private static $db; public static function getDBO() { if (!self::$db) self::$db = new PDO(...); return self::$db; } } function getSomething() { $conn = DB_Instance::getDBO(); . . . } </code></pre> <p>If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.</p>
[ { "answer_id": 219599, "author": "Jon Raphaelson", "author_id": 27546, "author_profile": "https://Stackoverflow.com/users/27546", "pm_score": 8, "selected": true, "text": "class ConnectionFactory\n{\n private static $factory;\n private $db;\n\n public static function getFactory()\n {\n if (!self::$factory)\n self::$factory = new ConnectionFactory(...);\n return self::$factory;\n }\n\n public function getConnection() {\n if (!$this->db)\n $this->db = new PDO(...);\n return $this->db;\n }\n}\n\nfunction getSomething()\n{\n $conn = ConnectionFactory::getFactory()->getConnection();\n .\n .\n .\n}\n" }, { "answer_id": 50555311, "author": "Lenin Zapata", "author_id": 3557834, "author_profile": "https://Stackoverflow.com/users/3557834", "pm_score": 0, "selected": false, "text": "<?php // file0.php\n\nfinal class Main_Class\n{\n private static $instance;\n private $time;\n\n private final function __construct()\n {\n $this->time = 0;\n }\n public final static function getInstance() : self\n {\n if (self::$instance instanceof self) {\n return self::$instance;\n }\n\n return self::$instance = new self();\n }\n public final function __clone()\n {\n throw new LogicException(\"Cloning timer is prohibited\");\n }\n public final function __sleep()\n {\n throw new LogicException(\"Serializing timer is prohibited\");\n }\n public final function __wakeup()\n {\n throw new LogicException(\"UnSerializing timer is prohibited\");\n }\n}\n <?php // file1.php\nglobal $YUZO;\n$YUZO = new YUZO; // YUZO is name class\n <?php // file2.php\nglobal $YUZO;\n$YUZO->method1()->run();\n$YUZO->method2( 'parameter' )->html()->print();\n In conclusion:" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
130,894
<p>I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but:</p> <ul> <li>It is an older version (lacking features I need)</li> <li>I need slightly different compile options than the default.</li> </ul> <p>What is the easiest way of doing it? I am concerned about a couple of things</p> <ul> <li>How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.)</li> <li>How I can I prevent the update system installing the older version in the repo on an update?</li> <li>How I can prevent the system installing a newer version (when its out), overwriting my custom package?</li> </ul>
[ { "answer_id": 131090, "author": "Daniel Bungert", "author_id": 21093, "author_profile": "https://Stackoverflow.com/users/21093", "pm_score": 5, "selected": false, "text": "dpkg-buildpackage -us -uc -nc\n echo 'nullidentd hold' | dpkg --set-selections\n nullidentd (99:1.0-4) unstable; urgency=low\n" }, { "answer_id": 133844, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 3, "selected": false, "text": "zcat ~/downloaded.diff.gz | patch -p1\nchmod +x debian/rules\n dpkg-buildpackage -rfakeroot -us -uc\n" }, { "answer_id": 308961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "apt-get install devscripts apt-get build-dep libdrm2\napt-get source libdrm2\ncd libdrm-2.3.1\nuupdate ~/Downloads/libdrm-2.4.1.tar.gz\ncd ../libdrm-2.4.1\ndpkg-buildpackage -us -uc -nc\n" }, { "answer_id": 7996582, "author": "thiton", "author_id": 847601, "author_profile": "https://Stackoverflow.com/users/847601", "pm_score": 1, "selected": false, "text": "pbuilder" }, { "answer_id": 9620733, "author": "Allard Hoeve", "author_id": 1178372, "author_profile": "https://Stackoverflow.com/users/1178372", "pm_score": 1, "selected": false, "text": "apt-get build-dep\n deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free\n apt-get install cowbuilder\n apt-get source cowsay\n\n# do your magic editing\ndpkg-source -b cowsay-3.03+dfsg1 # build the new source packages\ncowbuilder --build cowsay_3.03+dfsg1-2.dsc # build the packages from source\n" }, { "answer_id": 12485164, "author": "Dariusz Cieslak", "author_id": 1681483, "author_profile": "https://Stackoverflow.com/users/1681483", "pm_score": 3, "selected": false, "text": "sudo apt-get update\nsudo apt-get build-dep ccache\napt-get -b source ccache\nsudo dpkg -i ccache*.deb\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
130,898
<p>How can I perform list comprehensions in C#?</p>
[ { "answer_id": 130915, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": -1, "selected": false, "text": "public List<string> ValidUsers(List<User> users) {\n List<string> names = new List<string>();\n foreach(User user in users) {\n if(user.Valid) {\n names.Add(user.Name);\n }\n }\n return names;\n}\n" }, { "answer_id": 130945, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": " return (from user in users\n where user.Valid\n select user.Name).ToArray();\n" }, { "answer_id": 684218, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 6, "selected": false, "text": "[0,2,4,6,8,10,12,14,16,18]\n list = [2*number for number in range(0,10)]\n var list2 = from number in Enumerable.Range(0, 10) select 2*number;\n" }, { "answer_id": 954090, "author": "λ Jonas Gorauskas", "author_id": 11507, "author_profile": "https://Stackoverflow.com/users/11507", "pm_score": 6, "selected": false, "text": "ArrayList evens = new ArrayList();\nArrayList numbers = Range(10);\nint size = numbers.Count;\nint i = 0;\n\nwhile (i < size) \n{\n if (i % 2 == 0) \n {\n evens.Add(i);\n }\n i++;\n}\n IEnumerable<int> numbers = Enumerable.Range(0, 10);\nvar evens = from num in numbers where num % 2 == 0 select num;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21944/" ]
130,913
<p>Is it at the state where it is actually useful and can do more than rename classes?</p>
[ { "answer_id": 130926, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "* Declare Method\n* Extract Baseclass\n* Extract Constant\n* Extract Method\n* Extract Subclass\n* Hide Method\n* Implement Method\n* Move Field / Method\n* Replace Number\n* Separate Class\n* Generate Getters and Setters\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13760/" ]
130,916
<p>I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.</p>
[ { "answer_id": 130983, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 2, "selected": false, "text": "mount -t tmpfs none /mnt/point\n swapiness drop_cache /proc/sys/vm" }, { "answer_id": 154047, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 2, "selected": false, "text": "FILE_FLAG_SEQUENTIAL_SCAN\n FILE_FLAG_NO_BUFFERING\n" }, { "answer_id": 154076, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 3, "selected": true, "text": "posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);\nwhile( bytes > 0 ) {\n bytes = pread(fd, buffer, 64 * 1024, current_pos);\n current_pos += 64 * 1024;\n posix_fadvise(fd, 0, current_pos, POSIX_FADV_DONTNEED);\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15307/" ]
130,941
<p>In a VB.Net Windows Service I'm currently pooling units of work with: </p> <pre><code>ThreadPool.QueueUserWorkItem(operation, nextQueueID) </code></pre> <p>In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: </p> <pre><code> Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString)) With sqlcmd .CommandType = CommandType.Text .CommandText = "UPDATE [some table]" .Parameters.Add("@ID", SqlDbType.Int).Value = msgID .Connection.Open() .ExecuteNonQuery() .Connection.Close() 'Found connections not closed quick enough' End With End Using </code></pre> <p>When running a <code>netstat -a -o</code> on the server I'm seeing about 50 connections to SQL server sitting on <code>IDLE</code> or <code>ESTABLISHED</code>, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. </p> <p>The connection string is global to the application (doesn't change), and has <code>Pooling=true</code> defined as well. </p> <p>Now will each of these threads have their own <code>ConnectionPool</code>, or is there one <code>ConnectionPool</code> for the entire .EXE process?</p>
[ { "answer_id": 131787, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "Using SqlConnection connection = New SqlConnection(ConnString)\n Using sqlcmd As New SqlCommand(\"\", connection) \n With sqlcmd \n ... etc\n End With \n End Using\nEnd Using\n" }, { "answer_id": 429861, "author": "Marcus Erickson", "author_id": 38373, "author_profile": "https://Stackoverflow.com/users/38373", "pm_score": 1, "selected": false, "text": "Using SqlConnection connection = New SqlConnection(ConnString)\n\n TRY\n Using sqlcmd As New SqlCommand(\"\", connection)\n With sqlcmd\n ... etc\n End With\n End Using\n FINALLY\n connection.Close()\n\nEnd Using\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952/" ]
130,948
<p>I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:</p> <pre><code>file = File.open("path-to-file.tar.gz") contents = "" file.each {|line| contents &lt;&lt; line } </code></pre> <p>I thought that would be enough to convert it to a string, but then when I try to write it back out like this...</p> <pre><code>newFile = File.open("test.tar.gz", "w") newFile.write(contents) </code></pre> <p>It isn't the same file. Doing <code>ls -l</code> shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?</p>
[ { "answer_id": 130984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "require 'base64'\n\nfile_contents = Base64.encode64(tar_file_data)\n" }, { "answer_id": 130987, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 4, "selected": false, "text": "contents = File.read(\"e.tgz\")\nnewFile = File.open(\"ee.tgz\", \"w\")\nnewFile.write(contents)\n" }, { "answer_id": 131001, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 10, "selected": true, "text": "file = File.open(\"path-to-file.tar.gz\", \"rb\")\ncontents = file.read\n file.close file" }, { "answer_id": 131096, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 7, "selected": false, "text": "contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }\n" }, { "answer_id": 271300, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "s = File.open(filename, 'rb') { |f| f.read }\n s = IO.read(filename)\n" }, { "answer_id": 4565144, "author": "Alex", "author_id": 197359, "author_profile": "https://Stackoverflow.com/users/197359", "pm_score": 4, "selected": false, "text": "string = File.open('file.txt', 'rb') { |file| file.read }\n" }, { "answer_id": 27103819, "author": "Boris", "author_id": 4092408, "author_profile": "https://Stackoverflow.com/users/4092408", "pm_score": -1, "selected": false, "text": "File.open(\"my_tar.txt\").each {|line| puts line}\n File.new(\"name_file.txt\", \"r\").each {|line| puts line}\n" }, { "answer_id": 30799222, "author": "bardzo", "author_id": 4354686, "author_profile": "https://Stackoverflow.com/users/4354686", "pm_score": 4, "selected": false, "text": "data = IO.binread(path/filaname)\n data = IO.read(path/file)\n" }, { "answer_id": 67305904, "author": "David Moles", "author_id": 27358, "author_profile": "https://Stackoverflow.com/users/27358", "pm_score": 1, "selected": false, "text": "IO.binread IO.read data = File.read(name, {:encoding => 'BINARY'})\n data = File.read(name, encoding: 'BINARY')\n 'BINARY' 'ASCII-8BIT'" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
131,014
<p>I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering <code>COL1</code> and <code>COL2</code> only. </p> <p>So let's say I have something like this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j aa 112 blah_m ab 111 blah_s bb 112 blah_d bb 112 blah_d cc 112 blah_w cc 113 blah_p </code></pre> <p>I need a SQL query that returns this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j bb 112 blah_d bb 112 blah_d </code></pre>
[ { "answer_id": 131018, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "SELECT a.col3, b.col3, a.col1, a.col2 \nFROM tablename a, tablename b\nWHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3\n SELECT a.col3, b.col3, a.col1, a.col2 \nFROM tablename a, tablename b\nWHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3\n AND a.oid < b.oid\n" }, { "answer_id": 131022, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "select\n *\nfrom\n theTable\nwhere\n col1 in\n (\n select\n col1\n from\n theTable\n group by\n col1||col2\n having\n count(col1||col2) > 1\n )\n" }, { "answer_id": 131026, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "select a.*, b.* from table a, table b where a.col1 = b.col1 and a.col2 = b.col2 and a.col3 != b.col3;\n" }, { "answer_id": 131031, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 3, "selected": false, "text": "SELECT a.COL1, a.COL2, a.COL3 \nFROM quux a, quux b\nWHERE a.COL1 = b.COL1 AND a.COL2 = b.COL2 AND a.COL3 <> b.COL3\nORDER BY a.COL1, a.COL2\n COL1 COL2 COL3\n ---------------------\n aa 111 blah_x\n aa 111 blah_j\n SELECT a.COL1, a.COL2, a.COL3\nFROM quux a, quux b\nWHERE a.COL1 = b.COL1 AND a.COL2 = b.COL2 AND a.ID <> b.ID\nORDER BY a.COL1, a.COL2\n COL1 COL2 COL3\n---------------------\naa 111 blah_x\naa 111 blah_j\nbb 112 blah_d\nbb 112 blah_d\n" }, { "answer_id": 131036, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "select t.* from table t\nleft join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2\nwhere c.count > 1\n" }, { "answer_id": 131043, "author": "Jonathan Schuster", "author_id": 21957, "author_profile": "https://Stackoverflow.com/users/21957", "pm_score": 2, "selected": false, "text": "SELECT a.COL1, a.COL2, a.COL3\nFROM YourTable a\nJOIN YourTable b ON b.COL1 = a.COL1 AND b.COL2 = a.COL2 AND b.COL3 <> a.COL3\n" }, { "answer_id": 131057, "author": "IK.", "author_id": 21283, "author_profile": "https://Stackoverflow.com/users/21283", "pm_score": 2, "selected": false, "text": "select COL1,COL2,COL3\nfrom theTable a\nwhere exists (select 'x'\n from theTable b\n where a.col1=b.col1\n and a.col2=b.col2\n and a.col3<>b.col3)\norder by col1,col2,col3\n" }, { "answer_id": 131332, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "select col1, col2, col3\nfrom\n(\nselect col1, col2, col3, count(*) over (partition by col1, col2) rows_per_col1_col2\nfrom table\n)\nwhere rows_per_col1_col2 > 1\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
131,023
<p>I know there is a list-comprehension library for common lisp (<a href="http://superadditive.com/projects/incf-cl/" rel="noreferrer">incf-cl</a>), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme?</p> <p>incf-cl is implemented in CL as a library using macros - shouldn't it be possible to use the same techniques to create one for Scheme?</p>
[ { "answer_id": 131246, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": true, "text": "(require srfi/42)" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
131,025
<p>Is it possible to do at least one of the following:</p> <p>1) Detect a setting of a Local Security Policy (Accounts: Limit local account use of blank passwords to console logon only)</p> <p>2) Modify that setting</p> <p>Using Win32/MFC?</p>
[ { "answer_id": 131246, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": true, "text": "(require srfi/42)" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
131,040
<p>I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:</p> <pre> <code> &lt;mx:Canvas> &lt;mx:Script> [Bindable] public var color:uint; &lt;/mx:Script> &lt;mx:Label text="foobar" color="{color}" /> &lt;/mx:Canvas> </code> </pre> <p>and then add the component in another mxml file, something along the lines of:</p> <pre> <code> &lt;foo:foo_label color="red" /> </code> </pre> <p>When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do</p> <pre><code>&lt;mx:Label text="foobar" color="red"></code></pre> <p>without any problems, and the color property is still type uint. </p> <p>My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special?</p> <p>Thanks.</p>
[ { "answer_id": 132076, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 4, "selected": true, "text": "[Style(name=\"labelColor\", type=\"uint\", format=\"Color\" )]\n" }, { "answer_id": 7631250, "author": "theaibo", "author_id": 825825, "author_profile": "https://Stackoverflow.com/users/825825", "pm_score": 2, "selected": false, "text": " public static function convertUintToString( color:uint ):String { \n return color.toString(16); \n } \n\n public static function convertStringToUint(value:String, mask:String):uint { \n var colorString:String = \"0x\" + value; \n var colorUint:uint = mx.core.Singleton.getInstance(\"mx.styles::IStyleManager2\").getColorName( colorString ); \n\n return colorUint; \n } \n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
131,049
<p>I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips &amp; tricks from somebody's blog. How do I make the copied content appear in a box with border?</p> <p>For example, the box at the end of this blog post looks pretty nice:<br> <a href="http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/" rel="noreferrer">http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/</a></p> <p>I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?</p>
[ { "answer_id": 131330, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 2, "selected": false, "text": "<div style=\"background-color: cyan; border-style: dashed;\">\nA bunch of text that will wrap.\n</div>\n" }, { "answer_id": 131757, "author": "Oddmund", "author_id": 4417, "author_profile": "https://Stackoverflow.com/users/4417", "pm_score": 5, "selected": false, "text": "<blockquote style=\"background-color: lightgrey; border: solid thin grey;\">\nDet er jeg som kjenner hemmeligheten din. Ikke et pip, gutten min.\n</blockquote>\n" }, { "answer_id": 131886, "author": "SamS", "author_id": 14068, "author_profile": "https://Stackoverflow.com/users/14068", "pm_score": 5, "selected": false, "text": "<div style=\"background-color: #ddf5eb; border-style: dotted;\">\n{{{1}}}\n</div>\n" }, { "answer_id": 12389988, "author": "scubasteve", "author_id": 478810, "author_profile": "https://Stackoverflow.com/users/478810", "pm_score": 4, "selected": false, "text": "<blockquote style=\"color: lightgrey; border: solid thin gray;\">\n {{{1}}}\n</blockquote>\n {{ quote | The text you want to quote }}\n" }, { "answer_id": 21567312, "author": "Genteel", "author_id": 3273356, "author_profile": "https://Stackoverflow.com/users/3273356", "pm_score": 0, "selected": false, "text": "<pre width=\"80%\">\n" }, { "answer_id": 30355475, "author": "Jeff Albrecht", "author_id": 884630, "author_profile": "https://Stackoverflow.com/users/884630", "pm_score": 2, "selected": false, "text": "<blockquote style=\"\n color: black;\n border: solid thin gray;\n padding-top: 10px;\n padding-right: 10px;\n padding-bottom: 10px;\n padding-left: 10px;\n \">\n{{{1}}}\n</blockquote>\n" }, { "answer_id": 43711388, "author": "Johnny Baloney", "author_id": 779449, "author_profile": "https://Stackoverflow.com/users/779449", "pm_score": 1, "selected": false, "text": "index.php?title=MediaWiki:Common.css <blockquote/> blockquote {\n background-color: #ddf5eb; \n border-style: dotted;\n}\n <pre/> pre {\n white-space: pre-wrap;\n white-space: -moz-pre-wrap; \n white-space: -pre-wrap; \n white-space: -o-pre-wrap; \n word-wrap: break-word;\n}\n <syntaxhighlight/> <source/> style" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068/" ]
131,050
<p>Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.</p> <p>I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.</p> <p>The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?</p>
[ { "answer_id": 131294, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 0, "selected": false, "text": "public class Foo {\n private static var instance : Foo;\n\n public Foo() {\n if( instance != null ) { \n throw new Exception (\"Singleton constructor called\");\n }\n instance = this;\n }\n\n public static getInstance() : Foo {\n if( instance == null ) {\n instance = new Foo();\n }\n return instance;\n }\n\n} \n" }, { "answer_id": 131340, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 0, "selected": false, "text": "package some.pack\n{\n public class Foo\n {\n public Foo(f : CheckFoo)\n {\n if (f == null) throw new Exception(...);\n }\n }\n\n static private inst : Foo;\n static public getInstance() : Foo\n {\n if (inst == null)\n inst = new Foo(new CheckFoo());\n return inst;\n }\n}\n\nclass CheckFoo\n{\n}\n" }, { "answer_id": 132003, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "package {\n public final class Singleton {\n private static var instance:Singleton = new Singleton();\n\n public function Singleton() {\n if( Singleton.instance ) {\n throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" ); \n }\n }\n\n public static function getInstance():Singleton { \n return Singleton.instance;\n }\n }\n}\n" }, { "answer_id": 132846, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 5, "selected": true, "text": "package {\n public class Singleton {\n\n private static var _instance:Singleton;\n\n public function Singleton(enforcer:SingletonEnforcer) {\n if( !enforcer) \n {\n throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" ); \n }\n }\n\n public static function get instance():Singleton\n {\n if(!Singleton._instance)\n {\n Singleton._instance = new Singleton(new SingletonEnforcer());\n }\n\n return Singleton._instance;\n }\n}\n\n}\nclass SingletonEnforcer{}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
131,053
<p>I have been getting an error in <strong>VB .Net</strong> </p> <blockquote> <p>object reference not set to an instance of object.</p> </blockquote> <p>Can you tell me what are the causes of this error ?</p>
[ { "answer_id": 131055, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "Option Strict On\nOption Explicit On\n" }, { "answer_id": 131098, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "Nothing null Option Strict On Option Explicit On Dim someString As String = someFunctionReturningString();\nIf ( someString Is Nothing ) Then\n Sysm.Console.WriteLine(someString.Length); // will throw the NullReferenceException\nEnd If\n" }, { "answer_id": 131175, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": true, "text": " dsData = getSQLData(conn,sql, blah,blah....)\n dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here\n dsData = getSQLData(conn,sql, blah,blah....)\n If dsData.Tables.Count = 0 Then Exit Sub\n dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here\n" }, { "answer_id": 131177, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 2, "selected": false, "text": "Dim result As String = SqlCommand.ExecuteScalar() 'just for scope'\nIf result Is Nothing OrElse IsDBNull(result) Then\n 'no result!'\nEnd If\n" }, { "answer_id": 131190, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": "Dim objDt as DataTable = objDs.Tables(\"tablename\")\n" }, { "answer_id": 6680958, "author": "Andrew Neely", "author_id": 825386, "author_profile": "https://Stackoverflow.com/users/825386", "pm_score": 3, "selected": false, "text": "Dim aPerson as PersonClass\n Dim aPerson as New PersonClass\n If aPerson Is Nothing Then\n aPerson = New PersonClass\nEnd If\n" }, { "answer_id": 49980059, "author": "Menuka Ishan", "author_id": 2940265, "author_profile": "https://Stackoverflow.com/users/2940265", "pm_score": 0, "selected": false, "text": "Dim cmd As IDbCommand\ncmd.Parameters.Clear()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
131,056
<p>Not sure how to ask a followup on SO, but this is in reference to an earlier question: <a href="https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list">Fetch one row per account id from list</a></p> <p>The query I'm working with is:</p> <pre><code>SELECT * FROM scores s1 WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score &lt; s2.score) ORDER BY score DESC </code></pre> <p>This selects the top scores, and limits results to one row per accountid; their top score.</p> <p>The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.</p> <p>Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?</p> <p>Thanks again!</p>
[ { "answer_id": 131060, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT UserID, score\nFROM scores s1\nWHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)\nORDER BY score DESC\n" }, { "answer_id": 131066, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "select accountid, max(score) from scores group by accountid;\n" }, { "answer_id": 131322, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "select ...\nfrom (\n select accountid,\n score,\n ...\n row_number() over \n (partition by accountid\n order by score desc) score_rank\n from scores)\nwhere score_rank = 1;\n select ...\nfrom (\n select accountid,\n score,\n ...\n max(score) over (partition by accountid) max_score\n from scores)\nwhere score = max_score;\n" }, { "answer_id": 131877, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "SELECT accountid, MAX(score) \nFROM scores \nGROUP BY accountid;\n SELECT s1.*\nFROM scores AS s1\n LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid \n AND s1.score < s2.score)\nWHERE s2.accountid IS NULL;\n SELECT s1.*\nFROM scores AS s1\n LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid \n AND s1.score < s2.score)\n LEFT OUTER JOIN scores AS s3 ON (s1.accountid = s3.accountid \n AND s1.score = s3.score AND s1.gamedate < s3.gamedate) \nWHERE s2.accountid IS NULL\n AND s3.accountid IS NULL;\n" }, { "answer_id": 132828, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM scores\nWHERE scoreid in\n(\n SELECT max(scoreid)\n FROM scores as s2\n JOIN\n (\n SELECT max(score) as maxscore, accountid\n FROM scores s1\n GROUP BY accountid\n ) sub ON s2.score = sub.maxscore AND s2.accountid = s1.accountid\n GROUP BY s2.score, s2.accountid\n)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
131,062
<p>I've read numerous posts about people having problems with <code>viewWillAppear</code> when you do not create your view hierarchy <em>just</em> right. My problem is I can't figure out what that means.</p> <p>If I create a <code>RootViewController</code> and call <code>addSubView</code> on that controller, I would expect the added view(s) to be wired up for <code>viewWillAppear</code> events. </p> <p>Does anyone have an example of a complex programmatic view hierarchy that successfully receives <code>viewWillAppear</code> events at every level?</p> <p>Apple's Docs state:</p> <blockquote> <p>Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.</p> </blockquote> <p>The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view?</p> <p>I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.</p>
[ { "answer_id": 135418, "author": "Josh Gagnon", "author_id": 7944, "author_profile": "https://Stackoverflow.com/users/7944", "pm_score": 3, "selected": false, "text": "[self.navigationController pushViewController:<view> animated:<BOOL>];\n viewWillAppear addSubView" }, { "answer_id": 144935, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 5, "selected": false, "text": "viewWillAppear [myViewController viewWillAppear:NO];\n" }, { "answer_id": 179151, "author": "Martin Gordon", "author_id": 2481, "author_profile": "https://Stackoverflow.com/users/2481", "pm_score": 1, "selected": false, "text": "-addSubview: [viewController.view addSubview:anotherViewController.view]" }, { "answer_id": 211091, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": false, "text": "navigationController:willShowViewController:animated:\nnavigationController:didShowViewController:animated:\n" }, { "answer_id": 2057427, "author": "Antoine", "author_id": 249885, "author_profile": "https://Stackoverflow.com/users/249885", "pm_score": 3, "selected": false, "text": "UINavigationController viewWillAppear viewWillAppear [super viewWillAppear:animated];\n" }, { "answer_id": 4229031, "author": "Andrew", "author_id": 513938, "author_profile": "https://Stackoverflow.com/users/513938", "pm_score": 1, "selected": false, "text": "ViewWillAppear UITableViewController UINavigationController UITableView" }, { "answer_id": 4241990, "author": "AndrewS", "author_id": 173964, "author_profile": "https://Stackoverflow.com/users/173964", "pm_score": 2, "selected": false, "text": "[view addSubview:subview] [view addSubview:subviewController.view] [subviewController viewWillAppear:NO]" }, { "answer_id": 4256538, "author": "Gaurav", "author_id": 437149, "author_profile": "https://Stackoverflow.com/users/437149", "pm_score": 1, "selected": false, "text": "[self.navigationController setDelegate:self];\n" }, { "answer_id": 4355780, "author": "hol", "author_id": 382009, "author_profile": "https://Stackoverflow.com/users/382009", "pm_score": 2, "selected": false, "text": "- (void) viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n [subNavCntlr viewWillAppear:animated];\n}\n\n- (void) viewWillDisappear:(BOOL)animated\n{\n [super viewWillDisappear:animated];\n\n [subNavCntlr viewWillDisappear:animated];\n}\n - (void)viewDidLoad {\n\n // This is the root View Controller\n rootTable *rootTableController = [[rootTable alloc]\n initWithStyle:UITableViewStyleGrouped];\n\n subNavCntlr = [[UINavigationController alloc] \n initWithRootViewController:rootTableController];\n\n [rootTableController release];\n\n subNavCntlr.view.frame = subNavContainer.bounds;\n\n [subNavContainer addSubview:subNavCntlr.view];\n\n [super viewDidLoad];\n}\n @interface navTestViewController : UIViewController <UINavigationControllerDelegate> {\n IBOutlet UIView *subNavContainer;\n UINavigationController *subNavCntlr;\n}\n\n@end\n" }, { "answer_id": 4508301, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 4, "selected": false, "text": "UINavigationControllerDelegate" }, { "answer_id": 6833875, "author": "Sam", "author_id": 135700, "author_profile": "https://Stackoverflow.com/users/135700", "pm_score": 2, "selected": false, "text": "UITabBarDelegate UINavigationBarDelegate [tabBarController viewWillAppear:NO];\n[tabBarController viewDidAppear:NO];\n [navBarController viewWillAppear:NO];\n[navBarController viewDidAppear:NO];\n window\n UITabBarController (subclass of)\n UIViewController (subclass of) // <-- manually calls [navController viewWill/DidAppear\n UINavigationController (subclass of)\n UIViewController (subclass of) // <-- still receives viewWill/Did..etc all the way down from a tab switch at the top of the chain without needing to use ANY delegate methods\n UINavigationBarDelegate UITabBarControllerDelegate - (void)transitionFromViewController:(UIViewController*)aFromViewController toViewController:(UIViewController*)aToViewController \n viewWill/Did.. UITabBarController" }, { "answer_id": 8157562, "author": "Sean", "author_id": 934741, "author_profile": "https://Stackoverflow.com/users/934741", "pm_score": -1, "selected": false, "text": "- (void)viewWillAppear:(BOOL)animated\n{\n [self performSelector:@selector(methodOne) \n withObject:nil afterDelay:0];\n}\n" }, { "answer_id": 11152273, "author": "Arash Zeinoddini", "author_id": 1391007, "author_profile": "https://Stackoverflow.com/users/1391007", "pm_score": 2, "selected": false, "text": "[self.navigationController pushViewController:detaiViewController animated:YES];\n[detailNewsViewController viewWillAppear:YES];\n [[self.navigationController popViewControllerAnimated:YES] viewWillAppear:YES];\n" }, { "answer_id": 20402075, "author": "gdm", "author_id": 778508, "author_profile": "https://Stackoverflow.com/users/778508", "pm_score": 2, "selected": false, "text": "UIView* a UIView* b" }, { "answer_id": 31682471, "author": "Hari Kunwar", "author_id": 3892773, "author_profile": "https://Stackoverflow.com/users/3892773", "pm_score": 2, "selected": false, "text": "- (void)viewDidLoad {\n [super viewDidLoad];\n // Do any additional setup after loading the view.\n UIViewController *viewController = ...;\n [self addChildViewController:viewController];\n [self.view addSubview:viewController.view];\n [viewController didMoveToParentViewController:self];\n}\n" }, { "answer_id": 52944364, "author": "ober", "author_id": 1668686, "author_profile": "https://Stackoverflow.com/users/1668686", "pm_score": 1, "selected": false, "text": "modalPresentationStyle = .custom viewWillAppear beginAppearanceTransition endAppearanceTransition" }, { "answer_id": 53863204, "author": "Vadim Motorine", "author_id": 6918530, "author_profile": "https://Stackoverflow.com/users/6918530", "pm_score": 1, "selected": false, "text": "protocol MyViewWillAppearProtocol{func myViewWillAppear()}\n class ForceUpdateOnViewAppear: NSObject, UINavigationControllerDelegate {\nfunc navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool){\n if let updatedCntllr: MyViewWillAppearProtocol = viewController as? MyViewWillAppearProtocol{\n updatedCntllr.myViewWillAppear()\n }\n}\n" }, { "answer_id": 56599649, "author": "BilalReffas", "author_id": 4142753, "author_profile": "https://Stackoverflow.com/users/4142753", "pm_score": 4, "selected": false, "text": "ViewWillDisappear ViewDidDisappear ViewWillAppear ViewDidAppear" }, { "answer_id": 58416153, "author": "dollardime", "author_id": 972024, "author_profile": "https://Stackoverflow.com/users/972024", "pm_score": 2, "selected": false, "text": "yourVC.modalPresentationStyle = UIModalPresentationFullScreen;\n" }, { "answer_id": 61223070, "author": "user2385491", "author_id": 2385491, "author_profile": "https://Stackoverflow.com/users/2385491", "pm_score": 0, "selected": false, "text": " viewWillAppear(true)\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21964/" ]
131,068
<p>The Date object in JavaScript performs differently machine to machine and browser to browser in respect to the function's resolution in milliseconds. I've found most machines have a resolution of about 16 ms on IE, where Chrome or Firefox may have a resolution as good as 1ms.</p> <p>Is there another function available to JavaScript in general or IE specifically that will give a better time resolution? I am trying to trap and record <code>keyDown</code> and <code>keyUp</code> times in milliseconds and need it in the +/- 10 ms range or less.</p> <p>To see an illustration of this, check out the "resolutions of new date()" section of this page. There is a table with a test button that evaluates the current machine/browser's JavaScript time resolution in milliseconds. Interestingly, Chrome regularly gets a resolution of 1ms. </p> <p><a href="http://www.merlyn.demon.co.uk/js-dates.htm#OV" rel="nofollow noreferrer">http://www.merlyn.demon.co.uk/js-dates.htm#OV</a> </p> <p>My quest is for a JavaScript date-time method that will give sub 10ms resolution across browsers. something to replace or improve Date().</p>
[ { "answer_id": 131262, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 2, "selected": false, "text": "System.currentTimeMillis()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21965/" ]
131,085
<p>I would like to create a copy of a database with approximately 40 InnoDB tables and around 1.5GB of data with mysqldump and MySQL 5.1.</p> <p>What are the best parameters (ie: --single-transaction) that will result in the quickest dump and load of the data?</p> <p>As well, when loading the data into the second DB, is it quicker to:</p> <p>1) pipe the results directly to the second MySQL server instance and use the --compress option</p> <p>or</p> <p>2) load it from a text file (ie: mysql &lt; my_sql_dump.sql)</p>
[ { "answer_id": 131114, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "--compress" }, { "answer_id": 4383629, "author": "Dave Dopson", "author_id": 407731, "author_profile": "https://Stackoverflow.com/users/407731", "pm_score": 5, "selected": false, "text": "nc -l 7878 > mysql-dump.sql\n mysqldump $OPTS | nc myhost.mydomain.com 7878\n --opt --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16447/" ]
131,091
<p>I setup my own open id provider on my personal server, and added a redirect to https in my apache config file. When not using a secure connection (when I disable the redirect) I can log in fine, but with the redirect I can't log in with this error message:</p> <p>The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.</p> <p>I'm guessing that this is because I am using a self signed certificate.</p> <p>Can anyone confirm if the self signed certificate is the issue? If not does anyone have any ideas what the problem is?</p>
[ { "answer_id": 239138, "author": "Yang Zhao", "author_id": 31095, "author_profile": "https://Stackoverflow.com/users/31095", "pm_score": 3, "selected": false, "text": "checkid_immediate checkid_setup // Redirect OpenID authentication requests to https:// of same URL\n// Assuming valid OpenID operation over GET\nif (!isset($_SERVER['HTTPS']) &&\n ($_GET['openid_mode'] == 'checkid_immediate' ||\n $_GET['openid_mode'] == 'checkid_setup'))\n http_redirect(\"https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}\");\n openid.return_to secure checkid_immediate" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
131,110
<p>I am creating an HTTP handler that listens for calls to a specific file type, and handles it accordingly. My HTTP Handler listens for .bcn files, then writes a cookie to the user's computer and sends back an image... this will be used in advertising banners so that the user is tagged as seeing the banner, and we can then offer special deals when they visit our site later.</p> <p>The problem i'm having is getting access to the Page object... of course an HTTPHandler is not actually a page, and since the Response object lives within the Page object, I can't get access to it to write the cookie.</p> <p>Is there a way around this, or do i need to revert back to just using a standard aspx page to do this?</p> <p>Thanks heaps.. Greg</p>
[ { "answer_id": 131152, "author": "Jeeby", "author_id": 21969, "author_profile": "https://Stackoverflow.com/users/21969", "pm_score": 0, "selected": false, "text": "HttpContext.Current.Response.Cookies.Add(cookie);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
131,116
<p>I'm wondering if updating statistics has helped you before and how did you know to update them?</p>
[ { "answer_id": 131168, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": true, "text": "exec sp_updatestats\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
131,121
<p>If I have a Range object--for example, let's say it refers to cell <code>A1</code> on a worksheet called <code>Book1</code>. So I know that calling <code>Address()</code> will get me a simple local reference: <code>$A$1</code>. I know it can also be called as <code>Address(External:=True)</code> to get a reference including the workbook name and worksheet name: <code>[Book1]Sheet1!$A$1</code>.</p> <p>What I want is to get an address including the sheet name, but not the book name. I really don't want to call <code>Address(External:=True)</code> and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get <code>Sheet1!$A$1</code>?</p>
[ { "answer_id": 131155, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 7, "selected": true, "text": "Dim cell As Range\nDim cellAddress As String\nSet cell = ThisWorkbook.Worksheets(1).Cells(1, 1)\ncellAddress = cell.Parent.Name & \"!\" & cell.Address(External:=False)\n cellAddress = \"'\" & cell.Parent.Name & \"'!\" & cell.Address(External:=False) \n" }, { "answer_id": 131185, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 2, "selected": false, "text": "Dim cell As Range\nDim address As String\nSet cell = Worksheets(1).Cells.Range(\"A1\")\naddress = cell.address(External:=True)\naddress = Right(address, Len(address) - InStr(1, address, \"]\"))\n" }, { "answer_id": 688610, "author": "TimS", "author_id": 83470, "author_profile": "https://Stackoverflow.com/users/83470", "pm_score": -1, "selected": false, "text": "Dim cell as Range\nDim address as String\nSet cell = Sheet1.Range(\"A1\")\naddress = cell.Name\n address = Replace(address, \"=\", \"\")\n" }, { "answer_id": 1266074, "author": "raph82", "author_id": 113885, "author_profile": "https://Stackoverflow.com/users/113885", "pm_score": 2, "selected": false, "text": "Address() Application.WorksheetFunction Evaluate() Evaluate(\"ADDRESS(\" & rng.Row & \",\" & rng.Column & \",1,1,\"\"\" & _\n rng.Worksheet.Name & \"\"\")\")\n Range rng Public Function AddressEx(rng As Range) As String\n\n Dim strTmp As String\n\n strTmp = Evaluate(\"ADDRESS(\" & rng.Row & \",\" & _\n rng.Column & \",1,1,\"\"\" & rng.Worksheet.Name & \"\"\")\")\n\n If (rng.Count > 1) Then\n\n strTmp = strTmp & \":\" & rng.Cells(rng.Count) _\n .Address(RowAbsolute:=True, ColumnAbsolute:=True)\n\n End If\n\n AddressEx = strTmp\n\nEnd Function\n" }, { "answer_id": 5432001, "author": "rinku", "author_id": 676637, "author_profile": "https://Stackoverflow.com/users/676637", "pm_score": -1, "selected": false, "text": "Dim rg As Range\nSet rg = Range(\"A1:E10\")\nDim i As Integer\nFor i = 1 To rg.Rows.Count\n\n For j = 1 To rg.Columns.Count\n rg.Cells(i, j).Value = rg.Cells(i, j).Address(False, False)\n\n Next\nNext\n" }, { "answer_id": 17954921, "author": "Luciano Evaristo Guerche", "author_id": 2635415, "author_profile": "https://Stackoverflow.com/users/2635415", "pm_score": 4, "selected": false, "text": "Split(cell.address(External:=True), \"]\")(1)\n" }, { "answer_id": 24112118, "author": "Jeff", "author_id": 3720789, "author_profile": "https://Stackoverflow.com/users/3720789", "pm_score": 0, "selected": false, "text": "Function SumRange(RangeName as range) \n\nDim strCellRef, strSheetName, strRngName As String\n\nstrCellRef = RangeName.Address \nstrSheetName = RangeName.Worksheet.Name & \"!\" \nstrRngName = strSheetName & strCellRef \n" }, { "answer_id": 28025767, "author": "HarveyFrench", "author_id": 4413676, "author_profile": "https://Stackoverflow.com/users/4413676", "pm_score": 0, "selected": false, "text": "Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String\n\n Const Seperator As String = \",\"\n\n Dim WorksheetName As String\n Dim TheAddress As String\n Dim Areas As Areas\n Dim Area As Range\n\n WorksheetName = \"'\" & Range.Worksheet.Name & \"'\"\n\n For Each Area In Range.Areas\n' ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12\n TheAddress = TheAddress & WorksheetName & \"!\" & Area.Address(External:=False) & Seperator\n\n Next Area\n\n GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))\n\n If blnBuildAddressForNamedRangeValue Then\n GetAddressWithSheetname = \"=\" & GetAddressWithSheetname\n End If\n\nEnd Function\n" }, { "answer_id": 38344905, "author": "ArnonK", "author_id": 6583035, "author_profile": "https://Stackoverflow.com/users/6583035", "pm_score": 0, "selected": false, "text": "rngYourRange.Address(,,,TRUE)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6209/" ]
131,128
<p>Short version: I'm wondering if it's possible, and how best, to utilise CPU specific instructions within a DLL?</p> <p>Slightly longer version: When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.</p> <p>Does this mean that they are strictly built for the lowest common denominator (ie. the minimum platform supported by the OS)? Or is there some technique that is used to export a single interface within the DLL but utilise CPU specific code behind the scenes to get optimal performance? And if so, how is it done?</p>
[ { "answer_id": 131203, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": true, "text": "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\n" }, { "answer_id": 131251, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "/arch" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11694/" ]
131,164
<p>I have a number of code value tables that contain a code and a description with a Long id.</p> <p>I now want to create an entry for an Account Type that references a number of codes, so I have something like this:</p> <pre><code>insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_type_standard_seq.nextval, ts.tax_status_id, r.recipient_id from tax_status ts, recipient r where ts.tax_status_code = ? and r.recipient_code = ?) </code></pre> <p>This retrieves the appropriate values from the tax_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table.</p> <p>I've tried using NVL on the ? and on the r.recipient_id. </p> <p>I've tried to force an outer join on the r.recipient_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row.</p> <p>Anyone know of a way of doing this?</p> <p>I can obviously modify the statement so that I do the lookup of the recipient_id externally, and have a ? instead of r.recipient_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.</p>
[ { "answer_id": 131183, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 6, "selected": true, "text": "INSERT INTO account_type_standard \n (account_type_Standard_id, tax_status_id, recipient_id) \nVALUES( \n (SELECT account_type_standard_seq.nextval FROM DUAL),\n (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), \n (SELECT recipient_id FROM recipient WHERE recipient_code = ?)\n)\n (SELECT account_type_standard_seq.nextval FROM DUAL),\n account_type_standard_seq.nextval,\n" }, { "answer_id": 131554, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "insert into account_type_standard \n(account_type_Standard_id, tax_status_id, recipient_id)\n(\nselect \n account_type_standard_seq.nextval,\n ts.tax_status_id, \n r.recipient_id\nfrom tax_status ts, recipient r\nwhere (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))\nand (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))\n" }, { "answer_id": 132705, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)\nselect account_type_standard_seq.nextval,\n ts.tax_status_id, \n ( select r.recipient_id\n from recipient r\n where r.recipient_code = ?\n )\nfrom tax_status ts\nwhere ts.tax_status_code = ?\n" }, { "answer_id": 138674, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "INSERT INTO account_type_standard \n (account_type_Standard_id, tax_status_id, recipient_id) \nVALUES( \n account_type_standard_seq.nextval,\n (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),\n (SELECT recipient_id FROM recipient WHERE recipient_code = ?)\n)\n" }, { "answer_id": 2872150, "author": "Arjun", "author_id": 345895, "author_profile": "https://Stackoverflow.com/users/345895", "pm_score": -1, "selected": false, "text": "insert into received_messages(id, content, status)\n values (RECEIVED_MESSAGES_SEQ.NEXT_VAL, empty_blob(), '');\n" }, { "answer_id": 13601299, "author": "paparao", "author_id": 1859208, "author_profile": "https://Stackoverflow.com/users/1859208", "pm_score": 1, "selected": false, "text": "insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)\nselect account_type_standard_seq.nextval,\n ts.tax_status_id, \n ( select r.recipient_id\n from recipient r\n where r.recipient_code = ?\n )\nfrom tax_status ts\nwhere ts.tax_status_code = ?\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5382/" ]
131,179
<p>Trying to install the RMagick gem is failing with an error about being unable to find ImageMagick libraries, even though I'm sure they are installed.</p> <p>The pertinent output from gem install rmagick is:</p> <pre><code>checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.6.0. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** </code></pre> <p>And looking in mkmf.log reveals:</p> <pre><code>have_library: checking for InitializeMagick() in -lMagick... -------------------- no "/usr/local/bin/gcc -o conftest -I. -I/usr/local/lib/ruby/1.8/i386-solaris2.10 -I. -I/usr/local/include/ImageMagick -I/usr/local/include/ImageMagick conftest.c -L. - L/usr/local/lib -Wl,-R/usr/local/lib -L/usr/local/lib -L/usr/local/lib -R/usr/local/lib -lfreetype -lz -L/usr/local/lib -L/usr/local/lib -lMagickCore -lruby-static - lMagick -ldl -lcrypt -lm -lc" ld: fatal: library -lMagick: not found ld: fatal: File processing errors. No output written to conftest </code></pre> <p>This is on Solaris 10 x86 with ImageMagick version 6.4.3 and RMagick version 2.6.0</p> <p>If I need to add something to LDFLAGS, its not clear to me what that would be. I installed ImageMagick from source and it should be in the usual places. ie,</p> <pre><code># ls -l /usr/local/lib/ | grep -i magick drwxr-xr-x 5 root root 512 Sep 24 23:09 ImageMagick-6.4.3/ -rw-r--r-- 1 root root 10808764 Sep 25 02:09 libMagickCore.a -rwxr-xr-x 1 root root 1440 Sep 25 02:09 libMagickCore.la* -rw-r--r-- 1 root root 2327072 Sep 25 02:09 libMagickWand.a -rwxr-xr-x 1 root root 1472 Sep 25 02:09 libMagickWand.la* </code></pre> <p>ImageMagick-6.4.3/ contains nothing interesting and I can't find any other files that I might be able to point gem install at.</p> <p>Any advice would be much appreciated!! googling hasn't been too helpful.</p> <p>thanks -</p>
[ { "answer_id": 149490, "author": "rory", "author_id": 8063, "author_profile": "https://Stackoverflow.com/users/8063", "pm_score": 3, "selected": true, "text": "--with-shared make export CFLAGS=\"-liconv\"\n ./configure --disable-static --with-modules --without-perl --with-quantum-depth=8 --with-bzlib=no --with-libiconv\n make make install gem install rmagick" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8063/" ]
131,196
<p>I am interested in calling <a href="http://sourceforge.net/projects/sox" rel="nofollow noreferrer">SoX</a>, an open source console application, from another Windows GUI program (written in Delphi naturally). Instead of dealing with scraping and hiding the console window, I would like to just convert the application to a DLL that I can call from my application. </p> <p>Before I start down this path I am curious how much work I should expect to be in for? Are we talking a major undertaking, or is there a straight forward solution? I know some C, but am by no means an expert. </p> <p>I am not expecting SoX specific details, just EXE console application conversion to DLL in general. If someone is familiar with SoX though, even better.</p>
[ { "answer_id": 131396, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 2, "selected": false, "text": "LIBRARY \"name.DLL\" \n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255/" ]
131,241
<p>Take the following two lines of code:</p> <pre><code>for (int i = 0; i &lt; some_vector.size(); i++) { //do stuff } </code></pre> <p>And this:</p> <pre><code>for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } </code></pre> <p>I'm told that the second way is preferred. Why exactly is this?</p>
[ { "answer_id": 131254, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "for(size_t i = 0; i < myvector.size(); i++)\n{\n MyClass &item = myvector[i];\n\n // Do stuff to \"item\".\n}\n" }, { "answer_id": 131271, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 9, "selected": true, "text": "T elem = some_vector[i];\n operator[](std::size_t) size() std::for_each() std::transform()" }, { "answer_id": 131304, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "int size_type for (std::vector<Foo>::size_type i = 0; i < myvector.size(); ++i)\n{\n Foo& this_foo = myvector[i];\n // Do stuff with this_foo\n}\n" }, { "answer_id": 131319, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 5, "selected": false, "text": "some_iterator = some_vector.begin(); \nwhile (some_iterator != some_vector.end())\n{\n if (/* some condition */)\n {\n some_iterator = some_vector.erase(some_iterator);\n // some_iterator now positioned at the element after the deleted element\n }\n else\n {\n if (/* some other condition */)\n {\n some_iterator = some_vector.insert(some_iterator, some_new_value);\n // some_iterator now positioned at new element\n }\n ++some_iterator;\n }\n}\n" }, { "answer_id": 131324, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "\nfor(std::vector<Foo>::const_iterator pos=foos.begin(); pos != foos.end(); ++pos)\n{\n // Foo & foo = *pos; // this won't compile\n const Foo & foo = *pos; // this will compile\n}\n" }, { "answer_id": 131725, "author": "Krirk", "author_id": 17521, "author_profile": "https://Stackoverflow.com/users/17521", "pm_score": 0, "selected": false, "text": "some_vector[0].left=0;\nsome_vector[0].top =0;<br>\n\nfor (int i = 1; i < some_vector.size(); i++)\n{\n\n some_vector[i].left = some_vector[i-1].width + some_vector[i-1].left;\n if(i % 6 ==0)\n {\n some_vector[i].top = some_vector[i].top.height + some_vector[i].top;\n some_vector[i].left = 0;\n }\n\n}\n" }, { "answer_id": 132125, "author": "user22044", "author_id": 22044, "author_profile": "https://Stackoverflow.com/users/22044", "pm_score": 1, "selected": false, "text": "std::vector<>" }, { "answer_id": 133367, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 3, "selected": false, "text": "for( size_t i = 0; i < some_vector.size(); ++i )\n{\n T& rT = some_vector[i];\n // now do something with rT\n}\n'\n" }, { "answer_id": 138933, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 4, "selected": false, "text": "std::for_each(some_vector.begin(), some_vector.end(), &do_stuff);" }, { "answer_id": 144357, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 4, "selected": false, "text": "std::for_each [1..6].each { |i| print i; } for_each algorithms foreach foreach" }, { "answer_id": 373053, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();\n some_iterator++)\n{\n //do stuff\n}\n for (int i = 0; i < some_vector.size(); i++)\n{\n //do stuff\n}\n while (it != end){\n //do stuff\n ++it;\n}\n" }, { "answer_id": 838279, "author": "Marc Eaddy", "author_id": 25029, "author_profile": "https://Stackoverflow.com/users/25029", "pm_score": 2, "selected": false, "text": "mul vector<int> v v[i] &v + sizeof(int) * i" }, { "answer_id": 1118103, "author": "AareP", "author_id": 11741, "author_profile": "https://Stackoverflow.com/users/11741", "pm_score": 1, "selected": false, "text": "for(int i=0;i<anims.size();i++)\n for(int j=0;j<bones.size();j++)\n {\n int animIndex = i;\n int boneIndex = j;\n\n\n // in relatively short code I use indices i and j\n ... animation_matrices[i][j] ...\n\n // in long and complicated code I use indices animIndex and boneIndex\n ... animation_matrices[animIndex][boneIndex] ...\n\n\n }\n" }, { "answer_id": 46161362, "author": "danpla", "author_id": 7225714, "author_profile": "https://Stackoverflow.com/users/7225714", "pm_score": 2, "selected": false, "text": "std::vector reserve()" }, { "answer_id": 59079263, "author": "Marcus Harrison", "author_id": 3292006, "author_profile": "https://Stackoverflow.com/users/3292006", "pm_score": 0, "selected": false, "text": "operator++(T&) operator*(T) operator!=(const &T, const &T) #include <iostream>\ntemplate <class InputIterator>\nvoid printAll(InputIterator& begin, InputIterator& end)\n{\n for (auto current = begin; current != end; ++current) {\n std::cout << *current << \"\\n\";\n }\n}\n\n// elsewhere...\n\nprintAll(myVector.begin(), myVector.end());\n #include <random>\n\nclass RandomIterator\n{\nprivate:\n std::mt19937 random;\n std::uint_fast32_t current;\n std::uint_fast32_t floor;\n std::uint_fast32_t ceil;\n\npublic:\n RandomIterator(\n std::uint_fast32_t floor = 0,\n std::uint_fast32_t ceil = UINT_FAST32_MAX,\n std::uint_fast32_t seed = std::mt19937::default_seed\n ) :\n floor(floor),\n ceil(ceil)\n {\n random.seed(seed);\n ++(*this);\n }\n\n RandomIterator& operator++()\n {\n current = floor + (random() % (ceil - floor));\n }\n\n std::uint_fast32_t operator*() const\n {\n return current;\n }\n\n bool operator!=(const RandomIterator &that) const\n {\n return current != that.current;\n }\n};\n\nint main()\n{\n // roll a 1d6 until we get a 6 and print the results\n RandomIterator firstRandom(1, 7, std::random_device()());\n RandomIterator secondRandom(6, 7);\n printAll(firstRandom, secondRandom);\n\n return 0;\n}\n template<class InputIterator, typename T>\nclass FilterIterator\n{\nprivate:\n InputIterator internalIterator;\n\npublic:\n FilterIterator(const InputIterator &iterator):\n internalIterator(iterator)\n {\n }\n\n virtual bool condition(T) = 0;\n\n FilterIterator<InputIterator, T>& operator++()\n {\n do {\n ++(internalIterator);\n } while (!condition(*internalIterator));\n\n return *this;\n }\n\n T operator*()\n {\n // Needed for the first result\n if (!condition(*internalIterator))\n ++(*this);\n return *internalIterator;\n }\n\n virtual bool operator!=(const FilterIterator& that) const\n {\n return internalIterator != that.internalIterator;\n }\n};\n\ntemplate <class InputIterator>\nclass EvenIterator : public FilterIterator<InputIterator, std::uint_fast32_t>\n{\npublic:\n EvenIterator(const InputIterator &internalIterator) :\n FilterIterator<InputIterator, std::uint_fast32_t>(internalIterator)\n {\n }\n\n bool condition(std::uint_fast32_t n)\n {\n return !(n % 2);\n }\n};\n\n\nint main()\n{\n // Rolls a d20 until a 20 is rolled and discards odd rolls\n EvenIterator<RandomIterator> firstRandom(RandomIterator(1, 21, std::random_device()()));\n EvenIterator<RandomIterator> secondRandom(RandomIterator(20, 21));\n printAll(firstRandom, secondRandom);\n\n return 0;\n}\n" }, { "answer_id": 60338688, "author": "honk", "author_id": 2675154, "author_profile": "https://Stackoverflow.com/users/2675154", "pm_score": 2, "selected": false, "text": "for for (auto &item : some_vector)\n{\n //do stuff\n}\n item auto operator[] for const for (auto const &item : some_vector) { ... }" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
131,263
<p>As much as I generally don't like the discussion/subjective posts on SO, I have really come to appreciate the "Hidden Secrets" set of posts that people have put together. They provide a great overview of some commonly missed tools that you might now otherwise discover.</p> <p>For this question I would like to explore the Visual Studio .NET debugger. What are some of the "hidden secrets" in the VS.NET debugger that you use often or recently discovered and wish you would have known long ago?</p>
[ { "answer_id": 131265, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 3, "selected": false, "text": "$exception Exception" }, { "answer_id": 131268, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "F11 Shift-F11 F10" }, { "answer_id": 131283, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "err,hr" }, { "answer_id": 131285, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 5, "selected": false, "text": "$ADDRESS $CALLER $CALLSTACK $FUNCTION $PID $PNAME $TID $TNAME" }, { "answer_id": 131345, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 4, "selected": false, "text": "System.Diagnostics Debugger Debugger.Break(); // Programmatically set a break point\nDebugger.Launch(); // Launch the debugger if not already attached\nDebugger.IsAttached // Check if the debugger is attached\n System.Diagnostics // Displays the value of Property1 for any \"MyClass\" instance in the debugger\n[DebuggerDisplay(\"{Property1}\")]\npublic class MyClass {\n public string Property1 { get; set; }\n\n [DebuggerStepThrough]\n public void DontStepInto() {\n // An action we don't want to debug\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
131,303
<p>How do you measure the memory usage of an application or process in Linux?</p> <p>From the blog article of <em><a href="http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html" rel="noreferrer">Understanding memory usage on Linux</a></em>, <code>ps</code> is not an accurate tool to use for this intent.</p> <blockquote> <p><strong>Why <code>ps</code> is &quot;wrong&quot;</strong></p> <p>Depending on how you look at it, <code>ps</code> is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up <strong>if it were the only process running</strong>. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by <code>ps</code> are almost definitely <em>wrong</em>.</p> </blockquote> <p><sub>(Note: This question is covered <a href="https://stackoverflow.com/q/63166/15161">here</a> in great detail.)</sub></p>
[ { "answer_id": 131346, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 10, "selected": true, "text": "ps valgrind --tool=massif <executable> <arguments>\n massif.out.12345 ms_print memcheck" }, { "answer_id": 131399, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 8, "selected": false, "text": "$ ps aux\n /proc/$pid/status ps aux" }, { "answer_id": 147348, "author": "Dprado", "author_id": 21943, "author_profile": "https://Stackoverflow.com/users/21943", "pm_score": 5, "selected": false, "text": "linux-gate.so.1 => (0x00ccb000)\nlibrt.so.1 => /lib/librt.so.1 (0x06bc7000)\nlibacl.so.1 => /lib/libacl.so.1 (0x00230000)\nlibselinux.so.1 => /lib/libselinux.so.1 (0x00162000)\nlibc.so.6 => /lib/libc.so.6 (0x00b40000)\nlibpthread.so.0 => /lib/libpthread.so.0 (0x00cb4000)\n/lib/ld-linux.so.2 (0x00b1d000)\nlibattr.so.1 => /lib/libattr.so.1 (0x00229000)\nlibdl.so.2 => /lib/libdl.so.2 (0x00cae000)\nlibsepol.so.1 => /lib/libsepol.so.1 (0x0011a000)\n" }, { "answer_id": 1237930, "author": "Paul Biggar", "author_id": 104021, "author_profile": "https://Stackoverflow.com/users/104021", "pm_score": 7, "selected": false, "text": "cat /proc/1234/smaps\n" }, { "answer_id": 1238159, "author": "juanjux", "author_id": 150404, "author_profile": "https://Stackoverflow.com/users/150404", "pm_score": 2, "selected": false, "text": "ps -o rss,command _aproximation_" }, { "answer_id": 1999717, "author": "holmes", "author_id": 239054, "author_profile": "https://Stackoverflow.com/users/239054", "pm_score": 4, "selected": false, "text": "virtual shared shared private private\nsize RSS PSS clean dirty clean dirty object\n-------- -------- -------- -------- -------- -------- -------- ------------------------------\n 4 0 0 0 0 0 0 0:00 0 [vsyscall]\n 4 4 0 4 0 0 0 [vdso]\n 88 28 28 0 0 4 24 [stack]\n 12 12 12 0 0 0 12 7909 /lib/ld-2.11.1.so\n 12 4 4 0 0 0 4 89529 /usr/lib/locale/en_US.utf8/LC_IDENTIFICATION\n 28 0 0 0 0 0 0 86661 /usr/lib/gconv/gconv-modules.cache\n 4 0 0 0 0 0 0 87660 /usr/lib/locale/en_US.utf8/LC_MEASUREMENT\n 4 0 0 0 0 0 0 89528 /usr/lib/locale/en_US.utf8/LC_TELEPHONE\n 4 0 0 0 0 0 0 89527 /usr/lib/locale/en_US.utf8/LC_ADDRESS\n 4 0 0 0 0 0 0 87717 /usr/lib/locale/en_US.utf8/LC_NAME\n 4 0 0 0 0 0 0 87873 /usr/lib/locale/en_US.utf8/LC_PAPER\n 4 0 0 0 0 0 0 13879 /usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES\n 4 0 0 0 0 0 0 89526 /usr/lib/locale/en_US.utf8/LC_MONETARY\n 4 0 0 0 0 0 0 89525 /usr/lib/locale/en_US.utf8/LC_TIME\n 4 0 0 0 0 0 0 11378 /usr/lib/locale/en_US.utf8/LC_NUMERIC\n 1156 8 8 0 0 4 4 11372 /usr/lib/locale/en_US.utf8/LC_COLLATE\n 252 0 0 0 0 0 0 11321 /usr/lib/locale/en_US.utf8/LC_CTYPE\n 128 52 1 52 0 0 0 7909 /lib/ld-2.11.1.so\n 2316 32 11 24 0 0 8 7986 /lib/libncurses.so.5.7\n 2064 8 4 4 0 0 4 7947 /lib/libdl-2.11.1.so\n 3596 472 46 440 0 4 28 7933 /lib/libc-2.11.1.so\n 2084 4 0 4 0 0 0 7995 /lib/libnss_compat-2.11.1.so\n 2152 4 0 4 0 0 0 7993 /lib/libnsl-2.11.1.so\n 2092 0 0 0 0 0 0 8009 /lib/libnss_nis-2.11.1.so\n 2100 0 0 0 0 0 0 7999 /lib/libnss_files-2.11.1.so\n 3752 2736 2736 0 0 864 1872 [heap]\n 24 24 24 0 0 0 24 [anon]\n 916 616 131 584 0 0 32 /bin/bash\n-------- -------- -------- -------- -------- -------- -------- ------------------------------\n 22816 4004 3005 1116 0 876 2012 TOTAL\n" }, { "answer_id": 2816070, "author": "Anil", "author_id": 338950, "author_profile": "https://Stackoverflow.com/users/338950", "pm_score": 8, "selected": false, "text": "sudo pmap -x <process pid>\n" }, { "answer_id": 3666523, "author": "CashCow", "author_id": 442284, "author_profile": "https://Stackoverflow.com/users/442284", "pm_score": 4, "selected": false, "text": "getrusage() /proc/[pid]/statm [pid] getpid()" }, { "answer_id": 5217434, "author": "Nick W.", "author_id": 647804, "author_profile": "https://Stackoverflow.com/users/647804", "pm_score": 3, "selected": false, "text": "vmstat -s vmstat -s" }, { "answer_id": 7000517, "author": "pokute", "author_id": 652691, "author_profile": "https://Stackoverflow.com/users/652691", "pm_score": 3, "selected": false, "text": "#!/bin/ksh\n#\n# Returns total memory used by process $1 in kb.\n#\n# See /proc/NNNN/smaps if you want to do something\n# more interesting.\n#\n\nIFS=$'\\n'\n\nfor line in $(</proc/$1/smaps)\ndo\n [[ $line =~ ^Size:\\s+(\\S+) ]] && ((kb += ${.sh.match[1]}))\ndone\n\nprint $kb\n" }, { "answer_id": 13754307, "author": "thomasrutter", "author_id": 53212, "author_profile": "https://Stackoverflow.com/users/53212", "pm_score": 7, "selected": false, "text": "ps -A v" }, { "answer_id": 15196995, "author": "Vineeth", "author_id": 2130910, "author_profile": "https://Stackoverflow.com/users/2130910", "pm_score": 3, "selected": false, "text": "ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf(\"%13.2f Mb \",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf(\"%s \",$x) } print \"\" }' | awk '{total=total + $1} END {print total}'\n" }, { "answer_id": 16432017, "author": "Rocco Corsi", "author_id": 2360683, "author_profile": "https://Stackoverflow.com/users/2360683", "pm_score": 3, "selected": false, "text": "gcore <pid>\n" }, { "answer_id": 25184004, "author": "test30", "author_id": 781312, "author_profile": "https://Stackoverflow.com/users/781312", "pm_score": 3, "selected": false, "text": "google-chrome while true; do ps aux | awk ‚{print $5, $11}’ | grep chrome | sort -n > /tmp/a.txt; sleep 1; diff /tmp/{b,a}.txt; mv /tmp/{a,b}.txt; done;\n" }, { "answer_id": 30298898, "author": "Yahya Yahyaoui", "author_id": 1377439, "author_profile": "https://Stackoverflow.com/users/1377439", "pm_score": 5, "selected": false, "text": "top\n top -p <PID>\n top | grep <PROCESS NAME>\n" }, { "answer_id": 33532736, "author": "Moonchild", "author_id": 2887185, "author_profile": "https://Stackoverflow.com/users/2887185", "pm_score": 6, "selected": false, "text": "time time which time /usr/bin/time ls $ /usr/bin/time --verbose ls\n(...)\nCommand being timed: \"ls\"\nUser time (seconds): 0.00\nSystem time (seconds): 0.00\nPercent of CPU this job got: 0%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00\nAverage shared text size (kbytes): 0\nAverage unshared data size (kbytes): 0\nAverage stack size (kbytes): 0\nAverage total size (kbytes): 0\nMaximum resident set size (kbytes): 2372\nAverage resident set size (kbytes): 0\nMajor (requiring I/O) page faults: 1\nMinor (reclaiming a frame) page faults: 121\nVoluntary context switches: 2\nInvoluntary context switches: 9\nSwaps: 0\nFile system inputs: 256\nFile system outputs: 0\nSocket messages sent: 0\nSocket messages received: 0\nSignals delivered: 0\nPage size (bytes): 4096\nExit status: 0\n" }, { "answer_id": 34871273, "author": "Roselyn Verbo Domingo", "author_id": 3985677, "author_profile": "https://Stackoverflow.com/users/3985677", "pm_score": 0, "selected": false, "text": "snmp snmp echo \"IP address: \"\nread ip\necho \"Specfiy PID: \"\nread pid\necho \"Interval in seconds: \"\nread interval\n\nwhile [ 1 ]\ndo\n date\n snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfCPU.$pid\n snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfMem.$pid\n sleep $interval;\ndone\n" }, { "answer_id": 36991325, "author": "Thomas Shaiker", "author_id": 6282986, "author_profile": "https://Stackoverflow.com/users/6282986", "pm_score": 4, "selected": false, "text": "ps aux --sort pmem %MEM ps aux | awk '{print $2, $4, $11}' | sort -k2r | head -n 15 top -a %MEM" }, { "answer_id": 44711589, "author": "Lokendra Singh Rawat", "author_id": 7015811, "author_profile": "https://Stackoverflow.com/users/7015811", "pm_score": 7, "selected": false, "text": "ps -eo size,pid,user,command --sort -size | \\\n awk '{ hr=$1/1024 ; printf(\"%13.2f Mb \",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf(\"%s \",$x) } print \"\" }' |\\\n cut -d \"\" -f2 | cut -d \"-\" -f1\n 0.00 Mb COMMAND\n 1288.57 Mb /usr/lib/firefox\n 821.68 Mb /usr/lib/chromium/chromium\n 762.82 Mb /usr/lib/chromium/chromium\n 588.36 Mb /usr/sbin/mysqld\n 547.55 Mb /usr/lib/chromium/chromium\n 523.92 Mb /usr/lib/tracker/tracker\n 476.59 Mb /usr/lib/chromium/chromium\n 446.41 Mb /usr/bin/gnome\n 421.62 Mb /usr/sbin/libvirtd\n 405.11 Mb /usr/lib/chromium/chromium\n 302.60 Mb /usr/lib/chromium/chromium\n 291.46 Mb /usr/lib/chromium/chromium\n 284.56 Mb /usr/lib/chromium/chromium\n 238.93 Mb /usr/lib/tracker/tracker\n 223.21 Mb /usr/lib/chromium/chromium\n 197.99 Mb /usr/lib/chromium/chromium\n 194.07 Mb conky\n 191.92 Mb /usr/lib/chromium/chromium\n 190.72 Mb /usr/bin/mongod\n 169.06 Mb /usr/lib/chromium/chromium\n 155.11 Mb /usr/bin/gnome\n 136.02 Mb /usr/lib/chromium/chromium\n 125.98 Mb /usr/lib/chromium/chromium\n 103.98 Mb /usr/lib/chromium/chromium\n 93.22 Mb /usr/lib/tracker/tracker\n 89.21 Mb /usr/lib/gnome\n 80.61 Mb /usr/bin/gnome\n 77.73 Mb /usr/lib/evolution/evolution\n 76.09 Mb /usr/lib/evolution/evolution\n 72.21 Mb /usr/lib/gnome\n 69.40 Mb /usr/lib/evolution/evolution\n 68.84 Mb nautilus\n 68.08 Mb zeitgeist\n 60.97 Mb /usr/lib/tracker/tracker\n 59.65 Mb /usr/lib/evolution/evolution\n 57.68 Mb apt\n 55.23 Mb /usr/lib/gnome\n 53.61 Mb /usr/lib/evolution/evolution\n 53.07 Mb /usr/lib/gnome\n 52.83 Mb /usr/lib/gnome\n 51.02 Mb /usr/lib/udisks2/udisksd\n 50.77 Mb /usr/lib/evolution/evolution\n 50.53 Mb /usr/lib/gnome\n 50.45 Mb /usr/lib/gvfs/gvfs\n 50.36 Mb /usr/lib/packagekit/packagekitd\n 50.14 Mb /usr/lib/gvfs/gvfs\n 48.95 Mb /usr/bin/Xwayland :1024\n 46.21 Mb /usr/bin/gnome\n 42.43 Mb /usr/bin/zeitgeist\n 42.29 Mb /usr/lib/gnome\n 41.97 Mb /usr/lib/gnome\n 41.64 Mb /usr/lib/gvfs/gvfsd\n 41.63 Mb /usr/lib/gvfs/gvfsd\n 41.55 Mb /usr/lib/gvfs/gvfsd\n 41.48 Mb /usr/lib/gvfs/gvfsd\n 39.87 Mb /usr/bin/python /usr/bin/chrome\n 37.45 Mb /usr/lib/xorg/Xorg vt2\n 36.62 Mb /usr/sbin/NetworkManager\n 35.63 Mb /usr/lib/caribou/caribou\n 34.79 Mb /usr/lib/tracker/tracker\n 33.88 Mb /usr/sbin/ModemManager\n 33.77 Mb /usr/lib/gnome\n 33.61 Mb /usr/lib/upower/upowerd\n 33.53 Mb /usr/sbin/gdm3\n 33.37 Mb /usr/lib/gvfs/gvfsd\n 33.36 Mb /usr/lib/gvfs/gvfs\n 33.23 Mb /usr/lib/gvfs/gvfs\n 33.15 Mb /usr/lib/at\n 33.15 Mb /usr/lib/at\n 30.03 Mb /usr/lib/colord/colord\n 29.62 Mb /usr/lib/apt/methods/https\n 28.06 Mb /usr/lib/zeitgeist/zeitgeist\n 27.29 Mb /usr/lib/policykit\n 25.55 Mb /usr/lib/gvfs/gvfs\n 25.55 Mb /usr/lib/gvfs/gvfs\n 25.23 Mb /usr/lib/accountsservice/accounts\n 25.18 Mb /usr/lib/gvfs/gvfsd\n 25.15 Mb /usr/lib/gvfs/gvfs\n 25.15 Mb /usr/lib/gvfs/gvfs\n 25.12 Mb /usr/lib/gvfs/gvfs\n 25.10 Mb /usr/lib/gnome\n 25.10 Mb /usr/lib/gnome\n 25.07 Mb /usr/lib/gvfs/gvfsd\n 24.99 Mb /usr/lib/gvfs/gvfs\n 23.26 Mb /usr/lib/chromium/chromium\n 22.09 Mb /usr/bin/pulseaudio\n 19.01 Mb /usr/bin/pulseaudio\n 18.62 Mb (sd\n 18.46 Mb (sd\n 18.30 Mb /sbin/init\n 18.17 Mb /usr/sbin/rsyslogd\n 17.50 Mb gdm\n 17.42 Mb gdm\n 17.09 Mb /usr/lib/dconf/dconf\n 17.09 Mb /usr/lib/at\n 17.06 Mb /usr/lib/gvfs/gvfsd\n 16.98 Mb /usr/lib/at\n 16.91 Mb /usr/lib/gdm3/gdm\n 16.86 Mb /usr/lib/gvfs/gvfsd\n 16.86 Mb /usr/lib/gdm3/gdm\n 16.85 Mb /usr/lib/dconf/dconf\n 16.85 Mb /usr/lib/dconf/dconf\n 16.73 Mb /usr/lib/rtkit/rtkit\n 16.69 Mb /lib/systemd/systemd\n 13.13 Mb /usr/lib/chromium/chromium\n 13.13 Mb /usr/lib/chromium/chromium\n 10.92 Mb anydesk\n 8.54 Mb /sbin/lvmetad\n 7.43 Mb /usr/sbin/apache2\n 6.82 Mb /usr/sbin/apache2\n 6.77 Mb /usr/sbin/apache2\n 6.73 Mb /usr/sbin/apache2\n 6.66 Mb /usr/sbin/apache2\n 6.64 Mb /usr/sbin/apache2\n 6.63 Mb /usr/sbin/apache2\n 6.62 Mb /usr/sbin/apache2\n 6.51 Mb /usr/sbin/apache2\n 6.25 Mb /usr/sbin/apache2\n 6.22 Mb /usr/sbin/apache2\n 3.92 Mb bash\n 3.14 Mb bash\n 2.97 Mb bash\n 2.95 Mb bash\n 2.93 Mb bash\n 2.91 Mb bash\n 2.86 Mb bash\n 2.86 Mb bash\n 2.86 Mb bash\n 2.84 Mb bash\n 2.84 Mb bash\n 2.45 Mb /lib/systemd/systemd\n 2.30 Mb (sd\n 2.28 Mb /usr/bin/dbus\n 1.84 Mb /usr/bin/dbus\n 1.46 Mb ps\n 1.21 Mb openvpn hackthebox.ovpn\n 1.16 Mb /sbin/dhclient\n 1.16 Mb /sbin/dhclient\n 1.09 Mb /lib/systemd/systemd\n 0.98 Mb /sbin/mount.ntfs /dev/sda3 /media/n0bit4/Data\n 0.97 Mb /lib/systemd/systemd\n 0.96 Mb /lib/systemd/systemd\n 0.89 Mb /usr/sbin/smartd\n 0.77 Mb /usr/bin/dbus\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.74 Mb /usr/bin/dbus\n 0.71 Mb /usr/lib/apt/methods/http\n 0.68 Mb /bin/bash /usr/bin/mysqld_safe\n 0.68 Mb /sbin/wpa_supplicant\n 0.66 Mb /usr/bin/dbus\n 0.61 Mb /lib/systemd/systemd\n 0.54 Mb /usr/bin/dbus\n 0.46 Mb /usr/sbin/cron\n 0.45 Mb /usr/sbin/irqbalance\n 0.43 Mb logger\n 0.41 Mb awk { hr=$1/1024 ; printf(\"%13.2f Mb \",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf(\"%s \",$x) } print \"\" }\n 0.40 Mb /usr/bin/ssh\n 0.34 Mb /usr/lib/chromium/chrome\n 0.32 Mb cut\n 0.32 Mb cut\n 0.00 Mb [kthreadd]\n 0.00 Mb [ksoftirqd/0]\n 0.00 Mb [kworker/0:0H]\n 0.00 Mb [rcu_sched]\n 0.00 Mb [rcu_bh]\n 0.00 Mb [migration/0]\n 0.00 Mb [lru\n 0.00 Mb [watchdog/0]\n 0.00 Mb [cpuhp/0]\n 0.00 Mb [cpuhp/1]\n 0.00 Mb [watchdog/1]\n 0.00 Mb [migration/1]\n 0.00 Mb [ksoftirqd/1]\n 0.00 Mb [kworker/1:0H]\n 0.00 Mb [cpuhp/2]\n 0.00 Mb [watchdog/2]\n 0.00 Mb [migration/2]\n 0.00 Mb [ksoftirqd/2]\n 0.00 Mb [kworker/2:0H]\n 0.00 Mb [cpuhp/3]\n 0.00 Mb [watchdog/3]\n 0.00 Mb [migration/3]\n 0.00 Mb [ksoftirqd/3]\n 0.00 Mb [kworker/3:0H]\n 0.00 Mb [kdevtmpfs]\n 0.00 Mb [netns]\n 0.00 Mb [khungtaskd]\n 0.00 Mb [oom_reaper]\n 0.00 Mb [writeback]\n 0.00 Mb [kcompactd0]\n 0.00 Mb [ksmd]\n 0.00 Mb [khugepaged]\n 0.00 Mb [crypto]\n 0.00 Mb [kintegrityd]\n 0.00 Mb [bioset]\n 0.00 Mb [kblockd]\n 0.00 Mb [devfreq_wq]\n 0.00 Mb [watchdogd]\n 0.00 Mb [kswapd0]\n 0.00 Mb [vmstat]\n 0.00 Mb [kthrotld]\n 0.00 Mb [ipv6_addrconf]\n 0.00 Mb [acpi_thermal_pm]\n 0.00 Mb [ata_sff]\n 0.00 Mb [scsi_eh_0]\n 0.00 Mb [scsi_tmf_0]\n 0.00 Mb [scsi_eh_1]\n 0.00 Mb [scsi_tmf_1]\n 0.00 Mb [scsi_eh_2]\n 0.00 Mb [scsi_tmf_2]\n 0.00 Mb [scsi_eh_3]\n 0.00 Mb [scsi_tmf_3]\n 0.00 Mb [scsi_eh_4]\n 0.00 Mb [scsi_tmf_4]\n 0.00 Mb [scsi_eh_5]\n 0.00 Mb [scsi_tmf_5]\n 0.00 Mb [bioset]\n 0.00 Mb [kworker/1:1H]\n 0.00 Mb [kworker/3:1H]\n 0.00 Mb [kworker/0:1H]\n 0.00 Mb [kdmflush]\n 0.00 Mb [bioset]\n 0.00 Mb [kdmflush]\n 0.00 Mb [bioset]\n 0.00 Mb [jbd2/sda5\n 0.00 Mb [ext4\n 0.00 Mb [kworker/2:1H]\n 0.00 Mb [kauditd]\n 0.00 Mb [bioset]\n 0.00 Mb [drbd\n 0.00 Mb [irq/27\n 0.00 Mb [i915/signal:0]\n 0.00 Mb [i915/signal:1]\n 0.00 Mb [i915/signal:2]\n 0.00 Mb [ttm_swap]\n 0.00 Mb [cfg80211]\n 0.00 Mb [kworker/u17:0]\n 0.00 Mb [hci0]\n 0.00 Mb [hci0]\n 0.00 Mb [kworker/u17:1]\n 0.00 Mb [iprt\n 0.00 Mb [iprt\n 0.00 Mb [kworker/1:0]\n 0.00 Mb [kworker/3:0]\n 0.00 Mb [kworker/0:0]\n 0.00 Mb [kworker/2:0]\n 0.00 Mb [kworker/u16:0]\n 0.00 Mb [kworker/u16:2]\n 0.00 Mb [kworker/3:2]\n 0.00 Mb [kworker/2:1]\n 0.00 Mb [kworker/1:2]\n 0.00 Mb [kworker/0:2]\n 0.00 Mb [kworker/2:2]\n 0.00 Mb [kworker/0:1]\n 0.00 Mb [scsi_eh_6]\n 0.00 Mb [scsi_tmf_6]\n 0.00 Mb [usb\n 0.00 Mb [bioset]\n 0.00 Mb [kworker/3:1]\n 0.00 Mb [kworker/u16:1]\n" }, { "answer_id": 51389219, "author": "GypsyCosmonaut", "author_id": 6639975, "author_profile": "https://Stackoverflow.com/users/6639975", "pm_score": 5, "selected": false, "text": "ps_mem ps_mem -p <pid>\n $ ps_mem -S -p $(pgrep firefox)\n\nPrivate + Shared = RAM used Swap used Program\n\n355.0 MiB + 38.7 MiB = 393.7 MiB 35.9 MiB firefox\n---------------------------------------------\n 393.7 MiB 35.9 MiB\n=============================================\n" }, { "answer_id": 65277087, "author": "Sruli", "author_id": 6556355, "author_profile": "https://Stackoverflow.com/users/6556355", "pm_score": 2, "selected": false, "text": "sudo smem | awk '/firefox/{swap += $5; pss += $7;} END {print \"swap = \"swap/1024\" PSS = \"pss/1024}' sudo smem | awk '/libvirt/{swap += $5; pss += $7;} END {print \"swap = \"swap/1024\" PSS = \"pss/1024}' swap = 0 PSS = 2096.92 swap = 224.75 PSS = 421.455" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
131,326
<p>I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.</p>
[ { "answer_id": 131339, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<type>[,] <name> = new <type>[<first dimenison>,<second dimension>];\n" }, { "answer_id": 131347, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": -1, "selected": false, "text": "data structures c#\n" }, { "answer_id": 131363, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 0, "selected": false, "text": "<type>[][] <name> = new <type>[<first dimension>];\nfor (int i = 0; i < <first dimension>; i++)\n{\n <name>[i] = new <type>[<second dimension>];\n}\n <type> item = <name>[<first index>][<second index>];\n" }, { "answer_id": 131387, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 2, "selected": false, "text": "for (y = 0; y < ysize; y++){\n for (x = 0; x < xsize; x++){\n theArray[y*xsize + x] = //some stuff!\n }\n}\n totalsize = xsize*ysize;\nfor (x = 0; x < totalsize; x++){\n theArray[x] = //some stuff!\n}\n" }, { "answer_id": 131388, "author": "jarrodn", "author_id": 15273, "author_profile": "https://Stackoverflow.com/users/15273", "pm_score": 1, "selected": false, "text": "int[][] intGrid;\n Dictionary<KeyValuePair<int,int>,string>;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
131,335
<p>For some of the customers that we develop software for, we are required to "guarantee" a certain amount of spare resources (memory, disk space, CPU). Memory and disk space are simple, but CPU is a bit more difficult.</p> <p>One technique that we have used is to create a process that consumes a guaranteed amount of CPU time (say 2.5 seconds every 5 seconds). We run this process at highest priority in order to guarantee that it runs and consumes all of its required CPU cycles. </p> <p>If our normal applications are able to run at an acceptable level of performance and can pass all of their functionality tests while the spare time process is running as well, then we "assume" that we have met our commitment for spare CPU time.</p> <p>I'm sure that there are other techniques for doing the same thing, and would like to learn about them.</p>
[ { "answer_id": 131427, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "/sys/devices/system/cpu/cpu0/cpufreq/" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19853/" ]
131,367
<p>I am going to install SVN for my personal projects. Is it better to install it on a spare machine(Win XP) or will I save myself grief if I install it on the machine I use for development(Vista). </p>
[ { "answer_id": 131397, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 0, "selected": false, "text": "svnadmin create c:\\repo" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1628/" ]
131,406
<p>There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?</p> <p>Here are a few methods that I know of:</p> <pre><code>var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2 </code></pre> <p>I'm sure there are others out there. Suggestions?</p>
[ { "answer_id": 131413, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": -1, "selected": false, "text": "a | 0" }, { "answer_id": 131421, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 2, "selected": false, "text": "var num = 2.7; // typeof num is \"Number\"\nnum.toFixed(0) == \"3\"\n" }, { "answer_id": 131434, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 2, "selected": false, "text": "var i = parseInt(n, 10);\n '010' 8 10" }, { "answer_id": 131538, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "toFixed var myFloat = 2.5;\nvar myInt = myFloat.toFixed(0);\n Math.floor() Number.toFixed()" }, { "answer_id": 136647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "var string = '1';\nvar integer = a * 1;\n" }, { "answer_id": 2445014, "author": "bcherry", "author_id": 211776, "author_profile": "https://Stackoverflow.com/users/211776", "pm_score": 3, "selected": false, "text": "var x = 2.5;\nconsole.log(~~x); // 2\n http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&cd=1&hl=en&ct=clnk&gl=us" }, { "answer_id": 6362472, "author": "Ken Rosaka", "author_id": 800175, "author_profile": "https://Stackoverflow.com/users/800175", "pm_score": 3, "selected": false, "text": "Number.prototype.integer = function () {\n return Math[this < 0 ? 'ceil' : 'floor'](this);\n}\n var x = 1.2, y = -1.2;\n\nx.integer(); // 1\ny.integer(); // -1\n\n(-10 / 3).integer(); // -3\n" }, { "answer_id": 7337219, "author": "arunjitsingh", "author_id": 377392, "author_profile": "https://Stackoverflow.com/users/377392", "pm_score": 2, "selected": false, "text": "value value value value = ~~(value)\nvalue = value | 0;\nvalue = value & 0xFF; // one byte; use this if you want to limit the integer to\n // a predefined number of bits/bytes\n ~~(\"123.45\") === 123 0 ~~(undefined) === 0\n~~(NaN) === 0\n~~(\"ABC\") === 0\n 0x ~~(\"0xAF\") === 175\n parseInt() Math.floor() Errors 0" }, { "answer_id": 28667325, "author": "Kokizzu", "author_id": 1620210, "author_profile": "https://Stackoverflow.com/users/1620210", "pm_score": 2, "selected": false, "text": "Chrome ~~num num|0 Math.floor parseInt num>>0 |0 num - num%1" }, { "answer_id": 36131850, "author": "GitaarLAB", "author_id": 588079, "author_profile": "https://Stackoverflow.com/users/588079", "pm_score": 3, "selected": false, "text": "String Number String Number Number -252 +252 Number 252 2(211/2=1024) Infinity Number 252+0.25 = 4503599627370496.25 4503599627370496 252+0.50 = 4503599627370496.50 4503599627370496 252+0.75 = 4503599627370496.75 4503599627370497 252+1.25 = 4503599627370497.25 4503599627370497 252+1.50 = 4503599627370497.50 4503599627370498 252+1.75 = 4503599627370497.75 4503599627370498 252+2.50 = 4503599627370498.50 4503599627370498 252+3.50 = 4503599627370499.50 4503599627370500 Number x.1 to x.9 0.1 1/(23=8)=0.125 0 0.9 1-1/(23=8)=0.875 1 ±2(53-3=50) x.1 x.9 ±2(53-6=47) ±2(53-9=44) ±2(53-13=40) ±2(53-16=37) ±2(53-19=34) ±2(53-23=30) ±2(53-26=27) ±2(53-29=24) ±2(53-33=20) ±2(53-36=17) ±253 ±(253+1) -253 +253 -(253 - 1) = -9007199254740991 Number.MIN_SAFE_INTEGER +(253 - 1) = +9007199254740991 Number.MAX_SAFE_INTEGER Number.MIN_SAFE_INTEGER || (Number.MIN_SAFE_INTEGER=\n -(Number.MAX_SAFE_INTEGER=9007199254740991) //Math.pow(2,53)-1\n);\n Number.isSafeInteger() Number true false false NaN Infinity String Number.isSafeInteger || (Number.isSafeInteger = function(value){\n return typeof value === 'number' && \n value === Math.floor(value) &&\n value < 9007199254740992 &&\n value > -9007199254740992;\n});\n Math.trunc() Math.floor() Math.ceil() Math.round() Math.trunc() Math.trunc() Math.trunc || (Math.trunc = function(n){\n return n < 0 ? Math.ceil(n) : Math.floor(n); \n});\n Math[n < 0 ? 'ceil' : 'floor'](n); Math.trunc(/* Number or String */) Number Number -2^52 +2^52 Number ±2^52 ±2^53 4503599627370509.5 4503599627370510 ±2^53 % 1 result = n-n%1 n-=n%1 (n)-(n%1) (2.5) - (0.5) = 2 (-2.5) - (-0.5) = -2 --=+ (-2.5) + (0.5) = -2 Number Math.trunc() Number Number Number Number -2^31 +2^31 ~~num num|0 num>>0 0 +2^32 num>>>0 0 -4294967295 (n < 0 ? -(-n>>>0) : n>>>0) Math String parseInt(/*String*/, /*Radix*/) Number parseInt() Math String String ±2^52 Math.trunc() Math.intToInf || (Math.intToInf = function(n){\n return n < 0 ? Math.floor(n) : Math.ceil(n); \n});\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
131,433
<p>I've read <a href="http://www.xs4all.nl/~hipster/lib/scheme/gauche/define-syntax-primer.txt" rel="noreferrer">JRM's Syntax-rules Primer</a> for the Merely Eccentric and it has helped me understand syntax-rules and how it's different from common-lisp's define-macro. syntax-rules is only one way of implementing a syntax transformer within define-syntax.</p> <p>I'm looking for two things, the first is more examples and explanations of syntax-rules and the second is good sources for learning the other ways of using define-syntax. What resources do you recommend?</p>
[ { "answer_id": 133356, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": true, "text": "syntax-case define-syntax syntax-case syntax-case" }, { "answer_id": 54969998, "author": "Flux", "author_id": 5916915, "author_profile": "https://Stackoverflow.com/users/5916915", "pm_score": 2, "selected": false, "text": "define-syntax" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
131,439
<p>I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.</p>
[ { "answer_id": 131492, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 2, "selected": false, "text": "$ gdb /path/to/exec 1234 # 1234 is the pid of the running process\n" }, { "answer_id": 131539, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 7, "selected": true, "text": "void create_dump(void)\n{\n if(!fork()) {\n // Crash the app in your favorite way here\n *((void*)0) = 42;\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ]
131,445
<p>What does it take to get C++ <strong>tr1</strong> members (shared_ptr especially, but we'd like function and bind and ALL the others) working with <strong>GCC 3.4.4</strong> (for the Nokia <strong>N810</strong> tablet computer). </p> <p>Has anyone done this? Attempted this? </p> <p>It may <strong>not</strong> be feasible for us to upgrade to GCC 4.x to cross-compile for this device (but if you've done that, we'd love to know). </p> <p>There may be many approaches, and I'd like to avoid dead ends others have hit.</p> <p>We're trying to avoid bringing in boost, since it can be pretty interdependent (you bring in one boost header and you end up with 20 more), and keeping code size down is important to us. </p> <p>Thank you!</p>
[ { "answer_id": 131457, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "std::tr1 std::tr1" }, { "answer_id": 131485, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "g++-3.4 libstdc++" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17055/" ]
131,448
<p>I have a ListView which sometimes I need to put around 10000 items in. ListViews don't really handle this well, and they lock up for a couple of seconds while they sort the items and draw them. If you add the items in individually, it's even worse, locking up for nearly a minute.</p> <p>To get around this, I thought I'd try populating the ListView before I need to display it, but unfortunately it has other ideas. It only starts drawing when I turn the panel that contains the ListView visible, making the program hang for a couple of seconds.</p> <p>Any ideas for how I can eliminate this delay? Or is there another component that's relatively easy to use that is better at showing large quantities of data?</p>
[ { "answer_id": 131496, "author": "Jack B Nimble", "author_id": 3800, "author_profile": "https://Stackoverflow.com/users/3800", "pm_score": 0, "selected": false, "text": "for (int ix=0; ix < 10000; ix ++)\n{\n listView1.Items.Add(ix.ToString());\n Application.DoEvents();\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
[ { "answer_id": 131452, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "if element in mylist:\n index = mylist.index(element)\n # ... do something\nelse:\n # ... do something else\n" }, { "answer_id": 131930, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 0, "selected": false, "text": "d = dict((x, loc) for (loc,x) in enumerate(chars))\n...\nindex = d.get(chars_to_find, -1) # Second argument is default if not found.\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
131,456
<p>How do I apply the MarshalAsAttribute to the return type of the code below?</p> <pre><code>public ISomething Foo() { return new MyFoo(); } </code></pre>
[ { "answer_id": 131467, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": true, "text": "[return: MarshalAs(<your marshal type>)]\npublic ISomething Foo()\n{\n return new MyFoo();\n}\n" }, { "answer_id": 131471, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 2, "selected": false, "text": "[return:MarshalAs]\npublic ISomething Foo()\n{\n return new MyFoo();\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
131,473
<p>G'day Stackoverflowers,</p> <p>I'm the author of Perl's <a href="http://search.cpan.org/perldoc?autodie" rel="nofollow noreferrer">autodie</a> pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to <a href="http://search.cpan.org/perldoc?Fatal" rel="nofollow noreferrer">Fatal</a>, but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the <code>Fatal</code> module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above.</p> <p>The next release of <code>autodie</code> will add special handling for calls to <code>flock</code> with the <code>LOCK_NB</code> (non-blocking) option. While a failed <code>flock</code> call would normally result in an exception under <code>autodie</code>, a failed call to <code>flock</code> using <code>LOCK_NB</code> will merely return false if the returned errno (<code>$!</code>) is <code>EWOULDBLOCK</code>.</p> <p>The reason for this is so people can continue to write code like:</p> <pre><code>use Fcntl qw(:flock); use autodie; # All perl built-ins now succeed or die. open(my $fh, '&lt;', 'some_file.txt'); my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can. if ($lock) { # Opportuntistically do something with the locked file. } </code></pre> <p>In the above code, a lock that fails because someone else has the file locked already (<code>EWOULDBLOCK</code>) is not considered to be a hard error, so autodying <code>flock</code> merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying <code>flock</code> generates an appropriate exception when it sees that our errno is not <code>EWOULDBLOCK</code>.</p> <p>This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the <code>LOCK_NB</code> option, it doesn't define <code>EWOULDBLOCK</code>. Instead, the errno returned is 33 ("Domain error") when blocking would occur.</p> <p>Obviously I can hard-code this as a constant into <code>autodie</code>, but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of <code>POSIX::EWOULDBLOCK</code>, but I can't for the life of me find where such a thing would be defined. If you can help, let me know.</p> <p>Answers I specifically don't want:</p> <ul> <li>Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about).</li> <li>Not supporting <code>LOCK_NB</code> functionality at all under Windows.</li> <li>Assuming that any failure from a <code>LOCK_NB</code> call to <code>flock</code> should return merely false.</li> <li>Suggestions that I ask on p5p or <a href="http://perlmonks.org/" rel="nofollow noreferrer">perlmonks</a>. I already know about them.</li> <li>An explanation of how <code>flock</code>, or exceptions, or <code>Fatal</code> work. I already know. Intimately.</li> </ul>
[ { "answer_id": 131798, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "ERROR_LOCK_VIOLATION" }, { "answer_id": 131867, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "$^E ERROR_LOCK_VIOLATION winerror.h" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19422/" ]
131,481
<p>I have a rails app that I have serving up XML on an infrequent basis. This is being run with mongrel and mysql. I've found that if I don't exercise the app for longer than a few hours it goes dead and starts throwing Errno::EPIPE errors. It seems that the mysql connection get timed out for inactivity or something like that.</p> <p>It can be restarted with 'mongrel_rails restart -P /path/to/the/mongrel.pid' ... but that's not really a solution. My collaborator expects the app to be there when he is working on his part (and I am most likely not around).</p> <p>My question is:</p> <ul> <li>What can I do to prevent this problem from occurring in the 1st place? (e.g. don't time me out!!).</li> <li>Failing that, is there some code I can insert somewhere to automatically remake the Db connection?</li> </ul>
[ { "answer_id": 143956, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 0, "selected": false, "text": " http://rubyforge.org/projects/zventstools/\n \"Reconnect to the MySQL server when you hit a lost connection error\".\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17251/" ]
131,516
<p>I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change </p> <pre> Uses * Uses unit1 in 'unit1.pas' * unit1 unit2 in 'unit2.pas' * unit2 ... * ... </pre> <p>in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found. This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file.<p></p> <p>I'm running <code>make -f [then some options]</code>, the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the <code>in 'unit1.pas</code> is removed. <p></p>
[ { "answer_id": 131526, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 1, "selected": false, "text": "ifdef package" }, { "answer_id": 131927, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 0, "selected": false, "text": "program a;\n\nuses\n ACondUnits;\n\n...\n unit ACondUnits;\n\ninterface\n\nuses\n{$IFDEF UseD7MM}\n Delphi7MM;\n{$ELSE}\n FastMM4;\n{$ENDIF}\n\nimplementation\n\nend.\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
131,518
<p>In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section):</p> <pre><code>&lt;httpHandlers&gt; &lt;add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" /&gt; &lt;/httpHandlers&gt; </code></pre> <p>This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working. Any idea why this would be the case?</p> <p>Cheers Greg</p>
[ { "answer_id": 131531, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<add verb=\"*\" path=\"*.asmx\" type=\"System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services\" validate=\"false\">\n validate=\"false\"" }, { "answer_id": 131658, "author": "Jeeby", "author_id": 21969, "author_profile": "https://Stackoverflow.com/users/21969", "pm_score": 2, "selected": false, "text": "<httpHandlers>\n <add verb=\"*\" path=\"*.bcn\" type=\"Internet2008.Beacon.BeaconHandler, Internet2008\" validate=\"false\" />\n <add verb=\"*\" path=\"*.asmx\" type=\"System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" validate=\"false\"/>\n</httpHandlers>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
131,559
<p>Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique.</p> <p>So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether).</p> <p>How do I achieve that?</p>
[ { "answer_id": 131563, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": -1, "selected": false, "text": "/(foo|bar)\n" }, { "answer_id": 131574, "author": "Codeslayer", "author_id": 4021, "author_profile": "https://Stackoverflow.com/users/4021", "pm_score": 5, "selected": true, "text": "/^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line)\n/fred\\|joe : Search for FRED OR JOE\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17716/" ]
131,600
<p>I need to create an installer program that will do install the following:</p> <ol> <li>ASP.Net Website </li> <li>Windows Service</li> <li>SQL Express if it isn't installed and the user doesn't have a SQL Server</li> <li>Dundas Charts</li> <li>ASP.Net AJAX v.1.0</li> <li>ReportViewer control (for 2.0 Framework)</li> <li>Check Framework prerequisites (2.0)</li> <li>Configure IIS and app.config (data connection strings, etc.)</li> </ol> <p>Is it realistic to be able to do this with a VS Setup Project? Or, should I be looking at other install tools? </p>
[ { "answer_id": 931544, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "CreateDirectory $INSTDIR\nSetOutPath $INSTDIR\n; HERE UNZIP ACTUALLY THE FILES (ADD *.js files if needed ) \n; PACK ALL THE FILES EXCEPT THOSE WITH FILE EXTENSIONS after the /x\nFile /r /x *.suo /x *.MDF /x *.exclude /x *.ldf /x *.pl /x *.nsis /x *.cmd \"siteFolderName\\*.*\"\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
131,605
<p>What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system?</p> <p>To put this in perspective, here are a couple of use cases:</p> <ol> <li>version control for VBA modules </li> <li>more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc</li> <li>the users are not too technical and the fewer version control systems used the better</li> <li>Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet. </li> </ol>
[ { "answer_id": 132084, "author": "GUI Junkie", "author_id": 11498, "author_profile": "https://Stackoverflow.com/users/11498", "pm_score": 2, "selected": false, "text": "Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i%, sName$\n\n With ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n If .VBComponents(i%).CodeModule.CountOfLines > 0 Then\n sName$ = .VBComponents(i%).CodeModule.Name\n .VBComponents(i%).Export \"C:\\Code\\\" & sName$ & \".vba\"\n End If\n Next i\n End With\nEnd Sub\n" }, { "answer_id": 2003792, "author": "Demosthenex", "author_id": 243588, "author_profile": "https://Stackoverflow.com/users/243588", "pm_score": 7, "selected": true, "text": "Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i%, sName$\n\nWith ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n If .VBComponents(i%).CodeModule.CountOfLines > 0 Then\n sName$ = .VBComponents(i%).CodeModule.Name\n .VBComponents(i%).Export \"X:\\Tools\\MyExcelMacros\\\" & sName$ & \".vba\"\n End If\n Next i\nEnd With\n\nEnd Sub\n\nSub ImportCodeModules()\n\nWith ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n\n ModuleName = .VBComponents(i%).CodeModule.Name\n\n If ModuleName <> \"VersionControl\" Then\n If Right(ModuleName, 6) = \"Macros\" Then\n .VBComponents.Remove .VBComponents(ModuleName)\n .VBComponents.Import \"X:\\Data\\MySheet\\\" & ModuleName & \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n Private Sub Workbook_Open()\n\nImportCodeModules\n\nEnd Sub\n\nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n\nSaveCodeModules\n\nEnd Sub\n" }, { "answer_id": 22256698, "author": "przemo_li", "author_id": 330242, "author_profile": "https://Stackoverflow.com/users/330242", "pm_score": 3, "selected": false, "text": "Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i As Integer, name As String\n\nWith ThisWorkbook.VBProject\n For i = .VBComponents.count To 1 Step -1\n If .VBComponents(i).Type <> vbext_ct_Document Then\n If .VBComponents(i).CodeModule.CountOfLines > 0 Then\n name = .VBComponents(i).CodeModule.name\n .VBComponents(i).Export Application.ThisWorkbook.Path & _\n \"\\git\\\" & name & \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n\nSub ImportCodeModules()\nDim i As Integer\nDim ModuleName As String\n\nWith ThisWorkbook.VBProject\n For i = .VBComponents.count To 1 Step -1\n\n ModuleName = .VBComponents(i).CodeModule.name\n\n If ModuleName <> \"VersionControl\" Then\n If .VBComponents(i).Type <> vbext_ct_Document Then\n .VBComponents.Remove .VBComponents(ModuleName)\n .VBComponents.Import Application.ThisWorkbook.Path & _\n \"\\git\\\" & ModuleName & \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n Private Sub Workbook_Open()\n\n ImportCodeModules\n\nEnd Sub\n\nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n\n SaveCodeModules\n\nEnd Sub\n" }, { "answer_id": 30127696, "author": "dslosky", "author_id": 4921888, "author_profile": "https://Stackoverflow.com/users/4921888", "pm_score": 3, "selected": false, "text": "SaveCodeModules() Sub SaveCodeModules(dir As String)\n\n'This code Exports all VBA modules\nDim moduleName As String\nDim vbaType As Integer\n\nWith ThisWorkbook.VBProject\n For i = 1 To .VBComponents.count\n If .VBComponents(i).CodeModule.CountOfLines > 0 Then\n moduleName = .VBComponents(i).CodeModule.Name\n vbaType = .VBComponents(i).Type\n\n If vbaType = 1 Then\n .VBComponents(i).Export dir & moduleName & \".vba\"\n ElseIf vbaType = 3 Then\n .VBComponents(i).Export dir & moduleName & \".frm\"\n ElseIf vbaType = 100 Then\n .VBComponents(i).Export dir & moduleName & \".cls\"\n End If\n\n End If\n Next i\nEnd With\n\nEnd Sub\n .frm .frx Sheet1 Sheet2 ThisWorkbook .cls .cls Sub ImportCodeModules(dir As String)\n\nDim modList(0 To 0) As String\nDim vbaType As Integer\n\n' delete all forms, modules, and code in MEOs\nWith ThisWorkbook.VBProject\n For Each comp In .VBComponents\n\n moduleName = comp.CodeModule.Name\n\n vbaType = .VBComponents(moduleName).Type\n\n If moduleName <> \"DevTools\" Then\n If vbaType = 1 Or _\n vbaType = 3 Then\n\n .VBComponents.Remove .VBComponents(moduleName)\n\n ElseIf vbaType = 100 Then\n\n ' we can't simply delete these objects, so instead we empty them\n .VBComponents(moduleName).CodeModule.DeleteLines 1, .VBComponents(moduleName).CodeModule.CountOfLines\n\n End If\n End If\n Next comp\nEnd With\n\n' make a list of files in the target directory\nSet FSO = CreateObject(\"Scripting.FileSystemObject\")\nSet dirContents = FSO.getfolder(dir) ' figure out what is in the directory we're importing\n\n' import modules, forms, and MEO code back into workbook\nWith ThisWorkbook.VBProject\n For Each moduleName In dirContents.Files\n\n ' I don't want to import the module this script is in\n If moduleName.Name <> \"DevTools.vba\" Then\n\n ' if the current code is a module or form\n If Right(moduleName.Name, 4) = \".vba\" Or _\n Right(moduleName.Name, 4) = \".frm\" Then\n\n ' just import it normally\n .VBComponents.Import dir & moduleName.Name\n\n ' if the current code is a microsoft excel object\n ElseIf Right(moduleName.Name, 4) = \".cls\" Then\n Dim count As Integer\n Dim fullmoduleString As String\n Open moduleName.Path For Input As #1\n\n count = 0 ' count which line we're on\n fullmoduleString = \"\" ' build the string we want to put into the MEO\n Do Until EOF(1) ' loop through all the lines in the file\n\n Line Input #1, moduleString ' the current line is moduleString\n If count > 8 Then ' skip the junk at the top of the file\n\n ' append the current line `to the string we'll insert into the MEO\n fullmoduleString = fullmoduleString & moduleString & vbNewLine\n\n End If\n count = count + 1\n Loop\n\n ' insert the lines into the MEO\n .VBComponents(Replace(moduleName.Name, \".cls\", \"\")).CodeModule.InsertLines .VBComponents(Replace(moduleName.Name, \".cls\", \"\")).CodeModule.CountOfLines + 1, fullmoduleString\n\n Close #1\n\n End If\n End If\n\n Next moduleName\nEnd With\n\nEnd Sub\n dir SaveCodeModules \"C:\\...\\YourDirectory\\Project\\source\\\"\nImportCodeModules \"C:\\...\\YourDirectory\\Project\\source\\\"\n" }, { "answer_id": 30273256, "author": "nmz787", "author_id": 253127, "author_profile": "https://Stackoverflow.com/users/253127", "pm_score": 3, "selected": false, "text": "[diff \"xlsx\"]\n binary = true\n textconv = python `git rev-parse --show-toplevel`/src/util/git-xlsx-textconv.py\n [diff \"xlsx\"]\n binary = true\n textconv = python C:/Python27/Scripts/git-xlsx-textconv.py\n *.xlsx diff=xlsx\n" }, { "answer_id": 54755379, "author": "LShaver", "author_id": 5560474, "author_profile": "https://Stackoverflow.com/users/5560474", "pm_score": 0, "selected": false, "text": "*.txt ActiveWorkbook.VBProject.VBComponents(\"moduleName\").Export\"C:\\Path\\To\\Spreadsheet\\moduleName.txt\"\n *.txt" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
131,619
<h2>Question</h2> <p>Using XSLT 1.0, given a string with arbitrary characters how can I get back a string that meets the following rules.</p> <ol> <li>First character must be one of these: a-z, A-Z, colon, or underscore</li> <li>All other characters must be any of those above or 0-9, period, or hyphen</li> <li>If any character does not meet the above rules, replace it with an underscore</li> </ol> <h2>Background</h2> <p>In an XSLT I'm translating some attributes into elements, but I need to be sure the attribute doesn't contain any values that can't be used in an element name. I don't care much about the integrity of the attribute being converted to the name as long as it's being converted predictably. I also don't need to compensate for <em>every</em> valid character in an element name (there's a bunch).</p> <p>The problem I was having was with the attributes having spaces coming in, which the translate function can easily convert to underscores:</p> <pre><code>translate(@name,' ','_') </code></pre> <p>But soon after I found some of the attributes using slashes, so I have to add that now too. This will quickly get out of hand. I want to be able to define a whitelist of allowed characters, and replace any non-allowed characters with an underscore, but translate works as by replacing from a blacklist.</p>
[ { "answer_id": 132240, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<xsl:template name=\"normalizeName\">\n <xsl:param name=\"name\" />\n <xsl:param name=\"isFirst\" select=\"true()\" />\n <xsl:if test=\"$name != ''\">\n <xsl:variable name=\"first\" select=\"substring($name, 1, 1)\" />\n <xsl:variable name=\"rest\" select=\"substring($name, 2)\" />\n <xsl:choose>\n <xsl:when test=\"contains('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_', $first) or\n (not($first) and contains('0123456789.-', $first))\">\n <xsl:value-of select=\"$first\" />\n </xsl:when>\n <xsl:otherwise>\n <xsl:text>_</xsl:text>\n </xsl:otherwise>\n </xsl:choose>\n <xsl:call-template name=\"normalizeName\">\n <xsl:with-param name=\"name\" select=\"$rest\" />\n <xsl:with-param name=\"isFirst\" select=\"false()\" />\n </xsl:call-template>\n </xsl:if>\n</xsl:template>\n <xsl:variable name=\"underscores\"\n select=\"'_______________________________________________________'\" />\n<xsl:variable name=\"initialNameChars\"\n select=\"'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_'\" />\n<xsl:variable name=\"nameChars\"\n select=\"concat($initialNameChars, '0123456789.-')\" />\n translate() translate() <xsl:template name=\"normalizeName\">\n <xsl:param name=\"name\" />\n <xsl:variable name=\"first\" select=\"substring($name, 1, 1)\" />\n <xsl:variable name=\"rest\" select=\"substring($name, 2)\" />\n <xsl:variable name=\"illegalFirst\"\n select=\"translate($first, $initialNameChars, '')\" />\n <xsl:variable name=\"illegalRest\"\n select=\"translate($rest, $nameChars, '')\" />\n <xsl:value-of select=\"concat(translate($first, $illegalFirst, $underscores),\n translate($rest, $illegalRest, $underscores))\" />\n</xsl:template>\n <!--Generate string with given number of replacement-->\n<xsl:template name=\"gen-replacement\">\n<xsl:param name=\"n\"/>\n <xsl:if test=\"$n > 0\">\n <xsl:call-template name=\"gen-replacement\">\n <xsl:with-param name=\"n\" select=\"$n - 1\"/>\n </xsl:call-template>\n <xsl:text>_</xsl:text>\n </xsl:if>\n</xsl:template>\n <xsl:variable name=\"replacement\"><xsl:call-template name=\"gen-replacement\"><xsl:with-param name=\"n\" select=\"string-length($value)\"/></xsl:call-template></xsl:variable>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
131,628
<p>I wrote some code with a lot of recursion, that takes quite a bit of time to complete. Whenever I "pause" the run to look at what's going on I get: </p> <blockquote> <blockquote> <p>Cannot evaluate expression because the code of the current method is optimized.</p> </blockquote> </blockquote> <p>I think I understand what that means. However, what puzzles me is that after I hit step, the code is not "optimized" anymore, and I can look at my variables. How does this happen? How can the code flip back and forth between optimized and non-optimzed code?</p>
[ { "answer_id": 36870787, "author": "Raghavendra Prasad", "author_id": 6257514, "author_profile": "https://Stackoverflow.com/users/6257514", "pm_score": 3, "selected": false, "text": "Optimize Code" }, { "answer_id": 39897613, "author": "Guish", "author_id": 1456661, "author_profile": "https://Stackoverflow.com/users/1456661", "pm_score": 2, "selected": false, "text": "[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]\n AssemblyInfo" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
131,653
<p>I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:</p> <pre><code>&lt;p style="font-size: 24px"&gt;asdf&lt;/p&gt; </code></pre> <p>What's the syntax for embedding a rule like:</p> <pre><code>a:hover {text-decoration: underline;} </code></pre> <p>into the style attribute of an A tag? It's obviously not this...</p> <pre><code>&lt;a href="foo" style="text-decoration: underline"&gt;bar&lt;/a&gt; </code></pre> <p>...since that would apply all the time, as opposed to just during hover.</p>
[ { "answer_id": 131660, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 8, "selected": true, "text": "<a href=\"test.html\" style=\"{color: blue; background: white} \n :visited {color: green}\n :hover {background: yellow}\n :visited:hover {color: purple}\">Test</a>\n" }, { "answer_id": 131664, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 5, "selected": false, "text": "<a onmouseover=\"this.style.textDecoration='underline';\" \n onmouseout=\"this.style.textDecoration='none';\">bar</a>\n" }, { "answer_id": 131682, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 4, "selected": false, "text": "a.hovertest:hover\n{\ntext-decoration:underline;\n}\n\n<a href=\"http://example.com\" class=\"foo bar hovertest\">blah</a>\n" }, { "answer_id": 25333956, "author": "Roberto", "author_id": 3945826, "author_profile": "https://Stackoverflow.com/users/3945826", "pm_score": 5, "selected": false, "text": "<a href=\"#\" onmouseover=\"this.style.color='orange';\" onmouseout=\"this.style.color='';\">My Link</a>\n <script>\n /** Change the style **/\n function overStyle(object){\n object.style.color = 'orange';\n // Change some other properties ...\n }\n\n /** Restores the style **/\n function outStyle(object){\n object.style.color = 'orange';\n // Restore the rest ...\n }\n</script>\n\n<a href=\"#\" onmouseover=\"overStyle(this)\" onmouseout=\"outStyle(this)\">My Link</a>\n" }, { "answer_id": 26372047, "author": "Josh Kernich", "author_id": 2205806, "author_profile": "https://Stackoverflow.com/users/2205806", "pm_score": 1, "selected": false, "text": "<div style=\"position:relative;width:100px;background:#ddffdd;overflow:hidden;\" onmouseover=\"this.style.overflow='';\" onmouseout=\"this.style.overflow='hidden';\">first hover<div style=\"width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;\">stuff inside</div></div>\n" }, { "answer_id": 60869890, "author": "michielbdejong", "author_id": 680454, "author_profile": "https://Stackoverflow.com/users/680454", "pm_score": 0, "selected": false, "text": "<p> '&:hover'" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
131,666
<p>What is the right place to store program data files which are the same for every user but have to be writeable for the program? What would be the equivalent location on MS Windows XP? I have read that C:\ProgramData is not writeable after installation by normal users. Is that true? How can I retrieve that directory programmatically using the Platform SDK?</p>
[ { "answer_id": 131684, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 4, "selected": true, "text": "SHGetFolderPath() CSIDL_COMMON_APPDATA %ALLUSERSPROFILE%" }, { "answer_id": 131688, "author": "dennisV", "author_id": 20208, "author_profile": "https://Stackoverflow.com/users/20208", "pm_score": 1, "selected": false, "text": "CString strPath;\n::SHGetSpecialFolderPath(NULL, strPath.GetBuffer(1024), CSIDL_COMMON_APPDATA, FALSE);\n" }, { "answer_id": 539484, "author": "Enrico Detoma", "author_id": 19808, "author_profile": "https://Stackoverflow.com/users/19808", "pm_score": 2, "selected": false, "text": "SHGetFolderPath SHGetKnownFolderPath" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21683/" ]
131,681
<p>What techniques and/or modules are available to implement robust rate limiting (requests|bytes/ip/unit time) in apache?</p>
[ { "answer_id": 20356408, "author": "Diego Fernández Durán", "author_id": 709588, "author_profile": "https://Stackoverflow.com/users/709588", "pm_score": 5, "selected": false, "text": "SecRuleEngine On\n\n<LocationMatch \"^/somepath\">\n SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog\n SecAction \"phase:5,deprecatevar:ip.somepathcounter=1/1,pass,nolog\"\n SecRule IP:SOMEPATHCOUNTER \"@gt 60\" \"phase:2,pause:300,deny,status:509,setenv:RATELIMITED,skip:1,nolog\"\n SecAction \"phase:2,pass,setvar:ip.somepathcounter=+1,nolog\"\n Header always set Retry-After \"10\" env=RATELIMITED\n</LocationMatch>\n\nErrorDocument 509 \"Rate Limit Exceeded\"\n" }, { "answer_id": 20707343, "author": "wuzer", "author_id": 2792350, "author_profile": "https://Stackoverflow.com/users/2792350", "pm_score": 3, "selected": false, "text": "mod_evasive" }, { "answer_id": 28502392, "author": "Panama Jack", "author_id": 330987, "author_profile": "https://Stackoverflow.com/users/330987", "pm_score": 4, "selected": false, "text": "Sample configuration:\n# minimum request rate (bytes/sec at request reading):\nQS_SrvRequestRate 120\n\n# limits the connections for this virtual host:\nQS_SrvMaxConn 800\n\n# allows keep-alive support till the server reaches 600 connections:\nQS_SrvMaxConnClose 600\n\n# allows max 50 connections from a single ip address:\nQS_SrvMaxConnPerIP 50\n\n# disables connection restrictions for certain clients:\nQS_SrvMaxConnExcludeIP 172.18.3.32\nQS_SrvMaxConnExcludeIP 192.168.10.\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8171/" ]
131,704
<p>Eclipse 3.4[.x] - also known as <a href="http://www.eclipse.org/downloads/packages/" rel="noreferrer">Ganymede</a> - comes with this new mechanism of provisioning called <strong>p2</strong>.</p> <p>"Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the <a href="http://developers.sun.com/mobility/midp/articles/ota" rel="noreferrer">Sun Web site</a>.</p> <p>Eclipse has an extended <a href="http://wiki.eclipse.org/Category:Equinox_p2" rel="noreferrer">wiki section</a> in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new components However after reading it.</p> <p>I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with <strong>local</strong> file (either on your computer or on an UNC path '\server\path'), as <a href="http://wiki.eclipse.org/Equinox_p2_PDE_Integration" rel="noreferrer">illustrated here</a>, but also by the files:</p> <ul> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs</li> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs</li> </ul> <p>p2 mechanism is used to update eclipse itself, through an <a href="http://download.eclipse.org/eclipse/updates/3.4" rel="noreferrer">eclipse 3.4 update site</a>, and reference in those '.prefs' files with line like:</p> <blockquote> <p>repositories/file:_C:_jv_eclipse_eclipse-SDK-3.4-win32_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/</p> </blockquote> <p>Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, <strong>in order to have an upgrade process entirely run locally</strong>, without having to access the web?<br> I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well.</p> <p>Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)</p>
[ { "answer_id": 711754, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": 5, "selected": true, "text": "./eclipse\\\n -nosplash -consolelog -debug\\\n -vm \"${VM}\"\\\n -application org.eclipse.equinox.p2.director.app.application\\\n -metadataRepository file:${SHARED_REPOSITORY_DIR}\\\n -artifactRepository file:${SHARED_REPOSITORY_DIR}\\\n -installIU \"${4-org.eclipse.sdk.ide}\"\\\n -destination \"${3}\"\\\n -profile \"${1}\"\\\n -profileProperties org.eclipse.update.install.features=true\\\n -bundlepool ${SHARED_BUNDLEPOOL_DIR}\\\n -p2.os linux\\\n -p2.ws gtk\\\n -p2.arch \"${2}\"\\\n \\\n -vmargs\\\n -Xms64m -Xmx1024m -XX:MaxPermSize=256m\\\n -Declipse.p2.data.area=${SHARED_P2_DIR}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
131,718
<p>Is there a simple way to write a common function for each of the <code>CRUD (create, retreive, update, delete)</code> operations in <code>PHP</code> WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a <code>mySQL database</code>. Another requirement is that the function should be able to support joins I.e. it should be able to insert data into multiple tables if required. </p> <p>I know that these tasks could be done by using a framework but because of various reasons - too lengthy to explain here - I cannot use them.</p>
[ { "answer_id": 131814, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 0, "selected": false, "text": "get_class() get_class_vars()" }, { "answer_id": 133479, "author": "lewis", "author_id": 14442, "author_profile": "https://Stackoverflow.com/users/14442", "pm_score": 2, "selected": true, "text": "$data = array(array('name' => 'id', 'type' => 'hidden')\n , array('name' => 'student', 'type' => 'text', 'title' => 'Student'));\n new MyScaffold($table, 'edit', $data, $_GET['id']);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22009/" ]
131,728
<p>I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution.</p> <p>I would like to be able to upload files using the Document Manager of this control.</p> <p>However, these files are larger than whatever the default setting is for maximum upload file size.</p> <p>Can anyone point me in the right direction to fix this?</p> <p><hr> Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.</p>
[ { "answer_id": 131737, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": true, "text": "<system.web>\n <httpRuntime maxRequestLength=\"102400\" executionTimeout= \"3600\" />\n</system.web>\n" }, { "answer_id": 131773, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "RadEditor1.DocumentManager.MaxUploadFileSize = 4194304;\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
131,788
<p>I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). </p> <p>For example find all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file.</p> <p>At this moment the cases I can think of that it needs to account for are:</p> <ol> <li><p>The file being parsed is in the same package as the search class. </p> <p>find foo.bar.Baz references in foo/bar/Boing.java</p></li> <li><p>It should ignore comments.</p> <pre><code>// this is a comment saying this method returns a foo.bar.Baz or Baz instance // it shouldn't count /* a multiline comment as well this shouldn't count if I put foo.bar.Baz or Baz in here either */ </code></pre></li> <li><p>In-line fully qualified references.</p> <pre><code>foo.bar.Baz fb = new foo.bar.Baz(); </code></pre></li> <li><p>References based off an import statement.</p> <pre><code>import foo.bar.Baz; ... Baz b = new Baz(); </code></pre></li> </ol> <p>What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps?</p> <pre><code>open F, $File::Find::name or die; # these three things are already known # $classToFind looking for references of this class # $pkgToFind the package of the class you're finding references of # $currentPkg package name of the file being parsed while(&lt;F&gt;){ # ... do work here } close F; # the results are availble here in some form </code></pre>
[ { "answer_id": 131959, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 4, "selected": true, "text": "\\bimport\\b \\b\\Q$toFind\\E\\b if( m[\n \\G\n (?:\n [^'\"/]+\n | /(?![/*])\n )+\n ]xgc\n) {\n my $code = substr( $_, $-[0], $+[0] - $-[0] );\n my $imported = 0;\n while( $code =~ /\\b(import\\s+)?\\Q$package\\E\\b/g ) {\n if( $1 ) {\n ... # Found importing of package\n while( $code =~ /\\b\\Q$class\\E\\b/g ) {\n ... # Found mention of imported class\n }\n last;\n }\n ... # Found a package reference\n }\n} elsif( m[ \\G ' (?: [^'\\\\]+ | \\\\. )* ' ]xgc\n || m[ \\G \" (?: [^\"\\\\]+ | \\\\. )* \" ]xgc\n) {\n # skip quoted strings\n} elsif( m[\\G//.*]g­c ) {\n # skip C++ comments\n" }, { "answer_id": 131970, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "my $in_comment;\nmy %matches;\nmy $line_num = 0;\nmy $full_target = 'foo.bar.Baz';\nmy $short_target = (split /\\./, $full_target)[-1]; # segment after last . (Baz)\n\nwhile (my $line = <F>) {\n $line_num++;\n if ($in_comment) {\n next unless $line =~ m|\\*/|; # ignore line unless it ends the comment\n $line =~ s|.*\\*/||; # delete everything prior to end of comment\n } elsif ($line =~ m|/\\*|) {\n if ($line =~ m|\\*/|) { # catch /* and */ on same line\n $line =~ s|/\\*.*\\*/||;\n } else {\n $in_comment = 1;\n $line =~ s|/\\*.*||; # clear from start of comment to end of line\n }\n }\n\n $line =~ s/\\\\\\\\.*//; # remove single-line comments\n $matches{$line_num} = $line if $line =~ /$full_target| $short_target/;\n}\n\nfor my $key (sort keys %matches) {\n print $key, ': ', $matches{$key}, \"\\n\";\n}\n" }, { "answer_id": 142497, "author": "polarbear", "author_id": 3636, "author_profile": "https://Stackoverflow.com/users/3636", "pm_score": 2, "selected": false, "text": " my $className = 'Baz';\n my $searchPkg = 'foo.bar';\n my @potentialRefs, my @confirmedRefs;\n my $samePkg = 0;\n my $imported = 0;\n my $currentPkg = 'com.bob';\n $currentPkg =~ s/\\//\\./g;\n if($currentPkg eq $searchPkg){\n $samePkg = 1; \n }\n my $inMultiLineComment = 0;\n open F, $_ or die;\n my $lineNum = 0;\n while(<F>){\n $lineNum++;\n if($inMultiLineComment){\n if(m|^.*?\\*/|){\n s|^.*?\\*/||; #get rid of the closing part of the multiline comment we're in\n $inMultiLineComment = 0;\n }else{\n next;\n }\n }\n if(length($_) > 0){\n s|\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"||g; #remove strings first since java cannot have multiline string literals\n s|/\\*.*?\\*/||g; #remove any multiline comments that start and end on the same line\n s|//.*$||; #remove the // comments from what's left\n if (m|/\\*.*$|){\n $inMultiLineComment = 1 ;#now if you have any occurence of /* then then at least some of the next line is in the multiline comment\n s|/\\*.*$||g;\n }\n }else{\n next; #no sense continuing to process a blank string\n }\n\n if (/^\\s*(import )?($searchPkg)?(.*)?\\b$className\\b/){\n if($imported || $samePkg){\n push(@confirmedRefs, $lineNum);\n }else {\n push(@potentialRefs, $lineNum);\n }\n if($1){\n $imported = 1;\n } elsif($2){\n push(@confirmedRefs, $lineNum);\n }\n }\n }\n close F; \n if($imported){\n push(@confirmedRefs,@potentialRefs);\n }\n\n for (@confirmedRefs){\n print \"$_\\n\";\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636/" ]
131,793
<p>I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?</p>
[ { "answer_id": 131826, "author": "John Ferguson", "author_id": 8312, "author_profile": "https://Stackoverflow.com/users/8312", "pm_score": 4, "selected": true, "text": "library foolib; \n\nuses\n foo in 'foo.pas',\n baz in 'baz.pas';\n\n{$R *.RES}\n\nexports\n foofunc name 'foofunc';\n\nend;\n" }, { "answer_id": 132227, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "{$R *.RES}" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312/" ]
131,803
<p>I notice that modern C and C++ code seems to use <code>size_t</code> instead of <code>int</code>/<code>unsigned int</code> pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.</p>
[ { "answer_id": 131833, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 10, "selected": true, "text": "size_t sizeof offsetof size_t unsigned int" }, { "answer_id": 131860, "author": "azeemarif", "author_id": 14996, "author_profile": "https://Stackoverflow.com/users/14996", "pm_score": 7, "selected": false, "text": "size_t size_t" }, { "answer_id": 4295225, "author": "Rose Perrone", "author_id": 365298, "author_profile": "https://Stackoverflow.com/users/365298", "pm_score": 7, "selected": false, "text": "size_t size_t size_t unsigned int unsigned int 4294967295 4294967295 unsigned long int long size_t size_t unsigned int unsigned long unsigned long long" }, { "answer_id": 18972136, "author": "Graeme Burke", "author_id": 2809374, "author_profile": "https://Stackoverflow.com/users/2809374", "pm_score": 2, "selected": false, "text": "stddef.h' to be whatever type the system's fixincludes' script will massage the system's" }, { "answer_id": 34886762, "author": "Zebrafish", "author_id": 4696802, "author_profile": "https://Stackoverflow.com/users/4696802", "pm_score": 2, "selected": false, "text": "size_t unsigned int size_t unsigned long long" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
131,805
<p>What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice.</p> <p>Thanks.</p>
[ { "answer_id": 131824, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 1, "selected": false, "text": "select into" }, { "answer_id": 131825, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 3, "selected": false, "text": "CREATE TABLE dest_table AS (SELECT * FROM source_table);\n INSERT INTO dest_table (SELECT * FROM source_table);\n" }, { "answer_id": 131861, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 4, "selected": true, "text": "INSERT INTO database_b.table (SELECT * FROM database_a.table)\n" }, { "answer_id": 134190, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 1, "selected": false, "text": "mysqldump somedb sometable -u user -p | mysql otherdb -u user -p\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11193/" ]
131,811
<p>Can someone explain why how the result for the following unpack is computed?</p> <pre><code>"aaa".unpack('h2H2') #=&gt; ["16", "61"] </code></pre> <p>In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).</p>
[ { "answer_id": 131858, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "a h2 H2" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18432/" ]
131,812
<p>I want to calculate the time span between 2 times which I saved in a database. So literally I want to know the length of time between the 2 values.</p> <p>14:10:20 - 10:05:15 = 02:05:05</p> <p>So the result would be 02:05:05.</p> <p>How would I be able to achieve this using C#?</p> <p>14:10:20 is the format I saved it in in my database.</p>
[ { "answer_id": 131820, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 4, "selected": true, "text": ".Subtract() TimeSpan difference = t1.Subtract(t2);" }, { "answer_id": 131851, "author": "Niklas Winde", "author_id": 9077, "author_profile": "https://Stackoverflow.com/users/9077", "pm_score": 0, "selected": false, "text": "DateTime then = DateTime.Now;\nThread.Sleep(500);\nDateTime now = DateTime.Now;\nTimeSpan time = now - then;\nMessageBox.Show(time.ToString());\n" }, { "answer_id": 132035, "author": "lowglider", "author_id": 9602, "author_profile": "https://Stackoverflow.com/users/9602", "pm_score": 2, "selected": false, "text": "DateTime DateTime SQLCommand getTimeCommand = new SQLCommand(\"SELECT time FROM table\", dbConnection);\nSQLDataReader myReader = getTimeCommand.ExecuteReader();\nwhile (myReader.Read())\n{\n DateTime time = myReader.GetDateTime(0);\n}\nmyReader.Close();\n DateTime DateTime.Parse \n DateTime.ParseExact\n ParseExact TimeSpan DateTime time1, time2; //filled with your timevalues from the db\nTimeSpan elapsed = d2 - d1;\n elapsed DateTimes TimeSpan" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
131,847
<p>I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)</p> <p>I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.</p> <p>seems like the answer must be really simple but I'm just not seeing it... thanks for the help!</p>
[ { "answer_id": 131876, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "(-2.5,6)\n *-----\n |\\x\n | \\\n | \\\n9 | \\\n | \\\n | x\\\n +------* (5,-3)\n 7.5\n -1\ntan (9/7.5)\n" }, { "answer_id": 132068, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 2, "selected": false, "text": "F(5, -3) = 5^2 * A + (-3)^2 * B + (-15) * C + D = 0 \nF(2.5, -6) = (2.5)^2 * A + (-6)^2 * B + (-15) * C + D = 0 \ndF(2.5, -6)/dx = 2*(2.5) * A + (-6) * C = 0 \ndF(5, -3)/dy = 2*(-3) * B + 5 * C = 0 \n 25A + 9B - 15C + D = 0 //1\n6.25A + 36B - 15C + D = 0 //2\n 5A - 6C = 0 //3\n - 6B + 5C = 0 //4\n 25A + 9B - 15C = 1 //1\n 5A - 6C = 0 //3\n - 6B + 5C = 0 //4\n x = ξcos(φ) - ηsin(φ)\ny = ξsin(φ) + ηcos(φ)\n F(x(ξ, η), y(ξ, η)) = G(ξ, η) =\n A (ξ^2cos^2(φ) + η^2sin^2(φ) - 2ξηcos(φ)sin(φ))\n+ B (ξ^2sin^2(φ) + η^2cos^2(φ) + 2ξηcos(φ)sin(φ))\n+ C (ξ^2cos(φ)sin(φ) - η^2cos(φ)sin(φ) + ξη(cos^2(φ) - sin^2(φ))) + D\n 2cos(φ)sin(φ) = sin(2φ)\ncos^2(φ) - sin^2(φ) = cos(2φ)\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
131,866
<p>I have a serializiable object with listeners registered. Currently the list of listeners is stored in the object as <code>transient</code>. When the object is serialized and then deserialized, obviously the listeners are no longer registered.</p> <p>What would be the safest and best way to go about re-registering the listeners automatically once the object is deserialized? Is there a good design pattern that would help here?</p>
[ { "answer_id": 133734, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 2, "selected": false, "text": " private void readObject(ObjectInputStream in) \n throws ClassNotFoundException, IOException {\n // do normal serialization first!\n in.defaultReadObject();\n\n // put code here that can somehow reconstruct your listeners\n // presumably you have someplace you can look them up\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
131,871
<p>I'd love to figure it out myself but I was wondering <strong>roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?</strong> For example how does C# turn this:</p> <pre><code>IEnumerator&lt;string&gt; strings(IEnumerable&lt;string&gt; args) { IEnumerator&lt;string&gt; enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } </code></pre> <p>into this:</p> <pre><code>bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false; } </code></pre> <p>Of course the result can be completely different depending on the original code.</p>
[ { "answer_id": 132085, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 7, "selected": true, "text": "foreach (var x in y)\n{\n //body\n}\n var enumerator = y.GetEnumerator();\nwhile (enumerator.MoveNext())\n{\n var x = enumerator.Current;\n //body\n}\n\nif (y != null)\n{\n enumerator.Dispose();\n}\n class ClosureEnumerable : IEnumerable<string>\n {\n private IEnumerable<string> args;\n private ClassType originalThis;\n public ClosureEnumerator(ClassType origThis, IEnumerable<string> args)\n {\n this.args = args;\n this.origianlThis = origThis;\n }\n public IEnumerator<string> GetEnumerator()\n {\n return new Closure(origThis, args);\n }\n }\n\nclass Closure : IEnumerator<string>\n{\n public Closure(ClassType originalThis, IEnumerable<string> args)\n {\n state = 0;\n this.args = args;\n this.originalThis = originalThis;\n }\n\n private IEnumerable<string> args;\n private IEnumerator<string> enumerator2;\n private IEnumerator<string> argEnumerator;\n\n //- Here ClassType is the type of the object that contained the method\n // This may be optimized away if the method does not access any \n // class members\n private ClassType originalThis;\n\n //This holds the state value.\n private int state;\n //The current value to return\n private string currentValue;\n\n public string Current\n {\n get \n {\n return currentValue;\n }\n }\n}\n currentValue = expr;\nstate = //the state number of the yield statement;\nreturn true;\n state = -1;\nreturn false;\n IEnumerator<string> strings(IEnumerable<string> args)\n{\n return new ClosureEnumerable(this,args);\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
131,901
<p>I am trying to copy a file using the following code:</p> <pre><code>File targetFile = new File(targetPath + File.separator + filename); ... targetFile.createNewFile(); fileInputStream = new FileInputStream(fileToCopy); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[64*1024]; int i = 0; while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i); } </code></pre> <p>For some users the <code>targetFile.createNewFile</code> results in this exception:</p> <pre><code>java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) </code></pre> <p>Filename and directory name seem to be correct. The directory <code>targetPath</code> is even checked for existence before the copy code is executed and the filename looks like this: <code>AB_timestamp.xml</code></p> <p>The user has write permissions to the <code>targetPath</code> and can copy the file without problems using the OS.</p> <p>As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.</p>
[ { "answer_id": 133845, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "File targetFile = new File(targetPath, filename);\n" }, { "answer_id": 204143, "author": "Turismo", "author_id": 5271, "author_profile": "https://Stackoverflow.com/users/5271", "pm_score": 0, "selected": false, "text": "File parentFolder = new File(targetPath);\n... do some checks on parentFolder here ...\nFile targetFile = new File(parentFolder, filename);\ntargetFile.createNewFile();\nfileInputStream = new FileInputStream(fileToCopy);\nfileOutputStream = new FileOutputStream(targetFile);\nbyte[] buffer = new byte[64*1024];\nint i = 0;\nwhile((i = fileInputStream.read(buffer)) != -1) {\n fileOutputStream.write(buffer, 0, i);\n}\n" }, { "answer_id": 4921530, "author": "w.pasman", "author_id": 606450, "author_profile": "https://Stackoverflow.com/users/606450", "pm_score": 2, "selected": false, "text": "import java.io.File;\npublic class TestWrite {\n\n public static void main(String[] args) {\n if (args.length!=1) {\n throw new IllegalArgumentException(\"Expected 1 argument: dir for tmp file\");\n }\n try {\n File.createTempFile(\"bla\",\".tmp\",new File(args[0]));\n } catch (Exception e) {\n System.out.println(\"exception:\"+e);\n e.printStackTrace();\n }\n }\n}\n" }, { "answer_id": 35444964, "author": "Adam Hughes", "author_id": 4076764, "author_profile": "https://Stackoverflow.com/users/4076764", "pm_score": 5, "selected": false, "text": "myfile_HH:mm:ss.csv" }, { "answer_id": 74408100, "author": "user20481302", "author_id": 20481302, "author_profile": "https://Stackoverflow.com/users/20481302", "pm_score": 0, "selected": false, "text": "FileUtils.copyFile(src,new File(\"C:\\\\Users\\\\daiva\\\\eclipse-workspace\\\\PracticeProgram\\\\Screenshot\\\\adi.png\"));\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5271/" ]
131,902
<p>I am wondering what security concerns there are to implementing a <code>PHP evaluator</code> like this:</p> <pre><code>&lt;?php eval($_POST['codeInput']); %&gt; </code></pre> <p>This is in the context of making a <code>PHP sandbox</code> so sanitising against <code>DB input</code> etc. isn't a massive issue.</p> <p>Users destroying the server the file is hosted on is.</p> <p>I've seen <code>Ruby simulators</code> so I was curious what's involved security wise (vague details at least).</p> <hr> <p>Thanks all. I'm not even sure on which answer to accept because they are all useful.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911">Owen's answer</a> summarises what I suspected (the server itself would be at risk).</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019">arin's answer</a> gives a great example of the potential problems.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167">Geoff's answer</a> and <a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118">randy's answer</a> echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.</p>
[ { "answer_id": 137019, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 4, "selected": true, "text": "eval() <?php\n eval(\"shell_exec(\\\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\\\");\");\n?>\n" }, { "answer_id": 739930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "eval() exec exec $variable()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
131,944
<p>How do I read a time value and then insert it into a TimeSpan variables?</p>
[ { "answer_id": 131960, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 1, "selected": false, "text": "TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);\n DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);\n" }, { "answer_id": 131963, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 0, "selected": false, "text": "var span = new TimeSpan(hours, minutes, seconds);\n var newSpan = span.Add(new TimeSpan(hours, minutes, seconds));\n" }, { "answer_id": 131968, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 2, "selected": false, "text": "TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);\n" }, { "answer_id": 131980, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "string input = \"08:00\";\nDateTime time;\nif (!DateTime.TryParse(input, out time))\n{\n // invalid input\n return;\n}\n\nTimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
131,955
<p>Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?</p> <p>The typical <kbd>Shift</kbd>+<kbd>Insert</kbd> does not seem to work here.</p>
[ { "answer_id": 133332, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 8, "selected": true, "text": "; Redefine only when the active window is a console window \n#IfWinActive ahk_class ConsoleWindowClass\n\n; Close Command Window with Ctrl+w\n$^w::\nWinGetTitle sTitle\nIf (InStr(sTitle, \"-\")=0) { \n Send EXIT{Enter}\n} else {\n Send ^w\n}\n\nreturn \n\n\n; Ctrl+up / Down to scroll command window back and forward\n^Up::\nSend {WheelUp}\nreturn\n\n^Down::\nSend {WheelDown}\nreturn\n\n\n; Paste in command window\n^V::\n; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)\nSend !{Space}ep\nreturn\n\n#IfWinActive \n" }, { "answer_id": 2421490, "author": "Huw Walters", "author_id": 291033, "author_profile": "https://Stackoverflow.com/users/291033", "pm_score": 5, "selected": false, "text": "; Use backslash instead of backtick (yes, I am a C++ programmer).\n#EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nSendInput {Raw}%clipboard2%\nreturn\n" }, { "answer_id": 2762050, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 2, "selected": false, "text": "; Paste in command window\n^V::\n; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)\nSend !+{Space}ep\nreturn\n" }, { "answer_id": 17630810, "author": "Djee", "author_id": 2500798, "author_profile": "https://Stackoverflow.com/users/2500798", "pm_score": 2, "selected": false, "text": "; Use backslash instead of backtick (yes, I am a C++ programmer).\n#EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nSendInput {Raw}%clipboard2%\nreturn\n #EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nclipboard3 := \"\"\nLoop {\n if (a_index>strlen(clipboard2))\n break \n char_asc := Asc(SubStr(clipboard2, a_Index, 1)) \n if (char_asc > 127 and char_asc < 256)\n add_zero := \"0\"\n else\n add_zero := \"\" \n clipboard3 := clipboard3 . \"{Asc \" . add_zero . char_asc . \"}\"\n}\nSendInput %clipboard3%\nreturn\n" }, { "answer_id": 35676684, "author": "U007D", "author_id": 1541330, "author_profile": "https://Stackoverflow.com/users/1541330", "pm_score": 1, "selected": false, "text": "stty lnext ^q stop undef start undef \"\\C-v\": paste-from-clipboard\n\"\\C-C\": copy-to-clipboard\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
131,975
<p>I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as:</p> <pre><code>&lt;bean id="Mary" class="foo.bar.Female"&gt; &lt;property name="age" value="23"/&gt; &lt;/bean&gt; &lt;bean id="John" class="foo.bar.Male"&gt; &lt;property name="girlfriend" ref="Mary"/&gt; &lt;/bean&gt; </code></pre> <p>compared to plain old java code such as:</p> <pre><code>Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); </code></pre> <p>which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.)</p> <hr> <p><strong>UPDATE:</strong><br/> In case of</p> <pre><code>IService myService;// ... public void doSomething() { myService.fetchData(); } </code></pre> <p>How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it.</p> <p>It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use.</p> <hr> <p><strong>UPDATE 2:</strong><br/> I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file.</p> <hr> <p><strong>UPDATE 3:</strong><br/></p> <blockquote> <p>External configuration of mapping between interfaces and their concrete implementations </p> </blockquote> <p>What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?!</p> <blockquote> <p>You save coding time because you provide mappings declaratively, not in a procedural code </p> </blockquote> <p>I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it.</p> <blockquote> <p>Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)</p> </blockquote> <p>I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values.</p> <pre><code>mary = new FakeFemale(); </code></pre> <p>I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it?</p> <p>When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it?</p> <hr> <p><strong>LAST UPDATE:</strong><br/> Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.</p>
[ { "answer_id": 132011, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 0, "selected": false, "text": "IService myService;\n// ...\npublic void doSomething() {\n myService.fetchData();\n}\n" }, { "answer_id": 132049, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<bean id=\"jane\" class=\"foo.bar.HotFemale\">\n <property name=\"age\" value=\"19\"/>\n</bean>\n<bean id=\"mary\" class=\"foo.bar.Female\">\n <property name=\"age\" value=\"23\"/>\n</bean>\n<bean id=\"john\" class=\"foo.bar.Male\">\n <property name=\"girlfriend\" ref=\"jane\"/>\n</bean>\n" }, { "answer_id": 137714, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 1, "selected": false, "text": " UI-context.xml\n Model-context.xml\n Controller-context.xml\n AlternateUI-context.xml\n Model-context.xml\n Controller-context.xml\n ControllerAdditions-context.xml\n" }, { "answer_id": 155963, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 2, "selected": false, "text": "<bean id=\"base\" parent=\"RootXFireBean\">\n <property name=\"secondProperty\" ref=\"secondBean\" />\n</bean>\n\n<bean id=\"secondBean\" parent=\"secondaryXFireBean\">\n <property name=\"firstProperty\" ref=\"thirdBean\" />\n</bean>\n\n<bean id=\"thirdBean\" parent=\"thirdXFireBean\">\n <property name=\"secondProperty\" ref=\"myNewBean\" />\n</bean>\n\n<bean id=\"myNewBean\" class=\"WowItsActuallyTheCodeThatChanged\" />\n public class TheFirstPointlessClass extends SomeXFireClass {\n public TheFirstPointlessClass() {\n setFirstProperty(new TheSecondPointlessClass());\n setSecondProperty(new TheThingThatWasHereBefore());\n }\n}\n\npublic class TheSecondPointlessClass extends YetAnotherXFireClass {\n public TheSecondPointlessClass() {\n setFirstProperty(TheThirdPointlessClass());\n }\n}\n\npublic class TheThirdPointlessClass extends GeeAnotherXFireClass {\n public TheThirdPointlessClass() {\n setFirstProperty(new AnotherThingThatWasHereBefore());\n setSecondProperty(new WowItsActuallyTheCodeThatChanged());\n }\n}\n\npublic class WowItsActuallyTheCodeThatChanged extends TheXFireClassIActuallyCareAbout {\n public WowItsActuallyTheCodeThatChanged() {\n }\n\n public overrideTheMethod(Object[] arguments) {\n //Do overridden stuff\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ]
131,985
<p>See the question. I want to see the methods and classes offered by a DLLs library.</p>
[ { "answer_id": 55172723, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "ildasm ildasm c:\\MyNetAssembly.dll\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
131,989
<p>I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option:</p> <pre><code>dig @ns1.foo.example example.com axfr </code></pre> <p>But this never works. Has anyone a better idea/approach</p>
[ { "answer_id": 132009, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 3, "selected": false, "text": "nslookup ls -d example.com > outfile.txt\n outfile.txt" }, { "answer_id": 132014, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 8, "selected": true, "text": "ns1.foo.example dig a.example.com dig b.example.com" }, { "answer_id": 147568, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 3, "selected": false, "text": "#nslookup\n\n>ls example.com\n" }, { "answer_id": 2337811, "author": "Miroslav Mirkov", "author_id": 281620, "author_profile": "https://Stackoverflow.com/users/281620", "pm_score": 5, "selected": false, "text": "dig example.com soa dig @ns.SOA.example example.com axfr" }, { "answer_id": 2865955, "author": "Paul Melici", "author_id": 345104, "author_profile": "https://Stackoverflow.com/users/345104", "pm_score": 7, "selected": false, "text": "stackexchange.com" }, { "answer_id": 5044496, "author": "Victor Klos", "author_id": 623543, "author_profile": "https://Stackoverflow.com/users/623543", "pm_score": 6, "selected": false, "text": "$ host -l example.com AXFR transfer failed" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22029/" ]
131,993
<p>Subversion is a great way to update our web applications on our servers. With a simple <code>svn update</code> all changed files get... well, changed.</p> <p>Except for the omnipresent configuration files such as <code>config.php</code> which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server.</p> <p>With the <code>update</code> command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file.</p> <p>But I don't want to set the <code>svn:ignore</code> property either, since the config file belongs to the project.</p> <p>Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?</p>
[ { "answer_id": 132036, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 2, "selected": true, "text": "[general]\ninfo=misc\ndb.password=secret\ndb.host=localhost\n\n[production : general]\ninfo=only on production system\ndb.password=secret1\n\n[testing : general]\ninfo=only on test system\ndb.password=secret2\n\n[dev : general]\ninfo=only on dev system\ndb.password=secret3\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260/" ]
132,030
<p>Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. </p> <p>Now, I would like to do 2 things. </p> <p>First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?</p> <p>Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?</p> <p>Looking forward to see your suggestions, cheers.</p> <p>Did as described in the first answer. Worked like a charm.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<ElementManifest Location=\"mywebpartManifest.xml\"> <Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n <Module Name=\"Yourfile.xslt\" Url=\"Style Library\" Path=\"\" RootWebOnly=\"TRUE\">\n <File Url=\"yourfile.xslt\" Type=\"GhostableInLibrary\" />\n </Module>\n</Elements>\n <Module Name=\"myWebpart\" List=\"113\" Url=\"_catalogs/wp\" RootWebOnly=\"FALSE\">\n <File Url=\"myWebpart.webpart\" Type=\"GhostableInLibrary\" />\n</Module>\n <Resources>\n <Resource Location=\"SimpleFeature\\Feature.xml\"/>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17577/" ]
132,038
<p>I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate <code>Outlook.Application</code> and directly calling its methods.</p> <p>I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...</p> <p>What I have found is that the actual work is done by <code>sendmail.dll</code>, there is a handler defined in registry under <code>HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}</code>. I would like either to use this dll somehow or to simulate the same steps it does.</p> <p>Thanks for your input.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<ElementManifest Location=\"mywebpartManifest.xml\"> <Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n <Module Name=\"Yourfile.xslt\" Url=\"Style Library\" Path=\"\" RootWebOnly=\"TRUE\">\n <File Url=\"yourfile.xslt\" Type=\"GhostableInLibrary\" />\n </Module>\n</Elements>\n <Module Name=\"myWebpart\" List=\"113\" Url=\"_catalogs/wp\" RootWebOnly=\"FALSE\">\n <File Url=\"myWebpart.webpart\" Type=\"GhostableInLibrary\" />\n</Module>\n <Resources>\n <Resource Location=\"SimpleFeature\\Feature.xml\"/>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10560/" ]
132,052
<p>I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (<a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42411" rel="noreferrer">details</a>).</p> <p>I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:</p> <ul> <li>No external dependencies</li> <li>Simple and reliable</li> <li>Support for <a href="http://www.freesoft.org/CIE/RFC/1945/58.htm" rel="noreferrer"><code>If-Modified-Since</code></a> header (i.e. custom <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)" rel="noreferrer"><code>getLastModified</code></a> method)</li> <li>(Optional) support for gzip encoding, etags,...</li> </ul> <p>Is such a servlet available somewhere? The closest I can find is <a href="http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758" rel="noreferrer">example 4-10</a> from the servlet book.</p> <p><strong>Update:</strong> The URL structure I want to use - in case you are wondering - is simply:</p> <pre class="lang-xml prettyprint-override"><code> &lt;servlet-mapping&gt; &lt;servlet-name&gt;main&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;default&lt;/servlet-name&gt; &lt;url-pattern&gt;/static/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>So all requests should be passed to the main servlet, unless they are for the <code>static</code> path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the <code>static</code> folder).</p>
[ { "answer_id": 132932, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": true, "text": "StaticServlet If-Modified-Since ServletUtils StaticServlet coalesce COALESCE public static <T> T coalesce(T...ts) {\n for(T t: ts)\n if(t != null)\n return t;\n return null;\n}\n" }, { "answer_id": 558771, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 0, "selected": false, "text": "<Configure class=\"org.mortbay.jetty.handler.ContextHandler\">\n<Set name=\"contextPath\">/static</Set>\n<Set name=\"resourceBase\"><SystemProperty name=\"jetty.home\" default=\".\"/>/static/</Set>\n<Set name=\"handler\">\n <New class=\"org.mortbay.jetty.handler.ResourceHandler\">\n <Set name=\"cacheControl\">max-age=3600,public</Set>\n </New>\n </Set>\n</Configure>\n" }, { "answer_id": 837020, "author": "axtavt", "author_id": 103154, "author_profile": "https://Stackoverflow.com/users/103154", "pm_score": 6, "selected": false, "text": "\npackage com.example;\n\nimport java.io.*;\n\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class DefaultWrapperServlet extends HttpServlet\n{ \n public void doGet(HttpServletRequest req, HttpServletResponse resp)\n throws ServletException, IOException\n {\n RequestDispatcher rd = getServletContext().getNamedDispatcher(\"default\");\n\n HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {\n public String getServletPath() { return \"\"; }\n };\n\n rd.forward(wrapped, resp);\n }\n}\n" }, { "answer_id": 1467740, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 2, "selected": false, "text": "package com.example;\n\nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport org.apache.catalina.servlets.DefaultServlet;\n\npublic class StaticServlet extends DefaultServlet\n{\n protected String pathPrefix = \"/static\";\n\n public void init(ServletConfig config) throws ServletException\n {\n super.init(config);\n\n if (config.getInitParameter(\"pathPrefix\") != null)\n {\n pathPrefix = config.getInitParameter(\"pathPrefix\");\n }\n }\n\n protected String getRelativePath(HttpServletRequest req)\n {\n return pathPrefix + super.getRelativePath(req);\n }\n}\n <servlet>\n <servlet-name>StaticServlet</servlet-name>\n <servlet-class>com.example.StaticServlet</servlet-class>\n <init-param>\n <param-name>pathPrefix</param-name>\n <param-value>/static</param-value>\n </init-param> \n</servlet>\n\n<servlet-mapping>\n <servlet-name>StaticServlet</servlet-name>\n <url-pattern>/static/*</url-pattern>\n</servlet-mapping> \n" }, { "answer_id": 1483443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " <servlet>\n <servlet-name>springapp</servlet-name>\n <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>jsp</servlet-name>\n <url-pattern>/WEB-INF/jsp/*</url-pattern>\n </servlet-mapping>\n\n <servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>/favicon.ico</url-pattern>\n </servlet-mapping>\n\n <servlet-mapping>\n <servlet-name>springapp</servlet-name>\n <url-pattern>/*</url-pattern>\n </servlet-mapping>\n" }, { "answer_id": 3582215, "author": "Taylor Gautier", "author_id": 19013, "author_profile": "https://Stackoverflow.com/users/19013", "pm_score": 6, "selected": false, "text": "<servlet-mapping> \n <servlet-name>default</servlet-name>\n <url-pattern>*.html</url-pattern>\n</servlet-mapping>\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>*.jpg</url-pattern>\n</servlet-mapping>\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>*.png</url-pattern>\n</servlet-mapping>\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>*.css</url-pattern>\n</servlet-mapping>\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>*.js</url-pattern>\n</servlet-mapping>\n\n<servlet-mapping>\n <servlet-name>myAppServlet</servlet-name>\n <url-pattern>/</url-pattern>\n</servlet-mapping>\n" }, { "answer_id": 9046095, "author": "Fareed Alnamrouti", "author_id": 427622, "author_profile": "https://Stackoverflow.com/users/427622", "pm_score": 4, "selected": false, "text": "<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>*.js</url-pattern>\n <url-pattern>*.css</url-pattern>\n <url-pattern>*.ico</url-pattern>\n <url-pattern>*.png</url-pattern>\n <url-pattern>*.jpg</url-pattern>\n <url-pattern>*.htc</url-pattern>\n <url-pattern>*.gif</url-pattern>\n</servlet-mapping> \n" }, { "answer_id": 29991447, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 5, "selected": false, "text": "ETag If-None-Match If-Modified-Since public abstract class StaticResourceServlet extends HttpServlet {\n\n private static final long serialVersionUID = 1L;\n private static final long ONE_SECOND_IN_MILLIS = TimeUnit.SECONDS.toMillis(1);\n private static final String ETAG_HEADER = \"W/\\\"%s-%s\\\"\";\n private static final String CONTENT_DISPOSITION_HEADER = \"inline;filename=\\\"%1$s\\\"; filename*=UTF-8''%1$s\";\n\n public static final long DEFAULT_EXPIRE_TIME_IN_MILLIS = TimeUnit.DAYS.toMillis(30);\n public static final int DEFAULT_STREAM_BUFFER_SIZE = 102400;\n\n @Override\n protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException {\n doRequest(request, response, true);\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n doRequest(request, response, false);\n }\n\n private void doRequest(HttpServletRequest request, HttpServletResponse response, boolean head) throws IOException {\n response.reset();\n StaticResource resource;\n\n try {\n resource = getStaticResource(request);\n }\n catch (IllegalArgumentException e) {\n response.sendError(HttpServletResponse.SC_BAD_REQUEST);\n return;\n }\n\n if (resource == null) {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n\n String fileName = URLEncoder.encode(resource.getFileName(), StandardCharsets.UTF_8.name());\n boolean notModified = setCacheHeaders(request, response, fileName, resource.getLastModified());\n\n if (notModified) {\n response.sendError(HttpServletResponse.SC_NOT_MODIFIED);\n return;\n }\n\n setContentHeaders(response, fileName, resource.getContentLength());\n\n if (head) {\n return;\n }\n\n writeContent(response, resource);\n }\n\n /**\n * Returns the static resource associated with the given HTTP servlet request. This returns <code>null</code> when\n * the resource does actually not exist. The servlet will then return a HTTP 404 error.\n * @param request The involved HTTP servlet request.\n * @return The static resource associated with the given HTTP servlet request.\n * @throws IllegalArgumentException When the request is mangled in such way that it's not recognizable as a valid\n * static resource request. The servlet will then return a HTTP 400 error.\n */\n protected abstract StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException;\n\n private boolean setCacheHeaders(HttpServletRequest request, HttpServletResponse response, String fileName, long lastModified) {\n String eTag = String.format(ETAG_HEADER, fileName, lastModified);\n response.setHeader(\"ETag\", eTag);\n response.setDateHeader(\"Last-Modified\", lastModified);\n response.setDateHeader(\"Expires\", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME_IN_MILLIS);\n return notModified(request, eTag, lastModified);\n }\n\n private boolean notModified(HttpServletRequest request, String eTag, long lastModified) {\n String ifNoneMatch = request.getHeader(\"If-None-Match\");\n\n if (ifNoneMatch != null) {\n String[] matches = ifNoneMatch.split(\"\\\\s*,\\\\s*\");\n Arrays.sort(matches);\n return (Arrays.binarySearch(matches, eTag) > -1 || Arrays.binarySearch(matches, \"*\") > -1);\n }\n else {\n long ifModifiedSince = request.getDateHeader(\"If-Modified-Since\");\n return (ifModifiedSince + ONE_SECOND_IN_MILLIS > lastModified); // That second is because the header is in seconds, not millis.\n }\n }\n\n private void setContentHeaders(HttpServletResponse response, String fileName, long contentLength) {\n response.setHeader(\"Content-Type\", getServletContext().getMimeType(fileName));\n response.setHeader(\"Content-Disposition\", String.format(CONTENT_DISPOSITION_HEADER, fileName));\n\n if (contentLength != -1) {\n response.setHeader(\"Content-Length\", String.valueOf(contentLength));\n }\n }\n\n private void writeContent(HttpServletResponse response, StaticResource resource) throws IOException {\n try (\n ReadableByteChannel inputChannel = Channels.newChannel(resource.getInputStream());\n WritableByteChannel outputChannel = Channels.newChannel(response.getOutputStream());\n ) {\n ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);\n long size = 0;\n\n while (inputChannel.read(buffer) != -1) {\n buffer.flip();\n size += outputChannel.write(buffer);\n buffer.clear();\n }\n\n if (resource.getContentLength() == -1 && !response.isCommitted()) {\n response.setHeader(\"Content-Length\", String.valueOf(size));\n }\n }\n }\n\n}\n interface StaticResource {\n\n /**\n * Returns the file name of the resource. This must be unique across all static resources. If any, the file\n * extension will be used to determine the content type being set. If the container doesn't recognize the\n * extension, then you can always register it as <code>&lt;mime-type&gt;</code> in <code>web.xml</code>.\n * @return The file name of the resource.\n */\n public String getFileName();\n\n /**\n * Returns the last modified timestamp of the resource in milliseconds.\n * @return The last modified timestamp of the resource in milliseconds.\n */\n public long getLastModified();\n\n /**\n * Returns the content length of the resource. This returns <code>-1</code> if the content length is unknown.\n * In that case, the container will automatically switch to chunked encoding if the response is already\n * committed after streaming. The file download progress may be unknown.\n * @return The content length of the resource.\n */\n public long getContentLength();\n\n /**\n * Returns the input stream with the content of the resource. This method will be called only once by the\n * servlet, and only when the resource actually needs to be streamed, so lazy loading is not necessary.\n * @return The input stream with the content of the resource.\n * @throws IOException When something fails at I/O level.\n */\n public InputStream getInputStream() throws IOException;\n\n}\n getStaticResource() /files/foo.ext @WebServlet(\"/files/*\")\npublic class FileSystemResourceServlet extends StaticResourceServlet {\n\n private File folder;\n\n @Override\n public void init() throws ServletException {\n folder = new File(\"/path/to/the/folder\");\n }\n\n @Override\n protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {\n String pathInfo = request.getPathInfo();\n\n if (pathInfo == null || pathInfo.isEmpty() || \"/\".equals(pathInfo)) {\n throw new IllegalArgumentException();\n }\n\n String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());\n final File file = new File(folder, Paths.get(name).getFileName().toString());\n\n return !file.exists() ? null : new StaticResource() {\n @Override\n public long getLastModified() {\n return file.lastModified();\n }\n @Override\n public InputStream getInputStream() throws IOException {\n return new FileInputStream(file);\n }\n @Override\n public String getFileName() {\n return file.getName();\n }\n @Override\n public long getContentLength() {\n return file.length();\n }\n };\n }\n\n}\n /files/foo.ext byte[] content @WebServlet(\"/files/*\")\npublic class YourEntityResourceServlet extends StaticResourceServlet {\n\n @EJB\n private YourEntityService yourEntityService;\n\n @Override\n protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {\n String pathInfo = request.getPathInfo();\n\n if (pathInfo == null || pathInfo.isEmpty() || \"/\".equals(pathInfo)) {\n throw new IllegalArgumentException();\n }\n\n String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());\n final YourEntity yourEntity = yourEntityService.getByName(name);\n\n return (yourEntity == null) ? null : new StaticResource() {\n @Override\n public long getLastModified() {\n return yourEntity.getLastModified();\n }\n @Override\n public InputStream getInputStream() throws IOException {\n return new ByteArrayInputStream(yourEntityService.getContentById(yourEntity.getId()));\n }\n @Override\n public String getFileName() {\n return yourEntity.getName();\n }\n @Override\n public long getContentLength() {\n return yourEntity.getContentLength();\n }\n };\n }\n\n}\n" }, { "answer_id": 41531500, "author": "Grigory Kislin", "author_id": 548473, "author_profile": "https://Stackoverflow.com/users/548473", "pm_score": 1, "selected": false, "text": "@WebServlet(\"\")" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6918/" ]
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
[ { "answer_id": 132114, "author": "gulgi", "author_id": 1109480, "author_profile": "https://Stackoverflow.com/users/1109480", "pm_score": 5, "selected": false, "text": "import traceback\n\ntraceback.print_stack()\n" }, { "answer_id": 132123, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": false, "text": ">>> import traceback\n>>> def x():\n>>> print traceback.extract_stack()\n\n>>> x()\n[('<stdin>', 1, '<module>', None), ('<stdin>', 2, 'x', None)]\n import signal\nimport traceback\n\nsignal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack))\n SIGUSR1" }, { "answer_id": 133384, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 9, "selected": true, "text": "import code, traceback, signal\n\ndef debug(sig, frame):\n \"\"\"Interrupt running process, and provide a python prompt for\n interactive debugging.\"\"\"\n d={'_frame':frame} # Allow access to frame object.\n d.update(frame.f_globals) # Unless shadowed by global\n d.update(frame.f_locals)\n\n i = code.InteractiveConsole(d)\n message = \"Signal received : entering python shell.\\nTraceback:\\n\"\n message += ''.join(traceback.format_stack(frame))\n i.interact(message)\n\ndef listen():\n signal.signal(signal.SIGUSR1, debug) # Register handler\n os.kill(pid, signal.SIGUSR1)\n" }, { "answer_id": 147114, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 7, "selected": false, "text": "pdb.set_trace() (w)here ~/.gdbinit gdb -p PID pystack strace" }, { "answer_id": 618748, "author": "Gunnlaugur Briem", "author_id": 74683, "author_profile": "https://Stackoverflow.com/users/74683", "pm_score": 4, "selected": false, "text": "~/.gdbinit PyEval_EvalFrame PyEval_EvalFrameEx gdb -p PID pystack" }, { "answer_id": 2569696, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 6, "selected": false, "text": "import threading, sys, traceback\n\ndef dumpstacks(signal, frame):\n id2name = dict([(th.ident, th.name) for th in threading.enumerate()])\n code = []\n for threadId, stack in sys._current_frames().items():\n code.append(\"\\n# Thread: %s(%d)\" % (id2name.get(threadId,\"\"), threadId))\n for filename, lineno, name, line in traceback.extract_stack(stack):\n code.append('File: \"%s\", line %d, in %s' % (filename, lineno, name))\n if line:\n code.append(\" %s\" % (line.strip()))\n print(\"\\n\".join(code))\n\nimport signal\nsignal.signal(signal.SIGQUIT, dumpstacks)\n" }, { "answer_id": 5503185, "author": "Konstantin Tarashchanskiy", "author_id": 686041, "author_profile": "https://Stackoverflow.com/users/686041", "pm_score": 4, "selected": false, "text": "import traceback\nimport sys\ndef dumpstacks(signal, frame):\n code = []\n for threadId, stack in sys._current_frames().items():\n code.append(\"\\n# Thread: %d\" % (threadId))\n for filename, lineno, name, line in traceback.extract_stack(stack):\n code.append('File: \"%s\", line %d, in %s' % (filename, lineno, name))\n if line:\n code.append(\" %s\" % (line.strip()))\n print \"\\n\".join(code)\n\nimport signal\nsignal.signal(signal.SIGQUIT, dumpstacks)\n" }, { "answer_id": 7224091, "author": "Tim Foster", "author_id": 916854, "author_profile": "https://Stackoverflow.com/users/916854", "pm_score": 3, "selected": false, "text": "# pstack 16000 | grep : | head\n16000: /usr/bin/python2.6 /usr/lib/pkg.depotd --cfg svc:/application/pkg/serv\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:282 (_wait) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:295 (wait) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:242 (block) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/_init_.py:249 (quickstart) ]\n[ /usr/lib/pkg.depotd:890 (<module>) ]\n[ /usr/lib/python2.6/threading.py:256 (wait) ]\n[ /usr/lib/python2.6/Queue.py:177 (get) ]\n[ /usr/lib/python2.6/vendor-packages/pkg/server/depot.py:2142 (run) ]\n[ /usr/lib/python2.6/threading.py:477 (run)\netc.\n" }, { "answer_id": 9019164, "author": "Matt Joiner", "author_id": 149482, "author_profile": "https://Stackoverflow.com/users/149482", "pm_score": 4, "selected": false, "text": "faulthandler faulthandler" }, { "answer_id": 10165776, "author": "Stefan", "author_id": 1019572, "author_profile": "https://Stackoverflow.com/users/1019572", "pm_score": 3, "selected": false, "text": "import sys, traceback, signal\nimport threading\nimport os\n\ndef dumpstacks(signal, frame):\n id2name = dict((th.ident, th.name) for th in threading.enumerate())\n for threadId, stack in sys._current_frames().items():\n print(id2name[threadId])\n traceback.print_stack(f=stack)\n\nsignal.signal(signal.SIGQUIT, dumpstacks)\n\nos.killpg(os.getpgid(0), signal.SIGQUIT)\n" }, { "answer_id": 16246063, "author": "vstinner", "author_id": 2325489, "author_profile": "https://Stackoverflow.com/users/2325489", "pm_score": 5, "selected": false, "text": "pip install faulthandler import faulthandler, signal\nfaulthandler.register(signal.SIGUSR1)\n kill -USR1 42" }, { "answer_id": 16247213, "author": "asmeurer", "author_id": 161801, "author_profile": "https://Stackoverflow.com/users/161801", "pm_score": 1, "selected": false, "text": "from pudb import set_interrupt_handler; set_interrupt_handler()\n c" }, { "answer_id": 17270641, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 3, "selected": false, "text": "gdb python-dbg python-debuginfo $ gdb -ex r --args python <programname>.py [arguments]\n gdb python <programname>.py <arguments> r gdb (gdb) thread apply all py-list\n" }, { "answer_id": 27465699, "author": "jtatum", "author_id": 746040, "author_profile": "https://Stackoverflow.com/users/746040", "pm_score": 0, "selected": false, "text": "import pdb, signal\nsignal.signal(signal.SIGINT, lambda sig, frame: pdb.Pdb().set_trace(frame))\n" }, { "answer_id": 29881630, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 6, "selected": false, "text": "$ sudo pip install pyrasite\n$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope\n$ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program\n" }, { "answer_id": 29911672, "author": "Michal Čihař", "author_id": 225718, "author_profile": "https://Stackoverflow.com/users/225718", "pm_score": 0, "selected": false, "text": "py-tracebacker=/var/run/uwsgi/pytrace\n uwsgi --connect-and-read /var/run/uwsgi/pytrace1\n" }, { "answer_id": 49899783, "author": "user7610", "author_id": 1047788, "author_profile": "https://Stackoverflow.com/users/1047788", "pm_score": 1, "selected": false, "text": "dnf install gdb python-debuginfo sudo apt-get install gdb python2.7-dbg gdb python <pid of running process> py-bt info threads thread apply all py-bt" }, { "answer_id": 54225121, "author": "jakvb", "author_id": 10924488, "author_profile": "https://Stackoverflow.com/users/10924488", "pm_score": 1, "selected": false, "text": ">>> import pdb\n>>> import my_function\n\n>>> def f():\n... pdb.set_trace()\n... my_function()\n... \n >>> f()\n> <stdin>(3)f()\n(Pdb) s\n--Call--\n> <stdin>(1)my_function()\n(Pdb) \n" }, { "answer_id": 60975328, "author": "saaj", "author_id": 2072035, "author_profile": "https://Stackoverflow.com/users/2072035", "pm_score": 3, "selected": false, "text": "py-spy dump --pid $SOME_PID $SOME_PID $ sudo py-spy dump --pid 31080\nProcess 31080: python3.7 -m chronologer -e production serve -u www-data -m\nPython v3.7.1 (/usr/local/bin/python3.7)\n\nThread 0x7FEF5E410400 (active): \"MainThread\"\n _wait (cherrypy/process/wspbus.py:370)\n wait (cherrypy/process/wspbus.py:384)\n block (cherrypy/process/wspbus.py:321)\n start (cherrypy/daemon.py:72)\n serve (chronologer/cli.py:27)\n main (chronologer/cli.py:84)\n <module> (chronologer/__main__.py:5)\n _run_code (runpy.py:85)\n _run_module_as_main (runpy.py:193)\nThread 0x7FEF55636700 (active): \"_TimeoutMonitor\"\n run (cherrypy/process/plugins.py:518)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885)\nThread 0x7FEF54B35700 (active): \"HTTPServer Thread-2\"\n accept (socket.py:212)\n tick (cherrypy/wsgiserver/__init__.py:2075)\n start (cherrypy/wsgiserver/__init__.py:2021)\n _start_http_thread (cherrypy/process/servers.py:217)\n run (threading.py:865)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885)\n...\nThread 0x7FEF2BFFF700 (idle): \"CP Server Thread-10\"\n wait (threading.py:296)\n get (queue.py:170)\n run (cherrypy/wsgiserver/__init__.py:1586)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885) \n" }, { "answer_id": 61975590, "author": "Wayne Lambert", "author_id": 11211077, "author_profile": "https://Stackoverflow.com/users/11211077", "pm_score": -1, "selected": false, "text": "logs # DEBUG: START DEBUG -->\nimport traceback\n\nwith open('logs/stack-trace.log', 'w') as file:\n traceback.print_stack(file=file)\n# DEBUG: END DEBUG --!\n" }, { "answer_id": 63302111, "author": "kmaork", "author_id": 2907819, "author_profile": "https://Stackoverflow.com/users/2907819", "pm_score": 2, "selected": false, "text": "hypno <pid> \"import traceback; traceback.print_stack()\"\n pyrasite pyringe IPython madbg attach <pid>\n bt" }, { "answer_id": 68686580, "author": "Phoenix87", "author_id": 1838793, "author_profile": "https://Stackoverflow.com/users/1838793", "pm_score": 2, "selected": false, "text": "-w/--where pipx install austin-tui\n austin-tui -p <pid>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189/" ]
132,070
<p>I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.</p> <p>How can I check that I'll not delete data that should not be deleted?</p> <p>I have a test database - just a copy of real one where I can do what I want :)</p> <p>The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?</p> <p>Any other ideas how to solve the problem?</p>
[ { "answer_id": 132106, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": true, "text": "select table_catalog,table_schema,table_name,column_name,rc.* from\ninformation_schema.constraint_column_usage ccu, \ninformation_schema.referential_constraints rc \nwhere ccu.constraint_name = rc.constraint_name\n" }, { "answer_id": 132222, "author": "Pavel", "author_id": 19101, "author_profile": "https://Stackoverflow.com/users/19101", "pm_score": 0, "selected": false, "text": "psql -U U_NAME -h`hostname` -c '\\d' | awk '{print $3}' > tables.list\n\nfor i in `cat tables.list `; do echo -n \"$i: \" >> tables.counts; psql -U U_NAME -h`hostname` -t -c \"select count(*) from $i\" >> tables.counts; done\n\nfor i in `cat tables.list `; do echo -n \"$i: \" >> tables.counts2; psql -U U_NAME -h`hostname` -t -c \"select count(*) from $i\" >> tables.counts2; done\n\ndiff tables.counts tables.counts2\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19101/" ]
132,092
<p>I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.</p> <p>What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.</p>
[ { "answer_id": 132096, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 4, "selected": false, "text": "% Build a list of args, like so:\nargs = {'a', 1, 'b', 2};\n% Then expand this into arguments:\noutput = func(args{:})\n" }, { "answer_id": 132843, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 5, "selected": false, "text": "x = rand(4,4);\nx(:)\n" }, { "answer_id": 132878, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 5, "selected": false, "text": "function y = transmog(x)\n%TRANSMOG Transmogrifies a matrix X using reverse orthogonal eigenvectors\n%\n% Usage:\n% y = transmog(x)\n%\n% SEE ALSO\n% UNTRANSMOG, TRANSMOG2\n" }, { "answer_id": 138688, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 3, "selected": false, "text": "\nx=rand(10,10);\nflattened=x(:);\nAcolumn=x(:,10);\nArow=x(10,:);\n\ny=rand(100);\nfirstSix=y(1:6);\nlastSix=y(end-5:end);\nalternate=y(1:2:end);\n" }, { "answer_id": 146875, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 3, "selected": false, "text": "function hLine=myplot(x,y,plotColor,markerType)\n% set defaults for optional paramters\nif nargin<4, markerType='none'; end\nif nargin<3, plotColor='k'; end\n\nhL = plot(x,y,'linetype','-', ... \n 'color',plotColor, ...\n 'marker',markerType, ...\n 'markerFaceColor',plotColor,'markerEdgeColor',plotColor);\n\n% return handle of plot object if required\nif nargout>0, hLine = hL; end\n" }, { "answer_id": 192271, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 5, "selected": false, "text": "x = rand(1,50) .* 100;\nxpart = x( x > 20 & x < 35);\n" }, { "answer_id": 202418, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 5, "selected": false, "text": "profile on\n% some lines of code\nprofile off\nprofile viewer\n tic toc tic;\n% some lines of code\ntoc;\n" }, { "answer_id": 202439, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 2, "selected": false, "text": "%Merge B into A based on Text identifiers\nUniverseA = {'A','B','C','D'};\nUniverseB = {'A','C','D'};\n\nDataA = [20 40 60 80];\nDataB = [30 50 70];\n\nMergeData = NaN(length(UniverseA),2);\n\nMergeData(:,1) = DataA;\n\n[tf, loc] = ismember(UniverseA, UniverseB);\n\nMergeData(tf,2) = DataB(loc(tf));\n\n MergeData =\n\n20 30\n40 NaN\n60 50\n80 70\n" }, { "answer_id": 202449, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 3, "selected": false, "text": "v = 1:10;\nv_reverse = v(length(v):-1:1);\n" }, { "answer_id": 284347, "author": "user36927", "author_id": 36927, "author_profile": "https://Stackoverflow.com/users/36927", "pm_score": 2, "selected": false, "text": "function iNeedle = findClosest(hay,needle)\n%FINDCLOSEST find the indicies of the closest elements in an array.\n% Given two vectors [A,B], findClosest will find the indicies of the values\n% in vector A closest to the values in vector B.\n[hay iOrgHay] = sort(hay(:)'); %#ok must have row vector\n\n% Use histogram to find indices of elements in hay closest to elements in\n% needle. The bins are centered on values in hay, with the edges on the\n% midpoint between elements.\n[iNeedle iNeedle] = histc(needle,[-inf hay+[diff(hay)/2 inf]]); %#ok\n\n% Reversing the sorting.\niNeedle = iOrgHay(iNeedle);\n" }, { "answer_id": 382258, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": "mfilename dbstack keyboard K>> dbstop error" }, { "answer_id": 382264, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": ",'Interpreter','latex' t=(0:0.001:1);\nplot(t,sin(2*pi*[t ; t+0.25]));\nxlabel('t'); \nylabel('$\\hat{y}_k=sin 2\\pi (t+{k \\over 4})$','Interpreter','latex');\nlegend({'$\\hat{y}_0$','$\\hat{y}_1$'},'Interpreter','latex');\n" }, { "answer_id": 382294, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "sim sim DstWorkspace SrcWorkspace simset Dstworkspace sim SrcWorkspace sim SrcWorkspace current function Y=run_my_sim(t,input1,params)\n% runs \"my_sim.mdl\" \n% with a From Workspace block referencing I1 as an input signal\n% and parameters referenced as fields of the \"params\" structure\n% and output retrieved from a To Workspace block with name O1.\nopt = simset('SrcWorkspace','current','DstWorkspace','current');\nI1 = struct('time',t,'signals',struct('values',input1,'dimensions',1));\nY = struct;\nY.t = sim('my_sim',t,opt);\nY.output1 = O1.signals.values;\n" }, { "answer_id": 382303, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "[c,h]=contour clabel(c,h,'fontsize',fontsize) fontsize" }, { "answer_id": 382370, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": "quad fminbnd % quick functions\nf = @(x) 3*x.^2 + 2*x + 7;\nt = (0:0.001:1);\nplot(t,f(t),t,f(2*t),t,f(3*t));\n\n% closures (linfunc below is a function that returns a function,\n% and the outer functions arguments are held for the lifetime\n% of the returned function.\nlinfunc = @(m,b) @(x) m*x+b;\nC2F = linfunc(9/5, 32);\nF2C = linfunc(5/9, -32*5/9);\n" }, { "answer_id": 382390, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 3, "selected": false, "text": "t = (0:0.005:10)';\nx = sin(2*pi*t);\nx(x>0.5 & t<5) = 0.5;\n% This limits all values of x to a maximum of 0.5, where t<5\nplot(t,x);\n" }, { "answer_id": 423347, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 3, "selected": false, "text": "switch number,\n case 1,\n outargs = fcn1(inargs);\n case 2,\n outargs = fcn2(inargs);\n ...\nend\n%\n%can be turned into\n%\nfcnArray = {@fcn1, @fcn2, ...};\noutargs = fcnArray{number}(inargs);\n" }, { "answer_id": 474071, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 3, "selected": false, "text": "set(gca,'fontsize',8,'linestyleorder','-','linewidth',0.3,'xtick',1:2:9);\n" }, { "answer_id": 729942, "author": "ymihere", "author_id": 74606, "author_profile": "https://Stackoverflow.com/users/74606", "pm_score": 4, "selected": false, "text": "M = rand(1000, 1000);\nv = rand(1000, 1);\nc = bsxfun(@plus, M, v);\n" }, { "answer_id": 730068, "author": "ymihere", "author_id": 74606, "author_profile": "https://Stackoverflow.com/users/74606", "pm_score": 3, "selected": false, "text": "reldiff = diff(a) ./ a(1:end-1)\n >> a=rand(1,7);\n>> diff(a) ./ a(1:end-1)\n\nans =\n -0.5822 -0.9935 224.2015 0.2708 -0.3328 0.0458\n\n>> a=1;\n>> diff(a) ./ a(1:end-1)\n??? Error using ==> rdivide\nMatrix dimensions must agree.\n >> diff(a, [], 2) ./ a(1, 1:end-1)\n\nans =\n\n Empty matrix: 1-by-0\n\n>> \n" }, { "answer_id": 1611773, "author": "Samil", "author_id": 51358, "author_profile": "https://Stackoverflow.com/users/51358", "pm_score": 4, "selected": false, "text": "line(xlim, [10 10]) line([5 5], ylim)" }, { "answer_id": 3931742, "author": "Samil", "author_id": 51358, "author_profile": "https://Stackoverflow.com/users/51358", "pm_score": 3, "selected": false, "text": "nargin function result = multiply(a, b)\nif nargin == 0 %no inputs provided, run using defaults for a and b\n clc;\n disp('RUNNING IN TEST MODE')\n a = 1;\n b = 2;\nend\n\nresult = a*b;\n" }, { "answer_id": 6492123, "author": "petrichor", "author_id": 198428, "author_profile": "https://Stackoverflow.com/users/198428", "pm_score": 2, "selected": false, "text": "persistent function av = runningAverage(x)\n% The number of values entered so far - declared persistent.\npersistent n;\n% The sum of values entered so far - declared persistent.\npersistent sumOfX;\nif x == 'reset' % Initialise the persistent variables.\n n = 0;\n sumOfX = 0;\n av = 0;\nelse % A data value has been added.\n n = n + 1;\n sumOfX = sumOfX + x;\n av = sumOfX / n; % Update the running average.\nend\n runningAverage('reset')\nans = 0\n>> runningAverage(5)\nans = 5\n>> runningAverage(10)\nans = 7.5000\n>> runningAverage(3)\nans = 6\n>> runningAverage('reset')\nans = 0\n>> runningAverage(8)\nans = 8\n" }, { "answer_id": 6816888, "author": "user244795", "author_id": 244795, "author_profile": "https://Stackoverflow.com/users/244795", "pm_score": 2, "selected": false, "text": "\n % useful abbreviations \n\nflat=@(x) x(:);\n\n% print basic statistics\nstats=@(x) sprintf('mean +/- s.d. \\t= %f +/- %f\\nmin, max \\t\\t= %f, %f\\nmedian, mode \\t= %f, %f', ...\n mean(flat(x)), std(flat(x)), min(flat(x)), max(flat(x)), median(flat(x)), mode(flat(x)) );\n\nnrows=@(x) size(x,1);\nncols=@(x) size(x,2);\nnslices=@(x) size(x,3);\n\n% this is just like ndims except it returns 0 for an empty matrix and\n% ignores dimensions of size 0.\nndim=@(x) length(find(size(x)));\n\n\n flat=@(x) x(:);\n\n% print basic statistics\nstats=@(x) sprintf('mean +/- s.d. \\t= %f +/- %f\\nmin, max \\t\\t= %f, %f\\nmedian, mode \\t= %f, %f', ...\n mean(flat(x)), std(flat(x)), min(flat(x)), max(flat(x)), median(flat(x)), mode(flat(x)) );\n\nnrows=@(x) size(x,1);\nncols=@(x) size(x,2);\nnslices=@(x) size(x,3);\n\n% this is just like ndims except it returns 0 for an empty matrix and\n% ignores dimensions of size 0.\nndim=@(x) length(find(size(x)));\n \n phantomData = phantom(); \n\nstats( phantomData(50:80, 50:80) )\n\n\n stats( phantomData(50:80, 50:80) )\n \n imagesc( phantomData ); \n\ntitle( sprintf('The image size is %d by %d by %d.', nrows(phantomData), ncols(phantomData), nslices(phantomData)) )\n\n\n title( sprintf('The image size is %d by %d by %d.', nrows(phantomData), ncols(phantomData), nslices(phantomData)) )\n " } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ]
132,116
<p>Please help! I'm really at my wits' end. My program is a little personal notes manager (google for "cintanotes"). On some computers (and of course I own none of them) it crashes with an unhandled exception just after start. Nothing special about these computers could be said, except that they tend to have AMD CPUs.</p> <p>Environment: Windows XP, Visual C++ 2005/2008, raw WinApi.</p> <p>Here is what is certain about this "Heisenbug":</p> <p>1) The crash happens only in the Release version.</p> <p>2) The crash goes away as soon as I remove all GDI-related stuff.</p> <p>3) BoundChecker has no complains.</p> <p>4) Writing a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?</p> <p>Any ideas would be greatly appreciated!</p> <p><strong>UPDATE: I've managed to get the app debugged on a "faulty" PC. The results:</strong></p> <p>"Unhandled exception at 0x0044a26a in CintaNotes.exe: 0xC000001D: Illegal Instruction."</p> <p>and code breaks on</p> <p>0044A26A cvtsi2sd xmm1,dword ptr [esp+14h] </p> <p><strong>So it seems that the problem was in the "Code Generation/Enable Enhanced Instruction Set" compiler option. It was set to "/arch:SSE2" and was crashing on the machines that didn't support SSE2. I've set this option to "Not Set" and the bug is gone. Phew!</strong></p> <p>Thank you all very much for help!!</p>
[ { "answer_id": 132254, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "this" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22046/" ]
132,118
<p>When you're using Tiles with Struts and do...</p> <pre><code>request.getRequestURL() </code></pre> <p>...you get the URL to e.g. <code>/WEB-INF/jsp/layout/newLayout.jsp</code> instead of the real URL that was entered/clicked by the user, something like <code>/context/action.do</code>.</p> <p>In newer Struts versions, 1.3.x and after, you can use the <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=58&amp;t=012300" rel="nofollow noreferrer">solution mentioned on javaranch</a> and get the real URL using the request attribute <a href="http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY" rel="nofollow noreferrer"><code>ORIGINAL_URI_KEY</code></a>.</p> <p>But how to do this in Struts 1.2.x?</p>
[ { "answer_id": 157120, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 1, "selected": false, "text": "private String getOriginalUri(HttpServletRequest request) {\n String targetUrl = request.getServletPath();\n if (request.getQueryString() != null) {\n targetUrl += \"?\" + request.getQueryString();\n }\n return targetUrl;\n}\n" }, { "answer_id": 3298572, "author": "digz6666", "author_id": 386213, "author_profile": "https://Stackoverflow.com/users/386213", "pm_score": 4, "selected": false, "text": "<% out.println(request.getAttribute(\"javax.servlet.forward.request_uri\")); %>\n <% out.println(request.getAttribute(\"javax.servlet.forward.query_string\")); %>\n" }, { "answer_id": 62894801, "author": "Carlos Fernando", "author_id": 10975299, "author_profile": "https://Stackoverflow.com/users/10975299", "pm_score": 0, "selected": false, "text": " request.getAttribute(\"javax.servlet.forward.request_uri\")\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
132,121
<p>i'm working with a multi-threaded program (using pthreads) that currently create a background thread (PTHREAD_DETACHED) and then invokes pthread_exit(0). My problem is that the process is then listed as "defunct" and curiously do not seems to "really exists" in /proc (which defeats my debugging strategies)</p> <p>I would like the following requirements to be met:</p> <ul> <li>the program should run function A in a loop and function B once</li> <li>given the PID of the program /proc/$pid/exe, /proc/$pid/maps and /proc/$pid/fd must be accessible (when the process is defunct, they are all empty or invalid links)</li> <li>it must be possible to suspend/interrupt the program with CTRL+C and CTRL+Z as usual</li> </ul> <p><em>edit:</em> I hesitate changing the program's interface for having A in the "main" thread and B in a spawned thread (they are currently in the other way). Would it solve the problem ?</p>
[ { "answer_id": 133550, "author": "tsg", "author_id": 15685, "author_profile": "https://Stackoverflow.com/users/15685", "pm_score": 0, "selected": false, "text": " while(1) {\n pause();\n }\n" }, { "answer_id": 274657, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 3, "selected": true, "text": "pthread_join()" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15304/" ]
132,136
<p>Does anyone know if IE6 ever misrenders pages with hidden <code>divs</code>? We currently have several <code>divs</code> which we display in the same space on the page, only showing one at a time and hiding all others.</p> <p>The problem is that the hidden <code>divs</code> components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.</p> <p>How do we fix this?</p>
[ { "answer_id": 132162, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 2, "selected": false, "text": "MyDiv.style.left = \"-1000px\";\n" }, { "answer_id": 132193, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "display:none; visibility:hidden;" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
132,164
<p>These <code>for</code>-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions:</p> <pre><code>1 for ( int i = 0; i != N; ++i ) 2 for ( int i = 0; i &lt; N; ++i ) </code></pre> <p>The difference becomes clear in the postconditions:</p> <ul> <li><p>The first one gives the strong guarantee that <code>i == N</code> after the loop terminates.</p></li> <li><p>The second one only gives the weak guarantee that <code>i &gt;= N</code> after the loop terminates, but you will be tempted to assume that <code>i == N</code>.</p></li> </ul> <p>If for any reason the increment <code>++i</code> is ever changed to something like <code>i += 2</code>, or if <code>i</code> gets modified inside the loop, or if <code>N</code> is negative, the program can fail:</p> <ul> <li><p>The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy.</p></li> <li><p>The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of <code>i == N</code>. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse.</p></li> </ul> <p>Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?</p>
[ { "answer_id": 132175, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "!= < !=" }, { "answer_id": 132180, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 1, "selected": false, "text": "for ( int i = 0 ; i >= 0 && i < N ; ++i) \n" }, { "answer_id": 132196, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "for ( int i = 0; i < N; ++i )\n" }, { "answer_id": 132230, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": "i for i for // version 1\n{ int i = 0;\n while (i != N) {\n ...\n ++i;\n }\n}\n i i i<N" }, { "answer_id": 132297, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "for (int i = 0; (i <= (n-1)); i++) { ... }\n for (int i = 1; (i <= n); i++) { ... }\n" }, { "answer_id": 1581115, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 0, "selected": false, "text": "for ( int i = 0; i < N; ++i )\n for ( int i = 0; i != N; ++i )\n" }, { "answer_id": 12937813, "author": "C-Otto", "author_id": 947526, "author_profile": "https://Stackoverflow.com/users/947526", "pm_score": 0, "selected": false, "text": "< var = x var = x+n n i==N i 1 i = i + 2 i%2 == N%2 <" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ]
132,186
<p>I wish to test a function that will generate <code>lorem ipsum</code> text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow:</p> <pre><code>Result = "&lt;p&gt;Some text&lt;/p&gt;"; Expected = array( '&lt;p' , 'regex', '/p' ); assertTags(resutl, expected) </code></pre> <p>I am using SimpleTest with CakePHP, but I think it should be a general question.</p>
[ { "answer_id": 132420, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "class ValidIp extends SimpleExpectation {\n\n function test($ip) {\n return (ip2long($ip) != -1);\n }\n\n function testMessage($ip) {\n return \"Address [$ip] should be a valid IP address\";\n }\n}\n $this->assert(new ValidIp(),$server->getIp());\n" }, { "answer_id": 132481, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 3, "selected": true, "text": "$expected = array(\n '<p',\n 'preg:/[A-Za-z\\.\\s\\,]+/',\n '/p'\n);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
132,231
<p>When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?</p>
[ { "answer_id": 132546, "author": "Bradley Beddoes", "author_id": 22087, "author_profile": "https://Stackoverflow.com/users/22087", "pm_score": 1, "selected": false, "text": "public static void main(String[] args) throws IOException, ConfigurationException {\n Deployer deployer = bootstrapSpring();\n\n deployer.execute();\n}\n\nprivate static Deployer bootstrapSpring()\n{\n FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(\"spring/deployerContext.xml\");\n\n Deployer deployer = (Deployer)appContext.getBean(\"deployer\");\n return deployer;\n}\n" }, { "answer_id": 134974, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 6, "selected": true, "text": "public class MyApp {\n public static String[] ARGS; \n public static void main(String[] args) {\n ARGS = args;\n // create context\n }\n}\n <util:constant static-field=\"MyApp.ARGS\"/>\n public class MyApp2 {\n public static void main(String[] args) {\n DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();\n\n // Define a bean and register it\n BeanDefinition beanDefinition = BeanDefinitionBuilder.\n rootBeanDefinition(Arrays.class, \"asList\")\n .addConstructorArgValue(args).getBeanDefinition();\n beanFactory.registerBeanDefinition(\"args\", beanDefinition);\n GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);\n // Must call refresh to initialize context \n cmdArgCxt.refresh();\n\n // Create application context, passing command line context as parent\n ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);\n\n // See if it's in the context\n System.out.println(\"Args: \" + mainContext.getBean(\"args\"));\n }\n\n private static String[] CONFIG_LOCATIONS = new String[] {\n \"applicationContext.xml\"\n };\n\n }\n" }, { "answer_id": 304026, "author": "BeWarned", "author_id": 37110, "author_profile": "https://Stackoverflow.com/users/37110", "pm_score": 3, "selected": false, "text": "getBean public static void main(String[] args) {\n Mybean m = (Mybean)context.getBean(\"mybean\", new Object[] {args});\n}\n" }, { "answer_id": 1195240, "author": "Brian Dilley", "author_id": 71050, "author_profile": "https://Stackoverflow.com/users/71050", "pm_score": 2, "selected": false, "text": "public class ExternalBeanReferneceFactoryBean \n extends AbstractFactoryBean\n implements BeanNameAware {\n\n private static Map<String, Object> instances = new HashMap<String, Object>();\n private String beanName;\n\n /**\n * @param instance the instance to set\n */\n public static void setInstance(String beanName, Object instance) {\n instances.put(beanName, instance);\n }\n\n @Override\n protected Object createInstance() \n throws Exception {\n return instances.get(beanName);\n }\n\n @Override\n public Class<?> getObjectType() {\n return instances.get(beanName).getClass();\n }\n\n @Override\n public void setBeanName(String name) {\n this.beanName = name;\n }\n\n}\n /**\n * Starts the job server.\n * @param args command line arguments\n */\npublic static void main(String[] args) {\n\n // parse the command line\n CommandLineParser parser = new GnuParser();\n CommandLine cmdLine = null;\n try {\n cmdLine = parser.parse(OPTIONS, args);\n } catch(ParseException pe) {\n System.err.println(\"Error parsing command line: \"+pe.getMessage());\n new HelpFormatter().printHelp(\"command\", OPTIONS);\n return;\n }\n\n // create root beanFactory\n DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();\n\n // register bean definition for the command line\n ExternalBeanReferneceFactoryBean.setInstance(\"commandLine\", cmdLine);\n beanFactory.registerBeanDefinition(\"commandLine\", BeanDefinitionBuilder\n .rootBeanDefinition(ExternalBeanReferneceFactoryBean.class)\n .getBeanDefinition());\n\n // create application context\n GenericApplicationContext rootAppContext = new GenericApplicationContext(beanFactory);\n rootAppContext.refresh();\n\n // create the application context\n ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { \n \"/commandlineapp/applicationContext.xml\"\n }, rootAppContext);\n\n System.out.println(appContext.getBean(\"commandLine\"));\n\n}\n" }, { "answer_id": 58031369, "author": "Gerardo Roza", "author_id": 6661361, "author_profile": "https://Stackoverflow.com/users/6661361", "pm_score": 0, "selected": false, "text": "java -jar app.jar --my.property=\"Property Value\"" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
132,233
<p>Unfortunatly I have to work in a older web application on a <code>PHP4</code> server; It now needs to parse a lot of <code>XM</code>L for calling <code>webservices (custom protocol, no SOAP/REST)</code>;</p> <p>Under <code>PHP5</code> I would use <code>SimpleXML</code> but that isn't available; There is <code>Dom XML</code> in <code>PHP4</code>, but it isn't default any more in <code>PHP5</code>.</p> <p>What are the other options? I'm looking for a solution that still works on <code>PHP5</code> once they migrate.</p> <p>A nice extra would be if the <code>XML</code> can be validated with a schema.</p>
[ { "answer_id": 132291, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "$xml = ...; // Get your XML data\n$xml_parser = xml_parser_create();\n\n// _start_element and _end_element are two functions that determine what\n// to do when opening and closing tags are found\nxml_set_element_handler($xml_parser, \"_start_element\", \"_end_element\");\n\n// How to handle each char (stripping whitespace if needs be, etc\nxml_set_character_data_handler($xml_parser, \"_character_data\"); \n\nxml_parse($xml_parser, $xml);\n" }, { "answer_id": 132716, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "start-element end-element" }, { "answer_id": 19740953, "author": "hakre", "author_id": 367456, "author_profile": "https://Stackoverflow.com/users/367456", "pm_score": 0, "selected": false, "text": "<?php\n/**\n * What to use for XML parsing / reading in PHP4\n * @link http://stackoverflow.com/q/132233/367456\n */\n\n$encoding = 'US-ASCII';\n // https://gist.github.com/hakre/46386de578619fbd898c\n$path = dirname(__FILE__) . '/time-series-example.xml';\n\n$parser_creator = 'xml_parser_create'; // alternative creator is 'xml_parser_create_ns'\n\nif (!function_exists($parser_creator)) {\n trigger_error(\n \"XML Parsers' $parser_creator() not found. XML Parser \"\n . '<http://php.net/xml> is required, activate it in your PHP configuration.'\n , E_USER_ERROR\n );\n return;\n}\n\n$parser = $parser_creator($encoding);\nif (!$parser) {\n trigger_error(sprintf('Unable to create a parser (Encoding: \"%s\")', $encoding), E_USER_ERROR);\n return;\n}\n\nxml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);\nxml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);\n\n$data = file_get_contents($path);\nif ($data === FALSE) {\n trigger_error(sprintf('Unable to open file \"%s\" for reading', $path));\n return;\n}\n$result = xml_parse_into_struct($parser, $data, $xml_struct_values);\nunset($data);\nxml_parser_free($parser);\nunset($parser);\n\nif ($result === 0) {\n trigger_error(sprintf('Unable to parse data of file \"%s\" as XML', $path));\n return;\n}\n\ndefine('TREE_NODE_TAG', 'tagName');\ndefine('TREE_NODE_ATTRIBUTES', 'attributes');\ndefine('TREE_NODE_CHILDREN', 'children');\n\ndefine('TREE_NODE_TYPE_TAG', 'array');\ndefine('TREE_NODE_TYPE_TEXT', 'string');\ndefine('TREE_NODE_TYPE_NONE', 'NULL');\n\n/**\n * XML Parser indezies for parse into struct values\n */\ndefine('XML_STRUCT_VALUE_TYPE', 'type');\ndefine('XML_STRUCT_VALUE_LEVEL', 'level');\ndefine('XML_STRUCT_VALUE_TAG', 'tag');\ndefine('XML_STRUCT_VALUE_ATTRIBUTES', 'attributes');\ndefine('XML_STRUCT_VALUE_VALUE', 'value');\n\n/**\n * XML Parser supported node types\n */\ndefine('XML_STRUCT_TYPE_OPEN', 'open');\ndefine('XML_STRUCT_TYPE_COMPLETE', 'complete');\ndefine('XML_STRUCT_TYPE_CDATA', 'cdata');\ndefine('XML_STRUCT_TYPE_CLOSE', 'close');\n\n/**\n * Tree Creator\n * @return array\n */\nfunction tree_create()\n{\n return array(\n array(\n TREE_NODE_TAG => NULL,\n TREE_NODE_ATTRIBUTES => NULL,\n TREE_NODE_CHILDREN => array(),\n )\n );\n}\n\n/**\n * Add Tree Node into Tree a Level\n *\n * @param $tree\n * @param $level\n * @param $node\n * @return array|bool Tree with the Node added or FALSE on error\n */\nfunction tree_add_node($tree, $level, $node)\n{\n $type = gettype($node);\n switch ($type) {\n case TREE_NODE_TYPE_TEXT:\n $level++;\n break;\n case TREE_NODE_TYPE_TAG:\n break;\n case TREE_NODE_TYPE_NONE:\n trigger_error(sprintf('Can not add Tree Node of type None, keeping tree unchanged', $type, E_USER_NOTICE));\n return $tree;\n default:\n trigger_error(sprintf('Can not add Tree Node of type \"%s\"', $type), E_USER_ERROR);\n return FALSE;\n }\n\n if (!isset($tree[$level - 1])) {\n trigger_error(\"There is no parent for level $level\");\n return FALSE;\n }\n\n $parent = & $tree[$level - 1];\n\n if (isset($parent[TREE_NODE_CHILDREN]) && !is_array($parent[TREE_NODE_CHILDREN])) {\n trigger_error(\"There are no children in parent for level $level\");\n return FALSE;\n }\n\n $parent[TREE_NODE_CHILDREN][] = & $node;\n $tree[$level] = & $node;\n\n return $tree;\n}\n\n/**\n * Creator of a Tree Node\n *\n * @param $value XML Node\n * @return array Tree Node\n */\nfunction tree_node_create_from_xml_struct_value($value)\n{\n static $xml_node_default_types = array(\n XML_STRUCT_VALUE_ATTRIBUTES => NULL,\n XML_STRUCT_VALUE_VALUE => NULL,\n );\n\n $orig = $value;\n\n $value += $xml_node_default_types;\n\n switch ($value[XML_STRUCT_VALUE_TYPE]) {\n case XML_STRUCT_TYPE_OPEN:\n case XML_STRUCT_TYPE_COMPLETE:\n $node = array(\n TREE_NODE_TAG => $value[XML_STRUCT_VALUE_TAG],\n // '__debug1' => $orig,\n );\n if (isset($value[XML_STRUCT_VALUE_ATTRIBUTES])) {\n $node[TREE_NODE_ATTRIBUTES] = $value[XML_STRUCT_VALUE_ATTRIBUTES];\n }\n if (isset($value[XML_STRUCT_VALUE_VALUE])) {\n $node[TREE_NODE_CHILDREN] = (array)$value[XML_STRUCT_VALUE_VALUE];\n }\n return $node;\n\n case XML_STRUCT_TYPE_CDATA:\n // TREE_NODE_TYPE_TEXT\n return $value[XML_STRUCT_VALUE_VALUE];\n\n case XML_STRUCT_TYPE_CLOSE:\n return NULL;\n\n default:\n trigger_error(\n sprintf(\n 'Unkonwn Xml Node Type \"%s\": %s', $value[XML_STRUCT_VALUE_TYPE], var_export($value, TRUE)\n )\n );\n return FALSE;\n }\n}\n\n$tree = tree_create();\n\nwhile ($tree && $value = array_shift($xml_struct_values)) {\n $node = tree_node_create_from_xml_struct_value($value);\n if (NULL === $node) {\n continue;\n }\n $tree = tree_add_node($tree, $value[XML_STRUCT_VALUE_LEVEL], $node);\n unset($node);\n}\n\nif (!$tree) {\n trigger_error('Parse error');\n return;\n}\n\nif ($xml_struct_values) {\n trigger_error(sprintf('Unable to process whole parsed XML array (%d elements left)', count($xml_struct_values)));\n return;\n}\n\n// tree root is the first child of level 0\nprint_r($tree[0][TREE_NODE_CHILDREN][0]);\n Array\n(\n [tagName] => dwml\n [attributes] => Array\n (\n [version] => 1.0\n [xmlns:xsd] => http://www.w3.org/2001/XMLSchema\n [xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance\n [xsi:noNamespaceSchemaLocation] => http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.xsd\n )\n\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => head\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => product\n [attributes] => Array\n (\n [srsName] => WGS 1984\n [concise-name] => time-series\n [operational-mode] => official\n )\n\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => title\n [children] => Array\n (\n [0] => NOAA's National Weather Service Forecast Data\n )\n\n )\n\n [1] => Array\n (\n [tagName] => field\n [children] => Array\n (\n [0] => meteorological\n )\n\n )\n\n [2] => Array\n (\n [tagName] => category\n [children] => Array\n (\n [0] => forecast\n )\n\n )\n\n [3] => Array\n (\n [tagName] => creation-date\n [attributes] => Array\n (\n [refresh-frequency] => PT1H\n )\n\n [children] => Array\n (\n [0] => 2013-11-02T06:51:17Z\n )\n\n )\n\n )\n\n )\n\n [1] => Array\n (\n [tagName] => source\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => more-information\n [children] => Array\n (\n [0] => http://www.nws.noaa.gov/forecasts/xml/\n )\n\n )\n\n [1] => Array\n (\n [tagName] => production-center\n [children] => Array\n (\n [0] => Meteorological Development Laboratory\n [1] => Array\n (\n [tagName] => sub-center\n [children] => Array\n (\n [0] => Product Generation Branch\n )\n\n )\n\n )\n\n )\n\n [2] => Array\n (\n [tagName] => disclaimer\n [children] => Array\n (\n [0] => http://www.nws.noaa.gov/disclaimer.html\n )\n\n )\n\n [3] => Array\n (\n [tagName] => credit\n [children] => Array\n (\n [0] => http://www.weather.gov/\n )\n\n )\n\n [4] => Array\n (\n [tagName] => credit-logo\n [children] => Array\n (\n [0] => http://www.weather.gov/images/xml_logo.gif\n )\n\n )\n\n [5] => Array\n (\n [tagName] => feedback\n [children] => Array\n (\n [0] => http://www.weather.gov/feedback.php\n )\n\n )\n\n )\n\n )\n\n )\n\n )\n\n [1] => Array\n (\n [tagName] => data\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => location\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => location-key\n [children] => Array\n (\n [0] => point1\n )\n\n )\n\n [1] => Array\n (\n [tagName] => point\n [attributes] => Array\n (\n [latitude] => 40.00\n [longitude] => -120.00\n )\n\n )\n\n )\n\n )\n\n [1] => Array\n (\n [tagName] => moreWeatherInformation\n [attributes] => Array\n (\n [applicable-location] => point1\n )\n\n [children] => Array\n (\n [0] => http://forecast.weather.gov/MapClick.php?textField1=40.00&textField2=-120.00\n )\n\n )\n\n [2] => Array\n (\n [tagName] => time-layout\n [attributes] => Array\n (\n [time-coordinate] => local\n [summarization] => none\n )\n\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => layout-key\n [children] => Array\n (\n [0] => k-p24h-n4-1\n )\n\n )\n\n [1] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-02T08:00:00-07:00\n )\n\n )\n\n [2] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-02T20:00:00-07:00\n )\n\n )\n\n [3] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-03T07:00:00-08:00\n )\n\n )\n\n [4] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-03T19:00:00-08:00\n )\n\n )\n\n [5] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-04T07:00:00-08:00\n )\n\n )\n\n [6] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-04T19:00:00-08:00\n )\n\n )\n\n [7] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-05T07:00:00-08:00\n )\n\n )\n\n [8] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-05T19:00:00-08:00\n )\n\n )\n\n )\n\n )\n\n [3] => Array\n (\n [tagName] => time-layout\n [attributes] => Array\n (\n [time-coordinate] => local\n [summarization] => none\n )\n\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => layout-key\n [children] => Array\n (\n [0] => k-p24h-n5-2\n )\n\n )\n\n [1] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-01T20:00:00-07:00\n )\n\n )\n\n [2] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-02T09:00:00-07:00\n )\n\n )\n\n [3] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-02T19:00:00-07:00\n )\n\n )\n\n ...\n\n [10] => Array\n (\n [tagName] => end-valid-time\n [children] => Array\n (\n [0] => 2013-11-06T08:00:00-08:00\n )\n\n )\n\n )\n\n )\n\n [4] => Array\n (\n [tagName] => time-layout\n [attributes] => Array\n (\n [time-coordinate] => local\n [summarization] => none\n )\n\n [children] => Array\n (\n [0] => Array\n (\n [tagName] => layout-key\n [children] => Array\n (\n [0] => k-p12h-n9-3\n )\n\n )\n\n [1] => Array\n (\n [tagName] => start-valid-time\n [children] => Array\n (\n [0] => 2013-11-01T17:00:00-07:00\n )\n\n )\n ...\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3215/" ]
132,241
<p>I know there is a standard behind all C compiler implementations, so there should be no hidden features. Despite that, I am sure all C developers have hidden/secret tricks they use all the time.</p>
[ { "answer_id": 132274, "author": "ComSubVie", "author_id": 15709, "author_profile": "https://Stackoverflow.com/users/15709", "pm_score": 5, "selected": false, "text": "strncpy(to, from, count)\nchar *to, *from;\nint count;\n{\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n" }, { "answer_id": 132290, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 5, "selected": false, "text": "...\na ^= b ; b ^= a; a ^=b;\n...\n FSM {\n STATE(x) {\n ...\n NEXTSTATE(y);\n }\n\n STATE(y) {\n ...\n if (x == 0) \n NEXTSTATE(y);\n else \n NEXTSTATE(x);\n }\n}\n #define FSM\n#define STATE(x) s_##x :\n#define NEXTSTATE(x) goto s_##x\n" }, { "answer_id": 132314, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 3, "selected": false, "text": "int v[100]; int index = 10; \n/* v[index] it's the same thing as index[v] */\n" }, { "answer_id": 132469, "author": "PypeBros", "author_id": 15304, "author_profile": "https://Stackoverflow.com/users/15304", "pm_score": 5, "selected": false, "text": "setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, (int[]){1}, sizeof(int));\n void myFunction(type* values) {\n while(*values) x=*values++;\n}\nmyFunction((type[]){val1,val2,val3,val4,0});\n" }, { "answer_id": 132558, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "struct cat {\n unsigned int legs:3; // 3 bits for legs (0-4 fit in 3 bits)\n unsigned int lives:4; // 4 bits for lives (0-9 fit in 4 bits)\n // ...\n};\n\ncat make_cat()\n{\n cat kitty;\n kitty.legs = 4;\n kitty.lives = 9;\n return kitty;\n}\n sizeof(cat) sizeof(char)" }, { "answer_id": 132702, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": false, "text": "int x = 'ABCD';\n x 0x41424344 0x44434241 enum state {\n stopped = 'STOP',\n running = 'RUN!',\n waiting = 'WAIT',\n};\n" }, { "answer_id": 132844, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "\nhexDigit = \"0123456789abcdef\"[someNybble];\n \nunsigned char bar[100];\nunsigned char *foo = bar;\nunsigned char blah = 42[foo];\n" }, { "answer_id": 133118, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 2, "selected": false, "text": "\nvoid callback(const char *msg, void *data)\n{\n // do something with msg, e.g.\n printf(\"%s\\n\", msg);\n\n return;\n data = NULL;\n}\n" }, { "answer_id": 133555, "author": "tonylo", "author_id": 4071, "author_profile": "https://Stackoverflow.com/users/4071", "pm_score": 7, "selected": false, "text": "#define likely(x) __builtin_expect((x),1)\n#define unlikely(x) __builtin_expect((x),0)\n void foo(int arg)\n{\n if (unlikely(arg == 0)) {\n do_this();\n return;\n }\n do_that();\n ...\n}\n" }, { "answer_id": 133590, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 5, "selected": false, "text": "#define FOO 16\n#define BAR 3\n\nmyStructType_t myStuff[] = {\n [FOO] = { foo1, foo2, foo3 },\n [BAR] = { bar1, bar2, bar3 },\n ...\n" }, { "answer_id": 133646, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "void foo(uint32_t extraPadding) {\n uint8_t commBuffer[sizeof(myProtocol_t) + extraPadding];\n" }, { "answer_id": 133714, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 6, "selected": false, "text": "int8_t\nint16_t\nint32_t\nuint8_t\nuint16_t\nuint32_t\n #define INT16 short\n#define INT32 long\n" }, { "answer_id": 133753, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 6, "selected": false, "text": "for (int i=0; i<10; i++, doSomethingElse())\n{\n /* whatever */\n}\n int j = (printf(\"Assigning variable j\\n\"), getValueFromSomewhere());\n" }, { "answer_id": 135336, "author": "yogeesh", "author_id": 9030, "author_profile": "https://Stackoverflow.com/users/9030", "pm_score": 2, "selected": false, "text": "uint32_t Int;\nfloat flt = 10.5; // say\n\nInt = *(uint32_t *)&flt;\n\nprintf (\"Float 10.5 is stored internally as %8X\\n\", Int);\n float flt = 10.5; // say\n\nprintf (\"Float 10.5 is stored internally as %8X\\n\", *(uint32_t *)&flt);\n *(float *)&Int = flt;\n typedef union\n{\n uint32_t Int;\n float flt;\n\n} FloatInt_type;\n" }, { "answer_id": 138075, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "typedef struct {\n unsigned int size;\n char buffer[1];\n} tSizedBuffer;\n\ntSizedBuffer *buff = (tSizedBuffer*)(malloc(sizeof(tSizedBuffer) + 99));\n\n// can now refer to buff->buffer[0..99].\n" }, { "answer_id": 147075, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 5, "selected": false, "text": "int my_printf (void *my_object, const char *my_format, ...)\n __attribute__ ((format (printf, 2, 3)));\n" }, { "answer_id": 147107, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 1, "selected": false, "text": "register" }, { "answer_id": 155726, "author": "mike511", "author_id": 9593, "author_profile": "https://Stackoverflow.com/users/9593", "pm_score": 6, "selected": false, "text": "struct mystruct a = {0};\n" }, { "answer_id": 207983, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": false, "text": "memcpy() typedef struct {\n int x;\n int y;\n} Point;\n Point point_new(int x, int y)\n{\n Point p;\n p.x = x;\n p.y = y;\n return p;\n}\n Point origin;\norigin = point_new(0, 0);\n" }, { "answer_id": 226139, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 4, "selected": false, "text": "//--- size of static_assertion array is negative if condition is not met\n#define STATIC_ASSERT(condition) \\\n typedef struct { \\\n char static_assertion[condition ? 1 : -1]; \\\n } static_assertion_t\n\n//--- ensure structure fits in \nSTATIC_ASSERT(sizeof(mystruct_t) <= 4096);\n" }, { "answer_id": 226888, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 3, "selected": false, "text": "#define ERR(name, fmt, ...) fprintf(stderr, \"ERROR \" #name \": \" fmt \"\\n\", \\\n __VAR_ARGS__)\n ERR(errCantOpen, \"File %s cannot be opened\", filename);\n" }, { "answer_id": 980530, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": false, "text": "int x[] = { 1, 2, 3, };\n\nenum foo { bar, baz, boom, };\n" }, { "answer_id": 1025017, "author": "aeflash", "author_id": 105208, "author_profile": "https://Stackoverflow.com/users/105208", "pm_score": 1, "selected": false, "text": "struct Point {\n float x;\n float y;\n float z;\n};\n Point a;\nint sum = 0, i = 0;\nfor( ; i < 3; i++)\n sum += ((float*)a)[i];\n" }, { "answer_id": 1025416, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": " \n\nstruct foo{\n int x;\n int y;\n char* name;\n};\n\nvoid main(){\n struct foo f = { .y = 23, .name = \"awesome\", .x = -38 };\n}\n\n\n struct foo{\n int x;\n int y;\n char* name;\n};\n\nvoid main(){\n struct foo f = { .y = 23, .name = \"awesome\", .x = -38 };\n}\n " }, { "answer_id": 1025705, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "__FILE__ \n__FUNCTION__\n__LINE__\n" }, { "answer_id": 1025714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#ifdef _DEBUG\n#define mmalloc(bytes) malloc(bytes);printf(\"malloc: %d\\t<%s@%d>\\n\", bytes, __FILE__, __LINE__);\n#define mrealloc(pointer, bytes) realloc(pointer, bytes);printf(\"realloc: %d\\t<%s@%d>\\n\", bytes, __FILE__, __LINE__);\n#else //_DEBUG\n#define mmalloc(bytes) malloc(bytes)\n#define mrealloc(pointer, bytes) realloc(pointer, bytes)\n #ifdef _DEBUG\n#define mmalloc(bytes) malloc(bytes);printf(\"malloc: %d\\t<%s@%d>\\n\", bytes, __FILE__, __LINE__);\n#define mrealloc(pointer, bytes) realloc(pointer, bytes);printf(\"realloc: %d\\t<%s@%d>\\n\", bytes, __FILE__, __LINE__);\n#define BAILIFNOT(Node, Check) if(Node->type != Check) return 0;\n#define NULLCHECK(var) if(var == NULL) setError(__FILE__, __LINE__, \"Null exception\", \" var \", FATAL);\n#define ASSERT(n) if( ! ( n ) ) { printf(\"<ASSERT FAILURE@%s:%d>\", __FILE__, __LINE__); fflush(0); __asm(\"int $0x3\"); }\n#define TRACE(n) printf(\"trace: %s <%s@%d>\\n\", n, __FILE__, __LINE__);fflush(0);\n#else //_DEBUG\n#define mmalloc(bytes) malloc(bytes)\n#define mrealloc(pointer, bytes) realloc(pointer, bytes)\n#define BAILIFNOT(Node, Check) {}\n#define NULLCHECK(var) {}\n#define ASSERT(n) {}\n#define TRACE(n) {}\n#endif //_DEBUG\n malloc: 12 <hash.c@298>\ntrace: nodeCreate <hash.c@302>\nmalloc: 5 <hash.c@308>\nmalloc: 16 <hash.c@316>\nmalloc: 256 <hash.c@320>\ntrace: dataLoadHead <hash.c@441>\nmalloc: 270 <hash.c@463>\nmalloc: 262144 <hash.c@467>\ntrace: dataLoadRecursive <hash.c@404>\n" }, { "answer_id": 1025748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "C_OO_NEW #define C_copy(to, from) to->copy(to, from)\n\n#define true 1\n#define false 0\n#define C_OO_PROTOTYPE(type)\\\nvoid type##_init (struct type##_struct *my);\\\nvoid type##_dispose (struct type##_struct *my);\\\nchar type##_equal (struct type##_struct *my, struct type##_struct *yours); \\\nstruct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from); \\\nconst type type##__prototype = {type##_init, type##_dispose, type##_equal, type##_copy\n\n#define C_OO_OVERHEAD(type)\\\n void (*init) (struct type##_struct *my);\\\n void (*dispose) (struct type##_struct *my);\\\n char (*equal) (struct type##_struct *my, struct type##_struct *yours); \\\n struct type##_struct *(*copy) (struct type##_struct *my, struct type##_struct *from); \n\n#define C_OO_IN(ret, type, function, ...) ret (* function ) (struct type##_struct *my, __VA_ARGS__);\n#define C_OO_OUT(ret, type, function, ...) ret type##_##function (struct type##_struct *my, __VA_ARGS__);\n\n#define C_OO_PNEW(type, instance)\\\n instance = ( type *) malloc(sizeof( type ));\\\n memcpy(instance, & type##__prototype, sizeof( type ));\n\n#define C_OO_NEW(type, instance)\\\n type instance;\\\n memcpy(&instance, & type ## __prototype, sizeof(type));\n\n#define C_OO_DELETE(instance)\\\n instance->dispose(instance);\\\n free(instance);\n\n#define C_OO_INIT(type) void type##_init (struct type##_struct *my){return;}\n#define C_OO_DISPOSE(type) void type##_dispose (struct type##_struct *my){return;}\n#define C_OO_EQUAL(type) char type##_equal (struct type##_struct *my, struct type##_struct *yours){return 0;}\n#define C_OO_COPY(type) struct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from){return 0;}\n" }, { "answer_id": 1025953, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 0, "selected": false, "text": "typeof(foo) copy_of_foo; //declare bar to be a variable of the same type as foo\ncopy_of_foo = foo; //now copy_of_foo has a backup of foo, for any type\n" }, { "answer_id": 1026588, "author": "kolistivra", "author_id": 126199, "author_profile": "https://Stackoverflow.com/users/126199", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n\nint main() {\n int a = 3;\n float b = 6.412355;\n printf(\"%.*f\\n\",a,b);\n return 0;\n}\n" }, { "answer_id": 1027608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "fflush(stdin) scanf(\"%*[^\\n]%*c\")" }, { "answer_id": 1636390, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "struct SomeStruct\n{\n unsigned a : 5;\n unsigned b : 1;\n unsigned c : 7;\n};\n xxxc cccc ccba aaaa\n" }, { "answer_id": 1715239, "author": "S.C. Madsen", "author_id": 102715, "author_profile": "https://Stackoverflow.com/users/102715", "pm_score": 3, "selected": false, "text": "#define D 1\n#define DD 2\n\nenum CompileTimeCheck\n{\n MAKE_SURE_DD_IS_TWICE_D = 1/(2*(D) == (DD)),\n MAKE_SURE_DD_IS_POW2 = 1/((((DD) - 1) & (DD)) == 0)\n};\n" }, { "answer_id": 2773676, "author": "Joe D", "author_id": 292979, "author_profile": "https://Stackoverflow.com/users/292979", "pm_score": 3, "selected": false, "text": "#define lambda(return_type, function_body) \\\n ({ return_type fn function_body fn })\n lambda (int, (int x, int y) { return x > y; })(1, 2)\n ({ int fn (int x, int y) { return x > y } fn; })(1, 2)\n" }, { "answer_id": 2793400, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 4, "selected": false, "text": "#define PATH \"/some/path/\" fd = open(PATH \"/file\", flags);\n char buffer[256];\nsnprintf(buffer, 256, \"%s/file\", PATH);\nfd = open(buffer, flags);\n" }, { "answer_id": 2914468, "author": "Steve Webb", "author_id": 351097, "author_profile": "https://Stackoverflow.com/users/351097", "pm_score": 3, "selected": false, "text": "__LINE__ __FILE__" }, { "answer_id": 4062921, "author": "onemasse", "author_id": 492716, "author_profile": "https://Stackoverflow.com/users/492716", "pm_score": 3, "selected": false, "text": "sscanf ( string, \"%d%n\", &number, &length );\nstring += length;\n #include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n 1 || puts(\"Hello\\n\");\n 0 || puts(\"Hi\\n\");\n 1 && puts(\"ROFL\\n\");\n 0 && puts(\"LOL\\n\");\n\n exit( 0 );\n}\n" }, { "answer_id": 4286818, "author": "Patrick Schlüter", "author_id": 146377, "author_profile": "https://Stackoverflow.com/users/146377", "pm_score": 3, "selected": false, "text": "struct {\n int a:3;\n int b:2;\n int :0;\n int c:4;\n int d:3;\n};\n 000aaabb 0ccccddd\n 0000aaab bccccddd\n char" }, { "answer_id": 4622475, "author": "thequark", "author_id": 377362, "author_profile": "https://Stackoverflow.com/users/377362", "pm_score": 1, "selected": false, "text": "sizeof sizeof sizeof int j;\nint i;\nj = sizeof(i++)\n i sizeof i sizeof f g h int f() + g() * h()\n g h f" }, { "answer_id": 4622548, "author": "thequark", "author_id": 377362, "author_profile": "https://Stackoverflow.com/users/377362", "pm_score": 2, "selected": false, "text": "__LINE__ __FILE__" }, { "answer_id": 8867485, "author": "Vicky Chijwani", "author_id": 504611, "author_profile": "https://Stackoverflow.com/users/504611", "pm_score": 2, "selected": false, "text": "== if (0 == count) {\n ...\n}\n if (count = 0)" }, { "answer_id": 8904056, "author": "Renan Greinert", "author_id": 1122858, "author_profile": "https://Stackoverflow.com/users/1122858", "pm_score": -1, "selected": false, "text": "int8_t\nint16_t\nint32_t\nint64_t\nuint8_t\nuint16_t\nuint32_t\nuint64_t\nfloat32_t\nfloat64_t\nchar_t\n" }, { "answer_id": 8930383, "author": "Patrick Schlüter", "author_id": 146377, "author_profile": "https://Stackoverflow.com/users/146377", "pm_score": 0, "selected": false, "text": "%n printf int pos1, pos2;\n char *string_of_unknown_length = \"we don't care about the length of this\";\n\n printf(\"Write text of unknown %n(%s)%n text\\n\", &pos1, string_of_unknown_length, &pos2);\n printf(\"%*s\\\\%*s/\\n\", pos1, \" \", pos2-pos1-2, \" \");\n printf(\"%*s\", pos1+1, \" \");\n for(int i=pos1+1; i<pos2-1; i++)\n putc('-', stdout);\n putc('\\n', stdout);\n Write text of unknown (we don't care about the length of this) text\n \\ /\n --------------------------------------\n" }, { "answer_id": 9220598, "author": "Colin King", "author_id": 1200911, "author_profile": "https://Stackoverflow.com/users/1200911", "pm_score": 0, "selected": false, "text": "void sw(int s)\n{\n switch (s) while (0) {\n case 0:\n printf(\"zero\\n\");\n continue;\n case 1:\n printf(\"one\\n\");\n continue;\n default:\n printf(\"something else\\n\");\n continue;\n }\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21548/" ]
132,242
<p>Consider this case:</p> <pre><code>dll = LoadDLL() dll-&gt;do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); </code></pre> <p>At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.</p>
[ { "answer_id": 132309, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "dll = DllLoad();\n\nptr = dll->alloc();\n\ndll->free(ptr);\n\nDllUnload(dll);\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17424/" ]
132,245
<p>The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store.</p> <p>It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods.</p> <p>So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.</p> <p>I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.</p> <pre><code>public class BaseDataObject { // internal data store private Dictionary&lt;string, object&gt; attachedData = new Dictionary&lt;string, object&gt;(); public void SetData(string key, object value) { attachedData[key] = value; } public object GetData(string key) { return attachedData[key]; } public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public static class Extensions { public static void SetBarValue(this BaseDataObject dataObject, int barValue) { /// Cannot attach a property to BaseDataObject? dataObject.SetData("bar", barValue); } } public class TestDemo { public void CreateTest() { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; // this does not work - it does not compile // cannot use extension method in the initialiser block // cannot make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) }; } } </code></pre> <p>One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.:</p> <pre><code>// fluent interface style public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); return dataObject; } // this works BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5); </code></pre> <p>But will this work in a LINQ query?</p>
[ { "answer_id": 132275, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 3, "selected": false, "text": "var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };\n BaseDataObject tempObject = new BaseDataObject();\ntempObject.SomeValue = 3;\ntempObject.SomeOtherValue = 4;\nBaseDataObject x = tempObject;\n var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };\nx.SetBarValue()\n public int BarValue\n{\n set\n {\n //Value should be ignored\n }\n}\n public class DataObjectWithBarValue : BaseDataObject\n{\n public void BarValue\n {\n set\n {\n SetData(\"bar\", value);\n }\n get\n {\n (int) GetData(\"bar\");\n }\n }\n}\n" }, { "answer_id": 132279, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "BaseDataObject test2 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4}).SetBarValue(5);\n" }, { "answer_id": 132324, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": true, "text": "public static T SetBarValue<T>(this T dataObject, int barValue)\n where T : BaseDataObject \n {\n dataObject.SetData(\"bar\", barValue);\n return dataObject;\n }\n" }, { "answer_id": 132356, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": " static T WithBarValue<T>(this T dataObject, int barValue)\n where T : BaseDataObject \n { dataObject.SetData(\"bar\", barValue); \n return dataObject;\n }\n\nvar x = new BaseDataObject{SomeValue=3, OtherValue=4}.WithBarValue(5);\n" }, { "answer_id": 136085, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "public class SubClassedDataObject : BaseDataObject\n{\n public int Bar\n {\n get { return (int)GetData(\"bar\"); }\n set { SetData(\"bar\", value); }\n }\n}\n SubClassedDataObject testSub = new SubClassedDataObject\n { SomeValue = 3, SomeOtherValue = 4, Bar = 5 };\n public static void SetBar(this BaseDataObject dataObject, int barValue)\n {\n dataObject.SetData(\"bar\", barValue);\n }\n public static int GetBar(this BaseDataObject dataObject)\n {\n return (int)dataObject.GetData(\"bar\");\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
132,277
<p>I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?</p>
[ { "answer_id": 132339, "author": "paul", "author_id": 11249, "author_profile": "https://Stackoverflow.com/users/11249", "pm_score": 3, "selected": false, "text": "public static bool IsUserInGroup(string lanid, string group)\n{\n DirectoryEntry entry = new DirectoryEntry(\"LDAP://\" + LDAPPATH);\n if(entry != null)\n {\n entry.Username=@\"LDAPUSER\";\n entry.Password=\"LDAPPASSWORD\";\n DirectorySearcher srch = new DirectorySearcher(entry);\n srch.Filter = String.Format(\"(&(objectClass=person)(sAMAccountName={0}))\", lanid);\n srch.PropertiesToLoad.Add(\"memberOf\");\n\n SearchResult result = srch.FindOne();\n if(result != null)\n {\n if(result.Properties.Contains(\"memberOf\"))\n {\n string lookfor = String.Format(\"cn={0},\", group.ToLower());\n foreach(string memberOf in result.Properties[\"memberOf\"])\n {\n if(memberOf.ToLower().StartsWith(lookfor))\n return true;\n }\n }\n }\n return false;\n }\n throw new Exception(String.Format(\"Could not get Directory lanid:{0}, group{1}\", lanid, group));\n}\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
132,305
<p>At work we have two servers, one is running an application a lot of people use which has an SQL Server 2000 back end. I have been free to query this for a long time but can't add anything to it such as stored procedures or extra tables. </p> <p>This has lead to us having a second SQL Server linked to the first one and me building up a library of stored procedures that query data from both sides using linked server. Some of these queries are taking longer than what I would like. </p> <p>Can someone point me to some good articles about using linked servers? I am particularly interested in finding out what data is being transferred between the two as usually the majority of the sql statement could be performed remotely but I have the feeling it may be transferring the full tables, it is usually just a join to a small final table locally.</p> <p>Also what do the linked server options do I currently have:</p> <ul> <li>Collation Compatible True</li> <li>Data Access True</li> <li>Rpc True</li> <li>Rpc Out True</li> <li>Use Remote Collation False</li> <li>Collation Name (Blank)</li> <li>Connection Timeout 0</li> <li>Query Timeout 0</li> </ul> <p><strong>EDIT:</strong></p> <p>Just thought I would update this post I used openqueries with dynamic parameters for a while to boost performance, thanks for the tip. However doing this can make queries more messy as you end up dealing with strings. finally this summer we upgraded SQL Server to 2008 and implemented live data mirroring. To be honest the open queries were approaching the speed of local queries for my tasks but the mirroring has certainly made the sql easier to deal with.</p>
[ { "answer_id": 143081, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 3, "selected": false, "text": "SELECT loc.field1, lnk.field1\nFROM MyTable loc\nINNER JOIN RemoteServer.Database.Schema.SomeTable lnk\n ON loc.id = lnk.id\n AND lnk.RecordDate = GETDATE()\nWHERE loc.SalesDate = GETDATE()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
132,318
<p>I have an ANSI encoded text file that should not have been encoded as ANSI as there were accented characters that ANSI does not support. I would rather work with UTF-8.</p> <p>Can the data be decoded correctly or is it lost in transcoding?</p> <p>What tools could I use?</p> <p>Here is a sample of what I have:</p> <pre><code>ç é </code></pre> <p>I can tell from context (café should be café) that these should be these two characters:</p> <pre><code>ç é </code></pre>
[ { "answer_id": 132327, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 3, "selected": false, "text": "vim -c \"set encoding=utf8\" -c \"set fileencoding=utf8\" -c \"wq\" filename\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18333/" ]
132,319
<p>I'm trying to determine a fast way of storing a set of objects, each of which have an x and y coordinate value, such that I can quickly retrieve all objects within a certain rectangle or circle. For small sets of objects (~100) the naive approach of simply storing them in a list, and iterating through it, is relatively quick. However, for much larger groups, that is expectedly slow. I've tried storing them in a pair of TreeMaps as well, one sorted on the x coordinate, and one sorted on the y coordinate, using this code:</p> <pre><code>xSubset = objectsByX.subSet( minX, maxX ); ySubset = objectsByY.subSet( minY, maxY ); result.addAll( xSubset ); result.retainAll( ySubset ); </code></pre> <p>This also works, and is faster for larger sets of objects, but is still slower than I would like. Part of the problem is also that these objects move around, and need to be inserted back into this storage, which means removing them from and re-adding them to the trees/lists. I can't help but think there must be better solutions out there. I'm implementing this in Java, if it makes any difference, though I expect any solution will be more in the form of a useful pattern/algorithm.</p>
[ { "answer_id": 133817, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 0, "selected": false, "text": " TreeMap<Integer, TreeMap<Integer, Point>> xMap = new TreeMap<Integer, TreeMap<Integer, Point>>();\n for (int x = 1; x < 100; x += 2)\n for (int y = 0; y < 100; y += 2)\n {\n Point p = new Point(x, y);\n TreeMap<Integer, Point> tempx = xMap.get(x);\n if (tempx == null)\n {\n tempx = new TreeMap<Integer, Point>();\n xMap.put(x, tempx);\n }\n tempx.put(y, p);\n }\n SortedMap<Integer, TreeMap<Integer, Point>> tempq = xMap.subMap(5, 8);\n Collection<Point> result = new HashSet<Point>();\n for (TreeMap<Integer, Point> smaller : tempq.values())\n {\n SortedMap<Integer, Point> smallerYet = smaller.subMap(6, 12);\n result.addAll(smallerYet.values());\n }\n for (Point q : result)\n {\n System.out.println(q);\n }\n }\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22070/" ]
132,323
<p>When iterating over elements of a vector it is preferred to use iterators instead of an index (see <a href="https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices">Why use iterators instead of array indices?</a>). </p> <pre><code>std::vector&lt;T&gt; vec; std::vector&lt;T&gt;::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { // do work } </code></pre> <p>However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility?</p> <ol> <li>Revert to the indexed loop<pre> std::vector vec; size_t i; for ( i = 0; i &lt; vec.size(); ++i ) { // use i } </pre></li> <li>Calculate offset<pre> std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = it - vec.begin(); // use i } </pre></li> <li>Use std::distance <pre> std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = std::distance( vec.begin(), it ); // use i } </pre></li> </ol>
[ { "answer_id": 133545, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 3, "selected": false, "text": "std::distance(vec.begin(), it) it vec" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
132,326
<p>My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set</p> <pre><code>_moHttpClient.setHttpConnectionFactoryTimeout(30000); </code></pre> <p>it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur</p>
[ { "answer_id": 132335, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": " HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();\n cmparams.setSoTimeout(10000);\n cmparams.setTcpNoDelay(true);\n HttpConnectionManager manager = new SimpleHttpConnectionManager();\n manager.setParams(cmparams);\n params = new HttpClientParams();\n params.setSoTimeout(5000);\n client = new HttpClient(params, manager);\n" }, { "answer_id": 585547, "author": "Brian Agnew", "author_id": 12960, "author_profile": "https://Stackoverflow.com/users/12960", "pm_score": 3, "selected": false, "text": "HttpConnectionParams setConnectionTimeout()\nsetSoTimeout()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
132,329
<p>Are there any good examples (websites or books) around of how to build a full text search engine in F#? </p>
[ { "answer_id": 132335, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": " HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();\n cmparams.setSoTimeout(10000);\n cmparams.setTcpNoDelay(true);\n HttpConnectionManager manager = new SimpleHttpConnectionManager();\n manager.setParams(cmparams);\n params = new HttpClientParams();\n params.setSoTimeout(5000);\n client = new HttpClient(params, manager);\n" }, { "answer_id": 585547, "author": "Brian Agnew", "author_id": 12960, "author_profile": "https://Stackoverflow.com/users/12960", "pm_score": 3, "selected": false, "text": "HttpConnectionParams setConnectionTimeout()\nsetSoTimeout()\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]