qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
52,092
<p>This caught my attention last night.</p> <p>On the latest <a href="http://altnetpodcast.com/episodes/10-oop-in-ruby" rel="nofollow noreferrer">ALT.NET Podcast</a> Scott Bellware discusses how as opposed to Ruby, languages like C#, Java et al. are not truly object oriented rather opting for the phrase &quot;class-oriented&quot;. They talk about this distinction in very vague terms without going into much detail or discussing the pros and cons much.</p> <p>What is the real difference here and how much does it matter? What are other languages then are &quot;object-oriented&quot;? It sounded pretty interesting but I don't want to have to learn Ruby just to know what if anything I am missing.</p> <h2>Update</h2> <p>After reading some of the answers below it seems like people generally agree that the reference is to duck-typing. What I'm not sure I understand still though is the claim that this ultimately changes all that much. Especially if you are already doing proper TDD with loose coupling etc. Can someone show me an example of a specific thing I could do with Ruby that I cannot do with C# and that exemplifies this different OOP approach?</p>
[ { "answer_id": 52107, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "__iter__() next()" }, { "answer_id": 93409, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "animal = Object.new # create a new instance of base Object\n\ndef animal.number_of_feet=(feet) # adding new methods to an Object instance. What?\n @number_of_feet = feet\nend\ndef animal.number_of_feet\n @number_of_feet\nend\n\ncat = animal.clone #inherits 'number_of_feet' behavior from animal\ncat.number_of_feet = 4\n\nfelix = cat.clone #inherits state of '4' and behavior from cat\nputs felix.number_of_feet # outputs 4\n class Container < (rand < 0.5 ? Array : Hash)\nend\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
52,098
<p>I'm developing an application for Windows Mobile Devices using Visual Studio .NET 2008 whose UI requires the use of a ComboBox control. Unfortunately, for devices with neither a hardware fullsize keyboard nor a touchscreen interface, there is no way to move (tab) from the ComboBox control to another control on the same form (say, specifying a product in the ComboBox and then moving to a text field to add a quantity).</p> <p>I've tried creating an event handler for the ComboBox's KeyPress event and setting the focus to the next control manually whenever the user presses the Right or Left directional key but unfortunately the event handler does not capture those key presses.</p> <p>Any ideas? I have a strong suspicion that this is being over-engineered and that there exists a better control more suited to what I need to do; I find it a bit inconceivable that tabbing out of a Combo Box control could be that difficult.</p> <p>Thanks!</p> <p>EDIT: Apparently I can capture the KeyDown and KeyUp events on the ComboBox, which allows me to set the focus or tab to the next control. Still over-engineered - still looking for ideas!</p>
[ { "answer_id": 52116, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 2, "selected": true, "text": "KeyDown KeyUp KeyPress" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943/" ]
52,108
<p>What is the shortcut to open a file within your solution in Visual Studio 2008 (+ Resharper)?</p>
[ { "answer_id": 79864, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 2, "selected": false, "text": ">of f f" }, { "answer_id": 106681, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 0, "selected": false, "text": ">" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
52,134
<p>How can I tell from the assembly name, or assembly class (or others like it), whether an assembly is part of the <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> framework (that is, <code>System.windows.Forms</code>)?</p> <p>So far I've considered the PublicKeyToken, and CodeBase properties, but these are not always the same for the whole framework.</p> <p>The reason I want this information is to get a list of assemblies that my EXE file is using that need to be on client machines, so I can package the correct files in a setup file without using the Visual Studio setup system. The problem is, I don't want to pick up any .NET framework assemblies, and I want it to be an automatic process that is easy to roll out whenever a major update is finished.</p> <p>The ultimate solution would be that there is an IsFramework property... :)</p>
[ { "answer_id": 52199, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "C:\\Windows\\Microsoft.NET\\Framework" }, { "answer_id": 749535, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "RedistList\\FrameworkList.xml" }, { "answer_id": 3472112, "author": "jpierson", "author_id": 83658, "author_profile": "https://Stackoverflow.com/users/83658", "pm_score": 3, "selected": false, "text": "var attribute = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0] as AssemblyProductAttribute;\nvar isFrameworkAssembly = (attribute.Product == \"Microsoft® .NET Framework\");\n" }, { "answer_id": 3666403, "author": "Johannes Rudolph", "author_id": 125407, "author_profile": "https://Stackoverflow.com/users/125407", "pm_score": 2, "selected": false, "text": "FXAssembly .class private abstract auto ansi sealed beforefieldinit FXAssembly\n extends [mscorlib]System.Object\n{\n .field assembly static literal string Version = string('2.0.0.0')\n\n}\n" }, { "answer_id": 14558666, "author": "Jean Hominal", "author_id": 113158, "author_profile": "https://Stackoverflow.com/users/113158", "pm_score": 2, "selected": false, "text": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\{FrameworkName}\\{FrameworkVersion} RedistList\\FrameworkList.xml C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\RedistList\\FrameworkList.xml" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4002/" ]
52,160
<p>How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?</p> <p>i.e. something like:</p> <pre><code>If Typeof(foobar) = "CommandButton" Then ... </code></pre> <p><strong>/EDIT:</strong> to clarify, I need to check on Dynamically Typed objects. An example:</p> <pre><code>Dim y As Object Set y = CreateObject("SomeType") Debug.Print( &lt;The type name of&gt; y) </code></pre> <p>Where the output would be "CommandButton"</p>
[ { "answer_id": 52181, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "IDispatch TypeOf(object) is class" }, { "answer_id": 52243, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 4, "selected": true, "text": "If TypeName(foobar) = \"CommandButton\" Then\n DoSomething\nEnd If\n Private Sub Command1_Click()\n Dim oObject As Object\n Set oObject = CreateObject(\"Scripting.FileSystemObject\")\n Debug.Print \"Object Type: \" & TypeName(oObject)\nEnd Sub\n Object Type: FileSystemObject" }, { "answer_id": 52255, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "Typename()\n" }, { "answer_id": 156240, "author": "sharvell", "author_id": 23095, "author_profile": "https://Stackoverflow.com/users/23095", "pm_score": 2, "selected": false, "text": "Private Sub cmdCommand1_Click()\nDim a As Variant\nDim b As Variant\nDim c As Object\nDim d As Object\nDim e As Boolean\n\na = \"\"\nb = 3\nSet c = Me.cmdCommand1\nSet d = CreateObject(\"Project1.Class1\")\ne = False\n\nDebug.Print TypeName(a)\nDebug.Print TypeName(b)\nDebug.Print TypeName(c)\nDebug.Print TypeName(d)\nDebug.Print TypeName(e)\nEnd Sub\n String\nInteger\nCommandButton\nClass1\nBoolean\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
52,176
<p>Since Graduating from a very small school in 2006 with a badly shaped &amp; outdated program (I'm a foreigner &amp; didn't know any better school at the time) I've come to realize that I missed a lot of basic concepts from a mathematical &amp; software perspective that are mostly the foundations of other higher concepts.</p> <p>I.e. I tried to listen/watch the open courseware from MIT on <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/CourseHome/" rel="nofollow noreferrer">Introduction to Algorithms</a> but quickly realized I was missing several mathematical concepts to better understand the course.</p> <p>So what are the core mathematical concepts a good software engineer should know? And what are the possible books/sites you will recommend me?</p>
[ { "answer_id": 52338, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 4, "selected": false, "text": "if (condition-1) {\n if (condition-2) {\n action-1\n } else {\n action-2\n} else {\n action-2\n}\n if (condition-1 and condition-2) {\n action-1\n} else {\n action-2\n}\n" }, { "answer_id": 52367, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 4, "selected": false, "text": "Computer graphics -> Linear Algebra\nGaming -> Linear Algebra, Physics\nComputer Linguistics -> Statistics, Graph Theory\nAI -> Statistics, Stochastics, Logic, Graph Theory\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5413/" ]
52,187
<p>I need to test a serial port application on Linux, however, my test machine only has one serial port. </p> <p>Is there a way to add a virtual serial port to Linux and test my application by emulating a device through a shell or script?</p> <p>Note: I cannot remap the port, it hard coded on ttys2 and I need to test the application as it is written.</p>
[ { "answer_id": 74517, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 7, "selected": true, "text": "/dev/ptyp5 /dev/ttyp5 ttyp5 /dev/ttys2 /dev/ttys2 ptyp5 ttys2 ptyp5" }, { "answer_id": 10555885, "author": "slonik", "author_id": 1384839, "author_profile": "https://Stackoverflow.com/users/1384839", "pm_score": 6, "selected": false, "text": "socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11\n" }, { "answer_id": 11374412, "author": "Peter Remmers", "author_id": 255776, "author_profile": "https://Stackoverflow.com/users/255776", "pm_score": 4, "selected": false, "text": "#ifndef init_MUTEX\n#define init_MUTEX(x) sema_init((x),1)\n#endif\n" }, { "answer_id": 19733677, "author": "cantoni", "author_id": 2236741, "author_profile": "https://Stackoverflow.com/users/2236741", "pm_score": 8, "selected": false, "text": "socat -d -d pty,raw,echo=0 pty,raw,echo=0\n 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/2\n2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/3\n2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5]\n cat < /dev/pts/2\n 2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2**\n2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3**\n2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs \n echo \"Test\" > /dev/pts/3\n" }, { "answer_id": 70152395, "author": "Sadeesh Kalhara", "author_id": 10341589, "author_profile": "https://Stackoverflow.com/users/10341589", "pm_score": 2, "selected": false, "text": "$ socat -d -d pty,link=/tmp/vserial1,raw,echo=0 pty,link=/tmp/vserial2,raw,echo=0\n /tmp/vserial1 /tmp/vserial2 /dev/pts/*" }, { "answer_id": 73639043, "author": "Dan2theR", "author_id": 2251217, "author_profile": "https://Stackoverflow.com/users/2251217", "pm_score": 1, "selected": false, "text": "parallel 'i=\"{1}\"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1))' ::: $(seq 0 2 3;)\n parallel --dryrun i=\"0\"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1))\ni=\"2\"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1))\n $(seq x y z;) parallel 'i=\"{1}\"; echo \"make psuedo_devices {1} $(($i+1))\"' ::: $(seq 0 2 3;) make psuedo_devices 0 1\nmake psuedo_devices 2 3\n link pstree -c -a $PROC_ID perl /usr/bin/parallel i=\"{1}\"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1)) ::: 0 2\n ├─bash -c i=\"0\"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1))\n │ └─socat -d -d pty,raw,echo=0,link=/home/user/pty0 pty,raw,echo=0,link=/home/user/pty1\n └─bash -c i=\"2\"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1))\n └─socat -d -d pty,raw,echo=0,link=/home/user/pty2 pty,raw,echo=0,link=/home/user/pty3\n lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty0 -> /dev/pts/4\nlrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty1 -> /dev/pts/6\nlrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty2 -> /dev/pts/7\nlrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty3 -> /dev/pts/8\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
52,213
<p>When a user hits Refresh on their browser, it reloads the page but keeps the contents of form fields. While I can see this being a useful default, it can be annoying on some dynamic pages, leading to a broken user experience.</p> <p>Is there a way, in HTTP headers or equivalents, to change this behaviour?</p>
[ { "answer_id": 52226, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 6, "selected": true, "text": "<input autocomplete=\"off\">\n" }, { "answer_id": 52229, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<body onload=\"document.FormName.reset();\">\n <script type=\"text/javascript\">\n document.getElementById('field1').value ='';\n document.getElementById('field2').value ='';\n document.getElementById('field3').value ='';\n</script>\n" }, { "answer_id": 86505, "author": "ThoriumBR", "author_id": 16545, "author_profile": "https://Stackoverflow.com/users/16545", "pm_score": 0, "selected": false, "text": "<input type=\"text\" name=\"foo\" value=\"\">\n" }, { "answer_id": 1812985, "author": "Fabien", "author_id": 21132, "author_profile": "https://Stackoverflow.com/users/21132", "pm_score": 2, "selected": false, "text": "<input type=\"text\" name=\"pin\" autocomplete=\"off\" />\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000/" ]
52,234
<p>Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?</p> <p>If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?</p>
[ { "answer_id": 52242, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 7, "selected": true, "text": "tf diff /shelveset:shelveset /format:unified\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
52,238
<p>How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?</p> <p>An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.</p>
[ { "answer_id": 52250, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": false, "text": "addClassName removeClassName <tr> var rows = $$('tbody tr'); \nfor (var i = 0; i < rows.length; i++) { \n rows[i].onmouseover = function() { $(this).addClassName('hilight'); } \n rows[i].onmouseout = function() { $(this).removeClassName('hilight'); } \n}\n" }, { "answer_id": 52253, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": true, "text": "<table id=\"mytable\">\n <tbody>\n <tr><td>Foo</td><td>Bar</td></tr>\n <tr><td>Bork</td><td>Bork</td></tr>\n\n </tbody>\n</table>\n\n<script type=\"text/javascript\">\n\n$$('#mytable tr').each(function(item) {\n item.observe('mouseover', function() {\n item.setStyle({ backgroundColor: '#ddd' });\n });\n item.observe('mouseout', function() {\n item.setStyle({backgroundColor: '#fff' });\n });\n});\n</script>\n" }, { "answer_id": 52258, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 1, "selected": false, "text": "$('tableId').getElementsBySelector('tr').each(function (row) {\n ...\n});\n $('tableId').getElementsBySelector('tr').each(function (row) {\n Event.observe(row, 'mouseover', function () {...do hightlight code...});\n});\n" }, { "answer_id": 52273, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "$$('#thetable tr:not(#headRow)').each(\n <tr id=\"headRow\">\n <th>Header 1</th>\n</tr>\n" }, { "answer_id": 143014, "author": "Fczbkk", "author_id": 22920, "author_profile": "https://Stackoverflow.com/users/22920", "pm_score": 2, "selected": false, "text": "tr:hover { background: red; }\n table.highlightable tr.highlight { background: red; }\n // when document loads\ndocument.observe( 'dom:loaded', function() {\n // find all rows in highlightable table\n $$( 'table.highlightable tr' ).each( function( row ) {\n // add/remove class \"highlight\" when mouse enters/leaves\n row.observe( 'mouseover', function( evt ) { evt.element().addClassName( 'highlight' ) } );\n row.observe( 'mouseout', function( evt ) { evt.element().removeClassName( 'highlight' ) } );\n } );\n} )\n <table class=\"highlightable\">\n ...\n</table>\n" }, { "answer_id": 2371048, "author": "Zloi", "author_id": 285270, "author_profile": "https://Stackoverflow.com/users/285270", "pm_score": 0, "selected": false, "text": "tr{ position: relative; }\ntd{ background-image: none } \n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3920/" ]
52,239
<p>We are working with an oracle database in which the person that set it up is "long gone" and thus do not know the sysdba password, but need it. We have root access to the box (its on linux). Is there any way to recover or change the sys passwords?</p>
[ { "answer_id": 52244, "author": "Paul Hargreaves", "author_id": 5330, "author_profile": "https://Stackoverflow.com/users/5330", "pm_score": 6, "selected": true, "text": "sqlplus \"/ as sysdba\"\n alter user sys identified by <new password>;\n" }, { "answer_id": 34349844, "author": "Lalit Kumar B", "author_id": 3989608, "author_profile": "https://Stackoverflow.com/users/3989608", "pm_score": 1, "selected": false, "text": "export ORACLE_HOME=<oracle_home_directory_till_db_home>\nexport PATH=$PATH:$ORACLE_HOME/bin\nexport ORACLE_SID=<your_oracle_sid>\nSQLPLUS / AS SYSDBA\n set ORACLE_HOME=<oracle_home_path_till_db_home>\nset PATH=%PATH%||%ORACLE_HOME%\\bin\nset ORACLE_SID=<your_oracle_sid>\nSQLPLUS / AS SYSDBA\n ALTER USER username IDENTIFIED BY password;\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
52,256
<p>I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed).</p> <p>Is it possible?</p>
[ { "answer_id": 52257, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "System.DirectoryServices.AccountManagement public static bool IsUserInGroup(string username, string groupname, ContextType type)\n{\n PrincipalContext context = new PrincipalContext(type);\n\n UserPrincipal user = UserPrincipal.FindByIdentity(\n context,\n IdentityType.SamAccountName,\n username);\n GroupPrincipal group = GroupPrincipal.FindByIdentity(\n context, groupname);\n\n return user.IsMemberOf(group);\n}\n" }, { "answer_id": 310125, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 1, "selected": false, "text": "using System.Security.Principal;\n\nWindowsIdentity identity = WindowsIdentity.GetCurrent();\nWindowsPrincipal wp = new WindowsPrincipal(identity);\n\nif (wp.IsInRole(\"BUILTIN\\Administrators\"))\n // Is Administrator\nelse\n // Is Not\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95/" ]
52,286
<p>Wrote the following in PowersHell as a quick iTunes demonstration:</p> <pre><code>$iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource foreach ($PList in $LibrarySource.Playlists) { write-host $PList.name } </code></pre> <p>This works well and pulls back a list of playlist names. However on trying to close iTunes a warning appears</p> <blockquote> <p>One or more applications are using the iTunes scripting interface. Are you sure you want to quit?</p> </blockquote> <p>Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?</p> <pre><code>Itunes 7.7.1, Windows XP </code></pre>
[ { "answer_id": 52309, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 3, "selected": true, "text": "\n [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)\n [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)\n powershell .\\scriptname.ps1" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330/" ]
52,312
<p>So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?</p>
[ { "answer_id": 52330, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 3, "selected": false, "text": "bool HasRight(string rightName, DomainObject obj) {\n try {\n CheckRight(rightName, obj);\n return true;\n }\n catch (Exception ex) {\n return false;\n }\n}\n\nvoid CheckRight(string rightName, DomainObject obj) {\n if (!_user.Rights.Contains(rightName))\n throw new Exception();\n}\n bool HasRight(string rightName, DomainObject obj) {\n return _user.Rights.Contains(rightName);\n}\n\nvoid CheckRight(string rightName, DomainObject obj) {\n if (!HasRight(rightName, obj))\n throw new Exception();\n}\n" }, { "answer_id": 52390, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 7, "selected": false, "text": "throw;" }, { "answer_id": 580510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public bool DeleteGallery(int id)\n{\n try\n {\n using (var transaction = new DbTransactionManager())\n {\n try\n {\n transaction.BeginTransaction();\n\n _galleryRepository.DeleteGallery(id, transaction);\n _galleryRepository.DeletePictures(id, transaction);\n\n FileManager.DeleteAll(id);\n\n transaction.Commit();\n }\n catch (DataAccessException ex)\n {\n Logger.Log(ex);\n transaction.Rollback(); \n throw new BusinessObjectException(\"Cannot delete gallery. Ensure business rules and try again.\", ex);\n }\n }\n }\n catch (DbTransactionException ex)\n {\n Logger.Log(ex);\n throw new BusinessObjectException(\"Cannot delete gallery.\", ex);\n }\n return true;\n}\n" }, { "answer_id": 2765798, "author": "Sebastian Ramadan", "author_id": 332409, "author_profile": "https://Stackoverflow.com/users/332409", "pm_score": -1, "selected": false, "text": "int x;\ntry {\n x = int.Parse(\"1234\");\n}\ncatch {\n return;\n}\n// some more code here...\n int x;\nif (int.TryParse(\"1234\", out x) == false) {\n return;\n}\n// some more code here\n while (int.TryParse(...))\n{\n ...\n}\n try {\n for (;;)\n {\n x = int.Parse(...);\n ...\n }\n}\ncatch\n{\n ...\n}\n" }, { "answer_id": 45701327, "author": "autistic", "author_id": 1989425, "author_profile": "https://Stackoverflow.com/users/1989425", "pm_score": 3, "selected": false, "text": "try catch try catch finally try catch finally Parse TryParse ConvertTo Int.Parse Int.TryParse TryParse try catch try catch try catch int x;\ntry {\n x = int.Parse(\"1234\");\n}\ncatch {\n return;\n}\n// some more code here...\n try catch int x;\nif (int.TryParse(\"1234\", out x) == false) {\n return;\n}\n// some more code here\n try catch try catch Int.TryParse try catch try catch try catch try catch finally try catch finally try try-block\ncatch ( ... ) catch-block-1\n... \ncatch ( ... ) catch-block-n\n try try try catch try garbage=42; catch finally try try-block\nfinally finally-block\n try try-block\ncatch ( ... ) catch-block-1\n... \ncatch ( ... ) catch-block-n\nfinally finally-block\n try { \n try \n try-block\n catch ( ... ) catch-block-1\n ... \n catch ( ... ) catch-block-n\n} \nfinally finally-block\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
52,313
<p>This question is kind of an add-on to this <a href="https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why">question</a></p> <p>In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) </p> <pre><code>switch (month) { case 0: add something to month totals case 1: add something to month totals case 2: add something to month totals default: break; } </code></pre> <p>Is there a logical alternative to this in C# without having to write out a ton of if statements?</p> <pre><code>if (month &lt;= 0) add something to month if (month &lt;= 1) add something to month if (month &lt;= 2) add something to month .... etc </code></pre>
[ { "answer_id": 52318, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 5, "selected": true, "text": "foreach(MonthSpecification spec in this.MonthSpecifications)\n{\n if(spec.IsSatisfiedBy(month))\n spec.Perform(month);\n}\n" }, { "answer_id": 52323, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "const int addToTotals[] = {123, 456, ..., 789};\n\nfor(i=month;i<12;i++)\n totals += addToTotals[i];\n" }, { "answer_id": 52388, "author": "jwarzech", "author_id": 3111, "author_profile": "https://Stackoverflow.com/users/3111", "pm_score": 3, "selected": false, "text": "switch(myVar)\n{\n case 1:\n case 2: // Case 1 or 2 get here\n break;\n}\n switch(myVar)\n {\n case 1: // Case 1 statement\n goto case 2;\n case 2: // Case 1 or 2 get here\n break;\n }\n" }, { "answer_id": 2564325, "author": "svv", "author_id": 307360, "author_profile": "https://Stackoverflow.com/users/307360", "pm_score": 0, "selected": false, "text": "case 2:\n\ncase 1:\n\ncase 0:\n\nbreak;\n\n\ndefault:\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4144/" ]
52,315
<p>We have some input data that sometimes appears with &amp;nbsp characters on the end.</p> <p>The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.</p> <p>Ltrim and Rtrim don't remove the characters, so we're forced to do something like:</p> <pre><code>UPDATE myTable SET myColumn = replace(myColumn,char(160),'') WHERE charindex(char(160),myColumn) &gt; 0 </code></pre> <p>This works for the &amp;nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?</p>
[ { "answer_id": 52327, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "-- Put something like this into a user function:\nDECLARE @cString VARCHAR(32)\nDECLARE @nPos INTEGER\nSELECT @cString = '90$%45623 *6%}~:@'\nSELECT @nPos = PATINDEX('%[^0-9]%', @cString)\n\nWHILE @nPos > 0\nBEGIN\nSELECT @cString = STUFF(@cString, @nPos, 1, '')\nSELECT @nPos = PATINDEX('%[^0-9]%', @cString)\nEND\n\nSELECT @cString \n" }, { "answer_id": 879018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "CREATE FUNCTION [dbo].[fnRemoveBadCharacter]\n(\n @BadString nvarchar(20)\n)\nRETURNS nvarchar(20)\nAS\nBEGIN\n\n DECLARE @nPos INTEGER\n SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)\n\n WHILE @nPos > 0\n BEGIN\n SELECT @BadString = STUFF(@BadString, @nPos, 1, '')\n SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)\n END\n\n RETURN @BadString\nEND\n UPDATE TableToUpdate\nSET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate)\nWHERE whatever\n" }, { "answer_id": 28970617, "author": "BrandonNeiger", "author_id": 4655121, "author_profile": "https://Stackoverflow.com/users/4655121", "pm_score": 0, "selected": false, "text": "--CleanType 1 - Remove all non alpanumeric\n-- 2 - Remove only alpha\n-- 3 - Remove only numeric\nCREATE FUNCTION [dbo].[fnCleanString] (\n @InputString varchar(8000)\n , @CleanType int \n , @LeaveSpaces bit \n) RETURNS varchar(8000)\nAS \nBEGIN\n\n -- // Declare variables\n -- ===========================================================\n DECLARE @Length int\n , @CurLength int = 1\n , @ReturnString varchar(8000)=''\n\n SELECT @Length = len(@InputString)\n\n -- // Begin looping through each char checking ASCII value\n -- ===========================================================\n WHILE (@CurLength <= (@Length+1))\n BEGIN\n IF (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 48 and 57 AND @CleanType in (1,3) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 65 and 90 AND @CleanType in (1,2) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) between 97 and 122 AND @CleanType in (1,2) )\n or (ASCII(SUBSTRING(@InputString,@CurLength,1)) = 32 AND @LeaveSpaces = 1 )\n BEGIN\n SET @ReturnString = @ReturnString + SUBSTRING(@InputString,@CurLength,1)\n END\n SET @CurLength = @CurLength + 1\n END\n\n RETURN @ReturnString\nEND\n" }, { "answer_id": 35891879, "author": "Tobi Adeyemi", "author_id": 6039441, "author_profile": "https://Stackoverflow.com/users/6039441", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION [dbo].[Mobile_NoAlpha](@Mobile VARCHAR(1000)) \nRETURNS VARCHAR(1000) \nAS \nBEGIN\n DECLARE @StartsWithPlus BIT = 0\n\n --check if the mobile starts with a plus(+)\n IF LEFT(@Mobile, 1) = '+'\n BEGIN\n SET @StartsWithPlus = 1\n\n --Take out the plus before using the regex to eliminate invalid characters\n SET @Mobile = RIGHT(@Mobile, LEN(@Mobile)-1) \n END\n\n WHILE PatIndex('%[^0-9]%', @Mobile) > 0 \n SET @Mobile = Stuff(@Mobile, PatIndex('%[^0-9]%', @Mobile), 1, '') \n\n IF @StartsWithPlus = 1\n SET @Mobile = '+' + @Mobile\n RETURN @Mobile \nEND\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5202/" ]
52,321
<p>Using the obsolete System.Web.Mail sending email works fine, here's the code snippet:</p> <pre><code> Public Shared Sub send(ByVal recipent As String, ByVal from As String, ByVal subject As String, ByVal body As String) Try Dim Message As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage Message.To = recipent Message.From = from Message.Subject = subject Message.Body = body Message.BodyFormat = MailFormat.Html Try SmtpMail.SmtpServer = MAIL_SERVER SmtpMail.Send(Message) Catch ehttp As System.Web.HttpException critical_error("Email sending failed, reason: " + ehttp.ToString) End Try Catch e As System.Exception critical_error(e, "send() in Util_Email") End Try End Sub </code></pre> <p>and here's the updated version:</p> <pre><code>Dim mailMessage As New System.Net.Mail.MailMessage() mailMessage.From = New System.Net.Mail.MailAddress(from) mailMessage.To.Add(New System.Net.Mail.MailAddress(recipent)) mailMessage.Subject = subject mailMessage.Body = body mailMessage.IsBodyHtml = True mailMessage.Priority = System.Net.Mail.MailPriority.Normal Try Dim smtp As New Net.Mail.SmtpClient(MAIL_SERVER) smtp.Send(mailMessage) Catch ex As Exception MsgBox(ex.ToString) End Try </code></pre> <p>I have tried many different variations and nothing seems to work, I have a feeling it may have to do with the SmtpClient, is there something that changed in the underlying code between these versions?</p> <p>There are no exceptions that are thrown back.</p>
[ { "answer_id": 52361, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 0, "selected": false, "text": "smtp.UseDefaultCredentials = True \n mailMessage.From = New System.Net.Mail.MailAddress(from)\nmailMessage.To.Add(New System.Net.Mail.MailAddress(recipent))\n mailMessage.From = New System.Net.Mail.MailAddress(from,recipent)\n" }, { "answer_id": 52371, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "smtp.Credentials = New Net.NetworkCredential(\"[email protected]\", \"password\")\n" }, { "answer_id": 52374, "author": "pete blair", "author_id": 5119, "author_profile": "https://Stackoverflow.com/users/5119", "pm_score": 1, "selected": false, "text": " <system.net>\n <mailSettings>\n <smtp from=\"[email protected]\">\n <network host=\"smtpserver1\" port=\"25\" userName=\"username\" password=\"secret\" defaultCredentials=\"true\" />\n </smtp>\n </mailSettings>\n </system.net>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4827/" ]
52,344
<p>I'm thinking this might be a quick and easy way to lower the form spam on our site just a little bit. The idea being that (I have read) spammers aren't running with javascript enabled. (Or at least they are accessing your website without running javascript. I.e., they aren't browsing up to it in IE or FF.</p> <p>I can use .asp or .aspx.</p>
[ { "answer_id": 52372, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "noscript noscript" }, { "answer_id": 52379, "author": "chrisofspades", "author_id": 2614, "author_profile": "https://Stackoverflow.com/users/2614", "pm_score": 1, "selected": false, "text": "Request.Browser.JavaScript window.location Request.Querystring" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
52,353
<p>I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause <code>OutOfMemoryError</code>s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a <code>VM</code>?</p> <p>Right now, I have code that says read up to <strong>32,000 rows</strong>, but I'd also like to have code that says read as many rows as possible until I've used <strong>32MB</strong> of memory. Maybe that is a different question, but I'd still like to know. </p>
[ { "answer_id": 52362, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": -1, "selected": false, "text": "Serializable myObject;\nObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (\"obj.ser\"));\noos.write (myObject);\noos.close ();\n" }, { "answer_id": 52391, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": false, "text": "// Get current size of heap in bytes\nlong heapSize = Runtime.getRuntime().totalMemory();\n\n// Get maximum size of heap in bytes. The heap cannot grow beyond this size.\n// Any attempt will result in an OutOfMemoryException.\nlong heapMaxSize = Runtime.getRuntime().maxMemory();\n\n// Get amount of free memory within the heap in bytes. This size will increase\n// after garbage collection and decrease as new objects are created.\nlong heapFreeSize = Runtime.getRuntime().freeMemory();\n" }, { "answer_id": 52393, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "byte HashMap" }, { "answer_id": 52395, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "Runtime.freeMemory()" }, { "answer_id": 52401, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 6, "selected": false, "text": " Serializable ser;\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(ser);\n oos.close();\n return baos.size();\n" }, { "answer_id": 52682, "author": "Stefan Karlsson", "author_id": 5438, "author_profile": "https://Stackoverflow.com/users/5438", "pm_score": 10, "selected": true, "text": "java.lang.instrument import java.lang.instrument.Instrumentation;\n\npublic class ObjectSizeFetcher {\n private static Instrumentation instrumentation;\n\n public static void premain(String args, Instrumentation inst) {\n instrumentation = inst;\n }\n\n public static long getObjectSize(Object o) {\n return instrumentation.getObjectSize(o);\n }\n}\n MANIFEST.MF Premain-Class: ObjectSizeFetcher\n getObjectSize() public class C {\n private int x;\n private int y;\n\n public static void main(String [] args) {\n System.out.println(ObjectSizeFetcher.getObjectSize(new C()));\n }\n}\n java -javaagent:ObjectSizeFetcherAgent.jar C\n" }, { "answer_id": 10587479, "author": "Miguel Gamboa", "author_id": 1140754, "author_profile": "https://Stackoverflow.com/users/1140754", "pm_score": 3, "selected": false, "text": "java.lang.instrument.Instrumentation premain Unsafe sun.misc UtilUnsafe sun.misc.Unsafe private static final int NR_BITS = Integer.valueOf(System.getProperty(\"sun.arch.data.model\"));\nprivate static final int BYTE = 8;\nprivate static final int WORD = NR_BITS/BYTE;\nprivate static final int MIN_SIZE = 16; \n\npublic static int sizeOf(Class src){\n //\n // Get the instance fields of src class\n // \n List<Field> instanceFields = new LinkedList<Field>();\n do{\n if(src == Object.class) return MIN_SIZE;\n for (Field f : src.getDeclaredFields()) {\n if((f.getModifiers() & Modifier.STATIC) == 0){\n instanceFields.add(f);\n }\n }\n src = src.getSuperclass();\n }while(instanceFields.isEmpty());\n //\n // Get the field with the maximum offset\n // \n long maxOffset = 0;\n for (Field f : instanceFields) {\n long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f);\n if(offset > maxOffset) maxOffset = offset; \n }\n return (((int)maxOffset/WORD) + 1)*WORD; \n}\nclass UtilUnsafe {\n public static final sun.misc.Unsafe UNSAFE;\n\n static {\n Object theUnsafe = null;\n Exception exception = null;\n try {\n Class<?> uc = Class.forName(\"sun.misc.Unsafe\");\n Field f = uc.getDeclaredField(\"theUnsafe\");\n f.setAccessible(true);\n theUnsafe = f.get(uc);\n } catch (Exception e) { exception = e; }\n UNSAFE = (sun.misc.Unsafe) theUnsafe;\n if (UNSAFE == null) throw new Error(\"Could not obtain access to sun.misc.Unsafe\", exception);\n }\n private UtilUnsafe() { }\n}\n" }, { "answer_id": 20014332, "author": "Jason C", "author_id": 616460, "author_profile": "https://Stackoverflow.com/users/616460", "pm_score": 2, "selected": false, "text": "public class Test1 {\n\n // non-static nested\n class Nested { }\n\n // static nested\n static class StaticNested { }\n\n static long getFreeMemory () {\n // waits for free memory measurement to stabilize\n long init = Runtime.getRuntime().freeMemory(), init2;\n int count = 0;\n do {\n System.out.println(\"waiting...\" + init);\n System.gc();\n try { Thread.sleep(250); } catch (Exception x) { }\n init2 = init;\n init = Runtime.getRuntime().freeMemory();\n if (init == init2) ++ count; else count = 0;\n } while (count < 5);\n System.out.println(\"ok...\" + init);\n return init;\n }\n\n Test1 () throws InterruptedException {\n\n Object[] s = new Object[10000];\n Object[] n = new Object[10000];\n Object[] t = new Object[10000];\n\n long init = getFreeMemory();\n\n //for (int j = 0; j < 10000; ++ j)\n // s[j] = new Separate();\n\n long afters = getFreeMemory();\n\n for (int j = 0; j < 10000; ++ j)\n n[j] = new Nested();\n\n long aftersn = getFreeMemory();\n\n for (int j = 0; j < 10000; ++ j)\n t[j] = new StaticNested();\n\n long aftersnt = getFreeMemory();\n\n System.out.println(\"separate: \" + -(afters - init) + \" each=\" + -(afters - init) / 10000);\n System.out.println(\"nested: \" + -(aftersn - afters) + \" each=\" + -(aftersn - afters) / 10000);\n System.out.println(\"static nested: \" + -(aftersnt - aftersn) + \" each=\" + -(aftersnt - aftersn) / 10000);\n\n }\n\n public static void main (String[] args) throws InterruptedException {\n new Test1();\n }\n\n}\n getFreeMemory() nested: 160000 each=16\nstatic nested: 160000 each=16\n" }, { "answer_id": 23511330, "author": "user835199", "author_id": 835199, "author_profile": "https://Stackoverflow.com/users/835199", "pm_score": 1, "selected": false, "text": "long heapSizeBefore = Runtime.getRuntime().totalMemory();\n\n// Code for object construction\n...\nlong heapSizeAfter = Runtime.getRuntime().totalMemory();\nlong size = heapSizeAfter - heapSizeBefore;\n" }, { "answer_id": 24423089, "author": "dlaudams", "author_id": 3777283, "author_profile": "https://Stackoverflow.com/users/3777283", "pm_score": 2, "selected": false, "text": "sun.misc.Unsafe Unsafe.addressSize() Unsafe.arrayIndexScale( Object[].class ) import java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.IdentityHashMap;\nimport java.util.Stack;\nimport sun.misc.Unsafe;\n\n/** Usage: \n * MemoryUtil.sizeOf( object )\n * MemoryUtil.deepSizeOf( object )\n * MemoryUtil.ADDRESS_MODE\n */\npublic class MemoryUtil\n{\n private MemoryUtil()\n {\n }\n\n public static enum AddressMode\n {\n /** Unknown address mode. Size calculations may be unreliable. */\n UNKNOWN,\n /** 32-bit address mode using 32-bit references. */\n MEM_32BIT,\n /** 64-bit address mode using 64-bit references. */\n MEM_64BIT,\n /** 64-bit address mode using 32-bit compressed references. */\n MEM_64BIT_COMPRESSED_OOPS\n }\n\n /** The detected runtime address mode. */\n public static final AddressMode ADDRESS_MODE;\n\n private static final Unsafe UNSAFE;\n\n private static final long ADDRESS_SIZE; // The size in bytes of a native pointer: 4 for 32 bit, 8 for 64 bit\n private static final long REFERENCE_SIZE; // The size of a Java reference: 4 for 32 bit, 4 for 64 bit compressed oops, 8 for 64 bit\n private static final long OBJECT_BASE_SIZE; // The minimum size of an Object: 8 for 32 bit, 12 for 64 bit compressed oops, 16 for 64 bit\n private static final long OBJECT_ALIGNMENT = 8;\n\n /** Use the offset of a known field to determine the minimum size of an object. */\n private static final Object HELPER_OBJECT = new Object() { byte b; };\n\n\n static\n {\n try\n {\n // Use reflection to get a reference to the 'Unsafe' object.\n Field f = Unsafe.class.getDeclaredField( \"theUnsafe\" );\n f.setAccessible( true );\n UNSAFE = (Unsafe) f.get( null );\n\n OBJECT_BASE_SIZE = UNSAFE.objectFieldOffset( HELPER_OBJECT.getClass().getDeclaredField( \"b\" ) );\n\n ADDRESS_SIZE = UNSAFE.addressSize();\n REFERENCE_SIZE = UNSAFE.arrayIndexScale( Object[].class );\n\n if( ADDRESS_SIZE == 4 )\n {\n ADDRESS_MODE = AddressMode.MEM_32BIT;\n }\n else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 8 )\n {\n ADDRESS_MODE = AddressMode.MEM_64BIT;\n }\n else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 4 )\n {\n ADDRESS_MODE = AddressMode.MEM_64BIT_COMPRESSED_OOPS;\n }\n else\n {\n ADDRESS_MODE = AddressMode.UNKNOWN;\n }\n }\n catch( Exception e )\n {\n throw new Error( e );\n }\n }\n\n\n /** Return the size of the object excluding any referenced objects. */\n public static long shallowSizeOf( final Object object )\n {\n Class<?> objectClass = object.getClass();\n if( objectClass.isArray() )\n {\n // Array size is base offset + length * element size\n long size = UNSAFE.arrayBaseOffset( objectClass )\n + UNSAFE.arrayIndexScale( objectClass ) * Array.getLength( object );\n return padSize( size );\n }\n else\n {\n // Object size is the largest field offset padded out to 8 bytes\n long size = OBJECT_BASE_SIZE;\n do\n {\n for( Field field : objectClass.getDeclaredFields() )\n {\n if( (field.getModifiers() & Modifier.STATIC) == 0 )\n {\n long offset = UNSAFE.objectFieldOffset( field );\n if( offset >= size )\n {\n size = offset + 1; // Field size is between 1 and PAD_SIZE bytes. Padding will round up to padding size.\n }\n }\n }\n objectClass = objectClass.getSuperclass();\n }\n while( objectClass != null );\n\n return padSize( size );\n }\n }\n\n\n private static final long padSize( final long size )\n {\n return (size + (OBJECT_ALIGNMENT - 1)) & ~(OBJECT_ALIGNMENT - 1);\n }\n\n\n /** Return the size of the object including any referenced objects. */\n public static long deepSizeOf( final Object object )\n {\n IdentityHashMap<Object,Object> visited = new IdentityHashMap<Object,Object>();\n Stack<Object> stack = new Stack<Object>();\n if( object != null ) stack.push( object );\n\n long size = 0;\n while( !stack.isEmpty() )\n {\n size += internalSizeOf( stack.pop(), stack, visited );\n }\n return size;\n }\n\n\n private static long internalSizeOf( final Object object, final Stack<Object> stack, final IdentityHashMap<Object,Object> visited )\n {\n // Scan for object references and add to stack\n Class<?> c = object.getClass();\n if( c.isArray() && !c.getComponentType().isPrimitive() )\n {\n // Add unseen array elements to stack\n for( int i = Array.getLength( object ) - 1; i >= 0; i-- )\n {\n Object val = Array.get( object, i );\n if( val != null && visited.put( val, val ) == null )\n {\n stack.add( val );\n }\n }\n }\n else\n {\n // Add unseen object references to the stack\n for( ; c != null; c = c.getSuperclass() )\n {\n for( Field field : c.getDeclaredFields() )\n {\n if( (field.getModifiers() & Modifier.STATIC) == 0 \n && !field.getType().isPrimitive() )\n {\n field.setAccessible( true );\n try\n {\n Object val = field.get( object );\n if( val != null && visited.put( val, val ) == null )\n {\n stack.add( val );\n }\n }\n catch( IllegalArgumentException e )\n {\n throw new RuntimeException( e );\n }\n catch( IllegalAccessException e )\n {\n throw new RuntimeException( e );\n }\n }\n }\n }\n }\n\n return shallowSizeOf( object );\n }\n}\n" }, { "answer_id": 26407668, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 1, "selected": false, "text": "int 4 import java.io.ByteArrayOutputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\npublic class ObjectSizeCalculator {\n private Object getFirstObjectReference(Object o) {\n String objectType = o.getClass().getTypeName();\n\n if (objectType.substring(objectType.length()-2).equals(\"[]\")) {\n try {\n if (objectType.equals(\"java.lang.Object[]\"))\n return ((Object[])o)[0];\n else if (objectType.equals(\"int[]\"))\n return ((int[])o)[0];\n else\n throw new RuntimeException(\"Not Implemented !\");\n } catch (IndexOutOfBoundsException e) {\n return null;\n }\n }\n\n return o;\n } \n\n public int getObjectSizeInBytes(Object o) {\n final String STRING_JAVA_TYPE_NAME = \"java.lang.String\";\n\n if (o == null)\n return 0;\n\n String objectType = o.getClass().getTypeName();\n boolean isArray = objectType.substring(objectType.length()-2).equals(\"[]\");\n\n Object objRef = getFirstObjectReference(o);\n if (objRef != null && !(objRef instanceof Serializable))\n throw new RuntimeException(\"Object must be serializable for measuring it's memory footprint using this method !\");\n\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(o);\n oos.close();\n byte[] bytes = baos.toByteArray();\n\n for (int i = bytes.length - 1, j = 0; i != 0; i--, j++) {\n if (objectType != STRING_JAVA_TYPE_NAME) {\n if (bytes[i] == 112)\n if (isArray)\n return j - 4;\n else\n return j;\n } else {\n if (bytes[i] == 0)\n return j - 1;\n }\n }\n } catch (Exception e) {\n return -1;\n }\n\n return -1;\n } \n\n}\n" }, { "answer_id": 28825937, "author": "Kanagavelu Sugumar", "author_id": 912319, "author_profile": "https://Stackoverflow.com/users/912319", "pm_score": 1, "selected": false, "text": "Used heap memory = sizeOfObj + sizeOfRef (* 4 bytes) in collection int [] intArray = new int [1]; will require 4 bytes.\nlong [] longArray = new long [1]; will require 8 bytes.\n Object[] objectArray = new Object[1]; will require 4 bytes. The object can be any user defined Object.\nLong [] longArray = new Long [1]; will require 4 bytes.\n ReferenceMemoryTest class ReferenceMemoryTest {\n public String refStr;\n public Object refObj;\n public Double refDoub; \n}\n" }, { "answer_id": 28900509, "author": "rich", "author_id": 180416, "author_profile": "https://Stackoverflow.com/users/180416", "pm_score": 5, "selected": false, "text": "new MemoryMeter().measureDeep(myHashMap);\n" }, { "answer_id": 29431949, "author": "reallynice", "author_id": 1504300, "author_profile": "https://Stackoverflow.com/users/1504300", "pm_score": 2, "selected": false, "text": "System.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n\ndo your job here\n\nSystem.gc();\nRuntime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n" }, { "answer_id": 30021105, "author": "Jeffrey Bosboom", "author_id": 3614835, "author_profile": "https://Stackoverflow.com/users/3614835", "pm_score": 7, "selected": false, "text": "VMSupport.vmDetails() Running 64-bit HotSpot VM.\nUsing compressed oop with 0-bit shift.\nUsing compressed klass with 3-bit shift.\nObjects are 8 bytes aligned.\nField sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\nArray element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\n ClassLayout.parseClass(Foo.class).toPrintable() toPrintable java.util.regex.Pattern java.util.regex.Pattern object internals:\n OFFSET SIZE TYPE DESCRIPTION VALUE\n 0 4 (object header) 01 00 00 00 (0000 0001 0000 0000 0000 0000 0000 0000)\n 4 4 (object header) 00 00 00 00 (0000 0000 0000 0000 0000 0000 0000 0000)\n 8 4 (object header) cb cf 00 20 (1100 1011 1100 1111 0000 0000 0010 0000)\n 12 4 int Pattern.flags 0\n 16 4 int Pattern.capturingGroupCount 1\n 20 4 int Pattern.localCount 0\n 24 4 int Pattern.cursor 48\n 28 4 int Pattern.patternLength 0\n 32 1 boolean Pattern.compiled true\n 33 1 boolean Pattern.hasSupplementary false\n 34 2 (alignment/padding gap) N/A\n 36 4 String Pattern.pattern (object)\n 40 4 String Pattern.normalizedPattern (object)\n 44 4 Node Pattern.root (object)\n 48 4 Node Pattern.matchRoot (object)\n 52 4 int[] Pattern.buffer null\n 56 4 Map Pattern.namedGroups null\n 60 4 GroupHead[] Pattern.groupNodes null\n 64 4 int[] Pattern.temp null\n 68 4 (loss due to the next object alignment)\nInstance size: 72 bytes (reported by Instrumentation API)\nSpace losses: 2 bytes internal + 4 bytes external = 6 bytes total\n GraphLayout.parseInstance(obj).toFootprint() Pattern.compile(\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$\") java.util.regex.Pattern instance footprint:\n COUNT AVG SUM DESCRIPTION\n 1 112 112 [C\n 3 272 816 [Z\n 1 24 24 java.lang.String\n 1 72 72 java.util.regex.Pattern\n 9 24 216 java.util.regex.Pattern$1\n 13 24 312 java.util.regex.Pattern$5\n 1 16 16 java.util.regex.Pattern$Begin\n 3 24 72 java.util.regex.Pattern$BitClass\n 3 32 96 java.util.regex.Pattern$Curly\n 1 24 24 java.util.regex.Pattern$Dollar\n 1 16 16 java.util.regex.Pattern$LastNode\n 1 16 16 java.util.regex.Pattern$Node\n 2 24 48 java.util.regex.Pattern$Single\n 40 1840 (total)\n GraphLayout.parseInstance(obj).toPrintable() java.util.regex.Pattern object externals:\n ADDRESS SIZE TYPE PATH VALUE\n d5e5f290 16 java.util.regex.Pattern$Node .root.next.atom.next (object)\n d5e5f2a0 120 (something else) (somewhere else) (something else)\n d5e5f318 16 java.util.regex.Pattern$LastNode .root.next.next.next.next.next.next.next (object)\n d5e5f328 21664 (something else) (somewhere else) (something else)\n d5e647c8 24 java.lang.String .pattern (object)\n d5e647e0 112 [C .pattern.value [^, [, a, -, z, A, -, Z, 0, -, 9, _, ., +, -, ], +, @, [, a, -, z, A, -, Z, 0, -, 9, -, ], +, \\, ., [, a, -, z, A, -, Z, 0, -, 9, -, ., ], +, $]\n d5e64850 448 (something else) (somewhere else) (something else)\n d5e64a10 72 java.util.regex.Pattern (object)\n d5e64a58 416 (something else) (somewhere else) (something else)\n d5e64bf8 16 java.util.regex.Pattern$Begin .root (object)\n d5e64c08 24 java.util.regex.Pattern$BitClass .root.next.atom.val$rhs (object)\n d5e64c20 272 [Z .root.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e64d30 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64d48 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e64d60 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64d78 24 java.util.regex.Pattern$1 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e64d90 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e64da8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e64dc0 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs.val$lhs (object)\n d5e64dd8 24 java.util.regex.Pattern$5 .root.next.atom.val$lhs (object)\n d5e64df0 24 java.util.regex.Pattern$5 .root.next.atom (object)\n d5e64e08 32 java.util.regex.Pattern$Curly .root.next (object)\n d5e64e28 24 java.util.regex.Pattern$Single .root.next.next (object)\n d5e64e40 24 java.util.regex.Pattern$BitClass .root.next.next.next.atom.val$rhs (object)\n d5e64e58 272 [Z .root.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e64f68 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e64f80 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n d5e64f98 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs.val$lhs (object)\n d5e64fb0 24 java.util.regex.Pattern$1 .root.next.next.next.atom.val$lhs.val$rhs (object)\n d5e64fc8 24 java.util.regex.Pattern$5 .root.next.next.next.atom.val$lhs (object)\n d5e64fe0 24 java.util.regex.Pattern$5 .root.next.next.next.atom (object)\n d5e64ff8 32 java.util.regex.Pattern$Curly .root.next.next.next (object)\n d5e65018 24 java.util.regex.Pattern$Single .root.next.next.next.next (object)\n d5e65030 24 java.util.regex.Pattern$BitClass .root.next.next.next.next.next.atom.val$rhs (object)\n d5e65048 272 [Z .root.next.next.next.next.next.atom.val$rhs.bits [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]\n d5e65158 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$lhs (object)\n d5e65170 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs.val$rhs (object)\n d5e65188 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$lhs (object)\n d5e651a0 24 java.util.regex.Pattern$1 .root.next.next.next.next.next.atom.val$lhs.val$lhs.val$rhs (object)\n d5e651b8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs.val$lhs (object)\n d5e651d0 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom.val$lhs (object)\n d5e651e8 24 java.util.regex.Pattern$5 .root.next.next.next.next.next.atom (object)\n d5e65200 32 java.util.regex.Pattern$Curly .root.next.next.next.next.next (object)\n d5e65220 120 (something else) (somewhere else) (something else)\n d5e65298 24 java.util.regex.Pattern$Dollar .root.next.next.next.next.next.next (object)\n" }, { "answer_id": 39406536, "author": "Tom", "author_id": 1762932, "author_profile": "https://Stackoverflow.com/users/1762932", "pm_score": 7, "selected": false, "text": "System.out.println(ObjectSizeCalculator.getObjectSize(new gnu.trove.map.hash.TObjectIntHashMap<String>(12000, 0.6f, -1)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new HashMap<String, Integer>(100000)));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(3));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 }));\nSystem.out.println(ObjectSizeCalculator.getObjectSize(new int[100]));\n 164192\n48\n16\n48\n416\n" }, { "answer_id": 47848790, "author": "Sai Kiran", "author_id": 7706962, "author_profile": "https://Stackoverflow.com/users/7706962", "pm_score": -1, "selected": false, "text": "`JSONObject.toString().getBytes(\"UTF-8\").length`\n" }, { "answer_id": 49449106, "author": "ACV", "author_id": 912829, "author_profile": "https://Stackoverflow.com/users/912829", "pm_score": 2, "selected": false, "text": "sizeof(o)" }, { "answer_id": 55404104, "author": "Ali Dehghani", "author_id": 1393484, "author_profile": "https://Stackoverflow.com/users/1393484", "pm_score": 0, "selected": false, "text": "Complex public class Complex {\n\n private final long real;\n private final long imaginary;\n\n // omitted\n}\n\n $ jmap -histo:live <pid> | grep Complex\n\n num #instances #bytes class name (module)\n-------------------------------------------------------\n 327: 1 32 Complex\n" }, { "answer_id": 56783991, "author": "David Ryan", "author_id": 5307079, "author_profile": "https://Stackoverflow.com/users/5307079", "pm_score": 2, "selected": false, "text": "public class JavaSize {\n\n private static final int NR_BITS = Integer.valueOf(System.getProperty(\"sun.arch.data.model\"));\n private static final int BYTE = 8;\n private static final int WORD = NR_BITS / BYTE;\n private static final int HEADER_SIZE = 8;\n\n public static int sizeOf(Class<?> clazz) {\n int result = 0;\n\n while (clazz != null) {\n Field[] fields = clazz.getDeclaredFields();\n for (int i = 0; i < fields.length; i++) {\n if (!Modifier.isStatic(fields[i].getModifiers())) {\n if (fields[i].getType().isPrimitive()) {\n Class<?> primitiveClass = fields[i].getType();\n if (primitiveClass == boolean.class || primitiveClass == byte.class) {\n result += 1;\n } else if (primitiveClass == short.class) {\n result += 2;\n } else if (primitiveClass == int.class || primitiveClass == float.class) {\n result += 4;\n } else if (primitiveClass == double.class || primitiveClass == long.class) {\n result += 8;\n }\n\n } else {\n // assume compressed references.\n result += 4;\n }\n }\n }\n\n clazz = clazz.getSuperclass();\n\n // round up to the nearest WORD length.\n if ((result % WORD) != 0) {\n result += WORD - (result % WORD);\n }\n }\n\n result += HEADER_SIZE;\n\n return result;\n }\n }\n" }, { "answer_id": 71230694, "author": "Maurice", "author_id": 6351733, "author_profile": "https://Stackoverflow.com/users/6351733", "pm_score": 0, "selected": false, "text": "SerializationUtils byte[] data = SerializationUtils.serialize(user);\nSystem.out.println(\"Approximate object size in bytes \" + data.length);\n" }, { "answer_id": 71683336, "author": "granadaCoder", "author_id": 214977, "author_profile": "https://Stackoverflow.com/users/214977", "pm_score": 2, "selected": false, "text": "//import org.ehcache.sizeof.SizeOf;\n\nSizeOf sizeOf = SizeOf.newInstance(); // (1)\nlong shallowSize = sizeOf.sizeOf(someObject); // (2)\nlong deepSize = sizeOf.deepSizeOf(someObject); // (3)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5074/" ]
52,356
<p>I'm still fairly new to T-SQL and SQL 2005. I need to import a column of integers from a table in database1 to a identical table (only missing the column I need) in database2. Both are sql 2005 databases. I've tried the built in import command in Server Management Studio but it's forcing me to copy the entire table. This causes errors due to constraints and 'read-only' columns (whatever 'read-only' means in sql2005). I just want to grab a single column and copy it to a table.</p> <p>There must be a simple way of doing this. Something like:</p> <pre><code>INSERT INTO database1.myTable columnINeed SELECT columnINeed from database2.myTable </code></pre>
[ { "answer_id": 52376, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 2, "selected": false, "text": "INSERT INTO Datbase1..MyTable\n (ColumnList)\nSELECT FieldsIWant\n FROM Database2..MyTable\n" }, { "answer_id": 52405, "author": "Carl", "author_id": 5449, "author_profile": "https://Stackoverflow.com/users/5449", "pm_score": 1, "selected": false, "text": "DECLARE @FirstField nvarchar(100)\n\nDECLARE ACursor CURSOR FOR\nSELECT FirstField FROM FirstTable \n\nOPEN ACursor\nFETCH NEXT FROM ACursor INTO @FirstField\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\n INSERT INTO SecondTable ( SecondField ) VALUES ( @FirstField )\n\n FETCH NEXT FROM ACursor INTO @FirstField\n\nEND\n\nCLOSE ACursor \nDEALLOCATE ACursor\n" }, { "answer_id": 52421, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "ALTER TABLE database2..targetTable\nADD targetColumn int null -- or whatever column definition is needed\n MERGE database2..targetTable AS t\nUSING (SELECT sourceColumn FROM sourceDatabase1..sourceTable) as s\nON t.PrimaryKeyCol = s.PrimaryKeyCol -- or whatever the match should be bassed on\nWHEN MATCHED THEN \n UPDATE SET t.targetColumn = s.sourceColumn\nWHEN NOT MATCHED THEN\n INSERT (targetColumn, [other columns ...]) VALUES (s.sourceColumn, [other values ..])\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433/" ]
52,357
<p>I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.</p> <p>I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".</p> <ul> <li>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</li> <li>Is the only difference between clog and cerr the buffering?</li> <li>How should I implement (or find) a more robust logging facility (links please)?</li> </ul>
[ { "answer_id": 52365, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "rdbuf ofstream ofs(\"logfile\");\ncout.rdbuf(ofs.rdbuf());\ncout << \"Goes to file.\" << endl;\n" }, { "answer_id": 52381, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 4, "selected": false, "text": "$ myprogram 2>&5 \n" }, { "answer_id": 4476129, "author": "unixman83", "author_id": 504239, "author_profile": "https://Stackoverflow.com/users/504239", "pm_score": 1, "selected": false, "text": "#define myerr(e) {CriticalSectionLocker crit; std::cerr << e << std::endl;}\n myerr(\"ERR: \" << message); myerr(\"WARN: \" << message << code << etc); ./programname.exe 2> ./stderr.log\nperl parsestderr.pl stderr.log\n" }, { "answer_id": 56308274, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#include <fstream>\n#include <iostream>\n\nclass redirecter\n{\npublic:\n redirecter(std::ostream & dst, std::ostream & src)\n : src(src), sbuf(src.rdbuf(dst.rdbuf())) {}\n ~redirecter() { src.rdbuf(sbuf); }\nprivate:\n std::ostream & src;\n std::streambuf * const sbuf;\n};\n\nvoid hello_world()\n{\n std::cout << \"Hello, world!\\n\";\n}\n\nint main()\n{\n std::ofstream log(\"hello-world.log\");\n redirecter redirect(log, std::cout);\n hello_world();\n return 0;\n}\n" }, { "answer_id": 57314550, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "std::clog std::wclog 2>output.log 3>output.log fd stdout stderr CDebug stderr stdout stderr /dev/console tty /dev/null command ...args... 2>/dev/null\n syslog() mail.log syslog() syslog(LOG_ERR, \"message #%d\", count++);\n printf() openlog() syslog() // (not tested... requires msg to be a string literal)\n#define LOG(lvl, msg, ...) \\\n syslog(lvl, msg \" (in \" __FILE__ \":%d)\", __VA_ARGS__, __LINE__)\n __func__ mail.err /var/log/mail/mail.err\nmail.* /var/log/mail/mail.log\n& stop\n /etc/rsyslog.d/ invoke-rc.d rsyslog restart\n syslog /var/log/mail fork(); fork(); .properties bin/build-snap syslog() [all]\ntype=file\nlock=true\nfilename=/var/log/snapwebsites/all.log\n\n[file]\nlock=false\nfilename=/var/log/snapwebsites/firewall.log\n all.log [file] SNAP_LOG_ERROR() snaplogger ${date} ${date:year} snaplogger normal secure normal secure" }, { "answer_id": 62689338, "author": "Apteryx", "author_id": 7420896, "author_profile": "https://Stackoverflow.com/users/7420896", "pm_score": 2, "selected": false, "text": "class redirecter\n{\npublic:\n redirecter(std::ostream & src, std::ostream & dst)\n : src_(src), sbuf(src.rdbuf(dst.rdbuf())) {}\n ~redirecter() { src.rdbuf(sbuf); }\nprivate:\n std::ostream & src_;\n std::streambuf * const sbuf_;\n // Prevent copying. \n redirecter( const redirecter& );\n redirecter& operator=( const redirecter& );\n};\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4662/" ]
52,359
<p>I'm trying to reduce the form spam on our website. (It's actually pretty recent).</p> <p>I seem to remember reading somewhere that the spammers aren't executing the Javascript on the site.</p> <p>Is that true? And if so, then could you simply check for javascript being disabled and then figure it's <em>likely</em> that it's spam?</p>
[ { "answer_id": 52382, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "<noscript>" }, { "answer_id": 52392, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 4, "selected": true, "text": "display: none;" }, { "answer_id": 171854, "author": "James", "author_id": 25251, "author_profile": "https://Stackoverflow.com/users/25251", "pm_score": 2, "selected": false, "text": "<noscript><p><label for=\"websiteurl99f\">Please type \"e73053\": </label><input type=\"text\" name=\"websiteurl99f\" id=\"websiteurl99f\" /></p></noscript>\n <script type=\"text/javascript\">/* <![CDATA[ */ document.write('<div><input type=\"hidden\" name=\"websiteurl99f\" value=\"e' + '73053\" \\/><\\/div>'); /* ]]> */</script>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
52,360
<p>What are the different ways (programmatically and otherwise) to determine what versions of .NET are running on a system?</p>
[ { "answer_id": 52422, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "System.Environment.Version\n" }, { "answer_id": 3161437, "author": "cognitiaclaeves", "author_id": 305442, "author_profile": "https://Stackoverflow.com/users/305442", "pm_score": 2, "selected": false, "text": "javascript:alert(navigator.userAgent)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141/" ]
52,398
<p>So I have some files I want to ignore in a subversion repository, but I don't want my ignore patterns for this to be propagated to the repository.</p> <p>In other words, I added some private files in my checkout that I want to keep, but they only exist for me and wouldn't make sense to be ignored for everyone, so if I use the svn:ignore, this will apply on the directory, and I either have to check that in (which I don't want to do), or see that this directory was modified every time I do an svn status.</p> <p>So, ideally I would like something like a .svnignore file which I could then mark to ignore itself as well as some other files (I think this is a possibility in git for example, using a .gitignore file, or whatever the name is).</p> <p>I'm guessing it might work to ignore the whole directory (maybe), but then I suspect I won't see any new files in that directory, which would also not be desirable.</p> <p>So does anybody know a way to do this in subversion?</p>
[ { "answer_id": 52574, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ".subversion Miscellany" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
52,400
<p>I'm sure this has already been asked and answered so I apologize in advance for that but I'm not figuring out the correct keywords to search for. Searching for "Pattern" hits way too many Q &amp; A's to be useful.</p> <p>I'm working on a regression testing app. I'm displaying a form on the screen and according to which user is logged in to the app some of the fields should be read-only. So I can abstract a field object and I can abstract a user object but what pattern should I be looking at to describe the intersection of these two concepts? In other words how should I describe that for Field 1 and User A, the field should be read-only? It seems like read-only (or not) should be a property of the Field class but as I said, it depends on which user is looking at the form. I've considered a simple two-dimensional array (e. g. ReadOnly[Field,User] = True) but I want to make sure I've picked the most effective structure to represent this. </p> <p>Are there any software design patterns regarding this kind of data structure? Am I overcomplicating things--would a two-dimensional array be the best way to go here? As I said if this has been asked and answered, I do apologize. I did search here and didn't find anything and a Google search failed to turn up anything either. </p>
[ { "answer_id": 52481, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 3, "selected": true, "text": "Field1ReadonlyRules = {\n 'user class 1' : True,\n 'user class 2' : False\n}\n\nfield1.readOnly = Field1ReadonlyRules[ someUser.userClass ]\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
52,430
<p>I've got the following rough structure:</p> <pre><code>Object -&gt; Object Revisions -&gt; Data </code></pre> <p>The Data can be shared between several Objects.</p> <p>What I'm trying to do is clean out old Object Revisions. I want to keep the first, active, and a spread of revisions so that the last change for a time period is kept. The Data might be changed a lot over the course of 2 days then left alone for months, so I want to keep the last revision before the changes started and the end change of the new set.</p> <p>I'm currently using a cursor and temp table to hold the IDs and date between changes so I can select out the low hanging fruit to get rid of. This means using @LastID, @LastDate, updates and inserts to the temp table, etc... </p> <p>Is there an easier/better way to calculate the date difference between the current row and the next row in my initial result set without using a cursor and temp table? </p> <p>I'm on sql server 2000, but would be interested in any new features of 2005, 2008 that could help with this as well.</p>
[ { "answer_id": 52455, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 2, "selected": false, "text": "SELECT DATEDIFF(HOUR, prev.ActivityDate, curr.ActivityDate)\n FROM MyTable curr\n JOIN MyTable prev\n ON prev.ObjectID = curr.ObjectID\n WHERE prev.ActivityDate =\n (SELECT MAX(maxtbl.ActivityDate)\n FROM MyTable maxtbl\n WHERE maxtbl.ObjectID = curr.ObjectID\n AND maxtbl.ActivityDate < curr.ActivityDate)\n" }, { "answer_id": 52706, "author": "ddowns", "author_id": 5201, "author_profile": "https://Stackoverflow.com/users/5201", "pm_score": 0, "selected": false, "text": "DECLARE @IDs TABLE \n(\n ID int , \n DateBetween int\n)\n\nDECLARE @OID int\nSET @OID = 6150\n\n-- Grab the revisions, calc the datediff, and insert into temp table var.\n\nINSERT @IDs\nSELECT ID, \n DATEDIFF(dd, \n (SELECT MAX(ActiveDate) \n FROM ObjectRevisionHistory \n WHERE ObjectID=@OID AND \n ActiveDate < ORH.ActiveDate), ActiveDate) \nFROM ObjectRevisionHistory ORH \nWHERE ObjectID=@OID\n\n\n-- Hard set DateBetween for special case revisions to always keep\n\n UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MIN(ID) FROM @IDs)\n\n UPDATE @IDs SET DateBetween = 1000 WHERE ID=(SELECT MAX(ID) FROM @IDs)\n\n UPDATE @IDs SET DateBetween = 1000 \n WHERE ID=(SELECT ID \n FROM ObjectRevisionHistory \n WHERE ObjectID=@OID AND Active=1)\n\n\n-- Select out IDs for however I need them\n\n SELECT * FROM @IDs\n SELECT * FROM @IDs WHERE DateBetween < 2\n SELECT * FROM @IDs WHERE DateBetween > 2\n" }, { "answer_id": 21113658, "author": "cs981khx", "author_id": 3193950, "author_profile": "https://Stackoverflow.com/users/3193950", "pm_score": 2, "selected": true, "text": "SELECT curr.*, DATEDIFF(MINUTE, prev.EventDateTime,curr.EventDateTime) Duration FROM DWLog curr join DWLog prev on prev.EventID = curr.EventID - 1" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5201/" ]
52,438
<p>I've been doing c# for a long time, and have never come across an easy way to just new up a hash.</p> <p>I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.</p> <pre><code>{ "whatever" =&gt; {i =&gt; 1}; "and then something else" =&gt; {j =&gt; 2}}; </code></pre>
[ { "answer_id": 52443, "author": "Wheelie", "author_id": 1131, "author_profile": "https://Stackoverflow.com/users/1131", "pm_score": 6, "selected": true, "text": "var students = new Dictionary<int, StudentName>()\n{\n { 111, new StudentName {FirstName=\"Sachin\", LastName=\"Karnik\", ID=211}},\n { 112, new StudentName {FirstName=\"Dina\", LastName=\"Salimzianova\", ID=317, }},\n { 113, new StudentName {FirstName=\"Andy\", LastName=\"Ruth\", ID=198, }}\n};\n" }, { "answer_id": 52503, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 3, "selected": false, "text": "public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data)\n{\n Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2));\n if (data == null || data.Length == 0) return dict;\n\n KeyType key = default(KeyType);\n ValueType value = default(ValueType);\n\n for (int i = 0; i < data.Length; i++)\n {\n if (i % 2 == 0)\n key = (KeyType) data[i];\n else\n {\n value = (ValueType) data[i];\n dict.Add(key, value);\n }\n }\n\n return dict;\n}\n IDictionary<string,object> myDictionary = Dict<string,object>(\n \"foo\", 50,\n \"bar\", 100\n);\n" }, { "answer_id": 1863840, "author": "Quadriceps Hexa", "author_id": 226777, "author_profile": "https://Stackoverflow.com/users/226777", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Dictionary\n{\n class Program\n {\n static void Main(string[] args)\n {\n Program p = new Program(); \n Dictionary<object, object > d = p.Dic<object, object>(\"Age\",32,\"Height\",177,\"wrest\",36);//(un)comment\n //Dictionary<object, object> d = p.Dic<object, object>();//(un)comment\n\n foreach(object o in d)\n {\n Console.WriteLine(\" {0}\",o.ToString());\n }\n Console.ReadLine(); \n }\n\n public Dictionary<K, V> Dic<K, V>(params object[] data)\n { \n //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null;\n if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary<K,V>(1){{ (K)new Object(), (V)new object()}};\n\n Dictionary<K, V> dc = new Dictionary<K, V>(data.Length / 2);\n int i = 0;\n while (i < data.Length)\n {\n dc.Add((K)data[i], (V)data[++i]);\n i++; \n }\n return dc; \n }\n }\n}\n" }, { "answer_id": 45072305, "author": "Matthew Lock", "author_id": 74585, "author_profile": "https://Stackoverflow.com/users/74585", "pm_score": 1, "selected": false, "text": "var ht = new Hashtable {\n { \"whatever\", new Hashtable {\n {\"i\", 1} \n } },\n { \"and then something else\", new Hashtable { \n {\"j\", 2}\n } }\n};\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
52,449
<p>Can I return it as an object if I am doing a </p> <pre><code>Select OneItem from Table Where OtherItem = "blah"? </code></pre> <p>Is there a better way to do this?</p> <p>I am building a constructor to return an object based on its name rather than its ID.</p>
[ { "answer_id": 52470, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "query.UniqueResult<T>()" }, { "answer_id": 214317, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "query.FirstResult()" }, { "answer_id": 243283, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 0, "selected": false, "text": "query.First() query.SingleOrDefault() query.Min(predicate)" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
52,485
<p>I have a Question class:</p> <pre><code>class Question { public int QuestionNumber { get; set; } public string Question { get; set; } public string Answer { get; set; } } </code></pre> <p>Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use <strong>&lt;%#Eval("Question")%></strong> to display the Question, and I use a TextBox and <strong>&lt;%#Bind("Answer")%></strong> to accept an answer.</p> <p>If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer.</p> <p>So far it works great.</p> <p>Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist.</p> <p>Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing.</p> <p>I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects.</p> <p>Surely there's an easy way to achieve all of this with little or no codebehind?</p> <p>It seems like all the bits are there, but there's some glue missing to stick them all together.</p> <p>Help!</p> <p>Anthony</p>
[ { "answer_id": 52513, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": true, "text": "foreach(RepeaterItem item in rptQuestions.Items)\n{\n //pull out question\n var question = (Question)item.DataItem;\n question.Answer = ((TextBox)item.FindControl(\"txtAnswer\")).Text;\n\n question.Save() ? <--- not sure what you want to do with it\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
52,492
<p>I just started using GNU Emacs as my text editor and I am concerned about getting afflicted with "<a href="http://en.wikipedia.org/wiki/Emacs#Emacs_pinky" rel="nofollow noreferrer">Emacs Pinky</a>" by having to constantly press the control key with my pinky finger as is required when using Emacs. How can I avoid potentially getting this type of repetitive strain injury?</p>
[ { "answer_id": 52564, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": false, "text": "[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout] \"Scancode Map\"=hex:00,00,00,00,00,00,00,00,03,00,00,00,3a,00,1d,00,1d,00,3a,00,00,00,00,00\n" }, { "answer_id": 53972, "author": "gerikson", "author_id": 3988, "author_profile": "https://Stackoverflow.com/users/3988", "pm_score": 1, "selected": false, "text": ".reg" }, { "answer_id": 12342971, "author": "Arne Babenhauserheide", "author_id": 7666, "author_profile": "https://Stackoverflow.com/users/7666", "pm_score": 3, "selected": false, "text": "Best wishes,\nArne\n ; buffer actions\n(key-chord-define-global \"vg\" 'eval-region)\n(key-chord-define-global \"vb\" 'eval-buffer)\n(key-chord-define-global \"cy\" 'yank-pop)\n(key-chord-define-global \"cg\" \"\\C-c\\C-c\")\n(key-chord-define-global \"äü\" 'control-lock-toggle)\n\n; frame actions\n(key-chord-define-global \"xo\" 'other-window);\n(key-chord-define-global \"x1\" 'delete-other-windows)\n(key-chord-define-global \"x0\" 'delete-window)\n(defun kill-this-buffer-if-not-modified ()\n (interactive)\n ; taken from menu-bar.el\n (if (menu-bar-non-minibuffer-window-p)\n (kill-buffer-if-not-modified (current-buffer))\n (abort-recursive-edit)))\n(key-chord-define-global \"xk\" 'kill-this-buffer-if-not-modified)\n\n; file actions\n(key-chord-define-global \"bf\" 'ido-switch-buffer)\n(key-chord-define-global \"cf\" 'ido-find-file)\n(key-chord-define-global \"zs\" \"\\C-x\\C-s\")\n(key-chord-define-global \"vc\" 'vc-next-action)\n" }, { "answer_id": 20020063, "author": "David Gruen", "author_id": 2999621, "author_profile": "https://Stackoverflow.com/users/2999621", "pm_score": 1, "selected": false, "text": "###########################\n# xbindkeys configuration #\n###########################\n# left mouse button ctrl key\n\"xdotool keydown ctrl\"\nb:1\n\"xdotool keyup ctrl\"\ncontrol + b:1 + Release\n# vi wanna be style editing\n\"xdotool keydown ctrl\"\nrelease+b:3\n\"xdotool keyup ctrl\"\nrelease+control+b:3\n# -------------------------\n" }, { "answer_id": 25173251, "author": "Sasanga Abeywickrama", "author_id": 1258508, "author_profile": "https://Stackoverflow.com/users/1258508", "pm_score": 0, "selected": false, "text": "NumpadIns::^s\nNumpadEnd::^c\nNumpadDown::^v\nNumpadPgDn::^x\nNumpadLeft::^+v\nNumpadClear::Control\nNumpadRight::^a\nNumpadHome::q\nNumpadUp::Tab\nNumpadDel::^f\nNumpadEnter::Space\n" }, { "answer_id": 30517673, "author": "Adrian Chira", "author_id": 4942300, "author_profile": "https://Stackoverflow.com/users/4942300", "pm_score": 0, "selected": false, "text": "#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.\nSendMode Input ; Recommended for new scripts due to its superior speed and reliability.\nSetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.\n\n^#e:: Gosub, start_emacs\n^#c:: Gosub, start_capture\n\n#IfWinActive emacs@ ahk_class Emacs\n\nUp::Return ; to not interfere with pressing <Down>\n\n; F21 = Alt\nRAlt::F21\n\n; F23 = Super\nRCtrl::F23\n\n#IfWinActive\n\nexit\n\nstart_emacs:\nIfWinExist emacs@ ahk_class Emacs\n WinActivate\nelse\n Run c:\\bin\\emacs\\bin\\runemacs.exe\n WinMaximize\nreturn\n\nstart_capture:\n Gosub, start_emacs\n SendInput {Ctrl down}xf{Ctrl up} {ctrl down}{shift down}{backspace}{ctrl up}{shift up}\n SendInput ~/org/capture.org {enter}\n SendInput {Alt down}x{Alt up} org-capture {enter}\nreturn\n ; prevent single key press from activating the given key\n;; http://emacs.1067599.n5.nabble.com/w32-pass-rwindow-to-system-td144902.html\n(setq w32-pass-lwindow-to-system nil\n w32-pass-rwindow-to-system nil\n w32-pass-apps-to-system nil)\n ; make sure the given key is not used as a modifier\n(setq w32-lwindow-modifier nil\n w32-rwindow-modifier nil\n w32-apps-modifier nil) ; Menu/App key\n ; misc\n(setq w32-recognize-altgr nil) ; C+M works: http://www.gnu.org/software/emacs/manual/html_node/emacs/Windows-Keyboard.html\n ; A-alt\n(define-key local-function-key-map (kbd \"<f21>\") 'event-apply-alt-modifier) ; RAlt in ahk\n ; H-hyper\n(define-key local-function-key-map (kbd \"<f22>\") 'event-apply-hyper-modifier) \n(define-key local-function-key-map (kbd \"<menu>\") 'event-apply-hyper-modifier)\n(define-key local-function-key-map (kbd \"<apps>\") 'event-apply-hyper-modifier) \n(define-key local-function-key-map (kbd \"<lwindow>\") 'event-apply-hyper-modifier)\n(define-key local-function-key-map (kbd \"<down>\") 'event-apply-hyper-modifier)\n ; s-super\n(define-key local-function-key-map (kbd \"<f23>\") 'event-apply-super-modifier) ; RCtrl in ahk\n(define-key local-function-key-map (kbd \"<right>\") 'event-apply-super-modifier) \n(define-key local-function-key-map (kbd \"<rwindow>\") 'event-apply-super-modifier)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
52,506
<p>A friend and I were discussing C++ templates. He asked me what this should do:</p> <pre><code>#include &lt;iostream&gt; template &lt;bool&gt; struct A { A(bool) { std::cout &lt;&lt; "bool\n"; } A(void*) { std::cout &lt;&lt; "void*\n"; } }; int main() { A&lt;true&gt; *d = 0; const int b = 2; const int c = 1; new A&lt; b &gt; (c) &gt; (d); } </code></pre> <p>The last line in main has two reasonable parses. Is 'b' the template argument or is <code>b &gt; (c)</code> the template argument? </p> <p>Although, it is trivial to compile this, and see what we get, we were wondering what resolves the ambiguity?</p>
[ { "answer_id": 52617, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": true, "text": "new A<b>(c) > d new A<(b > c)>(d);\n" }, { "answer_id": 52875, "author": "Lee Baldwin", "author_id": 5200, "author_profile": "https://Stackoverflow.com/users/5200", "pm_score": 2, "selected": false, "text": "< < > > static_cast<>" }, { "answer_id": 71706, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 3, "selected": false, "text": ">> >> > > template <bool>\nstruct A {\n A(bool);\n A(void*);\n};\n\ntemplate <typename T>\nclass C\n{\npublic:\n C (int);\n};\n\nint main() {\n A<true> *d = 0;\n const int b = 2;\n const int c = 1;\n new C <A< b >> (c) > (d); // #1\n new C <A< b > > (c) > (d); // #2\n}\n C<A<false>> c; // Parse error in C++ '98, '03 due to \"right shift operator\"\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4798/" ]
52,550
<p>What does the <code>,</code> operator do in C?</p>
[ { "answer_id": 52558, "author": "lillq", "author_id": 2064, "author_profile": "https://Stackoverflow.com/users/2064", "pm_score": 8, "selected": true, "text": "(expression1, expression2)\n expression1 expression2 expression2" }, { "answer_id": 52559, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": false, "text": "int f() { return 7; }\nint g() { return 8; }\n\nint x = (printf(\"assigning x\"), f(), g() );\n" }, { "answer_id": 52571, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "for (tmp=0, i = MAX; i > 0; i--)\n" }, { "answer_id": 52590, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 2, "selected": false, "text": "bool arraysAreMirrored(int a1[], int a2[], size_t size)\n{\n size_t i1, i2;\n for(i1 = 0, i2 = size - 1; i1 < size; i1++, i2--)\n {\n if(a1[i1] != a2[i2])\n {\n return false;\n }\n }\n\n return true;\n}\n while" }, { "answer_id": 52615, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 7, "selected": false, "text": "while string s;\nwhile(read_string(s), s.len() > 5)\n{\n //do something\n}\n string s;\nread_string(s);\nwhile(s.len() > 5)\n{\n //do something\n read_string(s);\n}\n" }, { "answer_id": 57573, "author": "Paul Stephenson", "author_id": 5536, "author_profile": "https://Stackoverflow.com/users/5536", "pm_score": 5, "selected": false, "text": "(expr1, expr2) { expr1; expr2; } expr2 for for (low = 0, high = MAXSIZE; low < high; low = newlow, high = newhigh)\n{\n /* do something with low and high and put new values\n in newlow and newhigh */\n}\n unsigned char outbuff[BUFFSIZE];\nunsigned char *ptr = outbuff;\n\n*ptr++ = first_byte_value;\n*ptr++ = second_byte_value;\n\nsend_buff(outbuff, (int)(ptr - outbuff));\n short int *((short *)ptr)++ = short_value;\n*((int *)ptr)++ = int_value;\n (short *)ptr *(short *)ptr = short_value;\nptr += sizeof(short);\n #define ASSIGN_INCR(p, val, type) ((*((type) *)(p) = (val)), (p) += sizeof(type))\n if (need_to_output_short)\n ASSIGN_INCR(ptr, short_value, short);\n\nlatest_pos = ASSIGN_INCR(ptr, int_value, int);\n\nsend_buff(outbuff, (int)(ASSIGN_INCR(ptr, last_value, int) - outbuff));\n for for" }, { "answer_id": 18444099, "author": "Shafik Yaghmour", "author_id": 1708801, "author_profile": "https://Stackoverflow.com/users/1708801", "pm_score": 6, "selected": false, "text": "for void rev(char *s, size_t len)\n{\n char *first;\n for ( first = s, s += len - 1; s >= first; --s)\n /*^^^^^^^^^^^^^^^^^^^^^^^*/ \n putchar(*s);\n}\n expression:\n assignment-expression\n expression , assignment-expression\n () #include <stdio.h>\n\nint main()\n{\n int x, y ;\n\n x = 1, 2 ;\n y = (3,4) ;\n\n printf( \"%d %d\\n\", x, y ) ;\n}\n 1 4\n" }, { "answer_id": 54038455, "author": "ViNi89", "author_id": 5770705, "author_profile": "https://Stackoverflow.com/users/5770705", "pm_score": -1, "selected": false, "text": "int i = (5,4,3,2,1);\nint j;\nj = 5,4,3,2,1;\nprintf(\"%d %d\\n\", i , j);\n 1 5\n i i ( is j , j 5 j = 5 int j = 5,4,3,2,1; ," } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064/" ]
52,557
<p>Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops?</p> <p>(this question is specific, not about optimization in general, thanks)</p>
[ { "answer_id": 52569, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "gperf" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277510/" ]
52,561
<p>What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?</p> <p>Thanks!</p>
[ { "answer_id": 52570, "author": "Espen Herseth Halvorsen", "author_id": 1542, "author_profile": "https://Stackoverflow.com/users/1542", "pm_score": 2, "selected": true, "text": "<!--#if expr=\"(${HTTP_USER_AGENT} = /iPhone/)\"--> \n\n<!-- \nplace iPhone code in here \n--> \n\n<!--#else --> \n\n<!-- \n place standard code to be used by non iphone browser. \n--> \n<!--#endif --> \n" }, { "answer_id": 3119990, "author": "Jimit", "author_id": 317834, "author_profile": "https://Stackoverflow.com/users/317834", "pm_score": 0, "selected": false, "text": "*\n\n (NSString *)flattenHTML:(NSString *)html {\n\n NSScanner *theScanner; NSString *text = nil;\n\n theScanner = [NSScanner scannerWithString:html];\n\n while ([theScanner isAtEnd] == NO) {\n\n // find start of tag\n [theScanner scanUpToString:@\"<\" intoString:NULL] ; \n\n\n // find end of tag\n [theScanner scanUpToString:@\">\" intoString:&text] ;\n\n\n // replace the found tag with a space\n //(you can filter multi-spaces out later if you wish)\n html = [html stringByReplacingOccurrencesOfString:\n [ NSString stringWithFormat:@\"%@>\", text]\n withString:@\" \"];\n\n } // while //\n\n return html;\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808/" ]
52,563
<p>I'm trying to let an <code>&lt;input type="text"&gt;</code> (henceforth referred to as “textbox”) fill a parent container by settings its <code>width</code> to <code>100%</code>. This works until I give the textbox a padding. This is then added to the content width and the input field overflows. Notice that in Firefox this only happens when rendering the content as standards compliant. In quirks mode, another box model seems to apply.</p> <p>Here's a minimal code to reproduce the behaviour in all modern browsers.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#x { background: salmon; padding: 1em; } #y, input { background: red; padding: 0 20px; width: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="x"&gt; &lt;div id="y"&gt;x&lt;/div&gt; &lt;input type="text"/&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>My question: <strong>How do I get the textbox to fit the container?</strong></p> <p><em>Notice</em>: for the <code>&lt;div id="y"&gt;</code>, this is straightforward: simply set <code>width: auto</code>. However, if I try to do this for the textbox, the effect is different and the textbox takes its default row count as width (even if I set <code>display: block</code> for the textbox).</p> <p>EDIT: David's solution would of course work. However, I do not want to modify the HTML – I do especially not want to add dummy elements with no semantic functionality. This is a typical case of <a href="http://en.wiktionary.org/wiki/Citations:divitis" rel="nofollow noreferrer">divitis</a> that I want to avoid at all cost. This can only be a last-resort hack.</p>
[ { "answer_id": 52575, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "margin: -1em;\n" }, { "answer_id": 52633, "author": "David Kolar", "author_id": 3283, "author_profile": "https://Stackoverflow.com/users/3283", "pm_score": 5, "selected": false, "text": "<div> <div> padding: 0 20px" }, { "answer_id": 53074, "author": "Ben", "author_id": 5005, "author_profile": "https://Stackoverflow.com/users/5005", "pm_score": 2, "selected": false, "text": "width: 100%;" }, { "answer_id": 1082765, "author": "Aseem Kishore", "author_id": 132978, "author_profile": "https://Stackoverflow.com/users/132978", "pm_score": 2, "selected": false, "text": "<div class=\"textbox\" id=\"username\">\n <div class=\"before\"></div>\n <div class=\"during\">\n <input type=\"text\" value=\"\" />\n </div>\n <div class=\"after\"></div>\n</div>\n" }, { "answer_id": 4472431, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 0, "selected": false, "text": "input {\n background: red;\n padding: 0;\n width: 100%;\n border: 0; //use 0 instead of \"none\" for ie7 \n}\n .text-box {\n padding: 0 20px;\n border: solid 1px #000000;\n}\n\n<body>\n <div id=\"x\">\n <div id=\"y\">x</div>\n <div class=\"text-box\"><input type=\"text\"/></div>\n </div>\n</body>\n" }, { "answer_id": 5405832, "author": "studioromeo", "author_id": 308886, "author_profile": "https://Stackoverflow.com/users/308886", "pm_score": 6, "selected": true, "text": "input[type=\"text\"] {\n -webkit-box-sizing: border-box; // Safari/Chrome, other WebKit\n -moz-box-sizing: border-box; // Firefox, other Gecko\n box-sizing: border-box; // Opera/IE 8+\n}\n" }, { "answer_id": 59520751, "author": "Andyba", "author_id": 1851028, "author_profile": "https://Stackoverflow.com/users/1851028", "pm_score": 2, "selected": false, "text": "#x {\n background: salmon;\n padding: 1em;\n display: flex;\n flex-wrap: wrap;\n}\n\n#y, input {\n background: red;\n padding: 0 20px;\n width: 100%;\n} <div id=\"x\">\n <div id=\"y\">x</div>\n <input type=\"text\"/>\n</div>" }, { "answer_id": 63966907, "author": "hoang21", "author_id": 3579956, "author_profile": "https://Stackoverflow.com/users/3579956", "pm_score": 0, "selected": false, "text": "input {\n width: 100%;\n margin-left: 0;\n margin-right: 0;\n}\n" }, { "answer_id": 64799327, "author": "G Hasse", "author_id": 9923799, "author_profile": "https://Stackoverflow.com/users/9923799", "pm_score": 0, "selected": false, "text": "// NO JAVA !!! ;-) html {\n height: 100%;\n}\n\nbody {\n position: fixed;\n margin: 0px;\n padding: 0px;\n border: 2px solid #FF0000;\n width: calc(100% - 4px);\n /* Demonstrate how form can fill body */\n min-height: calc(100% - 120px);\n margin-top: 60px;\n margin-bottom: 60px;\n}\n\n\n/* Example how to make a data entry form */\n\n.rx-form {\n display: table;\n table-layout: fixed;\n border: 1px solid #0000FF;\n width: 100%;\n border-collapse: separate;\n border-spacing: 5px;\n}\n\n.rx-caption {\n display: table-caption;\n border: 1px solid #000000;\n text-align: center;\n padding: 10px;\n margin: 10px;\n width: calc(100% - 40px);\n font-size: 2.5em;\n}\n\n.rx-row {\n display: table-row;\n /* To make frame on rows. Rows have no border... ? */\n box-shadow: 0px 0px 0px 1px rgb(0, 0, 0);\n}\n\n.rx-cell {\n display: table-cell;\n margin: 0px;\n padding: 4px;\n border: 1px solid #FF0000;\n}\n\n.rx-cell label {\n float: left;\n border: 1px solid #00FF00;\n width: 110px;\n padding: 4px;\n font-size: 1em;\n text-align: right;\n font-family: Arial, Helvetica, sans-serif;\n overflow: hidden;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.rx-cell label:after {\n content: \" :\";\n}\n\n.rx-cell input[type='text'] {\n float: right;\n border: 1px solid #FF00FF;\n padding: 4px;\n background-color: #eee;\n border-radius: 0px;\n font-family: Arial, Helvetica, sans-serif;\n font-size: 1em;\n /* Fill the cell - but subtract the label width - and litte more... */\n width: calc(100% - 130px);\n overflow: hidden;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\ninput[type='submit'] {\n font-size: 1.3em;\n} <html>\n<meta charset=\"UTF-8\">\n\n<body>\n\n <!-- \n G Hasse, gorhas at raditex dot nu \n This example have a lot of frames so we \n can experiment with padding and margins. \n -->\n\n <form>\n\n <div class='rx-form'>\n\n\n <div class='rx-caption'>\n Caption\n </div>\n\n\n <!-- First row of entry -->\n\n <div class='rx-row'>\n\n <div class='rx-cell'>\n <label for=\"input11\">Label 1-1</label>\n <input type=\"text\" name=\"input11\" id=\"input11\" value=\"Some latin text here. And if it is very long it will get ellipsis\" />\n </div>\n\n <div class='rx-cell'>\n <label for=\"input12\">Label 1-2</label>\n <input type=\"text\" name=\"input12\" id=\"input12\" value=\"The content of input 2\" />\n </div>\n\n <div class='rx-cell'>\n <label for=\"input13\">Label 1-3</label>\n <input type=\"text\" name=\"input13\" id=\"input13\" value=\"Content 3\" />\n </div>\n\n <div class='rx-cell'>\n <label for=\"input14\">Label 1-4</label>\n <input type=\"text\" name=\"input14\" id=\"input14\" value=\"Content 4\" />\n </div>\n\n </div>\n\n <!-- Next row of entry -->\n\n <div class='rx-row'>\n\n <div class='rx-cell'>\n <label for=\"input21\">Label 2-1</label>\n <input type=\"text\" name=\"input21\" id=\"input21\" value=\"Content 2-1\">\n </div>\n\n <div class='rx-cell'>\n <label for=\"input22\">Label 2-2</label>\n <input type=\"text\" name=\"input22\" id=\"input22\" value=\"Content 2-2\">\n </div>\n\n <div class='rx-cell'>\n <label for=\"input23\">Label 2-3</label>\n <input type=\"text\" name=\"input23\" id=\"input23\" value=\"Content 2-3\">\n </div>\n\n </div>\n\n\n <!-- Next row of entry -->\n\n <div class='rx-row'>\n\n <div class='rx-cell'>\n <label for=\"input21\">Label 2-1</label>\n <input type=\"text\" name=\"input21\" id=\"input21\" value=\"Content 2-1\">\n </div>\n\n <div class='rx-cell'>\n <label for=\"input22\">Label 2-2</label>\n <input type=\"text\" name=\"input22\" id=\"input22\" value=\"Content 2-2\">\n </div>\n\n <div class='rx-cell'>\n <label for=\"input23\">Label 2-3</label>\n <input type=\"text\" name=\"input23\" id=\"input23\" value=\"Content 2-3\">\n </div>\n\n </div>\n\n <!-- And some text in cells -->\n\n <div class='rx-row'>\n\n <div class='rx-cell'>\n <div>Cell content</div>\n </div>\n\n <div class='rx-cell'>\n <span>Cell content</span>\n </div>\n\n </div>\n\n\n\n <!-- And we place the submit buttons in a cell -->\n\n <div class='rx-row'>\n\n <div class='rx-cell'>\n <input type=\"submit\" name=\"submit1\" value=\"submit1\" />\n <input type=\"submit\" name=\"submit2\" value=\"submit2\" />\n </div>\n\n </div>\n\n <!-- End of form -->\n </div>\n </form>\n\n</body>\n\n</html>" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
52,591
<p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p> <pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate '' 10 words args.IsValid = args.Value.Split(" ").Length &lt;= 10 End Sub </code></pre> <p>Does anyone have a more thorough/accurate method of getting a word count?</p>
[ { "answer_id": 52610, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "(\\b.*\\b){0,10}\n" }, { "answer_id": 52737, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": true, "text": "\"^(\\b\\S+\\b\\s*){0,10}$\"\n [\\s\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\xBF]+\n split() length" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
52,600
<p>I have to use a third-party component without source code. I have the release DLL and release PDB file. Let's call it 'CorporateComponent.dll'. My own code creates objects from this DLL and calls methods on these objects.</p> <pre><code>CorpObject o = new CorpObject(); Int32 result = o.DoSomethingLousy(); </code></pre> <p>While debugging, the method 'DoSomethingLousy' throws an exception. What does the PDB file do for me? If it does something nice, how can I be sure I'm making use of it?</p>
[ { "answer_id": 53095, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 4, "selected": true, "text": "Symbols loaded The thread 0x6a0 has exited with code 0 (0x0).\nThe thread 0x1f78 has exited with code 0 (0x0).\n'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\\Development\\Src\\trunk\\ntity\\AvayaConfigurationService\\AvayaConfigurationService\\bin\\Debug \\AvayaConfigurationService.exe', Symbols loaded.\n'AvayaConfigurationService.vshost.exe' (Managed): Loaded 'C:\\Development\\Src\\trunk\\ntity\\AvayaConfigurationService\\AvayaConfigurationService\\bin\\Debug\\IPOConfigService.dll', No symbols loaded.\n Loaded 'C:\\Development\\src...\\bin\\Debug\\AvayaConfigurationService.exe', Symbols loaded." } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
52,646
<p>While cross-site scripting is generally regarded as negative, I've run into several situations where it's necessary.</p> <p>I was recently working within the confines of a very limiting content management system. I needed to include database code within the page, but the hosting server didn't have anything usable available. I set up a couple bare-bones scripts on my own server, originally thinking that I could use AJAX to import the contents of my scripts directly into the template of the CMS (thus retaining dynamic images, menu items, CSS, etc.). I was wrong.</p> <p>Due to the limitations of <code>XMLHttpRequest</code> objects, it's not possible to grab content from a different domain. So I thought <em>iFrame</em> - even though I'm not a fan of frames, I thought that I could create a frame that matched the width and height of the content so that it would appear native. Again, I was blocked by cross-site scripting "protections." While I could indeed load a remote file into the <em>iFrame</em>, I couldn't execute JavaScript to modify its size on either the host page or inside the loaded page.</p> <p>In this particular scenario, I wasn't able to point a subdomain to my server. <strong>I also couldn't create a script on the CMS server that could proxy content from my server, so my last thought was to use a remote JavaScript.</strong></p> <p>A remote JavaScript works. It breaks when the user has JavaScript disabled, which is a downside; but it works. The "problem" I was having with using a remote JavaScript was that I had to use the JS function <code>document.write()</code> to output any content. Any output that isn't JS causes script errors. In addition to using <code>document.write()</code> for every line, you also have to ensure that the content is escaped - or else you end up with more script errors.</p> <p>My solution was as follows:</p> <p>My script received a GET parameter ("page") and then looked for the file (<code>{$page}.php</code>), and read the contents into a variable. However, I had to use awkward buffering techniques in order to actually execute the included scripts (for things like database interaction) then strip the final content of all line break characters (<code>\n</code>) followed by escaping all required characters. The end result is that my original script (which outputs JavaScript) accesses seemingly "standard" scripts on my server and converts their standard output to JavaScript for displaying within the CMS template.</p> <p>While this solution works, it seems like there may be a better way to accomplish the same thing. What is the best way to make cross-site scripting work specifically for the purpose of including content from a completely different domain?</p>
[ { "answer_id": 2802549, "author": "plop", "author_id": 337228, "author_profile": "https://Stackoverflow.com/users/337228", "pm_score": 0, "selected": false, "text": "document.domain src='Site B/home.php' [php stuff]...[/php]\n[script type='text/javascript']document.domain='Site A'[/script]\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1581/" ]
52,652
<p>What are the available libraries for creating pretty charts and graphs in a Python application?</p>
[ { "answer_id": 926029, "author": "serbaut", "author_id": 84760, "author_profile": "https://Stackoverflow.com/users/84760", "pm_score": 4, "selected": false, "text": "from reportlab.graphics.shapes import Drawing\nfrom reportlab.graphics.charts.barcharts import VerticalBarChart\n\nd = Drawing(300, 200)\n\nchart = VerticalBarChart()\nchart.width = 260\nchart.height = 160\nchart.x = 20\nchart.y = 20\nchart.data = [[1,2], [3,4]]\nchart.categoryAxis.categoryNames = ['foo', 'bar']\nchart.valueAxis.valueMin = 0\n\nd.add(chart)\nd.save(fnRoot='test', formats=['png', 'pdf'])\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ]
52,657
<p>How are people unit testing code that uses Linq to SQL? </p>
[ { "answer_id": 9353934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public class ProductRepo {\n IExampleDataContext DB { get; set };\n public ProductRepo(IExampleDataContext db) {\n DB = db;\n }\n\n public List<Product> GetProducts() {\n return DB.Products.ToList();\n }\n}\n new ProductRepo(new MemoryExampleDataContext()).GetProducts(); // for testing\n new ProductRepo(new ExampleDataContext()).GetProducts(); // use the real DB\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
52,674
<p>Let's say you have a variable in a makefile fragment like the following:</p> <pre><code>MY_LIST=a b c d </code></pre> <p>How do I then reverse the order of that list? I need:</p> <pre><code>$(warning MY_LIST=${MY_LIST}) </code></pre> <p>to show</p> <pre><code>MY_LIST=d c b a </code></pre> <p>Edit: the real problem is that </p> <pre><code>ld -r some_object.o ${MY_LIST} </code></pre> <p>produces an <code>a.out</code> with undefined symbols because the items in <code>MY_LIST</code> are actually archives, but in the wrong order. If the order of <code>MY_LIST</code> is reversed, it will link correctly (I think). If you know a smarter way to get the link order right, clue me in.</p>
[ { "answer_id": 52722, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": false, "text": "(for d in ${MY_LIST}; do echo $$d; done) | tac" }, { "answer_id": 52903, "author": "ajax", "author_id": 5250, "author_profile": "https://Stackoverflow.com/users/5250", "pm_score": 3, "selected": false, "text": "ld -r foo.o -( a.a b.a c.a -)\n ld -r -o foo.o --whole-archive bar.a\n" }, { "answer_id": 16795504, "author": "Tripp Lilley", "author_id": 309233, "author_profile": "https://Stackoverflow.com/users/309233", "pm_score": 2, "selected": false, "text": "reverse = $(shell printf \"%s\\n\" $(strip $1) | tac)\n $(shell) printf $(info [ $(call reverse, one two three four ) ] )\n [ four three two one ]\n $(info ...)" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
52,676
<p>I'm a keyboard junkie. I love having a key sequence to do everything. What are your favorite keyboard shortcuts?</p> <p>I'll start by naming a couple of mine:</p> <p>1 - <kbd>Alt</kbd>-<kbd>Space</kbd> to access the windows menu for the current window</p> <p>2 - <kbd>F2</kbd> to rename a file in Windows Explorer</p>
[ { "answer_id": 843863, "author": "Peter Perháč", "author_id": 81520, "author_profile": "https://Stackoverflow.com/users/81520", "pm_score": 1, "selected": false, "text": "rightclick->Open Link in New Tab" }, { "answer_id": 19919862, "author": "Scott Pelak", "author_id": 2348267, "author_profile": "https://Stackoverflow.com/users/2348267", "pm_score": 3, "selected": false, "text": "System Information PATH" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
52,702
<p>I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. </p> <p>This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. </p> <p>Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)</p> <p>Here is a code snippet:</p> <pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open); long byteNum = fs.Length; byte[] pdfBytes = new byte[byteNum]; fs.Read(pdfBytes, 0, (int)byteNum); Response.AppendHeader("Content-disposition", "filename=Testme.doc"); Response.CacheControl = "no-cache"; Response.ContentType = "application/msword; charset=utf-8"; Response.Expires = -1; Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length); Response.Flush(); Response.Close(); fs.Close(); </code></pre> <p>Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 &amp; IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. </p> <p>IE does provide an advanced setting "Do not save encrypted pages to disk". </p> <p>I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.</p> <p>Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).</p> <p>Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?</p>
[ { "answer_id": 53078, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "\nResponse.AddHeader(\"Content-Disposition\", \"attachment;filename=myfile.doc\");\n \nprivate void ReadFile(string URL)\n{\n try\n {\n string uristring = URL;\n WebRequest myReq = WebRequest.Create(uristring);\n NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings[\"Username\"].ToString(), \n ConfigurationManager.AppSettings[\"Password\"].ToString(), \n ConfigurationManager.AppSettings[\"Domain\"].ToString());\n myReq.Credentials = netCredential;\n StringBuilder strSource = new StringBuilder(\"\");\n\n //get the stream of data \n string contentType = \"\";\n MemoryStream ms;\n // Send a request to download the pdf document and then get the response\n using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())\n {\n contentType = response.ContentType;\n // Get the stream from the server\n using (Stream stream = response.GetResponseStream())\n {\n // Use the ReadFully method from the link above:\n byte[] data = ReadFully(stream, response.ContentLength);\n // Return the memory stream.\n ms = new MemoryStream(data);\n }\n }\n\n Response.Clear();\n Response.ContentType = contentType;\n Response.AddHeader(\"Content-Disposition\", \"attachment;\");\n\n // Write the memory stream containing the pdf file directly to the Response object that gets sent to the client\n ms.WriteTo(Response.OutputStream);\n }\n catch (Exception ex)\n {\n throw new Exception(\"Error in ReadFile\", ex);\n }\n}\n" }, { "answer_id": 77958, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 2, "selected": false, "text": "System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(\".\") + \"\\\\\" + \"TestMe.doc\", System.IO.FileMode.Open);\nlong byteNum = fs.Length;\nbyte[] fileBytes = new byte[byteNum];\nfs.Read(fileBytes, 0, (int)byteNum);\n\nResponse.ClearContent();\nResponse.ClearHeaders();\nResponse.AppendHeader(\"Content-disposition\", \"attachment; filename=Testme.doc\");\nResponse.Cache.SetCacheability(HttpCacheability.Public);\nResponse.ContentType = \"application/octet-stream\";\nResponse.OutputStream.Write(fileBytes, 0, fileBytes.Length);\nResponse.Flush();\nResponse.Close();\nfs.Close();\nResponse.End();\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4764/" ]
52,703
<p>Has anyone encountered this oddity?</p> <p>I'm checking for the existence of a number of directories in one of my unit tests. <code>is_dir</code> is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging):</p> <pre><code>foreach($userfolders as $uf) { $uf = sprintf($uf, $user_id); $uf = ltrim($uf,'/'); $path = trim($base . '/' . $uf); $res = is_dir($path); //returns false except last time returns 1 $this-&gt;assertFalse($res, $path); } </code></pre> <p>The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3</p> <p>Things I have checked:</p> <pre><code> - Paths are full paths - The same thing happens on two separate machines (both running Ubuntu) - I have stepped through line by line in a debugger - Paths genuinely don't exist at the point where is_dir is called - While the code is paused on this line, I can actually drop to a shell and run </code></pre> <p>the interactive PHP interpreter and get the correct result - The paths are all WELL under 256 chars - I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing.</p> <p>Comments on the PHP docs point to the odd issue with <code>is_dir</code> but not this particular one.</p> <p>I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and <em>hopefully</em> an answer from somebody else who has seen this!</p>
[ { "answer_id": 52712, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 1, "selected": false, "text": "is_readable" }, { "answer_id": 52721, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 0, "selected": false, "text": "$path = trim($base . '/' . $uf);\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745/" ]
52,704
<p>How do I discard changes in my working copy that are not in the index?</p>
[ { "answer_id": 52713, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 13, "selected": false, "text": "git restore .\n git restore path/to/file/to/revert\n git switch git checkout git diff git diff --staged git checkout -- .\n git checkout -- path/to/file/to/revert\n --" }, { "answer_id": 52719, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 13, "selected": true, "text": "git stash save --keep-index --include-untracked\n --include-untracked git stash drop" }, { "answer_id": 1021384, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 9, "selected": false, "text": "git checkout .\n git checkout-index -a -f\n" }, { "answer_id": 6854469, "author": "Joshua Kunzmann", "author_id": 121037, "author_profile": "https://Stackoverflow.com/users/121037", "pm_score": 6, "selected": false, "text": "git diff | git apply --reverse\n" }, { "answer_id": 7773568, "author": "artur", "author_id": 201852, "author_profile": "https://Stackoverflow.com/users/201852", "pm_score": 5, "selected": false, "text": "git clean -f" }, { "answer_id": 8415829, "author": "E Ciotti", "author_id": 415032, "author_profile": "https://Stackoverflow.com/users/415032", "pm_score": 8, "selected": false, "text": "git clean -df\n -d -f clean.requireForce git help clean" }, { "answer_id": 11942626, "author": "blak3r", "author_id": 67268, "author_profile": "https://Stackoverflow.com/users/67268", "pm_score": 6, "selected": false, "text": "git checkout git checkout -- foo.txt git reset -- foo.txt git stash" }, { "answer_id": 12184274, "author": "Mariusz Nowak", "author_id": 96806, "author_profile": "https://Stackoverflow.com/users/96806", "pm_score": 11, "selected": false, "text": "git clean -df\ngit checkout -- .\n git clean -df git clean git checkout" }, { "answer_id": 17530055, "author": "twicejr", "author_id": 449217, "author_profile": "https://Stackoverflow.com/users/449217", "pm_score": 3, "selected": false, "text": "# add files\ngit add . \n# diff all the changes to a file\ngit diff --staged > ~/mijn-fix.diff\n# remove local changes \ngit reset && git checkout .\n# (later you can re-apply the diff:)\ngit apply ~/mijn-fix.diff\n" }, { "answer_id": 18632808, "author": "GlassGhost", "author_id": 144020, "author_profile": "https://Stackoverflow.com/users/144020", "pm_score": 4, "selected": false, "text": "sudo chmod -R 664 ./* && git checkout -- . && git clean -dfx\n" }, { "answer_id": 20930217, "author": "bbarker", "author_id": 3096687, "author_profile": "https://Stackoverflow.com/users/3096687", "pm_score": 3, "selected": false, "text": "$ git status\n# Not currently on any branch.\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/constraint_s2var.dats\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/parsing/parsing_s2var.dats\n#\n# Changes not staged for commit:\n# (use \"git add <file>...\" to update what will be committed)\n# (use \"git checkout -- <file>...\" to discard changes in working directory)\n#\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/constraint_s2Var.dats\n# modified: doc/PROJECT/MEDIUM/ATS-constraint/parsing/parsing_s2Var.dats\n" }, { "answer_id": 23707009, "author": "Bijan", "author_id": 323720, "author_profile": "https://Stackoverflow.com/users/323720", "pm_score": 5, "selected": false, "text": "git checkout -f man git-checkout -f, --force" }, { "answer_id": 23951175, "author": "vivekporwal04", "author_id": 1856106, "author_profile": "https://Stackoverflow.com/users/1856106", "pm_score": 4, "selected": false, "text": "cd path_to_project_folder # take you to your project folder/working directory \ngit checkout . # removes all unstaged changes in working directory\n" }, { "answer_id": 26299506, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 7, "selected": false, "text": "git checkout -p\n git add -p\n" }, { "answer_id": 29847393, "author": "piyushmandovra", "author_id": 3568378, "author_profile": "https://Stackoverflow.com/users/3568378", "pm_score": 5, "selected": false, "text": "git stash\n git stash apply \n" }, { "answer_id": 31886761, "author": "Nick", "author_id": 1563884, "author_profile": "https://Stackoverflow.com/users/1563884", "pm_score": 5, "selected": false, "text": "git add --all\n git fetch --all\n git reset --hard origin/branchname\n git reset --hard @{u}\n" }, { "answer_id": 32523024, "author": "Asped", "author_id": 1132243, "author_profile": "https://Stackoverflow.com/users/1132243", "pm_score": 5, "selected": false, "text": "git add .\ngit stash\n git stash drop\n git clean git add . -A git add . -A" }, { "answer_id": 32897226, "author": "onalbi", "author_id": 3090602, "author_profile": "https://Stackoverflow.com/users/3090602", "pm_score": 3, "selected": false, "text": "git diff git submodule update" }, { "answer_id": 35214606, "author": "msangel", "author_id": 449553, "author_profile": "https://Stackoverflow.com/users/449553", "pm_score": 4, "selected": false, "text": "git reset --hard <commit hash>\n" }, { "answer_id": 36924148, "author": "Martin G", "author_id": 3545094, "author_profile": "https://Stackoverflow.com/users/3545094", "pm_score": 7, "selected": false, "text": "git clean -dxn . # dry-run to inspect the list of files-to-be-removed\ngit clean -dxf . # REMOVE ignored/untracked files (in the current directory)\ngit checkout -- . # ERASE changes in tracked files (in the current directory)\n git clean -d -f -x .gitignore $GIT_DIR/info/exclude -e git reset -n -f clean.requireForce false -f -n -i .git -f" }, { "answer_id": 37274801, "author": "Erdem ÖZDEMİR", "author_id": 1836344, "author_profile": "https://Stackoverflow.com/users/1836344", "pm_score": 6, "selected": false, "text": "git checkout -- ." }, { "answer_id": 38367577, "author": "Lahiru Jayaratne", "author_id": 1616697, "author_profile": "https://Stackoverflow.com/users/1616697", "pm_score": 4, "selected": false, "text": "git clean -df\n" }, { "answer_id": 39383786, "author": "Ben Wilde", "author_id": 2284031, "author_profile": "https://Stackoverflow.com/users/2284031", "pm_score": 5, "selected": false, "text": "git stash -u\n git stash drop git checkout -- .\ngit clean -df\n git stash -u git checkout -- . git clean -df" }, { "answer_id": 41305623, "author": "Xaree Lee", "author_id": 1282160, "author_profile": "https://Stackoverflow.com/users/1282160", "pm_score": 1, "selected": false, "text": "git stash -k -u\n reset checkout clean git stash pop" }, { "answer_id": 43365551, "author": "Forhadul Islam", "author_id": 1467428, "author_profile": "https://Stackoverflow.com/users/1467428", "pm_score": 6, "selected": false, "text": "git checkout -- .\n git stash -u\n" }, { "answer_id": 44361801, "author": "Pau", "author_id": 4751165, "author_profile": "https://Stackoverflow.com/users/4751165", "pm_score": 3, "selected": false, "text": "discard = checkout --\n discard .\n discard filename\n cleanout = !git clean -df && git checkout -- .\n cleanout\n" }, { "answer_id": 45420441, "author": "Jesús Castro", "author_id": 2212414, "author_profile": "https://Stackoverflow.com/users/2212414", "pm_score": 3, "selected": false, "text": "git update-index --assume-unchanged file_to_ignore" }, { "answer_id": 49343276, "author": "2540625", "author_id": 2540625, "author_profile": "https://Stackoverflow.com/users/2540625", "pm_score": 6, "selected": false, "text": "checkout git checkout -- .\n -- . clean git clean -i \n -i clean stash git stash\n" }, { "answer_id": 56870406, "author": "SANGEETHA P.H.", "author_id": 7510315, "author_profile": "https://Stackoverflow.com/users/7510315", "pm_score": 5, "selected": false, "text": "git reset --hard git stash" }, { "answer_id": 57670112, "author": "Khem Raj Regmi", "author_id": 5591577, "author_profile": "https://Stackoverflow.com/users/5591577", "pm_score": 4, "selected": false, "text": "git checkout ." }, { "answer_id": 57880896, "author": "prosoitos", "author_id": 9210961, "author_profile": "https://Stackoverflow.com/users/9210961", "pm_score": 8, "selected": false, "text": "git restore <file>\n git restore .\n git restore git checkout git restore git switch git checkout git status git checkout -- <file> git checkout -- . git clean -df" }, { "answer_id": 73040730, "author": "G-Man", "author_id": 4616126, "author_profile": "https://Stackoverflow.com/users/4616126", "pm_score": 3, "selected": false, "text": "git checkout .\n" }, { "answer_id": 73620948, "author": "Cary", "author_id": 250428, "author_profile": "https://Stackoverflow.com/users/250428", "pm_score": -1, "selected": false, "text": "git revert --hard\n" }, { "answer_id": 74261094, "author": "Mohamed Eldefrawy", "author_id": 6627676, "author_profile": "https://Stackoverflow.com/users/6627676", "pm_score": 0, "selected": false, "text": "git checkout -- <file>" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
52,714
<p>In the STL almost all containers have an erase function. The question I have is in a vector, the erase function returns an iterator pointing to the next element in the vector. The map container does not do this. Instead it returns a void. Anyone know why there is this inconsistancy?</p>
[ { "answer_id": 52735, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "vector map" }, { "answer_id": 52761, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 2, "selected": false, "text": "erase" }, { "answer_id": 104372, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 4, "selected": false, "text": "erase iterator" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
52,732
<p>I need to dynamically create a Video object in ActionScript 2 and add it to a movie clip. In AS3 I just do this:</p> <pre><code>var videoViewComp:UIComponent; // created elsewhere videoView = new Video(); videoView.width = 400; videoView.height = 400; this.videoViewComp.addChild(videoView); </code></pre> <p>Unfortunately, I can't figure out how to accomplish this in AS2. Video isn't a child of MovieClip, so attachMovie() doesn't seem to be getting me anything. I don't see any equivalent to AS3's UIComponent.addChild() method either.</p> <p>Is there any way to dynamically create a Video object in AS2 that actually shows up on the stage?</p> <hr> <p>I potentially need multiple videos at a time though. Is it possible to duplicate that video object?</p> <p>I think I have another solution working. It's not optimal, but it fits with some of the things I have to do for other components so it's not too out of place in the project. Once I get it figured out I'll post what I did here.</p>
[ { "answer_id": 53254, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 0, "selected": false, "text": "videoview.visible = false swapDepth()" }, { "answer_id": 3603369, "author": "Tonio FERENER-VARI", "author_id": 435264, "author_profile": "https://Stackoverflow.com/users/435264", "pm_score": 0, "selected": false, "text": "import UTIL.MEDIA.MEDIAInstances\n\nclass Main\n\n{\n static function main() {\n\n var MEDIAInstancesInstance :MEDIAInstances = new MEDIAInstances (); \n\n _root.Video_Display.play (\"IsothermalCompression.flv\", 0);\n\n _root.VideoDisplayMC.onPress = function() { \n\n _root.Video_Display.seek (0); \n\n } // _root.displayMC.onPress = function() {\n\n } // static function main() \n\n} // class Main \n\n// \n\nimport UTIL.MEDIA.VideoDisplay \n\nclass UTIL.MEDIA.MEDIAInstances \n\n { \n\n function MEDIAInstances() \n\n {\n\n // depth \n _root.createEmptyMovieClip (\"VideoDisplayMC\", 500); \n //\n var Video_Display:VideoDisplay \n = \n new VideoDisplay(_root.VideoDisplayMC, \"Video_Display\", 1); \n\n Video_Display.setLocation(400, 0); Video_Display.setSize (320, 240); \n // \n _root.Video_Display = Video_Display; _root.VideoDisplayMC._alpha = 75; \n\n } // MEDIAInstances()\n\n} // class UTIL.MEDIA.MEDIAInstances\n\n//\n\nclass UTIL.MEDIA.VideoDisplay\n\n{\n private var display:MovieClip, nc:NetConnection, ns:NetStream;\n\n function VideoDisplay(parent:MovieClip, name:String, depth:Number)\n\n {\n display = parent.attachMovie(\"VideoDisplay\", name, depth);\n\n nc = new NetConnection(); nc.connect(null); ns = new NetStream(nc);\n\n display.video.attachVideo(ns);\n }\n function setSize(width:Number, heigth:Number):Void\n\n { display.video._width = width; display.video._height = heigth;}\n\n function setLocation(x:Number, y:Number):Void { display._x = x; display._y = y;}\n\n public function play(url:String, bufferTime:Number):Void\n {\n if (bufferTime != undefined) ns.setBufferTime(bufferTime); ns.play(url);\n }\n //\n public function pause():Void { ns.pause();}\n //\n public function seek(offset:Number):Void { ns.seek(offset); }\n\n} // UTIL.MEDIA.VideoDisplay\n" }, { "answer_id": 4334511, "author": "Tonio FERENER-VARI", "author_id": 527889, "author_profile": "https://Stackoverflow.com/users/527889", "pm_score": 1, "selected": false, "text": "< asset path=\"library\\video.swf\" />\n video.swf <xml version=\"1.0\" encoding=\"utf-8\" >\n<movie version=\"7\"> \n <frame>\n <library>\n <clip id=\"VideoDisplay\">\n <frame>\n <video id=\"VideoSurface\" width=\"160\" height=\"120\" />\n <place id=\"VideoSurface\" name=\"video\" />\n </frame>\n </clip>\n </library>\n </frame>\n</movie>\n public function pos():Number\n{\n return ns.time;\n}\n\n public function close():Void\n{\n return ns.close();\n}\n .flv .flv class util.VideoDisplay\n{\n //{ PUBLIC MEMBERS\n\n\n /**\n * Create a new video display surface\n */\n\n function VideoDisplay(targetURI:String, parent:MovieClip, name:String, depth:Number, initObj)\n\n {\n display = parent.attachMovie(\"VideoDisplay\", name, depth, initObj);\n\n // create video stream\n nc = new NetConnection();\n nc.connect(targetURI);\n ns = new NetStream(nc);\n\n // attach the video stream to the video object\n display.video.attachVideo(ns);\n }\n\n /**\n * Video surface dimensions\n */\n function setSize(width:Number, heigth:Number):Void\n {\n display.video._width = width;\n display.video._height = heigth;\n }\n /**\n * Video clip position\n */\n function setLocation(x:Number, y:Number):Void\n {\n display._x = x;\n display._y = y;\n }\n\n /**\n * Start streaming\n * @param url FLV file\n * @param bufferTime Buffer size (optional) \n */\n public function play(url:String, bufferTime:Number):Void\n {\n if (bufferTime != undefined) ns.setBufferTime(bufferTime);\n ns.play(url);\n }\n /**\n * Pause streaming\n */\n public function pause():Void\n {\n ns.pause();\n }\n /**\n * Seek position in video\n */\n public function seek(offset:Number):Void\n {\n ns.seek(offset);\n } \n\n /**\n * Get position in video\n */\n\n public function pos():Number\n {\n return ns.time;\n }\n\n public function close():Void\n {\n return ns.close();\n }\n\n //}\n\n //{ PRIVATE MEMBERS \n\n private var display:MovieClip;\n private var nc:NetConnection;\n private var ns:NetStream;\n\n //}\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
52,739
<p>Is there a good way to see what format an image is, without having to read the entire file into memory? </p> <p>Obviously this would vary from format to format (I'm particularly interested in TIFF files) but what sort of procedure would be useful to determine what kind of image format a file is without having to read through the entire file?</p> <p><strong>BONUS</strong>: What if the image is a Base64-encoded string? Any reliable way to infer it before decoding it?</p>
[ { "answer_id": 52750, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "file" }, { "answer_id": 52833, "author": "verix", "author_id": 5342, "author_profile": "https://Stackoverflow.com/users/5342", "pm_score": 1, "selected": false, "text": "file" }, { "answer_id": 99665, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 3, "selected": false, "text": "Qk3 /9j/ R0l" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
52,753
<p>What is best practice when creating your exception classes in a .NET solution: To derive from <code>System.Exception</code> or from <code>System.ApplicationException</code>?</p>
[ { "answer_id": 52762, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "ApplicationException ApplicationException Exception" }, { "answer_id": 52770, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 7, "selected": true, "text": "System.ApplicationException" }, { "answer_id": 1086628, "author": "Olivier de Rivoyre", "author_id": 26071, "author_profile": "https://Stackoverflow.com/users/26071", "pm_score": 1, "selected": false, "text": "private void buttonFoo_Click()\n{\n try\n {\n foo();\n } \n catch(ApplicationException ex)\n {\n Log.UserWarning(ex);\n MessageVox.Show(ex.Message);\n }\n catch(Exception ex)\n {\n Log.CodeError(ex);\n MessageBox.Show(\"Internal error.\");\n }\n}\n" }, { "answer_id": 1086636, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 5, "selected": false, "text": "System.Exception ApplicationException" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5392/" ]
52,755
<p>I am using Windows, and I have two monitors.</p> <p>Some applications will <em>always</em> start on my primary monitor, no matter where they were when I closed them.</p> <p>Others will always start on the <em>secondary</em> monitor, no matter where they were when I closed them.</p> <p>Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?</p> <p>@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into.</p>
[ { "answer_id": 53187, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 7, "selected": true, "text": "GetWindowPlacement() SetWindowPlacement() GetWindowPlacement() REG_BINARY WINDOWPLACEMENT SetWindowPlacement() nCmdShow if(nCmdShow != SW_SHOWNORMAL)\n placement.showCmd = nCmdShow; //allow shortcut to override\n setBounds() getBounds() WINDOWPLACEMENT" }, { "answer_id": 511735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "1. Open the application.\n2. Re-size the window so that it is not maximized or minimized.\n3. Move the window to the monitor you want it to open on by default.\n4. Close the application. Do not re-size prior to closing.\n5. Open the application.\n It should open on the monitor you just moved it to and closed it on.\n6. Maximize the window.\n" }, { "answer_id": 25909284, "author": "Croo", "author_id": 561709, "author_profile": "https://Stackoverflow.com/users/561709", "pm_score": 4, "selected": false, "text": "Shift + Win + [left,right] arrow keys" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
52,785
<p>I think this is specific to IE 6.0 but...</p> <p>In JavaScript I add a <code>div</code> to the DOM. I assign an <code>id</code> attribute. When I later try to pick up the <code>div</code> by the <code>id</code> all I get is <code>null</code>.</p> <p>Any suggestions?</p> <p>Example:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>Alert prints <code>"::null"</code></p> <p>Seems to work fine in Firefox 2.0+</p>
[ { "answer_id": 52791, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "// Create the Div\nvar oDiv = document.createElement('div');\ndocument.body.appendChild(oDiv);\n" }, { "answer_id": 52792, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "document.appendChild(newDiv);\n\nalert( document.getElementById(\"obj_1000\") );\n" }, { "answer_id": 52805, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "getElementById() id var newDiv = document.createElement(\"DIV\"); \nnewDiv.setAttribute(\"id\", \"obj_1000\");\ndocument.body.appendChild(newDiv);\n\nalert(\"Added:\"\n + newDiv.getAttribute(\"id\") \n + \":\" + newDiv.id + \":\" \n + document.getElementById(\"obj_1000\") );\n Added:obj_1000:obj_1000:[object]\n setAttribute()" }, { "answer_id": 52811, "author": "Markus", "author_id": 2490, "author_profile": "https://Stackoverflow.com/users/2490", "pm_score": 0, "selected": false, "text": "var newDiv = document.createElement(\"DIV\");\nnewDiv.setAttribute(\"id\", \"obj_1000\");\ndocument.appendChild(newDiv);\n\nalert(\"Added:\" +\n newDiv.getAttribute(\"id\") + \":\" +\n newDiv.id + \":\" +\n document.getElementById(\"obj_1000\"));\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
52,794
<p>How do I create a branch in subversion that is deeper' than just the 'branches' directory?</p> <p>I have the standard <code>trunk</code>, <code>tags</code> and <code>branches</code> structure and I want to create a branch that is several directories deeper than the 'branches' tag.</p> <p>Using the standard svn move method, it gives me a <strong>folder not found</strong> error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.</p> <p>What do I need to do to create this?</p> <p>For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?</p>
[ { "answer_id": 52799, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": true, "text": "svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject\n --parents" }, { "answer_id": 52804, "author": "xanadont", "author_id": 1886, "author_profile": "https://Stackoverflow.com/users/1886", "pm_score": 1, "selected": false, "text": "TortoiseSVN WYSIWYG" }, { "answer_id": 52878, "author": "warsze", "author_id": 4968, "author_profile": "https://Stackoverflow.com/users/4968", "pm_score": 1, "selected": false, "text": "SVN" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
52,797
<p>Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. </p> <p>Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.</p> <p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p> <p>My test library is located in say </p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p> </blockquote> <p>and I would like to get this path:</p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\</p> </blockquote> <p>The three suggestions so far fail me when I run from the MbUnit Gui:</p> <ul> <li><p><code>Environment.CurrentDirectory</code> gives <em>c:\Program Files\MbUnit</em></p></li> <li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code> gives <em>C:\Documents and Settings\george\Local Settings\Temp\ ....\DaoTests.dll</em></p></li> <li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code> gives the same as the previous.</p></li> </ul>
[ { "answer_id": 52802, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 5, "selected": false, "text": "string path = System.Reflection.Assembly.GetExecutingAssembly().Location\n" }, { "answer_id": 52803, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "Environment.CurrentDirectory; // This is the current directory of your application\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));\n\n// The location of the Assembly\nassembly.Location;\n" }, { "answer_id": 52956, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 8, "selected": false, "text": "//get the full location of the assembly with DaoTests in it\nstring fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;\n\n//get the folder that's in\nstring theDirectory = Path.GetDirectoryName( fullPath );\n" }, { "answer_id": 52969, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "var assembly = System.Reflection.Assembly.GetExecutingAssembly();\nvar assemblyPath = assembly.GetFiles()[0].Name;\nvar assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);\n" }, { "answer_id": 52987, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 4, "selected": false, "text": "System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n" }, { "answer_id": 52990, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 1, "selected": false, "text": "string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);\n" }, { "answer_id": 52996, "author": "dan gibson", "author_id": 4495, "author_profile": "https://Stackoverflow.com/users/4495", "pm_score": 3, "selected": false, "text": "Assembly a;\na = Assembly.GetAssembly(typeof(DaoTests));\nstring s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll\nAssert.AreEqual(true, s.StartsWith(\"FILE://\"), \"CodeBase is \" + s);\ns = s.Substring(7, s.LastIndexOf('/') - 7); // 7 = \"file://\"\nwhile (s.StartsWith(\"/\")) {\n s = s.Substring(1, s.Length - 1);\n}\ns = s.Replace(\"/\", \"\\\\\");\n" }, { "answer_id": 283917, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 11, "selected": true, "text": "public static string AssemblyDirectory\n{\n get\n {\n string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n UriBuilder uri = new UriBuilder(codeBase);\n string path = Uri.UnescapeDataString(uri.Path);\n return Path.GetDirectoryName(path);\n }\n}\n Assembly.Location CodeBase UriBuild.UnescapeDataString File:// GetDirectoryName" }, { "answer_id": 884444, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 3, "selected": false, "text": "Public Shared ReadOnly Property AssemblyDirectory() As String\n Get\n Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase\n Dim uriBuilder As New UriBuilder(codeBase)\n Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)\n Return Path.GetDirectoryName(assemblyPath)\n End Get\nEnd Property\n" }, { "answer_id": 2567233, "author": "Sneal", "author_id": 82906, "author_profile": "https://Stackoverflow.com/users/82906", "pm_score": 6, "selected": false, "text": "public static string GetDirectoryPath(this Assembly assembly)\n{\n string filePath = new Uri(assembly.CodeBase).LocalPath;\n return Path.GetDirectoryName(filePath); \n}\n var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();\n var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();\n" }, { "answer_id": 2887537, "author": "Jalal El-Shaer", "author_id": 95380, "author_profile": "https://Stackoverflow.com/users/95380", "pm_score": 8, "selected": false, "text": "var dir = AppDomain.CurrentDomain.BaseDirectory;\n" }, { "answer_id": 3051585, "author": "user368021", "author_id": 368021, "author_profile": "https://Stackoverflow.com/users/368021", "pm_score": 4, "selected": false, "text": "AppDomain.CurrentDomain.BaseDirectory\n" }, { "answer_id": 8594253, "author": "rcooley56", "author_id": 1110393, "author_profile": "https://Stackoverflow.com/users/1110393", "pm_score": -1, "selected": false, "text": "var i = Environment.CurrentDirectory.LastIndexOf(@\"\\\");\nvar path = Environment.CurrentDirectory.Substring(0,i); \n" }, { "answer_id": 9737418, "author": "Ignacio Soler Garcia", "author_id": 166452, "author_profile": "https://Stackoverflow.com/users/166452", "pm_score": 6, "selected": false, "text": "System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);\n" }, { "answer_id": 17060539, "author": "mmmmmm", "author_id": 767464, "author_profile": "https://Stackoverflow.com/users/767464", "pm_score": 0, "selected": false, "text": "ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nAssembly asm = Assembly.GetCallingAssembly();\nString path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);\n\nstring strLog4NetConfigPath = System.IO.Path.Combine(path, \"log4net.config\");\n" }, { "answer_id": 17440241, "author": "Valamas", "author_id": 511438, "author_profile": "https://Stackoverflow.com/users/511438", "pm_score": 0, "selected": false, "text": "Debug/Release/CustomName #if DEBUG public static string AppPath\n{\n get\n {\n DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);\n\n while (appPath.FullName.Contains(@\"\\bin\\\", StringComparison.CurrentCultureIgnoreCase)\n || appPath.FullName.EndsWith(@\"\\bin\", StringComparison.CurrentCultureIgnoreCase))\n {\n appPath = appPath.Parent;\n }\n return appPath.FullName;\n }\n}\n public static string BinPath\n{\n get\n {\n string binPath = AppDomain.CurrentDomain.BaseDirectory;\n\n if (!binPath.Contains(@\"\\bin\\\", StringComparison.CurrentCultureIgnoreCase)\n && !binPath.EndsWith(@\"\\bin\", StringComparison.CurrentCultureIgnoreCase))\n {\n binPath = Path.Combine(binPath, \"bin\");\n //-- Please improve this if there is a better way\n //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.\n#if DEBUG\n if (Directory.Exists(Path.Combine(binPath, \"Debug\"))) \n binPath = Path.Combine(binPath, \"Debug\");\n#else\n if (Directory.Exists(Path.Combine(binPath, \"Release\"))) \n binPath = Path.Combine(binPath, \"Release\");\n#endif\n }\n return binPath;\n }\n}\n" }, { "answer_id": 24249706, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": false, "text": "CodeBase file:// UnescapeDataString LocalPath Uri var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;\nvar filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;\nvar directoryPath = Path.GetDirectoryName(filePathToCodeBase);\n" }, { "answer_id": 24283320, "author": "user2009677", "author_id": 2009677, "author_profile": "https://Stackoverflow.com/users/2009677", "pm_score": -1, "selected": false, "text": "Server.MapPath(\"~/MyDir/MyFile.ext\")\n" }, { "answer_id": 32738924, "author": "Tez Wingfield", "author_id": 3305976, "author_profile": "https://Stackoverflow.com/users/3305976", "pm_score": 0, "selected": false, "text": "var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;\n" }, { "answer_id": 32863106, "author": "Andrey Bushman", "author_id": 1306132, "author_profile": "https://Stackoverflow.com/users/1306132", "pm_score": 0, "selected": false, "text": "NUnit NUnit NUnit TestDriven.NET MbUnit" }, { "answer_id": 32870042, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": false, "text": "public static class PathUtilities\n{\n public static string GetAdjacentFile(string relativePath)\n {\n return GetDirectoryForCaller(1) + relativePath;\n }\n public static string GetDirectoryForCaller()\n {\n return GetDirectoryForCaller(1);\n }\n\n\n public static string GetDirectoryForCaller(int callerStackDepth)\n {\n var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);\n return GetDirectoryForStackFrame(stackFrame);\n }\n\n public static string GetDirectoryForStackFrame(StackFrame stackFrame)\n {\n return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;\n }\n}\n" }, { "answer_id": 39216220, "author": "David C Fuchs", "author_id": 5719295, "author_profile": "https://Stackoverflow.com/users/5719295", "pm_score": 3, "selected": false, "text": "string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n" }, { "answer_id": 47760173, "author": "gamesguru", "author_id": 8555624, "author_profile": "https://Stackoverflow.com/users/8555624", "pm_score": 2, "selected": false, "text": "Application.StartupPath string slash = Path.DirectorySeparatorChar.ToString();\nstring root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n\nroot += slash;\nstring settingsIni = root + \"settings.ini\"\n" }, { "answer_id": 53048485, "author": "Fedor Shihantsov", "author_id": 1518180, "author_profile": "https://Stackoverflow.com/users/1518180", "pm_score": 2, "selected": false, "text": "public static string AssemblyDirectory\n{\n get\n {\n string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n UriBuilder uri = new UriBuilder(codeBase);\n //modification of the John Sibly answer \n string path = Uri.UnescapeDataString(uri.Path.Replace(\"/\", \"\\\\\") + \n uri.Fragment.Replace(\"/\", \"\\\\\"));\n return Path.GetDirectoryName(path);\n }\n}\n" }, { "answer_id": 58051383, "author": "Ilya Chernomordik", "author_id": 1671558, "author_profile": "https://Stackoverflow.com/users/1671558", "pm_score": 5, "selected": false, "text": "AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory\n" }, { "answer_id": 62626131, "author": "cube45", "author_id": 2663813, "author_profile": "https://Stackoverflow.com/users/2663813", "pm_score": 4, "selected": false, "text": "AppDomain.CurrentDomain.BaseDirectory AppContext.BaseDirectory\n" }, { "answer_id": 63626644, "author": "TPG", "author_id": 2463156, "author_profile": "https://Stackoverflow.com/users/2463156", "pm_score": 2, "selected": false, "text": "public string ApplicationPath\n {\n get\n {\n if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))\n {\n return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services\n }\n else\n {\n return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps \n }\n }\n }\n" }, { "answer_id": 68223295, "author": "Bennik2000", "author_id": 4563449, "author_profile": "https://Stackoverflow.com/users/4563449", "pm_score": 3, "selected": false, "text": "Assembly.Load(Byte[]) static void Main(string[] args)\n{\n var fileContent = File.ReadAllBytes(@\"C:\\Library.dll\");\n\n var assembly = Assembly.Load(fileContent);\n\n // Call the method of the library using reflection\n assembly\n ?.GetType(\"Library.LibraryClass\")\n ?.GetMethod(\"PrintPath\", BindingFlags.Public | BindingFlags.Static)\n ?.Invoke(null, null);\n\n Console.WriteLine(\"Hello from Application:\");\n Console.WriteLine($\"GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}\");\n Console.WriteLine($\"GetViaAssemblyLocation: {assembly.Location}\");\n Console.WriteLine($\"GetViaAppDomain : {AppDomain.CurrentDomain.BaseDirectory}\");\n\n Console.ReadLine();\n}\n public class LibraryClass\n{\n public static void PrintPath()\n {\n var assembly = Assembly.GetAssembly(typeof(LibraryClass));\n Console.WriteLine(\"Hello from Library:\");\n Console.WriteLine($\"GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}\");\n Console.WriteLine($\"GetViaAssemblyLocation: {assembly.Location}\");\n Console.WriteLine($\"GetViaAppDomain : {AppDomain.CurrentDomain.BaseDirectory}\");\n }\n}\n\n GetViaAssemblyCodeBase() private static string GetViaAssemblyCodeBase(Assembly assembly)\n{\n var codeBase = assembly.CodeBase;\n var uri = new UriBuilder(codeBase);\n return Uri.UnescapeDataString(uri.Path);\n}\n\n Hello from Library:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\nHello from Application:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
52,806
<p>As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.</p> <p>An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.</p> <p>Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (<code>Model-&gt;find()</code>, etc.), but I'm not sanguine about this.</p> <p>Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work...</p>
[ { "answer_id": 52814, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 2, "selected": false, "text": "SELECT entry-id, count(id) AS c \nFROM comment \nWHERE comment.createdate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) \nGROUP BY entry-id \nORDER BY c DESC\n" }, { "answer_id": 52838, "author": "Lost in Alabama", "author_id": 5285, "author_profile": "https://Stackoverflow.com/users/5285", "pm_score": 0, "selected": false, "text": "SELECT entry-id, count(id) AS c \nFROM comment \nWHERE comment_date + 30 >= sysdate\nGROUP BY entry-id \nORDER BY c DESC\n" }, { "answer_id": 52848, "author": "Daniel Wright", "author_id": 5030, "author_profile": "https://Stackoverflow.com/users/5030", "pm_score": 3, "selected": true, "text": "$this->loadModel('Comment');\n\n$this->Comment->find( 'all', array(\n 'fields' => array('COUNT(Comment.id) AS popularCount'),\n 'conditions' => array(\n 'Comment.created >' => strtotime('-1 month')\n ),\n 'group' => 'Comment.blog_post_id',\n 'order' => 'popularCount DESC',\n\n 'contain' => array(\n 'Entry' => array(\n 'fields' => array( 'Entry.title' )\n )\n )\n));\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5030/" ]
52,821
<pre><code>var e1 = new E1(); e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time context.e1s.imsertonsubmit(e1); context.submitchanges(); </code></pre>
[ { "answer_id": 52870, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 0, "selected": false, "text": "var e1 = new E1();\nvar e2 = new e2();\ne1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time\ncontext.e1s.insertonsubmit(e1);\ncontext.e2s.insertonsubmit(e2);\ncontext.submitchanges();\n" }, { "answer_id": 91471, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": false, "text": " MyDataContext mydc = new MyDataContext();\n System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions();\n lo.LoadWith<E1>(p => p.e2s);\n mydc.LoadOptions = lo;\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5236/" ]
52,822
<p>How can you import a foxpro DBF file in SQL Server?</p>
[ { "answer_id": 52828, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 5, "selected": true, "text": "SELECT * into SomeTable\nFROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;\nSourceDB=\\\\SomeServer\\SomePath\\;\nSourceType=DBF',\n'SELECT * FROM SomeDBF')\n" }, { "answer_id": 6346611, "author": "jnovation", "author_id": 798044, "author_profile": "https://Stackoverflow.com/users/798044", "pm_score": 2, "selected": false, "text": "select * from \n openrowset('VFPOLEDB','\\\\VM-GIS\\E\\Projects\\mymap.dbf';'';\n '','SELECT * FROM mymap')\n \\\\VM-GIS... mymap FROM" }, { "answer_id": 11973558, "author": "mark d", "author_id": 1601157, "author_profile": "https://Stackoverflow.com/users/1601157", "pm_score": 3, "selected": false, "text": "select * into CERTDATA\nfrom openrowset('VFPOLEDB','C:\\SomePath\\CERTDATA.DBF';'';\n '','SELECT ACTUAL, CERTID, FROM CERTDATA')\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
52,824
<p>Is it possible to merge to a branch that is not a direct parent or child in TFS? I suspect that the answer is no as this is what I've experienced while using it. However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one <strong>might</strong> be approved before feature two). This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.</p> <p>Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production. This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.</p> <p>What techniques can be used otherwise to mitigate a scenario such as the one(s) described above?</p>
[ { "answer_id": 52894, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "tf.exe merge /recursive /baseless $/TeamProject/SourceBranch $/TeamProject/TargetBranch\n" }, { "answer_id": 52909, "author": "Justin Dearing", "author_id": 3110, "author_profile": "https://Stackoverflow.com/users/3110", "pm_score": 5, "selected": true, "text": "Tf merge /baseless <<source path>> <<target path>> /recursive\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
52,842
<p><code>System.IO.Directory.GetFiles()</code> returns a <code>string[]</code>. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date? </p> <p><strong>Update:</strong> MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.</p>
[ { "answer_id": 52847, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": false, "text": "Dim Files() As String\nFiles = System.IO.Directory.GetFiles(\"C:\\\")\nArray.Sort(Files)\n" }, { "answer_id": 52865, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 2, "selected": false, "text": "IComparer comparer = new YourCustomComparer();\nArray.Sort(System.IO.Directory.GetFiles(), comparer);\n" }, { "answer_id": 52867, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 8, "selected": true, "text": "DirectoryInfo di = new DirectoryInfo(\"C:\\\\\");\nFileSystemInfo[] files = di.GetFileSystemInfos();\nvar orderedFiles = files.OrderBy(f => f.CreationTime);\n" }, { "answer_id": 149100, "author": "sebastiaan", "author_id": 5018, "author_profile": "https://Stackoverflow.com/users/5018", "pm_score": 4, "selected": false, "text": "Private Class DateComparer\n Implements System.Collections.IComparer\n\n Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare\n Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)\n Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)\n\n Dim Date1 As DateTime = FileInfo1.CreationTime\n Dim Date2 As DateTime = FileInfo2.CreationTime\n\n If Date1 > Date2 Then Return 1\n If Date1 < Date2 Then Return -1\n Return 0\n End Function\nEnd Class\n Dim DirectoryInfo As New System.IO.DirectoryInfo(\"C:\\\")\nDim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()\nDim comparer As IComparer = New DateComparer()\nArray.Sort(Files, comparer)\n" }, { "answer_id": 279142, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 4, "selected": false, "text": "DirectoryInfo dir = new DirectoryInfo(path);\nFileSystemInfo[] files = dir.GetFileSystemInfos();\n\n// sort them by creation time\nArray.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)\n {\n return a.LastWriteTime.CompareTo(b.LastWriteTime);\n });\n" }, { "answer_id": 2555123, "author": "Mehdi Anis", "author_id": 208325, "author_profile": "https://Stackoverflow.com/users/208325", "pm_score": 1, "selected": false, "text": "/O List by files in sorted order.\nsortorder N By name (alphabetic) S By size (smallest first)\n E By extension (alphabetic) D By date/time (oldest first)\n G Group directories first - Prefix to reverse order\n\nThe /S switch includes sub folders\n /t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField. \n\nValue Description \nc : Creation\na : Last access\nw : Last written\n" }, { "answer_id": 15544428, "author": "Simon Molloy", "author_id": 942604, "author_profile": "https://Stackoverflow.com/users/942604", "pm_score": 1, "selected": false, "text": "Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _\n New DirectoryInfo(\"c:\\temp\").GetFiles() _\n .OrderBy(Function(f As FileInfo) f.CreationTime)\nFor Each fi As IO.FileInfo In filePaths\n ' Do whatever you wish here\nNext\n" }, { "answer_id": 20548522, "author": "skeltech", "author_id": 3096197, "author_profile": "https://Stackoverflow.com/users/3096197", "pm_score": 2, "selected": false, "text": "For Each fi As IO.FileInfo In filePaths.reverse\n ' Do whatever you wish here\nNext\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
52,874
<p>I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.</p> <p>Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.</p> <p>Any ideas?</p>
[ { "answer_id": 52906, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 4, "selected": false, "text": "SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 );\n" }, { "answer_id": 52966, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 6, "selected": true, "text": "import java.awt.*;\nimport java.util.*;\npublic class Hal{\n\n public static void main(String[] args) throws Exception{\n Robot hal = new Robot();\n Random random = new Random();\n while(true){\n hal.delay(1000 * 60);\n int x = random.nextInt() % 640;\n int y = random.nextInt() % 480;\n hal.mouseMove(x,y);\n }\n }\n}\n" }, { "answer_id": 53276, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 2, "selected": false, "text": "import java.io.BufferedInputStream;\nimport java.io.IOException;\n\n/**\n * Disable sleep mode (record current setting beforehand), and re-enable sleep\n * mode. Works with Mac OS X using the \"pmset\" command.\n */\npublic class SleepSwitch {\n\n private int sleepTime = -1;\n\n public void disableSleep() throws IOException {\n if (sleepTime != -1) {\n // sleep time is already recorded, assume sleep is disabled\n return;\n }\n\n // query pmset for the current setting\n Process proc = Runtime.getRuntime().exec(\"pmset -g\");\n BufferedInputStream is = new BufferedInputStream(proc.getInputStream());\n StringBuffer output = new StringBuffer();\n int c;\n while ((c = is.read()) != -1) {\n output.append((char) c);\n }\n is.close();\n\n // parse the current setting and store the sleep time\n String outString = output.toString();\n String setting = outString.substring(outString.indexOf(\" sleep\\t\")).trim();\n setting = setting.substring(7, setting.indexOf(\" \")).trim();\n sleepTime = Integer.parseInt(setting);\n\n // set the sleep time to zero (disable sleep)\n Runtime.getRuntime().exec(\"pmset sleep 0\");\n }\n\n public void enableSleep() throws IOException {\n if (sleepTime == -1) {\n // sleep time is not recorded, assume sleep is enabled\n return;\n }\n\n // set the sleep time to the previously stored value\n Runtime.getRuntime().exec(\"pmset sleep \" + sleepTime);\n\n // reset the stored sleep time\n sleepTime = -1;\n }\n}\n" }, { "answer_id": 10280104, "author": "asloob", "author_id": 603125, "author_profile": "https://Stackoverflow.com/users/603125", "pm_score": 3, "selected": false, "text": "while(true){\n hal.delay(1000 * 30); \n Point pObj = MouseInfo.getPointerInfo().getLocation();\n System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y);\n hal.mouseMove(pObj.x + 1, pObj.y + 1); \n hal.mouseMove(pObj.x - 1, pObj.y - 1);\n pObj = MouseInfo.getPointerInfo().getLocation();\n System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y);\n }\n" }, { "answer_id": 19349044, "author": "Javier Carmona", "author_id": 2041804, "author_profile": "https://Stackoverflow.com/users/2041804", "pm_score": 1, "selected": false, "text": "while (true) {\n Thread.sleep(180000);//this is how long before it moves\n Point mouseLoc = MouseInfo.getPointerInfo().getLocation();\n Robot rob = new Robot();\n rob.mouseMove(mouseLoc.x, mouseLoc.y);\n}\n" }, { "answer_id": 30313322, "author": "ihatetoregister", "author_id": 517748, "author_profile": "https://Stackoverflow.com/users/517748", "pm_score": 2, "selected": false, "text": "caffeinate caffeinate" }, { "answer_id": 50833568, "author": "Santosh Jadi", "author_id": 3805521, "author_profile": "https://Stackoverflow.com/users/3805521", "pm_score": 0, "selected": false, "text": "public class Utils {\n public static void main(String[] args) throws AWTException {\n Robot rob = new Robot();\n PointerInfo ptr = null;\n while (true) {\n rob.delay(4000); // Mouse moves every 4 seconds\n ptr = MouseInfo.getPointerInfo();\n rob.mouseMove((int) ptr.getLocation().getX() + 1, (int) ptr.getLocation().getY() + 1);\n }\n }\n}\n" }, { "answer_id": 54684339, "author": "Anand Varkey Philips", "author_id": 3002336, "author_profile": "https://Stackoverflow.com/users/3002336", "pm_score": 2, "selected": false, "text": "@echo off\nsetlocal\n\nrem rem if JAVA is set and run from :startapp labeled section below, else the program exit through :end labeled section.\nif not \"[%JAVA_HOME%]\"==\"[]\" goto start_app\necho. JAVA_HOME not set. Application will not run!\ngoto end\n\n\n:start_app\necho. Using java in %JAVA_HOME%\nrem writes below code to Energy.java file.\n@echo import java.awt.MouseInfo; > Energy.java\n@echo import java.awt.Point; >> Energy.java\n@echo import java.awt.Robot; >> Energy.java\n@echo //Mouse Movement Simulation >> Energy.java\n@echo public class Energy { >> Energy.java\n@echo public static void main(String[] args) throws Exception { >> Energy.java\n@echo Robot energy = new Robot(); >> Energy.java\n@echo while (true) { >> Energy.java\n@echo energy.delay(1000 * 60); >> Energy.java\n@echo Point pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java\n@echo Point pObj2 = pObj; >> Energy.java\n@echo System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y); >> Energy.java\n@echo energy.mouseMove(pObj.x + 10, pObj.y + 10); >> Energy.java\n@echo energy.mouseMove(pObj.x - 10, pObj.y - 10); >> Energy.java\n@echo energy.mouseMove(pObj2.x, pObj.y); >> Energy.java\n@echo pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java\n@echo System.out.println(pObj.toString() + \"x>>\" + pObj.x + \" y>>\" + pObj.y); >> Energy.java\n@echo } >> Energy.java\n@echo } >> Energy.java\n@echo } >> Energy.java\n\nrem compile java code.\njavac Energy.java\nrem run java application in background.\nstart javaw Energy\necho. Your Secret Energy program is running...\ngoto end\n\n:end\nrem clean if files are created.\npause\ndel \"Energy.class\"\ndel \"Energy.java\"\n" }, { "answer_id": 56146892, "author": "maris", "author_id": 3853452, "author_profile": "https://Stackoverflow.com/users/3853452", "pm_score": -1, "selected": false, "text": "import java.util.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class NumLock extends Thread {\n public void run() {\n try {\n boolean flag = true;\n do {\n flag = !flag;\n\n Thread.sleep(6000);\n Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent. VK_NUM_LOCK, flag);\n }\n while(true);\n }\n catch(Exception e) {}\n }\n\n public static void main(String[] args) throws Exception {\n new NumLock().start();\n }\n}\n" }, { "answer_id": 65890299, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 3, "selected": false, "text": "import com.sun.jna.Native;\nimport com.sun.jna.Structure;\nimport com.sun.jna.Structure.FieldOrder;\nimport com.sun.jna.platform.win32.WTypes.LPWSTR;\nimport com.sun.jna.platform.win32.WinBase;\nimport com.sun.jna.platform.win32.WinDef.DWORD;\nimport com.sun.jna.platform.win32.WinDef.ULONG;\nimport com.sun.jna.platform.win32.WinNT.HANDLE;\nimport com.sun.jna.win32.StdCallLibrary;\n\n/**\n * Power management.\n *\n * @see <a href=\"https://stackoverflow.com/a/20996135/14731\">https://stackoverflow.com/a/20996135/14731</a>\n */\npublic enum PowerManagement\n{\n INSTANCE;\n\n @FieldOrder({\"version\", \"flags\", \"simpleReasonString\"})\n public static class REASON_CONTEXT extends Structure\n {\n public static class ByReference extends REASON_CONTEXT implements Structure.ByReference\n {\n }\n\n public ULONG version;\n public DWORD flags;\n public LPWSTR simpleReasonString;\n }\n\n private interface Kernel32 extends StdCallLibrary\n {\n HANDLE PowerCreateRequest(REASON_CONTEXT.ByReference context);\n\n /**\n * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n * @param requestType requestType is the ordinal value of {@link PowerRequestType}\n * @return true on success\n */\n boolean PowerSetRequest(HANDLE powerRequestHandle, int requestType);\n\n /**\n * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n * @param requestType requestType is the ordinal value of {@link PowerRequestType}\n * @return true on success\n */\n boolean PowerClearRequest(HANDLE powerRequestHandle, int requestType);\n\n enum PowerRequestType\n {\n PowerRequestDisplayRequired,\n PowerRequestSystemRequired,\n PowerRequestAwayModeRequired,\n PowerRequestMaximum\n }\n }\n\n private final Kernel32 kernel32;\n private HANDLE handle = null;\n\n PowerManagement()\n {\n // Found in winnt.h\n ULONG POWER_REQUEST_CONTEXT_VERSION = new ULONG(0);\n DWORD POWER_REQUEST_CONTEXT_SIMPLE_STRING = new DWORD(0x1);\n\n kernel32 = Native.load(\"kernel32\", Kernel32.class);\n REASON_CONTEXT.ByReference context = new REASON_CONTEXT.ByReference();\n context.version = POWER_REQUEST_CONTEXT_VERSION;\n context.flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;\n context.simpleReasonString = new LPWSTR(\"Your reason for changing the power setting\");\n handle = kernel32.PowerCreateRequest(context);\n if (handle == WinBase.INVALID_HANDLE_VALUE)\n throw new AssertionError(Native.getLastError());\n }\n\n /**\n * Prevent the computer from going to sleep while the application is running.\n */\n public void preventSleep()\n {\n if (!kernel32.PowerSetRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n throw new AssertionError(\"PowerSetRequest() failed\");\n }\n\n /**\n * Allow the computer to go to sleep.\n */\n public void allowSleep()\n {\n if (!kernel32.PowerClearRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n throw new AssertionError(\"PowerClearRequest() failed\");\n }\n}\n powercfg /requests SYSTEM:\n[PROCESS] \\Device\\HarddiskVolume1\\Users\\Gili\\.jdks\\openjdk-15.0.2\\bin\\java.exe\nYour reason for changing the power setting\n" }, { "answer_id": 67442227, "author": "Douglas Patriarche", "author_id": 92137, "author_profile": "https://Stackoverflow.com/users/92137", "pm_score": 2, "selected": false, "text": "import com.sun.jna.Library;\nimport com.sun.jna.Native;\nimport com.sun.jna.platform.mac.CoreFoundation;\nimport com.sun.jna.ptr.IntByReference;\n\npublic interface ExampleIOKit extends Library {\n ExampleIOKit INSTANCE = Native.load(\"IOKit\", ExampleIOKit.class);\n\n CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleSystemSleep = CoreFoundation.CFStringRef.createCFString(\"PreventUserIdleSystemSleep\");\n CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleDisplaySleep = CoreFoundation.CFStringRef.createCFString(\"PreventUserIdleDisplaySleep\");\n\n int kIOReturnSuccess = 0;\n\n int kIOPMAssertionLevelOff = 0;\n int kIOPMAssertionLevelOn = 255;\n\n int IOPMAssertionCreateWithName(CoreFoundation.CFStringRef assertionType,\n int assertionLevel,\n CoreFoundation.CFStringRef reasonForActivity,\n IntByReference assertionId);\n\n int IOPMAssertionRelease(int assertionId);\n}\n public class Example {\n private static final Logger _log = LoggerFactory.getLogger(Example.class);\n\n private int sleepPreventionAssertionId = 0;\n\n public void updateSleepPrevention(final boolean isEnabled) {\n if (isEnabled) {\n if (sleepPreventionAssertionId == 0) {\n final var assertionIdRef = new IntByReference(0);\n final var reason = CoreFoundation.CFStringRef.createCFString(\n \"Example preventing display sleep\");\n final int result = ExampleIOKit.INSTANCE.IOPMAssertionCreateWithName(\n ExampleIOKit.kIOPMAssertPreventUserIdleDisplaySleep,\n ExampleIOKit.kIOPMAssertionLevelOn, reason, assertionIdRef);\n if (result == ExampleIOKit.kIOReturnSuccess) {\n _log.info(\"Display sleep prevention enabled\");\n sleepPreventionAssertionId = assertionIdRef.getValue();\n }\n else {\n _log.error(\"IOPMAssertionCreateWithName returned {}\", result);\n }\n }\n }\n else {\n if (sleepPreventionAssertionId != 0) {\n final int result = ExampleIOKit.INSTANCE.IOPMAssertionRelease(sleepPreventionAssertionId);\n if (result == ExampleIOKit.kIOReturnSuccess) {\n _log.info(\"Display sleep prevention disabled\");\n }\n else {\n _log.error(\"IOPMAssertionRelease returned {}\", result);\n }\n sleepPreventionAssertionId = 0;\n }\n }\n }\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
52,880
<p>Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password?</p>
[ { "answer_id": 582108, "author": "jimmyorr", "author_id": 19239, "author_profile": "https://Stackoverflow.com/users/19239", "pm_score": 7, "selected": true, "text": "import urllib\nimport urllib2\n\nusername = '[email protected]'\npassword = '******'\n\n# Authenticate to obtain SID\nauth_url = 'https://www.google.com/accounts/ClientLogin'\nauth_req_data = urllib.urlencode({'Email': username,\n 'Passwd': password,\n 'service': 'reader'})\nauth_req = urllib2.Request(auth_url, data=auth_req_data)\nauth_resp = urllib2.urlopen(auth_req)\nauth_resp_content = auth_resp.read()\nauth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\\n') if x)\nauth_token = auth_resp_dict[\"Auth\"]\n\n# Create a cookie in the header using the SID \nheader = {}\nheader['Authorization'] = 'GoogleLogin auth=%s' % auth_token\n\nreader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'\nreader_req_data = urllib.urlencode({'all': 'true',\n 'output': 'xml'})\nreader_url = reader_base_url % (reader_req_data)\nreader_req = urllib2.Request(reader_url, None, header)\nreader_resp = urllib2.urlopen(reader_req)\nreader_resp_content = reader_resp.read()\n\nprint reader_resp_content\n" }, { "answer_id": 3517599, "author": "livibetter", "author_id": 242583, "author_profile": "https://Stackoverflow.com/users/242583", "pm_score": 3, "selected": false, "text": "import urllib\nimport urllib2\n\nusername = '[email protected]'\npassword = '******'\n\n# Authenticate to obtain Auth\nauth_url = 'https://www.google.com/accounts/ClientLogin'\n#auth_req_data = urllib.urlencode({'Email': username,\n# 'Passwd': password})\nauth_req_data = urllib.urlencode({'Email': username,\n 'Passwd': password,\n 'service': 'reader'})\nauth_req = urllib2.Request(auth_url, data=auth_req_data)\nauth_resp = urllib2.urlopen(auth_req)\nauth_resp_content = auth_resp.read()\nauth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\\n') if x)\n# SID = auth_resp_dict[\"SID\"]\nAUTH = auth_resp_dict[\"Auth\"]\n\n# Create a cookie in the header using the Auth\nheader = {}\n#header['Cookie'] = 'Name=SID;SID=%s;Domain=.google.com;Path=/;Expires=160000000000' % SID\nheader['Authorization'] = 'GoogleLogin auth=%s' % AUTH\n\nreader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'\nreader_req_data = urllib.urlencode({'all': 'true',\n 'output': 'xml'})\nreader_url = reader_base_url % (reader_req_data)\nreader_req = urllib2.Request(reader_url, None, header)\nreader_resp = urllib2.urlopen(reader_req)\nreader_resp_content = reader_resp.read()\n\nprint reader_resp_content\n service Auth Auth service=reader" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
52,883
<p>I'm looking for a graph algorithm with some unusual properties.</p> <p>Each edge in the graph is either an "up" edge or a "down" edge.</p> <p>A valid path can go an indefinite number of "up"'s followed by an indefinite number of "down"'s, or vice versa. However it cannot change direction more than once.</p> <p>E.g., a valid path might be A "up" B "up" C "down" E "down" F an invalid path might be A "up" B "down" C "up" D</p> <p>What is a good algorithm for finding the shortest valid path between two nodes? What about finding all of the equal length shortest paths?</p>
[ { "answer_id": 52920, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 5, "selected": true, "text": "UUUDDDD 3, 4" }, { "answer_id": 985840, "author": "ilya n.", "author_id": 115200, "author_profile": "https://Stackoverflow.com/users/115200", "pm_score": 1, "selected": false, "text": "Graph.shortest(from, to) [ (fst.shortest(A, C) + nxt.shortest(C, B)) \n for C in nodes , (fst, nxt) in [(up, down), (down, up)] ].reduce(min)\n [ [fst, nxt, C, fst.shortest(A, C), nxt.shortest(C,B)]\n for C in nodes , (fst, nxt) in [(up, down), (down, up)] ].reduce(myMin)\n myMin [fst, nxt, C, AC, BD] reduce" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
52,898
<p>I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.</p> <p>Example:</p> <p>Visual Studio:</p> <pre><code>SELECT [column1], [column2] etc... </code></pre> <p>My own way:</p> <pre><code>SELECT column1, column2 etc... </code></pre>
[ { "answer_id": 52901, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 9, "selected": true, "text": "[First Name]" }, { "answer_id": 52910, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 6, "selected": false, "text": "create table test ( id int, user varchar(20) )\n create table test ( id int, [user] varchar(20) )\n" }, { "answer_id": 52912, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 4, "selected": false, "text": "Select First Name From People\n Select [First Name] From People\n" }, { "answer_id": 65964158, "author": "zar", "author_id": 841330, "author_profile": "https://Stackoverflow.com/users/841330", "pm_score": 2, "selected": false, "text": "CREATE TABLE SchemaName.TableName (\n SchemaName.TableName dbo SchemaName CREATE TABLE [SchemaName].[TableName] (\n SchemaName dbo" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433/" ]
52,927
<p>I frequently find myself writing code like this:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; foreach (int i in list) { Console.Write("{0}\t", i.ToString()); } Console.WriteLine(); </code></pre> <p>Better would be something like this:</p> <pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; Console.WriteLine("{0}\t", list); </code></pre> <p>I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? </p>
[ { "answer_id": 52940, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": true, "text": "list.ForEach(i => Console.Write(\"{0}\\t\", i));\n" }, { "answer_id": 52941, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": " List<int> a = new List<int>() { 1, 2, 3, 4, 5 };\n a.ForEach(p => Console.WriteLine(p));\n" }, { "answer_id": 52942, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "list.ForEach(x=>Console.WriteLine(x));\n" }, { "answer_id": 52960, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 2, "selected": false, "text": "List<int> list = new List<int> { 1, 3, 5 };\nlist.ForEach(x => Console.WriteLine(x));\n" }, { "answer_id": 52972, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "Console.WriteLine(string.Join(\"\\t\", list));\n" }, { "answer_id": 65692, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "public static void WriteLine(this List<int> theList)\n{\n foreach (int i in list)\n {\n Console.Write(\"{0}\\t\", t.ToString());\n }\n Console.WriteLine();\n}\n list.WriteLine();\n" }, { "answer_id": 767963, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "new List<int> { 1, 3, 5 }.ForEach(Console.WriteLine);\n" }, { "answer_id": 949955, "author": "Ed Sykes", "author_id": 98551, "author_profile": "https://Stackoverflow.com/users/98551", "pm_score": 2, "selected": false, "text": "list.ForEach(i => Console.Write(\"{0}\\t\", i));\n public static void WriteLine(this List<int> theList)\n{\n foreach (int i in list)\n {\n Console.Write(\"{0}\\t\", t.ToString());\n }\n Console.WriteLine();\n}\n public static void WriteToConsole<T>(this IList<T> collection)\n{\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}\\t\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n}\n public static void WriteToConsole<T>(this IList<T> collection)\n{\n WriteToConsole<T>(collection, \"\\t\");\n}\n\npublic static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n{\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}{1}\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n}\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n public static class Extensions\n {\n public static void WriteToConsole<T>(this IList<T> collection)\n {\n WriteToConsole<T>(collection, \"\\t\");\n }\n\n public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n {\n int count = collection.Count();\n for(int i = 0; i < count; ++i)\n {\n Console.Write(\"{0}{1}\", collection[i].ToString(), delimiter);\n }\n Console.WriteLine();\n }\n }\n\n internal class Foo\n {\n override public string ToString()\n {\n return \"FooClass\";\n }\n }\n\n internal class Program\n {\n\n static void Main(string[] args)\n {\n var myIntList = new List<int> {1, 2, 3, 4, 5};\n var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};\n var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};\n // Using the standard delimiter /t\n myIntList.WriteToConsole();\n myDoubleList.WriteToConsole();\n myDoubleArray.WriteToConsole();\n myFooList.WriteToConsole();\n // Using our own delimiter ~\n myIntList.WriteToConsole(\"~\");\n Console.Read();\n }\n }\n}\n list.ForEach(i => Console.Write(\"{0}\\t\", i));\n public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)\n {\n int count = collection.Count();\n for (int i = 0; i < count; ++i)\n {\n actionToPerform(collection[i]); \n }\n Console.WriteLine();\n }\n public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n{\n collection.FastForEach(item => Console.Write(\"{0}{1}\", item.ToString(), delimiter));\n}\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n public static class Extensions\n {\n public static void WriteToConsole<T>(this IList<T> collection)\n {\n WriteToConsole<T>(collection, \"\\t\");\n }\n\n public static void WriteToConsole<T>(this IList<T> collection, string delimiter)\n {\n collection.FastForEach(item => Console.Write(\"{0}{1}\", item.ToString(), delimiter));\n }\n\n public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)\n {\n int count = collection.Count();\n for (int i = 0; i < count; ++i)\n {\n actionToPerform(collection[i]); \n }\n Console.WriteLine();\n }\n }\n\n internal class Foo\n {\n override public string ToString()\n {\n return \"FooClass\";\n }\n }\n\n internal class Program\n {\n\n static void Main(string[] args)\n {\n var myIntList = new List<int> {1, 2, 3, 4, 5};\n var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};\n var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};\n\n // Using the standard delimiter /t\n myIntList.WriteToConsole();\n myDoubleList.WriteToConsole();\n myDoubleArray.WriteToConsole();\n myFooList.WriteToConsole();\n\n // Using our own delimiter ~\n myIntList.WriteToConsole(\"~\");\n\n // What if we want to write them to separate lines?\n myIntList.FastForEach(item => Console.WriteLine(item.ToString()));\n Console.Read();\n }\n }\n}\n" }, { "answer_id": 15260381, "author": "Lev Lukomsky", "author_id": 406642, "author_profile": "https://Stackoverflow.com/users/406642", "pm_score": 1, "selected": false, "text": "var qwe = new List<int> {5, 2, 3, 8};\nConsole.WriteLine(string.Join(\"\\t\", qwe));\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593/" ]
52,950
<p>I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:</p> <p>before: <code>File.h</code></p> <p>after: <code>file.h</code></p> <p>I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?</p> <p><strong>[edit]</strong> I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.</p>
[ { "answer_id": 53116, "author": "MarkB", "author_id": 2996, "author_profile": "https://Stackoverflow.com/users/2996", "pm_score": 9, "selected": true, "text": "ignorecase [core] .git/config ignorecase = true git config core.ignorecase true\n git config --global core.ignorecase true\n" }, { "answer_id": 38288815, "author": "Andrew Arnott", "author_id": 46926, "author_profile": "https://Stackoverflow.com/users/46926", "pm_score": 4, "selected": false, "text": "git mv --cached name.txt NAME.TXT\n" }, { "answer_id": 64270783, "author": "FoxDeploy", "author_id": 1238413, "author_profile": "https://Stackoverflow.com/users/1238413", "pm_score": 2, "selected": false, "text": "git mv -f mynewapp.sln MyNewApp.sln" }, { "answer_id": 68185614, "author": "Matthew Barbara", "author_id": 3861691, "author_profile": "https://Stackoverflow.com/users/3861691", "pm_score": 0, "selected": false, "text": "git mv FileName fileNameTemp git mv fileNameTemp fileName" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
52,952
<p>So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch?</p>
[ { "answer_id": 299772, "author": "adparadox", "author_id": 1962, "author_profile": "https://Stackoverflow.com/users/1962", "pm_score": -1, "selected": false, "text": " /// <summary>\n /// Grabs the value from a specific datareader for a list of column names.\n /// </summary>\n /// <typeparam name=\"T\">Type of the value.</typeparam>\n /// <param name=\"reader\">Reader to grab data off of.</param>\n /// <param name=\"columnNames\">Column names that should be interrogated.</param>\n /// <returns>Value from the first correct column name or an exception if none of the columns exist.</returns>\n public static T GetColumnValue<T>(IDataReader reader, params string[] columnNames)\n {\n bool foundValue = false;\n T value = default(T);\n IndexOutOfRangeException lastException = null;\n\n foreach (string columnName in columnNames)\n {\n try\n {\n int ordinal = reader.GetOrdinal(columnName);\n value = (T)reader.GetValue(ordinal);\n foundValue = true;\n }\n catch (IndexOutOfRangeException ex)\n {\n lastException = ex;\n }\n }\n\n if (!foundValue)\n {\n string message = string.Format(\"Column(s) {0} could not be not found.\",\n string.Join(\", \", columnNames));\n\n throw new IndexOutOfRangeException(message, lastException);\n }\n\n return value;\n }\n" }, { "answer_id": 1271870, "author": "mrrrk", "author_id": 155791, "author_profile": "https://Stackoverflow.com/users/155791", "pm_score": 3, "selected": false, "text": " Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean\n For i As Integer = 0 To reader.FieldCount - 1\n If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True\n Next\n Return False\n End Function\n public static bool ReaderContainsColumn(IDataReader reader, string name)\n{\n for (int i = 0; i < reader.FieldCount; i++) {\n if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true; \n }\n return false;\n}\n" }, { "answer_id": 1271929, "author": "Tadmas", "author_id": 3750, "author_profile": "https://Stackoverflow.com/users/3750", "pm_score": 3, "selected": false, "text": "IDataReader.GetSchemaTable" }, { "answer_id": 1271952, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 0, "selected": false, "text": "DataTable dataTable = new DataTable();\ndataTable.Load(reader);\nforeach (var item in dataTable.Rows) \n{\n bool columnExists = item.Table.Columns.Contains(\"ColumnName\");\n}\n" }, { "answer_id": 22367187, "author": "Clement", "author_id": 552183, "author_profile": "https://Stackoverflow.com/users/552183", "pm_score": 2, "selected": false, "text": "Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == \"ColumnName\")\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
52,954
<p>Right now my ant task looks like.</p> <pre><code>&lt;javadoc sourcepath="${source}" destdir="${doc}"&gt; &lt;link href="http://java.sun.com/j2se/1.5.0/docs/api/" /&gt; &lt;/javadoc&gt; </code></pre> <p>And I'm getting this warning:</p> <pre><code>javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list </code></pre> <p>How do I get the javadoc to properly link to the API? I am behind a proxy.</p>
[ { "answer_id": 52973, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "ANT_OPTS=\"-Dhttp.proxyHost=proxy.y.com\" ant doc" }, { "answer_id": 54281, "author": "Rob Spieldenner", "author_id": 5118, "author_profile": "https://Stackoverflow.com/users/5118", "pm_score": 4, "selected": false, "text": "<arg value=\"-J-Dhttp.proxyHost=your.proxy.here\"/>\n<arg value=\"-J-Dhttp.proxyPort=##\"/>\n <javadoc sourcepath=\"${source}\" destdir=\"${doc}\">\n <link offline=\"true\" href=\"http://java.sun.com/j2se/1.5.0/docs/api/\" packagelistloc=\"path-containing-package-list\"/>\n</javadoc>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5118/" ]
52,964
<p>What is the best way to sort the results of a sql query into a random order within a stored procedure?</p>
[ { "answer_id": 52976, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 4, "selected": false, "text": "select foo from Bar order by newid()\n" }, { "answer_id": 52988, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 7, "selected": true, "text": "select top 1 * from mytable order by newid()\n SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;\n" }, { "answer_id": 3942379, "author": "endo64", "author_id": 333153, "author_profile": "https://Stackoverflow.com/users/333153", "pm_score": 3, "selected": false, "text": "SELECT * FROM a_table WHERE 0.01 >= CAST(CHECKSUM(NEWID(), a_column) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5466/" ]
52,984
<p>How do I setup an Ant task to generate <a href="http://emma.sourceforge.net" rel="noreferrer">Emma</a> code coverage reports?</p>
[ { "answer_id": 52994, "author": "Rob Spieldenner", "author_id": 5118, "author_profile": "https://Stackoverflow.com/users/5118", "pm_score": 5, "selected": true, "text": "<property file=\"build.properties\" />\n<property name=\"source\" location=\"src/main/java\" />\n<property name=\"test.source\" location=\"src/test/java\" />\n<property name=\"target.dir\" location=\"target\" />\n<property name=\"target\" location=\"${target.dir}/classes\" />\n<property name=\"test.target\" location=\"${target.dir}/test-classes\" />\n<property name=\"instr.target\" location=\"${target.dir}/instr-classes\" />\n <path id=\"compile.classpath\">\n <fileset dir=\"lib/main\">\n <include name=\"*.jar\" />\n </fileset>\n</path>\n\n<path id=\"test.compile.classpath\">\n <path refid=\"compile.classpath\" />\n <pathelement location=\"lib/test/junit-4.6.jar\" />\n <pathelement location=\"${target}\" />\n</path>\n\n<path id=\"junit.classpath\">\n <path refid=\"test.compile.classpath\" />\n <pathelement location=\"${test.target}\" />\n</path>\n <path id=\"emma.lib\" >\n <pathelement location=\"${emma.dir}/emma.jar\" />\n <pathelement location=\"${emma.dir}/emma_ant.jar\" />\n</path>\n <taskdef resource=\"emma_ant.properties\" classpathref=\"emma.lib\" />\n <target name=\"coverage.instrumentation\">\n <mkdir dir=\"${instr.target}\"/>\n <mkdir dir=\"${coverage}\"/>\n <emma>\n <instr instrpath=\"${target}\" destdir=\"${instr.target}\" metadatafile=\"${coverage}/metadata.emma\" mode=\"copy\">\n <filter excludes=\"*Test*\"/>\n </instr>\n </emma>\n <!-- Update the that will run the instrumented code -->\n <path id=\"test.classpath\">\n <pathelement location=\"${instr.target}\"/>\n <path refid=\"junit.classpath\"/>\n <pathelement location=\"${emma.dir}/emma.jar\"/>\n </path>\n</target>\n <jvmarg value=\"-Demma.coverage.out.file=${coverage}/coverage.emma\" />\n<jvmarg value=\"-Demma.coverage.out.merge=true\" />\n <target name=\"coverage.report\" depends=\"coverage.instrumentation\">\n <emma>\n <report sourcepath=\"${source}\" depth=\"method\">\n <fileset dir=\"${coverage}\" >\n <include name=\"*.emma\" />\n </fileset>\n <html outfile=\"${coverage}/coverage.html\" />\n </report>\n </emma>\n</target>\n" }, { "answer_id": 143208, "author": "wheleph", "author_id": 15647, "author_profile": "https://Stackoverflow.com/users/15647", "pm_score": 0, "selected": false, "text": "<emma>\n <ctl connect=\"${emma.rt.host}:${emma.rt.port}\" >\n <command name=\"coverage.get\" args=\"${emma.ec.file}\" />\n <command name=\"coverage.reset\" />\n </ctl>\n</emma>\n" }, { "answer_id": 201683, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<target> ant emma tests ant tests <target name=\"emma\" description=\"turns on EMMA instrumentation/reporting\" >\n <property name=\"emma.enabled\" value=\"true\" />\n <!-- EMMA instr class output directory: -->\n <property name=\"out.instr.dir\" value=\"${basedir}/outinstr\" />\n <mkdir dir=\"${out.instr.dir}\" />\n</target>\n\n<target name=\"run\" depends=\"init, compile\" description=\"runs the examples\" >\n <emma enabled=\"${emma.enabled}\" >\n <instr instrpathref=\"run.classpath\"\n destdir=\"${out.instr.dir}\" \n metadatafile=\"${coverage.dir}/metadata.emma\"\n merge=\"true\"\n />\n </emma>\n\n <!-- note from matt b: you could just as easily have a <junit> task here! -->\n <java classname=\"Main\" fork=\"true\" >\n <classpath>\n <pathelement location=\"${out.instr.dir}\" />\n <path refid=\"run.classpath\" />\n <path refid=\"emma.lib\" />\n </classpath> \n <jvmarg value=\"-Demma.coverage.out.file=${coverage.dir}/coverage.emma\" />\n <jvmarg value=\"-Demma.coverage.out.merge=true\" />\n </java>\n\n <emma enabled=\"${emma.enabled}\" >\n <report sourcepath=\"${src.dir}\" >\n <fileset dir=\"${coverage.dir}\" >\n <include name=\"*.emma\" />\n </fileset>\n\n <txt outfile=\"${coverage.dir}/coverage.txt\" />\n <html outfile=\"${coverage.dir}/coverage.html\" />\n </report>\n </emma>\n</target>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5118/" ]
52,989
<p>I have a generic Repository&lt;T&gt; class I want to use with an ObjectDataSource. Repository&lt;T&gt; lives in a separate project called DataAccess. According to <a href="http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/767f1a821d9b23da/b1e045958ae427a5?lnk=st#b1e045958ae427a5" rel="noreferrer">this post from the MS newsgroups</a> (relevant part copied below):</p> <blockquote> <p>Internally, the ObjectDataSource is calling Type.GetType(string) to get the type, so we need to follow the guideline documented in Type.GetType on how to get type using generics. You can refer to MSDN Library on Type.GetType:</p> <p><a href="http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx</a></p> <p>From the document, you will learn that you need to use backtick (`) to denotes the type name which is using generics.</p> <p>Also, here we must specify the assembly name in the type name string.</p> <p>So, for your question, the answer is to use type name like follows:</p> <p>TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"</p> </blockquote> <p>Okay, makes sense. When I try it, however, the page throws an exception:</p> <pre><code>&lt;asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" /&gt; </code></pre> <blockquote> <p>[InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]</p> </blockquote> <p>The curious thing is that this only happens when I'm viewing the page. When I open the "Configure Data Source" dialog from the VS2008 designer, it properly shows me the methods on my generic Repository class. Passing the TypeName string to Type.GetType() while debugging also returns a valid type. So what gives?</p>
[ { "answer_id": 53106, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 5, "selected": true, "text": "Type type = typeof(Repository<MessageCategory);\nstring assemblyQualifiedName = type.AssemblyQualifiedName;\n MyProject.Repository`1[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null\n" }, { "answer_id": 26492169, "author": "Philip Johnson", "author_id": 3365923, "author_profile": "https://Stackoverflow.com/users/3365923", "pm_score": 1, "selected": false, "text": "[DataObject]\npublic class DataAccessObject {\n private Repository<MessageCategory> _repository;\n\n // ctor omitted for clarity\n // ...\n\n [DataObjectMethod(DataObjectMethodType.Select)]\n public MessageCategory Get(int key) {\n return _repository.Get(key);\n }\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/52989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160/" ]
53,025
<p>I've been utilizing the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a> in my Flex projects, with asynchronous callback routes required between:</p> <ul> <li>whoever instantiated a given command object and the command object,</li> <li>the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.</li> </ul> <p>Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.</p> <p>Currently I have done this using <strong>callback function references</strong> with specific kinds of signatures, but I was wondering <em>if someone knew of a better (or an alternative) way?</em></p> <p>Here's an example to illustrate my current method:</p> <ul> <li>I might have a view object that spawns a <code>DeleteObjectCommand</code> instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say <code>"deleteObjectSuccessHandler()"</code> and <code>"deleteObjectFailureHandler()"</code> in this example) as callback function references to the command class's constructor.</li> <li>Then the command object would repeat this pattern with its connection to the "data access" object.</li> <li>When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its <code>deleteObjectSuccessHandler()</code> or <code>deleteObjectFailureHandler()</code> called.</li> </ul>
[ { "answer_id": 53743, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "RemoteObject HTTPService AsyncToken AsyncToken IResponder HTTPService send() AsyncToken ResultEvent.RESULT" }, { "answer_id": 53843, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": true, "text": "public function deleteThing( id : String ) : DeferredResponse {\n var deferredResponse : DeferredResponse = new DeferredResponse();\n\n var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);\n\n var result : Function = function( o : Object ) : void {\n deferredResponse.notifyResultListeners(o);\n }\n\n var fault : Function = function( o : Object ) : void {\n deferredResponse.notifyFaultListeners(o);\n }\n\n asyncToken.addResponder(new ClosureResponder(result, fault));\n\n return localAsyncToken;\n}\n DeferredResponse ClosureResponder AsyncToken DeferredResponse AsyncToken ClosureResponder IResponder result fault public function execute( ) : void {\n var deferredResponse : DeferredResponse = dao.deleteThing(\"3\");\n\n deferredResponse.addEventListener(ResultEvent.RESULT, onResult);\n deferredResponse.addEventListener(FaultEvent.FAULT, onFault);\n}\n execute" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4111/" ]
53,026
<p>I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema. I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.</p> <p>Any ideas?</p> <blockquote> <p>Reiterating again: Please don't answer I can write an application. I know that, And that is exactly what I'm trying to avoid.</p> </blockquote>
[ { "answer_id": 8827253, "author": "Jacob", "author_id": 181298, "author_profile": "https://Stackoverflow.com/users/181298", "pm_score": 6, "selected": true, "text": "select 'update [table name] set [xml field name] = ''' + \nconvert(varchar(max), [xml field name]) +\n''' where [primary key name] = ' + \nconvert(varchar(max), [primary key name]) from [table name]\n update thetable set thedata = '<root><name>Bob</name></root>' where thekey = 1\n" }, { "answer_id": 16287206, "author": "laktak", "author_id": 52817, "author_profile": "https://Stackoverflow.com/users/52817", "pm_score": 2, "selected": false, "text": "select 'update [table name] set [xml field name] = ''' + \nREPLACE(convert(varchar(max), [xml field name]), '''', '''''') +\n''' where [primary key name] = ' + \nconvert(varchar(max), [primary key name]) from [table name]\n" }, { "answer_id": 23250530, "author": "NightShovel", "author_id": 895218, "author_profile": "https://Stackoverflow.com/users/895218", "pm_score": 1, "selected": false, "text": "--Drop any previously existing objects, so we can run this multiple times.\nIF EXISTS (SELECT * FROM sysobjects WHERE Name = 'TableToUpdate')\n DROP TABLE TableToUpdate\nIF EXISTS (SELECT * FROM sysobjects WHERE Name = 'vw_TableToUpdate')\n DROP VIEW vw_TableToUpdate\n\n--Create our table with the XML column.\nCREATE TABLE TableToUpdate(\n Id INT NOT NULL CONSTRAINT Pk_TableToUpdate PRIMARY KEY CLUSTERED IDENTITY(1,1),\n XmlData XML NULL\n)\n\nGO\n\n--Create our view updatable view.\nCREATE VIEW dbo.vw_TableToUpdate\nAS\nSELECT\n Id,\n CONVERT(VARCHAR(MAX), XmlData) AS XmlText,\n XmlData\nFROM dbo.TableToUpdate\n\nGO\n\n--Create our trigger which takes the data keyed into a VARCHAR column and shims it into an XML format.\nCREATE TRIGGER TR_TableToView_Update\nON dbo.vw_TableToUpdate\nINSTEAD OF UPDATE\n\nAS\n\nSET NOCOUNT ON\n\nDECLARE\n@Id INT,\n@XmlText VARCHAR(MAX)\n\nDECLARE c CURSOR LOCAL STATIC FOR\nSELECT Id, XmlText FROM inserted\nOPEN c\n\nFETCH NEXT FROM c INTO @Id, @XmlText\nWHILE @@FETCH_STATUS = 0\nBEGIN\n /*\n Slight limitation here. We can't really do any error handling here because errors aren't really \"allowed\" in triggers.\n Ideally I would have liked to do a TRY/CATCH but meh.\n */\n UPDATE TableToUpdate\n SET\n XmlData = CONVERT(XML, @XmlText)\n WHERE\n Id = @Id\n\n FETCH NEXT FROM c INTO @Id, @XmlText\nEND\n\nCLOSE c\nDEALLOCATE c\n\nGO\n\n--Quick test before we go to SSMS\nINSERT INTO TableToUpdate(XmlData) SELECT '<Node1/>'\nUPDATE vw_TableToUpdate SET XmlText = '<Node1a/>'\nSELECT * FROM TableToUpdate\n" }, { "answer_id": 37735167, "author": "Vinnie Amir", "author_id": 5336001, "author_profile": "https://Stackoverflow.com/users/5336001", "pm_score": 2, "selected": false, "text": "SELECT XMLData FROM [YourTable]\nWHERE ID = @SomeID\n UPDATE [YourTable] SET XMLData = '<row><somefield1>Somedata</somefield1> \n </row>'\nWHERE ID = @SomeID\n" }, { "answer_id": 72232414, "author": "A P", "author_id": 1149580, "author_profile": "https://Stackoverflow.com/users/1149580", "pm_score": 0, "selected": false, "text": "ALTER TABLE [tablename]\nALTER COLUMN [columnname] varchar(max);\n ALTER TABLE [tablename]\nALTER COLUMN [columnname] XML;\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
53,041
<p>Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs</p> <p>Does anyone know for sure where these come from, and what they are used for?</p>
[ { "answer_id": 53048, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "Project" }, { "answer_id": 53050, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 5, "selected": true, "text": "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"ConsoleSandbox\", \"ConsoleSandbox\\ConsoleSandbox.csproj\", \"{55A1FD06-FB00-4F8A-9153-C432357F5CAC}\"\n GlobalSection(ProjectConfigurationPlatforms) = postSolution\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU\n {55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.Build.0 = Release|Any CPU\nEndGlobalSection\n Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"ConsoleSandbox\", \"ConsoleSandbox\\ConsoleSandbox.csproj\", \"{55A1FD06-FB00-4F8A-9153-C432357F5CAC}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Composite\", \"..\\CompositeWPF\\Source\\CAL\\Composite\\Composite.csproj\", \"{77138947-1D13-4E22-AEE0-5D0DD046CA34}\"\nEndProject\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
53,046
<p>In python, there are some special variables and filenames that are surrounded by double-underscores. For example, there is the</p> <pre><code>__file__ </code></pre> <p>variable. I am only able to get them to show up correctly inside of a code block. What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis?</p>
[ { "answer_id": 53052, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 6, "selected": true, "text": "\\__file__\n" }, { "answer_id": 53054, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 3, "selected": false, "text": "__file_\\_\n" }, { "answer_id": 54594, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "&#95;" }, { "answer_id": 7545179, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "`*" }, { "answer_id": 54740109, "author": "WAN QIAN", "author_id": 9229077, "author_profile": "https://Stackoverflow.com/users/9229077", "pm_score": 0, "selected": false, "text": "_\\_file__" }, { "answer_id": 55482838, "author": "Fouzi TAKELAIT", "author_id": 7916257, "author_profile": "https://Stackoverflow.com/users/7916257", "pm_score": 3, "selected": false, "text": "\\_\\_file\\_\\_\n" }, { "answer_id": 65333812, "author": "NachtgeistW", "author_id": 11090451, "author_profile": "https://Stackoverflow.com/users/11090451", "pm_score": 3, "selected": false, "text": "\\_\\_main.py__\n __main.py__\n `__main.py__`\n __main.py__" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
53,057
<p>When I drag &amp; drop a dll to the assembly folder on vista, I get the error "Access is denied: mydll.dll". How can I bypass the error message and add my dll to gac?</p>
[ { "answer_id": 74013, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 0, "selected": false, "text": "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
53,069
<p>I am writing a DDL script to drop a number of tables but need to identify all dependencies for those tables first. Those dependencies include foreign key constraints, stored procedures, views, etc. Preferably, I want to programmatically script out dropping those dependencies using the system tables/views before dropping the dependent table.</p>
[ { "answer_id": 53092, "author": "Almond", "author_id": 1603, "author_profile": "https://Stackoverflow.com/users/1603", "pm_score": -1, "selected": false, "text": "USE AdventureWorks\nGO\nEXEC sp_depends @objname = N'Sales.Customer' ;" }, { "answer_id": 1010628, "author": "glasnt", "author_id": 124019, "author_profile": "https://Stackoverflow.com/users/124019", "pm_score": 0, "selected": false, "text": "sysreferences select 'if exists (select name from sysobjects where name = '''+c.name+''') '\n+' alter table ' + t.name +' drop constraint '+ c.name \n from sysreferences sbr, sysobjects c, sysobjects t, sysobjects r\n where c.id = constrid \n and t.id = tableid \n and reftabid = r.id\n and r.name = 'my_table'\n drop constraint" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
53,086
<p>Is the return value of GetHashCode() guaranteed to be consistent assuming the same string value is being used? (C#/ASP.NET)</p> <p>I uploaded my code to a server today and to my surprise I had to reindex some data because my server (win2008 64-bit) was returning different values compared to my desktop computer.</p>
[ { "answer_id": 835571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": " /// <summary>\n /// Similar to String.GetHashCode but returns the same as the x86 version of String.GetHashCode for x64 and x86 frameworks.\n /// </summary>\n /// <param name=\"s\"></param>\n /// <returns></returns>\n public static unsafe int GetHashCode32(string s)\n {\n fixed (char* str = s.ToCharArray())\n {\n char* chPtr = str;\n int num = 0x15051505;\n int num2 = num;\n int* numPtr = (int*)chPtr;\n for (int i = s.Length; i > 0; i -= 4)\n {\n num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];\n if (i <= 2)\n {\n break;\n }\n num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];\n numPtr += 2;\n }\n return (num + (num2 * 0x5d588b65));\n }\n }\n" }, { "answer_id": 18352165, "author": "Sasha", "author_id": 91495, "author_profile": "https://Stackoverflow.com/users/91495", "pm_score": 0, "selected": false, "text": " /// <summary>\n /// Default implementation of string.GetHashCode is not consistent on different platforms (x32/x64 which is our case) and frameworks. \n /// FNV-1a - (Fowler/Noll/Vo) is a fast, consistent, non-cryptographic hash algorithm with good dispersion. (see http://isthe.com/chongo/tech/comp/fnv/#FNV-1a)\n /// </summary>\n private static int GetFNV1aHashCode(string str)\n {\n if (str == null)\n return 0;\n var length = str.Length;\n // original FNV-1a has 32 bit offset_basis = 2166136261 but length gives a bit better dispersion (2%) for our case where all the strings are equal length, for example: \"3EC0FFFF01ECD9C4001B01E2A707\"\n int hash = length;\n for (int i = 0; i != length; ++i)\n hash = (hash ^ str[i]) * 16777619;\n return hash;\n }\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
53,102
<p>From the <em>Immediate Window</em> in Visual Studio: </p> <pre><code>&gt; Path.Combine(@"C:\x", "y") "C:\\x\\y" &gt; Path.Combine(@"C:\x", @"\y") "\\y" </code></pre> <p>It seems that they should both be the same. </p> <p>The old FileSystemObject.BuildPath() didn't work this way...</p>
[ { "answer_id": 53110, "author": "elarson", "author_id": 5434, "author_profile": "https://Stackoverflow.com/users/5434", "pm_score": 2, "selected": false, "text": "urljoin('/some/abs/path', '../other') = '/some/abs/other'\n" }, { "answer_id": 53118, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 9, "selected": true, "text": "public static String Combine(String path1, String path2) {\n if (path1==null || path2==null)\n throw new ArgumentNullException((path1==null) ? \"path1\" : \"path2\");\n Contract.EndContractBlock();\n CheckInvalidPathChars(path1);\n CheckInvalidPathChars(path2);\n\n return CombineNoChecks(path1, path2);\n}\n\ninternal static string CombineNoChecks(string path1, string path2)\n{\n if (path2.Length == 0)\n return path1;\n\n if (path1.Length == 0)\n return path2;\n\n if (IsPathRooted(path2))\n return path2;\n\n char ch = path1[path1.Length - 1];\n if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&\n ch != VolumeSeparatorChar) \n return path1 + DirectorySeparatorCharAsString + path2;\n return path1 + path2;\n}\n" }, { "answer_id": 53122, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": false, "text": "public static string Combine(string path1, string path2)\n{\n if ((path1 == null) || (path2 == null))\n {\n throw new ArgumentNullException((path1 == null) ? \"path1\" : \"path2\");\n }\n CheckInvalidPathChars(path1);\n CheckInvalidPathChars(path2);\n if (path2.Length == 0)\n {\n return path1;\n }\n if (path1.Length == 0)\n {\n return path2;\n }\n if (IsPathRooted(path2))\n {\n return path2;\n }\n char ch = path1[path1.Length - 1];\n if (((ch != DirectorySeparatorChar) &&\n (ch != AltDirectorySeparatorChar)) &&\n (ch != VolumeSeparatorChar))\n {\n return (path1 + DirectorySeparatorChar + path2);\n }\n return (path1 + path2);\n}\n\n\npublic static bool IsPathRooted(string path)\n{\n if (path != null)\n {\n CheckInvalidPathChars(path);\n int length = path.Length;\n if (\n (\n (length >= 1) &&\n (\n (path[0] == DirectorySeparatorChar) ||\n (path[0] == AltDirectorySeparatorChar)\n )\n )\n\n ||\n\n ((length >= 2) &&\n (path[1] == VolumeSeparatorChar))\n )\n {\n return true;\n }\n }\n return false;\n}\n" }, { "answer_id": 24823642, "author": "Ferri", "author_id": 3780016, "author_profile": "https://Stackoverflow.com/users/3780016", "pm_score": 2, "selected": false, "text": "?Path.Combine(@\"C:\\test\", @\"\\test\".Substring(0, 1) == @\"\\\" ? @\"\\test\".Substring(1, @\"\\test\".Length - 1) : @\"\\test\");\n string Path1 = @\"C:\\Test\";\nstring Path2 = @\"\\test\";\nstring FullPath = Path.Combine(Path1, Path2.IsRooted() ? Path2.Substring(1, Path2.Length - 1) : Path2);\n" }, { "answer_id": 27271258, "author": "The King", "author_id": 733566, "author_profile": "https://Stackoverflow.com/users/733566", "pm_score": 3, "selected": false, "text": " string strFinalPath = string.Empty;\n string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\\\' });\n string normalizedSecondPath = Path2.TrimStart(new char[] { '\\\\' });\n strFinalPath = Path.Combine(normalizedFirstPath, normalizedSecondPath);\n return strFinalPath;\n" }, { "answer_id": 31131504, "author": "anhoppe", "author_id": 1178267, "author_profile": "https://Stackoverflow.com/users/1178267", "pm_score": 5, "selected": false, "text": "string sample1 = \"configuration/config.xml\";\nstring sample2 = \"/configuration/config.xml\";\nstring sample3 = \"\\\\configuration/config.xml\";\n\nstring dir1 = \"c:\\\\temp\";\nstring dir2 = \"c:\\\\temp\\\\\";\nstring dir3 = \"c:\\\\temp/\";\n\nstring path1 = PathCombine(dir1, sample1);\nstring path2 = PathCombine(dir1, sample2);\nstring path3 = PathCombine(dir1, sample3);\n\nstring path4 = PathCombine(dir2, sample1);\nstring path5 = PathCombine(dir2, sample2);\nstring path6 = PathCombine(dir2, sample3);\n\nstring path7 = PathCombine(dir3, sample1);\nstring path8 = PathCombine(dir3, sample2);\nstring path9 = PathCombine(dir3, sample3);\n private string PathCombine(string path1, string path2)\n{\n if (Path.IsPathRooted(path2))\n {\n path2 = path2.TrimStart(Path.DirectorySeparatorChar);\n path2 = path2.TrimStart(Path.AltDirectorySeparatorChar);\n }\n\n return Path.Combine(path1, path2);\n}\n" }, { "answer_id": 41615722, "author": "marsze", "author_id": 2060966, "author_profile": "https://Stackoverflow.com/users/2060966", "pm_score": 2, "selected": false, "text": "string GetFullPath(string path)\n{\n string baseDir = @\"C:\\Users\\Foo.Bar\";\n return Path.Combine(baseDir, path);\n}\n\n// Get full path for RELATIVE file path\nGetFullPath(\"file.txt\"); // = C:\\Users\\Foo.Bar\\file.txt\n\n// Get full path for ROOTED file path\nGetFullPath(@\"C:\\Temp\\file.txt\"); // = C:\\Temp\\file.txt\n \"\\\" new FileInfo(\"\\windows\"); // FullName = C:\\Windows, Exists = True\nnew FileInfo(\"windows\"); // FullName = C:\\Users\\Foo.Bar\\Windows, Exists = False\n" }, { "answer_id": 43507984, "author": "ergohack", "author_id": 4151626, "author_profile": "https://Stackoverflow.com/users/4151626", "pm_score": 3, "selected": false, "text": "public static class Pathy\n{\n public static string Combine(string path1, string path2)\n {\n if (path1 == null) return path2\n else if (path2 == null) return path1\n else return path1.Trim().TrimEnd(System.IO.Path.DirectorySeparatorChar)\n + System.IO.Path.DirectorySeparatorChar\n + path2.Trim().TrimStart(System.IO.Path.DirectorySeparatorChar);\n }\n\n public static string Combine(string path1, string path2, string path3)\n {\n return Combine(Combine(path1, path2), path3);\n }\n}\n Pathy System.IO.Path" }, { "answer_id": 45443974, "author": "Don Rolling", "author_id": 441862, "author_profile": "https://Stackoverflow.com/users/441862", "pm_score": 0, "selected": false, "text": " public static string Combine(string x, string y, char delimiter) {\n return $\"{ x.TrimEnd(delimiter) }{ delimiter }{ y.TrimStart(delimiter) }\";\n }\n\n public static string Combine(string[] xs, char delimiter) {\n if (xs.Length < 1) return string.Empty;\n if (xs.Length == 1) return xs[0];\n var x = Combine(xs[0], xs[1], delimiter);\n if (xs.Length == 2) return x;\n var ys = new List<string>();\n ys.Add(x);\n ys.AddRange(xs.Skip(2).ToList());\n return Combine(ys.ToArray(), delimiter);\n }\n" }, { "answer_id": 50339209, "author": "Arad", "author_id": 7734384, "author_profile": "https://Stackoverflow.com/users/7734384", "pm_score": 3, "selected": false, "text": "Combine / /SecondPath SecondPath" }, { "answer_id": 58023547, "author": "LazZiya", "author_id": 5519026, "author_profile": "https://Stackoverflow.com/users/5519026", "pm_score": 2, "selected": false, "text": "public class MyPath \n{\n public static string ForceCombine(params string[] paths)\n {\n return paths.Aggregate((x, y) => Path.Combine(x, y.TrimStart('\\\\')));\n }\n}\n" }, { "answer_id": 59379466, "author": "ilias iliadis", "author_id": 2362556, "author_profile": "https://Stackoverflow.com/users/2362556", "pm_score": 0, "selected": false, "text": "\\ cd D: D:\\ @\"\\x\" Path.Combine(@\"C:\\x\", @\"\\y\") \"\\\\y\" >cd C:\n>cd \\mydironC\\apath\n>cd D:\n>cd \\mydironD\\bpath\n>cd C:\n>cd\n>C:\\mydironC\\apath\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
53,108
<p>I have a table similar to this:</p> <pre><code>CREATE TABLE example ( id integer primary key, name char(200), parentid integer, value integer); </code></pre> <p>I can use the parentid field to arrange data into a tree structure.</p> <p>Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?</p> <p><strong>UPDATE:</strong> I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.</p> <p>BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow!</p>
[ { "answer_id": 53137, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "select \n lpad(' ',2*(level-1)) || to_char(child) s\n\nfrom \n test_connect_by \n\nstart with parent is null\nconnect by prior child = parent;\n" }, { "answer_id": 54362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "create or replace function example_subtree (integer)\nreturns setof example as\n'declare results record;\n child record;\n begin\n select into results * from example where parent_id = $1;\n if found then\n return next results;\n for child in select id from example\n where parent_id = $1\n loop\n for temp in select * from example_subtree(child.id)\n loop\n return next temp;\n end loop;\n end loop;\n end if;\n return null;\nend;' language 'plpgsql';\n\nselect sum(value) as value_sum\n from example_subtree(1234);\n" }, { "answer_id": 548619, "author": "Chris KL", "author_id": 58110, "author_profile": "https://Stackoverflow.com/users/58110", "pm_score": 5, "selected": false, "text": "WITH" }, { "answer_id": 656309, "author": "Dr.Pil", "author_id": 74881, "author_profile": "https://Stackoverflow.com/users/74881", "pm_score": 1, "selected": false, "text": "WITH RECURSIVE" }, { "answer_id": 4659750, "author": "Quassnoi", "author_id": 55159, "author_profile": "https://Stackoverflow.com/users/55159", "pm_score": 3, "selected": false, "text": "SQL CTE PostgreSQL 8.4 CREATE FUNCTION fn_hierarchy (parent INT)\nRETURNS SETOF example\nAS\n$$\n SELECT example\n FROM example\n WHERE id = $1\n UNION ALL\n SELECT fn_hierarchy(id)\n FROM example\n WHERE parentid = $1\n$$\nLANGUAGE 'sql';\n\nSELECT *\nFROM fn_hierarchy(1)\n" }, { "answer_id": 5701124, "author": "Endy Tjahjono", "author_id": 196451, "author_profile": "https://Stackoverflow.com/users/196451", "pm_score": 5, "selected": false, "text": "with recursive sumthis(id, val) as (\n select id, value\n from example\n where id = :selectedid\n union all\n select C.id, C.value\n from sumthis P\n inner join example C on P.id = C.parentid\n)\nselect sum(val) from sumthis\n sumthis id val union all select where id = :selectedid select" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
53,112
<p>What are good ways of dealing with the issues surrounding plugin code that interacts with outside system?</p> <p>To give a concrete and representative example, suppose I would like to use Subversion and Eclipse to develop plugins for WordPress. The main code body of WordPress is installed on the webserver, and the plugin code needs to be available in a subdirectory of that server.</p> <p>I could see how you could simply checkout a copy of your code directly under the web directory on a development machine, but how would you also then integrate this with the IDE?</p> <p>I am making the assumption here that all the code for the plugin is located under a single directory.</p> <p>Do most people just add the plugin as a project in an IDE and then place the working folder for the project wherever the 'main' software system wants it to be? Or do people use some kind of symlinks to their home directory?</p>
[ { "answer_id": 53137, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "select \n lpad(' ',2*(level-1)) || to_char(child) s\n\nfrom \n test_connect_by \n\nstart with parent is null\nconnect by prior child = parent;\n" }, { "answer_id": 54362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "create or replace function example_subtree (integer)\nreturns setof example as\n'declare results record;\n child record;\n begin\n select into results * from example where parent_id = $1;\n if found then\n return next results;\n for child in select id from example\n where parent_id = $1\n loop\n for temp in select * from example_subtree(child.id)\n loop\n return next temp;\n end loop;\n end loop;\n end if;\n return null;\nend;' language 'plpgsql';\n\nselect sum(value) as value_sum\n from example_subtree(1234);\n" }, { "answer_id": 548619, "author": "Chris KL", "author_id": 58110, "author_profile": "https://Stackoverflow.com/users/58110", "pm_score": 5, "selected": false, "text": "WITH" }, { "answer_id": 656309, "author": "Dr.Pil", "author_id": 74881, "author_profile": "https://Stackoverflow.com/users/74881", "pm_score": 1, "selected": false, "text": "WITH RECURSIVE" }, { "answer_id": 4659750, "author": "Quassnoi", "author_id": 55159, "author_profile": "https://Stackoverflow.com/users/55159", "pm_score": 3, "selected": false, "text": "SQL CTE PostgreSQL 8.4 CREATE FUNCTION fn_hierarchy (parent INT)\nRETURNS SETOF example\nAS\n$$\n SELECT example\n FROM example\n WHERE id = $1\n UNION ALL\n SELECT fn_hierarchy(id)\n FROM example\n WHERE parentid = $1\n$$\nLANGUAGE 'sql';\n\nSELECT *\nFROM fn_hierarchy(1)\n" }, { "answer_id": 5701124, "author": "Endy Tjahjono", "author_id": 196451, "author_profile": "https://Stackoverflow.com/users/196451", "pm_score": 5, "selected": false, "text": "with recursive sumthis(id, val) as (\n select id, value\n from example\n where id = :selectedid\n union all\n select C.id, C.value\n from sumthis P\n inner join example C on P.id = C.parentid\n)\nselect sum(val) from sumthis\n sumthis id val union all select where id = :selectedid select" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
53,128
<p>I have a webapp that uses JNDI lookups to get a connection to the database.</p> <p>The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.</p> <p>Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.</p> <pre><code>public class DatabaseBean { private static final Logger logger = Logger.getLogger(DatabaseBean.class); private Connection conn; private PreparedStatement prepStmt; /** * Zero argument constructor * Setup generic databse connection in here to avoid redundancy * The connection details are in /META-INF/context.xml */ public DatabaseBean() { try { InitialContext initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite"); conn = ds.getConnection(); } catch (SQLException SQLEx) { logger.fatal("There was a problem with the database connection."); logger.fatal(SQLEx); logger.fatal(SQLEx.getCause()); } catch (NamingException nameEx) { logger.fatal("There was a naming exception"); logger.fatal(nameEx); logger.fatal(nameEx.getCause()); } } /** * Execute a query. Do not use for statements (update delete insert etc). * * @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null. * @see #executeUpdate() for running update, insert delete etc. */ public ResultSet executeQuery() { ResultSet result = null; try { result = prepStmt.executeQuery(); logger.debug(prepStmt.toString()); } catch (SQLException SQLEx) { logger.fatal("There was an error running a query"); logger.fatal(SQLEx); } return result; } </code></pre> <p><em>SNIP</em></p> <pre><code>public void close() { try { prepStmt.close(); prepStmt = null; conn.close(); conn = null; } catch (SQLException SQLEx) { logger.warn("There was an error closing the database connection."); } } } </code></pre> <p>This is inside a javabean that uses the database connection.</p> <pre><code>public LinkedList&lt;ImportantNoticeBean&gt; getImportantNotices() { DatabaseBean noticesDBBean = new DatabaseBean(); LinkedList&lt;ImportantNoticeBean&gt; listOfNotices = new LinkedList&lt;ImportantNoticeBean&gt;(); try { PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " + "FROM importantnotices, users " + "WHERE importantnotices.username = users.username " + "AND NOW() &gt;= date_from AND NOW() &lt;= date_to;"); noticesDBBean.setPrepStmt(preStmt); ResultSet result = noticesDBBean.executeQuery(); while (result.next()) { ImportantNoticeBean noticeBean = new ImportantNoticeBean(); noticeBean.setAuthor(result.getString("pseudonym")); noticeBean.setMessage(result.getString("message")); noticeBean.setDateTo(result.getDate("date_to")); noticeBean.setDateFrom(result.getDate("date_from")); listOfNotices.add(noticeBean); } result.close(); } catch (SQLException SQLEx) { logger.error("There was an error in ImportantNoticesBean.getImportantNotices()"); logger.error(SQLEx); } finally { noticesDBBean.close(); } return listOfNotices; } &lt;Context reloadable="true"&gt; &lt;Resource name="jdbc/mysite" auth="Container" type="javax.sql.DataSource" username="user" password="password" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mysite" maxActive="10" maxIdle="5" maxWait="6000" removeAbandoned="true" logAbandoned="false" removeAbandonedTimeout="20" /&gt; &lt;/Context&gt; </code></pre>
[ { "answer_id": 54095, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 2, "selected": false, "text": "* Jakarta-Commons DBCP\n* Jakarta-Commons Collections\n* Jakarta-Commons Pool\n testWhileIdle=true\ntimeBetweenEvictionRunsMillis=300000\n" }, { "answer_id": 58778, "author": "Doug Miller", "author_id": 3431280, "author_profile": "https://Stackoverflow.com/users/3431280", "pm_score": 2, "selected": false, "text": "*SNIP*\nmaxActive=\"10\"\nmaxIdle=\"5\"\nmaxWait=\"7000\"\nremoveAbandoned=\"true\"\nlogAbandoned=\"false\"\nremoveAbandonedTimeout=\"3\"\n*SNIP*\n" }, { "answer_id": 1085473, "author": "Igor Zelaya", "author_id": 22769, "author_profile": "https://Stackoverflow.com/users/22769", "pm_score": 0, "selected": false, "text": " defaultAutoCommit=\"false\"\n defaultTransactionIsolation=\"REPEATABLE_READ\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n logAbandoned=\"true\" \n removeAbandoned=\"true\"\n removeAbandonedTimeout=\"300\" \n maxActive=\"-1\"\n initialSize=\"15\"\n maxIdle=\"10\"\n maxWait=\"10000\" \n username=\"youruser\"\n password=\"youruserpassword\"\n driverClassName=\"com.mysql.jdbc.Driver\"\n url=\"jdbc:mysql://yourhost/yourdatabase\"/>\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431280/" ]
53,135
<p>I know that we shouldn't being using the registry to store Application Data anymore, but in updating a Legacy application (and wanting to do the fewest changes), what Registry Hives are non-administrators allowed to use? </p> <p>Can I access all of <code>HKEY_CURRENT_USER</code> (the application currently access <code>HKEY_LOCAL_MACHINE</code>) without Administrator privileges? </p>
[ { "answer_id": 53181, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 8, "selected": true, "text": "HKEY_CURRENT_USER HKEY_LOCAL_MACHINE HKEY_CLASSES_ROOT HKEY_LOCAL_MACHINE\\Software\\Classes HKEY_CURRENT_USER HKEY_CURRENT_USER\\Software\\YourCompany\\YourProduct\\ HKEY_LOCAL_MACHINE Program files Windows %USERPROFILE% HKEY_CURRENT_CONFIG" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
53,161
<p>what I'm after is something I can feed a number into and it will return the highest order bit. I'm sure there's a simple way. Below is an example output (left is the input)</p> <pre>1 -> 1 2 -> 2 3 -> 2 4 -> 4 5 -> 4 6 -> 4 7 -> 4 8 -> 8 9 -> 8 ... 63 -> 32</pre>
[ { "answer_id": 53174, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": false, "text": "int highest_order_bit( int x )\n{\n int y = x;\n do { \n x = y;\n y = x & (x-1); //remove low order bit\n }\n while( y != 0 );\n return x;\n}\n" }, { "answer_id": 53175, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 6, "selected": true, "text": "int hob (int num)\n{\n if (!num)\n return 0;\n\n int ret = 1;\n\n while (num >>= 1)\n ret <<= 1;\n\n return ret;\n}\n" }, { "answer_id": 53184, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": false, "text": "int hibit(unsigned int n) {\n n |= (n >> 1);\n n |= (n >> 2);\n n |= (n >> 4);\n n |= (n >> 8);\n n |= (n >> 16);\n return n - (n >> 1);\n}\n" }, { "answer_id": 53298, "author": "Ben Lever", "author_id": 2045, "author_profile": "https://Stackoverflow.com/users/2045", "pm_score": 2, "selected": false, "text": "int highest_order_bit(int x)\n{\n static const int msb_lut[256] =\n {\n 0, 0, 1, 1, 2, 2, 2, 2, // 0000_0000 - 0000_0111\n 3, 3, 3, 3, 3, 3, 3, 3, // 0000_1000 - 0000_1111\n 4, 4, 4, 4, 4, 4, 4, 4, // 0001_0000 - 0001_0111\n 4, 4, 4, 4, 4, 4, 4, 4, // 0001_1000 - 0001_1111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0010_0000 - 0010_0111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0010_1000 - 0010_1111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0011_0000 - 0011_0111\n 5, 5, 5, 5, 5, 5, 5, 5, // 0011_1000 - 0011_1111\n\n 6, 6, 6, 6, 6, 6, 6, 6, // 0100_0000 - 0100_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0100_1000 - 0100_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0101_0000 - 0101_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0101_1000 - 0101_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0110_0000 - 0110_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0110_1000 - 0110_1111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0111_0000 - 0111_0111\n 6, 6, 6, 6, 6, 6, 6, 6, // 0111_1000 - 0111_1111\n\n 7, 7, 7, 7, 7, 7, 7, 7, // 1000_0000 - 1000_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1000_1000 - 1000_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1001_0000 - 1001_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1001_1000 - 1001_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1010_0000 - 1010_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1010_1000 - 1010_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1011_0000 - 1011_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1011_1000 - 1011_1111\n\n 7, 7, 7, 7, 7, 7, 7, 7, // 1100_0000 - 1100_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1100_1000 - 1100_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1101_0000 - 1101_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1101_1000 - 1101_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1110_0000 - 1110_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1110_1000 - 1110_1111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1111_0000 - 1111_0111\n 7, 7, 7, 7, 7, 7, 7, 7, // 1111_1000 - 1111_1111\n };\n\n int byte;\n int byte_cnt;\n\n for (byte_cnt = 3; byte_cnt >= 0; byte_cnt--)\n {\n byte = (x >> (byte_cnt * 8)) & 0xff;\n if (byte != 0)\n {\n return msb_lut[byte] + (byte_cnt * 8);\n }\n }\n\n return -1;\n}\n" }, { "answer_id": 1454990, "author": "dharga", "author_id": 176554, "author_profile": "https://Stackoverflow.com/users/176554", "pm_score": 2, "selected": false, "text": "int highestBit(int v){\n return fls(v) << 1;\n}\n" }, { "answer_id": 12376351, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 2, "selected": false, "text": "// Note doesn't cover the case of 0 (0 returns 1)\ninline unsigned int hibit( unsigned int x )\n{\n unsigned int log2Val = 0 ;\n while( x>>=1 ) log2Val++; // eg x=63 (111111), log2Val=5\n return 1 << log2Val ; // finds 2^5=32\n}\n" }, { "answer_id": 14085901, "author": "Fabian", "author_id": 343664, "author_profile": "https://Stackoverflow.com/users/343664", "pm_score": 5, "selected": false, "text": "fls 1<<(fls(input)-1)\n" }, { "answer_id": 30143805, "author": "Gavin Sellers", "author_id": 1123590, "author_profile": "https://Stackoverflow.com/users/1123590", "pm_score": 0, "selected": false, "text": "uint64_t highestBit(uint64_t a, uint64_t bit_min, uint64_t bit_max, uint16_t bit_shift){\n if(a == 0) return 0;\n if(bit_min >= bit_max){\n if((a & bit_min) != 0)\n return bit_min;\n return 0;\n }\n uint64_t bit_mid = bit_max >> bit_shift;\n bit_shift >>= 1;\n if((a >= bit_mid) && (a < (bit_mid << 1)))\n return bit_mid;\n else if(a > bit_mid)\n return highestBit(a, bit_mid, bit_max, bit_shift);\n else\n return highestBit(a, bit_min, bit_mid, bit_shift);\n\n}\n" }, { "answer_id": 42030874, "author": "Kean", "author_id": 849635, "author_profile": "https://Stackoverflow.com/users/849635", "pm_score": 3, "selected": false, "text": "static inline int_t get_msb32 (register unsigned int val)\n{\n return 32 - __builtin_clz(val);\n}\n\nstatic inline int get_msb64 (register unsigned long long val)\n{\n return 64 - __builtin_clzll(val);\n}\n" }, { "answer_id": 62509101, "author": "Анатолий", "author_id": 13789999, "author_profile": "https://Stackoverflow.com/users/13789999", "pm_score": 2, "selected": false, "text": "unsigned hibit(unsigned n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n return n - (n >> 1);\n}\n uint64_t hibit(uint64_t n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n n |= (n >> 32u);\n return n - (n >> 1);\n}\n __int128 hibit(__int128 n) {\n n |= (n >> 1u);\n n |= (n >> 2u);\n n |= (n >> 4u);\n n |= (n >> 8u);\n n |= (n >> 16u);\n n |= (n >> 32u);\n n |= (n >> 64u);\n return n - (n >> 1);\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057/" ]
53,162
<p>Given:</p> <pre><code>e = 'a' + 'b' + 'c' + 'd' </code></pre> <p>How do I write the above in two lines?</p> <pre><code>e = 'a' + 'b' + 'c' + 'd' </code></pre>
[ { "answer_id": 53173, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 5, "selected": false, "text": "\\ ( .. ) b = ((i1 < 20) and\n (i2 < 30) and\n (i3 < 40))\n b = (i1 < 20) and \\\n (i2 < 30) and \\\n (i3 < 40)\n" }, { "answer_id": 53180, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 12, "selected": true, "text": "a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, \n blahblah6, blahblah7)\n if (a == True and\n b == False):\n if a == True and \\\n b == False:\n a = ('1' + '2' + '3' +\n '4' + '5')\n a = '1' + '2' + '3' + \\\n '4' + '5'\n" }, { "answer_id": 53182, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 5, "selected": false, "text": "\\ if 1900 < year < 2100 and 1 <= month <= 12 \\\n and 1 <= day <= 31 and 0 <= hour < 24 \\\n and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date\n return 1\n" }, { "answer_id": 53200, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": false, "text": "with open('/path/to/some/file/you/want/to/read') as file_1, \\\n open('/path/to/some/file/being/written', 'w') as file_2:\n file_2.write(file_1.read())\n class Rectangle(Blob):\n\n def __init__(self, width, height,\n color='black', emphasis=None, highlight=0):\n if (width == 0 and height == 0 and\n color == 'red' and emphasis == 'strong' or\n highlight > 100):\n raise ValueError(\"sorry, you lose\")\n if width == 0 and height == 0 and (color == 'red' or\n emphasis is None):\n raise ValueError(\"I don't think so -- values are %s, %s\" %\n (width, height))\n Blob.__init__(self, width, height,\n color, emphasis, highlight)file_2.write(file_1.read())\n # Yes: easy to match operators with operands\n income = (gross_wages\n + taxable_interest\n + (dividends - qualified_dividends)\n - ira_deduction\n - student_loan_interest)\n" }, { "answer_id": 110882, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "\\ x = (tuples_first_value,\n second_value)\ny = 1 + \\\n 2\n" }, { "answer_id": 53117661, "author": "Hardik Sondagar", "author_id": 2553366, "author_profile": "https://Stackoverflow.com/users/2553366", "pm_score": 3, "selected": false, "text": "query = \" \".join([\n 'SELECT * FROM \"TableName\"',\n 'WHERE \"SomeColumn1\"=VALUE',\n 'ORDER BY \"SomeColumn2\"',\n 'LIMIT 5;'\n])\n" }, { "answer_id": 53657814, "author": "ivanleoncz", "author_id": 5780109, "author_profile": "https://Stackoverflow.com/users/5780109", "pm_score": 2, "selected": false, "text": "from app import (\n app, abort, make_response, redirect, render_template, request, session\n)\n" }, { "answer_id": 60844786, "author": "jlaurens", "author_id": 4858081, "author_profile": "https://Stackoverflow.com/users/4858081", "pm_score": 4, "selected": false, "text": "long_string = \"a very long string\"\nprint(\"a very long string\")\n long_string = (\n \"a \"\n \"very \"\n \"long \"\n \"string\"\n)\nprint(\n \"a \"\n \"very \"\n \"long \"\n \"string\"\n)\n a very long string s = (\n '''2+2='''\n f\"{2+2}\"\n)\n" }, { "answer_id": 64812795, "author": "Brandt", "author_id": 687896, "author_profile": "https://Stackoverflow.com/users/687896", "pm_score": 4, "selected": false, "text": "obj.method() () > res = (some_object\n .apply(args)\n .filter()\n .values)\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
53,164
<p>After working for a while developing games, I've been exposed to both variable frame rates (where you work out how much time has passed since the last tick and update actor movement accordingly) and fixed frame rates (where you work out how much time has passed and choose either to tick a fixed amount of time or sleep until the next window comes).</p> <p>Which method works best for specific situations? Please consider:</p> <ul> <li>Catering to different system specifications;</li> <li>Ease of development/maintenance;</li> <li>Ease of porting;</li> <li>Final performance.</li> </ul>
[ { "answer_id": 59512, "author": "Paul", "author_id": 5841, "author_profile": "https://Stackoverflow.com/users/5841", "pm_score": 3, "selected": false, "text": "const float STEP = 60.f / 1000.f;\nfloat accumulator = 0.f;\n\nvoid Update(float delta)\n{\n accumulator += delta;\n\n while(accumulator > STEP)\n {\n Simulate(STEP);\n accumulator -= STEP;\n }\n}\n" } ]
2008/09/09
[ "https://Stackoverflow.com/questions/53164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5488/" ]
53,208
<p>In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this. </p> <p>I want the child processes to be automatically closed <strong>if my main processes crashes</strong> or is closed.</p> <p>Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.</p> <p>How do I do this?</p>
[ { "answer_id": 53214, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 7, "selected": true, "text": "HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL\nif( ghJob == NULL)\n{\n ::MessageBox( 0, \"Could not create job object\", \"TEST\", MB_OK);\n}\nelse\n{\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };\n\n // Configure all child processes associated with the job to terminate when the\n jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)))\n {\n ::MessageBox( 0, \"Could not SetInformationJobObject\", \"TEST\", MB_OK);\n }\n}\n STARTUPINFO info={sizeof(info)};\nPROCESS_INFORMATION processInfo;\n\n// Launch child process - example is notepad.exe\nif (::CreateProcess( NULL, \"notepad.exe\", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))\n{\n ::MessageBox( 0, \"CreateProcess succeeded.\", \"TEST\", MB_OK);\n if(ghJob)\n {\n if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))\n {\n ::MessageBox( 0, \"Could not AssignProcessToObject\", \"TEST\", MB_OK);\n }\n }\n\n // Can we free handles now? Not sure about this.\n //CloseHandle(processInfo.hProcess); \n CloseHandle(processInfo.hThread);\n}\n" }, { "answer_id": 53227, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": -1, "selected": false, "text": "class myprocess\n{\npublic:\n myprocess(HANDLE hProcess)\n : _hProcess(hProcess)\n { }\n\n ~myprocess()\n {\n TerminateProcess(_hProcess, 0);\n }\n\nprivate:\n HANDLE _hProcess;\n};\n\nstd::list<myprocess> allprocesses;\n" }, { "answer_id": 69243480, "author": "Kohill Yang", "author_id": 14881537, "author_profile": "https://Stackoverflow.com/users/14881537", "pm_score": 0, "selected": false, "text": "static HANDLE hjob_kill_on_job_close=INVALID_HANDLE_VALUE;\nvoid init(){\n hjob_kill_on_job_close = CreateJobObject(NULL, NULL);\n if (hjob_kill_on_job_close){\n JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobli = { 0 };\n jobli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;\n SetInformationJobObject(hjob_kill_on_job_close,\n JobObjectExtendedLimitInformation,\n &jobli, sizeof(jobli));\n AssignProcessToJobObject(hjob_kill_on_job_close, GetCurrentProcess());\n }\n}\nvoid deinit(){\n if (hjob_kill_on_job_close) {\n CloseHandle(hjob_kill_on_job_close);\n }\n}\n JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE CREATE_BREAKAWAY_FROM_JOB CreateProcess CREATE_BREAKAWAY_FROM_JOB" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
53,224
<p>I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as &amp;#196;&amp;#196;RITALO!<br> That is, html uses escaped markup for the special characters, such as &amp;#196;</p> <p>Is there a simple way of reading the html into the correct python string? If it was XML/XHTML it would be easy, the parser would do it.</p>
[ { "answer_id": 53246, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": ">>> from BeautifulSoup import BeautifulSoup \n>>> html = \"<html>&#196;&#196;RITALO!</html>\"\n>>> soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)\n>>> print soup.contents[0].string\nÄÄRITALO!\n \"some_string\".decode('html_entities')" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5346/" ]
53,225
<p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
[ { "answer_id": 53322, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": true, "text": "def isbound(method):\n return method.im_self is not None\n \ndef instance(bounded_method):\n return bounded_method.im_self\n im_self None im_self im_class im_func im_self __self__ im_func __func__" }, { "answer_id": 18955425, "author": "Rob Agar", "author_id": 494373, "author_profile": "https://Stackoverflow.com/users/494373", "pm_score": 5, "selected": false, "text": "__self__ None def is_bound(m):\n return hasattr(m, '__self__')\n" }, { "answer_id": 50074581, "author": "Klaus", "author_id": 1479700, "author_profile": "https://Stackoverflow.com/users/1479700", "pm_score": 4, "selected": false, "text": "def my_decorator(*decorator_args, **decorator_kwargs):\n def decorate(f):\n print(hasattr(f, '__self__'))\n @wraps(f)\n def wrap(*args, **kwargs):\n return f(*args, **kwargs)\n return wrap\n return decorate\n\nclass test_class(object):\n @my_decorator()\n def test_method(self, *some_params):\n pass\n print False self self import inspect\n\ndef is_bounded(function):\n params = inspect.signature(function).parameters\n return params.get('self', None) is not None\n" }, { "answer_id": 65276709, "author": "Anakhand", "author_id": 6117426, "author_profile": "https://Stackoverflow.com/users/6117426", "pm_score": 0, "selected": false, "text": "six def is_bound_method(f):\n \"\"\"Whether f is a bound method\"\"\"\n try:\n return six.get_method_self(f) is not None\n except AttributeError:\n return False\n im_self six.get_method_self() AttributeError False im_self None False im_self None True __self__ six.get_method_self() AttributeError False False __self__ None True" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
53,256
<p>I have two elements:</p> <pre><code>&lt;input a&gt; &lt;input b onclick="..."&gt; </code></pre> <p>When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so <code>document.getElementsByName</code> is out. Looking into the event object, I thought <code>event.target.parentNode</code> would have some function like <code>getElementsByName</code>, but this does not seem to be the case with &lt;td&gt;s. Is there any simple way to do this?</p>
[ { "answer_id": 53261, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 4, "selected": true, "text": "a b prevSibling b a" }, { "answer_id": 53262, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "e.target e.srcElement function whichElement(e) {\n var targ;\n if (!e) var e = window.event;\n if (e.target) {\n targ=e.target;\n } else if (e.srcElement) {\n targ = e.srcElement;\n }\n\n if (targ.nodeType==3) { // defeat Safari bug \n targ = targ.parentNode;\n }\n\n var tname;\n tname = targ.tagName;\n alert(\"You clicked on a \" + tname + \" element.\");\n}\n nextSibling prevSibling" }, { "answer_id": 53536, "author": "ujh", "author_id": 4936, "author_profile": "https://Stackoverflow.com/users/4936", "pm_score": 1, "selected": false, "text": "b.up().down('a')\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429/" ]
53,260
<p>Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.</p> <p>Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.</p> <p>Can anyone recommend a way to handle this scenario when HTTP POST data is involved?</p> <p>Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.</p> <hr> <p><strong>Edit</strong> : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.</p>
[ { "answer_id": 53289, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 2, "selected": false, "text": "if ( !loggedIn ) {\n StorePostInSession();\n ShowLoginForm();\n}\n\nif ( postIsStored ) {\n RetrievePostFromSession();\n}\n" }, { "answer_id": 53315, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "\n CommentController {\n void AddComment() {\n if (!Request.User.IsAuthenticated && !AuthenticateUser()) {\n return;\n }\n // add comment to database\n }\n\n bool AuthenticateUser() {\n if (Request.Form[\"username\"] == \"\") {\n // show login page\n foreach (Key key in Request.Form) {\n // copy form values\n ViewData.Form.Add(\"hidden\", key, Request.Form[key]);\n }\n ViewData.Form.Action = Request.Url;\n\n ShowLoginView();\n return false;\n } else {\n // validate login\n return TryLogin(Request.Form[\"username\"], Request.Form[\"password\"]);\n } \n }\n }\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
53,292
<p>I'm trying to use the <a href="http://optiflag.rubyforge.org/discussion.html" rel="nofollow noreferrer">Optiflag</a> package in my Ruby code and whenever I try to do the necessary <code>require optiflag.rb</code>, my program fails with the standard <code>no such file to load -- optiflag</code> message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas?</p>
[ { "answer_id": 53313, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 3, "selected": true, "text": "require 'rubygems'\nrequire 'optiflag'\n" }, { "answer_id": 53390, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 2, "selected": false, "text": "require \"rubygems\"\nrequire \"optiflag\" # etc\n ruby -rubygems Something.rb\n RUBYOPT=rubygems\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
53,295
<p>I'm trying to use some data from a PlanPlusOnline account. They only provide a java web services API. The server for the site where the data will be used does not allow me to install Tomcat (edit: or a JVM for that matter). I'm not going to lie, I am a Java software engineer, and I do some web work on the side. I'm not familiar with web services or servlets, but I was willing to give it a shot. I'd much rather they have JSON access to the data, but as far as I know they don't. Any ideas?</p> <p>EDIT: to clarify. The web service provided by planplusonline is Java based. I am trying to access the data from this web service without using Java. I believe this is possible now, but I need to do more research. Anyone who can help point me in the right direction is appreciated.</p>
[ { "answer_id": 53360, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 0, "selected": false, "text": "public final class PlanPlusOnlineClient\n{\n //instance to this class so that we do not have to reinstantiate it every time\n private static PlanPlusOnlineClient _instance = new PlanPlusOnlineClient();\n\n //generated class by netbeans with information about the web service\n private PlanPlusOnlineService service = null;\n\n //another generated class by netbeans but this is a property of the service\n //that contains information about the individual methods available.\n private PlanPlusOnline port = null;\n\n private PlanPlusOnlineClient()\n {\n try\n {\n service = new PlanPlusOnlineService();\n port = service.getPlanPlusOnlinePort();\n }\n catch (MalformedURLException ex)\n {\n MessageLog.error(this, ex.getClass().getName(), ex);\n }\n }\n\n public static PlanPlusOnlineClient getInstance()\n {\n return _instance;\n }\n\n public static String getSomethingInteresting(String param)\n {\n //this will call one of the actual methods the web \n //service provides.\n return port.getSomethingIntersting(param);\n } \n\n}\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5054/" ]
53,316
<p>I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:</p> <pre><code>@CollectionOfElements(fetch = EAGER) @JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note")) @Column(name = "substitution") @IndexColumn(name = "listIndex", base = 0) @Lob private List&lt;String&gt; substitutions; </code></pre> <p>So basically I may have a Note with some subsitutions, say <code>"foo"</code> and <code>"fizzbuzz"</code>. So in my main table I could have a Note with id 4 and in my <code>NOTE_JOIN_TABLE</code> I would have two rows, <code>"foo"</code> and <code>"fizzbuzz"</code> that both have a relationship to the Note.</p> <p>However, when one of these is inserted into the DB <strong>the larger substitution values are cropped to be as long as the shortest.</strong> So in this case I would have <code>"foo"</code> and <code>"fiz"</code> in the DB instead of <code>"foo"</code> and <code>"fizzbuzz"</code>.</p> <p>Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate.</p>
[ { "answer_id": 53360, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 0, "selected": false, "text": "public final class PlanPlusOnlineClient\n{\n //instance to this class so that we do not have to reinstantiate it every time\n private static PlanPlusOnlineClient _instance = new PlanPlusOnlineClient();\n\n //generated class by netbeans with information about the web service\n private PlanPlusOnlineService service = null;\n\n //another generated class by netbeans but this is a property of the service\n //that contains information about the individual methods available.\n private PlanPlusOnline port = null;\n\n private PlanPlusOnlineClient()\n {\n try\n {\n service = new PlanPlusOnlineService();\n port = service.getPlanPlusOnlinePort();\n }\n catch (MalformedURLException ex)\n {\n MessageLog.error(this, ex.getClass().getName(), ex);\n }\n }\n\n public static PlanPlusOnlineClient getInstance()\n {\n return _instance;\n }\n\n public static String getSomethingInteresting(String param)\n {\n //this will call one of the actual methods the web \n //service provides.\n return port.getSomethingIntersting(param);\n } \n\n}\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
53,355
<p>Better yet, how can I make My Computer always open in Explorer as well?</p> <p>I usually make a shortcut to my programming directories on my quick launch bar, but I'd love for them to open in Explorer.</p>
[ { "answer_id": 53366, "author": "csjohnst", "author_id": 1292, "author_profile": "https://Stackoverflow.com/users/1292", "pm_score": 2, "selected": false, "text": "i.e.:\nexplorer /e,%HOMEDRIVE%%HOMEPATH%\n" }, { "answer_id": 53367, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": false, "text": "explorer /e,c:\\path explorer -d c:\\path" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
53,364
<p>Is it possible to generate PDF Documents in an Adobe AIR application without resorting to a round trip web service for generating the PDF? I've looked at the initial Flex Reports on GoogleCode but it requires a round trip for generating the actual PDF.</p> <p>Given that AIR is supposed to be the Desktop end for RIAs is there a way to accomplish this? I suspect I am overlooking something but my searches through the documentation don't reveal too much and given the target for AIR I can't believe that it's just something they didn't include.</p>
[ { "answer_id": 8766756, "author": "Kamran Aslam", "author_id": 653011, "author_profile": "https://Stackoverflow.com/users/653011", "pm_score": 0, "selected": false, "text": "public function createFlexPdf() : String\n{\n pdf = new PDF();\n pdf.setDisplayMode (Display.FULL_WIDTH,Layout.ONE_COLUMN,Mode.FIT_TO_PAGE,0.96);\n pdf.setViewerPreferences(ToolBar.SHOW,MenuBar.HIDE,WindowUI.SHOW,FitWindow.RESIZED,CenterWindow.CENTERED);\n pdf.addPage();\n var myFontStyle:IFont = new CoreFont ( FontFamily.COURIER );\n pdf.setFont(myFontStyle,10);\n pdf.addText('Kamran Aslam',10,20);//String, X-Coord, Y-Coord \n return savePDF();\n}\nprivate function savePDF():String\n{\n var fileStream:FileStream = new FileStream();\n var file:File = File.createTempDirectory();\n file = file.resolvePath(\"temp.pdf\");\n fileStream.open(file, FileMode.WRITE);\n var bytes:ByteArray = pdf.save(Method.LOCAL);\n fileStream.writeBytes(bytes);\n fileStream.close();\n return file.url;\n}\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4959/" ]
53,365
<p><em>(see <a href="https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly">here</a> for the problem I'm trying to solve)</em></p> <p>How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.</p> <p>I have the following in my log4j config:</p> <pre><code>log4j.logger.net.sf.hibernate.SQL=DEBUG log4j.logger.org.hibernate.SQL=DEBUG log4j.logger.net.sf.hibernate.type=DEBUG log4j.logger.org.hibernate.type=DEBUG </code></pre> <p>Which produces output such as:</p> <pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?) (org.hibernate.type.LongType) binding '170650' to parameter: 1 (org.hibernate.type.IntegerType) binding '0' to parameter: 2 (org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?) (org.hibernate.type.LongType) binding '170650' to parameter: 1 (org.hibernate.type.IntegerType) binding '1' to parameter: 2 </code></pre> <p>However you'll note that it never displays <code>parameter: 3</code> which is our clob.</p> <p>What I would really want is something like:</p> <pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?) (org.hibernate.type.LongType) binding '170650' to parameter: 1 (org.hibernate.type.IntegerType) binding '0' to parameter: 2 (org.hibernate.type.ClobType) binding 'something' to parameter: 3 (org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?) (org.hibernate.type.LongType) binding '170650' to parameter: 1 (org.hibernate.type.IntegerType) binding '1' to parameter: 2 (org.hibernate.type.ClobType) binding 'something else' to parameter: 3 </code></pre> <p>How do I get it to show this in the log?</p>
[ { "answer_id": 53419, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": true, "text": "log4j.logger.net.sf.hibernate=DEBUG\nlog4j.logger.org.hibernate=DEBUG\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
53,379
<p>Does anyone have examples of how to use <a href="http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php" rel="nofollow noreferrer">DBMS_APPLICATION_INFO</a> package with JBOSS? </p> <p>We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.</p> <p>I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.</p> <p>Has anyone done this before?</p>
[ { "answer_id": 378045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<local-tx-datasource>\n <jndi-name>jdbc/myDS</jndi-name>\n <connection-url>jdbc:oracle:thin:@10.10.1.15:1521:SID</connection-url>\n <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>\n <security-domain>MyEncryptDBPassword</security-domain>\n <valid-connection-checker-class-name>test.MyValidConn</valid-connection-checker-class-name>\n <metadata>\n <type-mapping>Oracle9i</type-mapping>\n </metadata>\n</local-tx-datasource>\n <dependency>\n <groupId>jboss</groupId>\n <artifactId>jboss-common-jdbc-wrapper</artifactId>\n <version>3.2.3</version>\n <scope>provided</scope>\n</dependency>\n public SQLException isValidConnection(Connection arg0) {\n CallableStatement statement;\n try {\n statement = arg0.prepareCall(\"call dbms_application_info.set_client_info('\"+getInfos()+\"')\");\n statement.execute();\n } catch (SQLException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n}\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
53,387
<p>I downloaded a couple of webapps and placed them in my /webapps folder. Some of them I could open by going to <code>http://localhost:8080/app1</code> and it would open. However, some others I would do the exact same thing and go to <code>http://localhost:8080/app2</code> and it will display "HTTP Status 404 - /app2/", even though I am sure it is there. I've checked that it contains a WEB-INF folder just like app1, and I've even restarted Tomcat to be sure.</p> <p>My question is: is there anything (perhaps in the web.xml file) that specifies what the URL has to be to start the webapp? Or is it simply just <code>http://localhost:8080/&lt;folder name&gt;</code> ?</p> <p>P.S. If you want to know exactly what app1 and app2 I am refering to: app1 (works) = <a href="http://assets.devx.com/sourcecode/11237.zip" rel="nofollow noreferrer">http://assets.devx.com/sourcecode/11237.zip</a> app2 (doesn't work) = <a href="http://www.laliluna.de/download/eclipse-spring-jdbc-tutorial.zip" rel="nofollow noreferrer">http://www.laliluna.de/download/eclipse-spring-jdbc-tutorial.zip</a></p> <p>I've tried a few others as well, some work, some don't. I'm just wondering if I'm missing something.</p>
[ { "answer_id": 53422, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": 2, "selected": false, "text": "eclipse-spring-jdbc-tutorial.zip\\SpringJdbc\\src\\test\\de\\laliluna\\library\\TestClient.java eclipse-spring-jdbc-tutorial.zip\\SpringJdbc\\src\\de\\laliluna\\library\\sample\\MyApplication.java" }, { "answer_id": 56312, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": ".war .war File>>Export" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
53,395
<p>I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.</p> <p>Abstract class:</p> <pre><code>public interface IOtherObjects; public abstract class MyObjects&lt;T&gt; where T : IOtherObjects { ... public List&lt;T&gt; ToList() { ... } } </code></pre> <p>Children:</p> <pre><code>public class MyObjectsA : MyObjects&lt;OtherObjectA&gt; //(where OtherObjectA implements IOtherObjects) { } public class MyObjectsB : MyObjects&lt;OtherObjectB&gt; //(where OtherObjectB implements IOtherObjects) { } </code></pre> <p>Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to <em>ToList</em> method of the <em>MyObjects</em> base class, as we do not specifically know the type of T at this point. </p> <p><strong>EDIT</strong> As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.</p> <p><strong>EDIT</strong> @Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)</p> <p>@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds</p> <p><strong>EDIT</strong> @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.</p> <p><strong>EDIT</strong>@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects. </p> <p>@Rob <strong>Again</strong> Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.</p> <p><strong>QUALIFYING EDIT</strong> in case I have been a little confusing</p> <p>To be more precise, (I may have let my latest implementation of this get it too complex):</p> <p>lets say I have 2 object types, B and C inheriting from object A.</p> <p>Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A. </p> <p>The above example was a watered-down example of the <em>List Of Less Specific</em> problem's latest incarnation.</p> <p>Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand</p> <p>@Rob <strong>Yet Again</strong> and Sara</p> <p>Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.</p> <p>The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).</p> <p>My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.</p> <p>I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.</p>
[ { "answer_id": 53406, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "foreach(var myObject in myObjectsList)\n foreach(var obj in myObject.ToList())\n //do something\n" }, { "answer_id": 53418, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": -1, "selected": false, "text": "interface IMyObjects : IEnumerable<IOtherObjects> {}\nabstract class MyObjects<T> : IMyObjects where T : IOtherObjects {}\n\nIEnumerable<IMyObjects> objs = ...;\nforeach (IMyObjects mo in objs) {\n foreach (IOtherObjects oo in mo) {\n Console.WriteLine(oo);\n }\n}\n" }, { "answer_id": 53446, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "// Original Code Snipped for Brevity - See Edit History if Req'd\n public List<OfType> TypedList<OfType>() where OfType : IOtherObjects\n {\n List<OfType> rtn = new List<OfType>();\n\n foreach (IOtherObjects o in _objects)\n {\n Type objType = o.GetType();\n Type reqType = typeof(OfType);\n\n if (objType == reqType)\n rtn.Add((OfType)o);\n }\n\n return rtn;\n }\n public abstract class MyObjects<T> where T : IOtherObjects\n{\n List<T> _objects = new List<T>();\n\n public List<T> ToList()\n {\n return _objects;\n }\n\n public List<IOtherObjects> ToBaseList()\n {\n List<IOtherObjects> rtn = new List<IOtherObjects>();\n foreach (IOtherObjects o in _objects)\n {\n rtn.Add(o);\n }\n return rtn;\n }\n}\n public abstract class MyObjects<T> where T : IOtherObjects\n{\n List<T> _objects = new List<T>();\n\n public List<IOtherObjects> Objects\n { get { return _objects; } }\n}\n#warning This won't compile, its for demo's sake.\n" }, { "answer_id": 84484, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "class B : A\nclass C : A\n List<B> listB;\nList<C> listC;\n List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()\n" }, { "answer_id": 98008, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 0, "selected": false, "text": "List<A>.Cast<B>().ToList<B>()\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
53,404
<p>An OleDB provider is a binary implementing COM interfaces provided by Microsoft. From that it seems to be possible to create a provider using C#. Is that correct? Is there a sample demonstrating that? If not, would you discourage me from doing that? I see that there are multiple unmanaged samples but I can't find any managed.</p>
[ { "answer_id": 53427, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": -1, "selected": false, "text": "using System.Data.OleDb;\n" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223/" ]
53,411
<p>I'm wondering about MP3 decoding/encoding, and I was hoping to pull this off in Flash using AS3</p> <p>I'm sure it'll be a right pain...</p> <p>I have no idea where to start, can anyone offer any pointers? reference material?</p> <p>----much later--- Thank you all very much for your input... It seems I have a long road ahead of me yet!</p>
[ { "answer_id": 67764, "author": "Jeremy Wadhams", "author_id": 8995, "author_profile": "https://Stackoverflow.com/users/8995", "pm_score": 1, "selected": false, "text": "exec()" } ]
2008/09/10
[ "https://Stackoverflow.com/questions/53411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5503/" ]