qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
59,819
<p>I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:</p> <pre><code>Contact { string First string Last string Phone } </code></pre> <p>How would I go about creating this so that I could use it in function like the following:</p> <pre><code>function PrintContact { param( [Contact]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } </code></pre> <p>Is something like this possible, or even recommended in PowerShell?</p>
[ { "answer_id": 59887, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 2, "selected": false, "text": "<p>There is the concept of PSObject and Add-Member that you could use.</p>\n\n<pre><code>$contact = New-Object PSObject\n\n$contact | Add-Member -memberType NoteProperty -name \"First\" -value \"John\"\n$contact | Add-Member -memberType NoteProperty -name \"Last\" -value \"Doe\"\n$contact | Add-Member -memberType NoteProperty -name \"Phone\" -value \"123-4567\"\n</code></pre>\n\n<p>This outputs like:</p>\n\n<pre><code>[8] » $contact\n\nFirst Last Phone\n----- ---- -----\nJohn Doe 123-4567\n</code></pre>\n\n<p>The other alternative (that I'm aware of) is to define a type in C#/VB.NET and load that assembly into PowerShell for use directly.</p>\n\n<p>This behavior is definitely encouraged because it allows other scripts or sections of your script work with an actual object.</p>\n" }, { "answer_id": 59980, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 6, "selected": false, "text": "<p>Creating custom types can be done in PowerShell.<br>\nKirk Munro actually has two great posts that detail the process thoroughly.</p>\n\n<ul>\n<li><a href=\"http://poshoholic.com/2008/07/03/essential-powershell-name-your-custom-object-types/\" rel=\"noreferrer\">Naming Custom Objects</a></li>\n<li><a href=\"http://poshoholic.com/2008/07/05/essential-powershell-define-default-properties-for-custom-objects/\" rel=\"noreferrer\">Defining Default Properties for Custom Objects</a></li>\n</ul>\n\n<p>The book <a href=\"http://www.manning.com/payette/\" rel=\"noreferrer\">Windows PowerShell In Action by Manning</a> also has a code sample for creating a domain specific language to create custom types. The book is excellent all around, so I really recommend it.</p>\n\n<p>If you are just looking for a quick way to do the above, you could create a function to create the custom object like</p>\n\n<pre><code>function New-Person()\n{\n param ($FirstName, $LastName, $Phone)\n\n $person = new-object PSObject\n\n $person | add-member -type NoteProperty -Name First -Value $FirstName\n $person | add-member -type NoteProperty -Name Last -Value $LastName\n $person | add-member -type NoteProperty -Name Phone -Value $Phone\n\n return $person\n}\n</code></pre>\n" }, { "answer_id": 61315, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 4, "selected": false, "text": "<p>This is the shortcut method:</p>\n\n<pre><code>$myPerson = \"\" | Select-Object First,Last,Phone\n</code></pre>\n" }, { "answer_id": 66693, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 8, "selected": true, "text": "<h2>Prior to PowerShell 3</h2>\n\n<p>PowerShell's Extensible Type System didn't originally let you create concrete types you can test against the way you did in your parameter. If you don't need that test, you're fine with any of the other methods mentioned above. </p>\n\n<p>If you want an actual type that you can cast to or type-check with, as in your example script ... it <strong>cannot</strong> be done without writing it in C# or VB.net and compiling. In PowerShell 2, you can use the \"Add-Type\" command to do it quite simmple:</p>\n\n<pre><code>add-type @\"\npublic struct contact {\n public string First;\n public string Last;\n public string Phone;\n}\n\"@\n</code></pre>\n\n<p><strong><em>Historical Note</em></strong>: In PowerShell 1 it was even harder. You had to manually use CodeDom, there is a very old function <a href=\"http://poshcode.org/scripts/190\" rel=\"noreferrer\">new-struct</a> script on PoshCode.org which will help. Your example becomes:</p>\n\n<pre><code>New-Struct Contact @{\n First=[string];\n Last=[string];\n Phone=[string];\n}\n</code></pre>\n\n<p>Using <code>Add-Type</code> or <code>New-Struct</code> will let you actually test the class in your <code>param([Contact]$contact)</code> and make new ones using <code>$contact = new-object Contact</code> and so on...</p>\n\n<h1>In PowerShell 3</h1>\n\n<p>If you don't need a \"real\" class that you can cast to, you don't have to use the Add-Member way that <a href=\"https://stackoverflow.com/a/59980/8718\">Steven and others have demonstrated</a> above.</p>\n\n<p>Since PowerShell 2 you could use the -Property parameter for New-Object:</p>\n\n<pre><code>$Contact = New-Object PSObject -Property @{ First=\"\"; Last=\"\"; Phone=\"\" }\n</code></pre>\n\n<p>And in PowerShell 3, we got the ability to use the <code>PSCustomObject</code> accelerator to add a TypeName:</p>\n\n<pre><code>[PSCustomObject]@{\n PSTypeName = \"Contact\"\n First = $First\n Last = $Last\n Phone = $Phone\n}\n</code></pre>\n\n<p>You're still only getting a single object, so you should make a <code>New-Contact</code> function to make sure that every object comes out the same, but you can now easily verify a parameter \"is\" one of those type by decorating a parameter with the <code>PSTypeName</code> attribute:</p>\n\n<pre><code>function PrintContact\n{\n param( [PSTypeName(\"Contact\")]$contact )\n \"Customer Name is \" + $contact.First + \" \" + $contact.Last\n \"Customer Phone is \" + $contact.Phone \n}\n</code></pre>\n\n<h1>In PowerShell 5</h1>\n\n<p>In PowerShell 5 everything changes, and we finally got <code>class</code> and <code>enum</code> as language keywords for defining types (there's no <code>struct</code> but that's ok):</p>\n\n<pre><code>class Contact\n{\n # Optionally, add attributes to prevent invalid values\n [ValidateNotNullOrEmpty()][string]$First\n [ValidateNotNullOrEmpty()][string]$Last\n [ValidateNotNullOrEmpty()][string]$Phone\n\n # optionally, have a constructor to \n # force properties to be set:\n Contact($First, $Last, $Phone) {\n $this.First = $First\n $this.Last = $Last\n $this.Phone = $Phone\n }\n}\n</code></pre>\n\n<p>We also got a new way to create objects without using <code>New-Object</code>: <code>[Contact]::new()</code> -- in fact, if you kept your class simple and don't define a constructor, you can create objects by casting a hashtable (although without a constructor, there would be no way to enforce that all properties must be set):</p>\n\n<pre><code>class Contact\n{\n # Optionally, add attributes to prevent invalid values\n [ValidateNotNullOrEmpty()][string]$First\n [ValidateNotNullOrEmpty()][string]$Last\n [ValidateNotNullOrEmpty()][string]$Phone\n}\n\n$C = [Contact]@{\n First = \"Joel\"\n Last = \"Bennett\"\n}\n</code></pre>\n" }, { "answer_id": 4667545, "author": "Nick Meldrum", "author_id": 32739, "author_profile": "https://Stackoverflow.com/users/32739", "pm_score": 3, "selected": false, "text": "<p>Steven Murawski's answer is great, however I like the shorter (or rather just the neater select-object instead of using add-member syntax):</p>\n\n<pre><code>function New-Person() {\n param ($FirstName, $LastName, $Phone)\n\n $person = new-object PSObject | select-object First, Last, Phone\n\n $person.First = $FirstName\n $person.Last = $LastName\n $person.Phone = $Phone\n\n return $person\n}\n</code></pre>\n" }, { "answer_id": 27492180, "author": "Florian JUDITH", "author_id": 4363832, "author_profile": "https://Stackoverflow.com/users/4363832", "pm_score": 2, "selected": false, "text": "<p>Here is the hard path to create custom types and store them in a collection.</p>\n\n<pre><code>$Collection = @()\n\n$Object = New-Object -TypeName PSObject\n$Object.PsObject.TypeNames.Add('MyCustomType.Contact.Detail')\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"First\" -value \"John\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Last\" -value \"Doe\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Phone\" -value \"123-4567\"\n$Collection += $Object\n\n$Object = New-Object -TypeName PSObject\n$Object.PsObject.TypeNames.Add('MyCustomType.Contact.Detail')\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"First\" -value \"Jeanne\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Last\" -value \"Doe\"\nAdd-Member -InputObject $Object -memberType NoteProperty -name \"Phone\" -value \"765-4321\"\n$Collection += $Object\n\nWrite-Ouput -InputObject $Collection\n</code></pre>\n" }, { "answer_id": 32506564, "author": "Benjamin Hubbard", "author_id": 2562189, "author_profile": "https://Stackoverflow.com/users/2562189", "pm_score": 3, "selected": false, "text": "<p>Surprised no one mentioned this simple option (vs 3 or later) for creating custom objects:</p>\n\n<pre><code>[PSCustomObject]@{\n First = $First\n Last = $Last\n Phone = $Phone\n}\n</code></pre>\n\n<p>The type will be PSCustomObject, not an actual custom type though. But it is probably the easiest way to create a custom object.</p>\n" }, { "answer_id": 57481684, "author": "JohnLBevan", "author_id": 361842, "author_profile": "https://Stackoverflow.com/users/361842", "pm_score": 1, "selected": false, "text": "<p>Here's one more option, which uses a similar idea to the PSTypeName solution mentioned by <a href=\"https://stackoverflow.com/a/66693/361842\">Jaykul</a> (and thus also requires PSv3 or above).</p>\n\n<h1>Example</h1>\n\n<ol>\n<li>Create a <strong><em>TypeName</em>.Types.ps1xml</strong> file defining your type. E.g. <code>Person.Types.ps1xml</code>:</li>\n</ol>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;Types&gt;\n &lt;Type&gt;\n &lt;Name&gt;StackOverflow.Example.Person&lt;/Name&gt;\n &lt;Members&gt;\n &lt;ScriptMethod&gt;\n &lt;Name&gt;Initialize&lt;/Name&gt;\n &lt;Script&gt;\n Param (\n [Parameter(Mandatory = $true)]\n [string]$GivenName\n ,\n [Parameter(Mandatory = $true)]\n [string]$Surname\n )\n $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName\n $this | Add-Member -MemberType 'NoteProperty' -Name 'Surname' -Value $Surname\n &lt;/Script&gt;\n &lt;/ScriptMethod&gt;\n &lt;ScriptMethod&gt;\n &lt;Name&gt;SetGivenName&lt;/Name&gt;\n &lt;Script&gt;\n Param (\n [Parameter(Mandatory = $true)]\n [string]$GivenName\n )\n $this | Add-Member -MemberType 'NoteProperty' -Name 'GivenName' -Value $GivenName -Force\n &lt;/Script&gt;\n &lt;/ScriptMethod&gt;\n &lt;ScriptProperty&gt;\n &lt;Name&gt;FullName&lt;/Name&gt;\n &lt;GetScriptBlock&gt;'{0} {1}' -f $this.GivenName, $this.Surname&lt;/GetScriptBlock&gt;\n &lt;/ScriptProperty&gt;\n &lt;!-- include properties under here if we don't want them to be visible by default\n &lt;MemberSet&gt;\n &lt;Name&gt;PSStandardMembers&lt;/Name&gt;\n &lt;Members&gt;\n &lt;/Members&gt;\n &lt;/MemberSet&gt;\n --&gt;\n &lt;/Members&gt;\n &lt;/Type&gt;\n&lt;/Types&gt;\n</code></pre>\n\n<ol start=\"2\">\n<li>Import your type: <code>Update-TypeData -AppendPath .\\Person.Types.ps1xml</code></li>\n<li>Create an object of your custom type: <code>$p = [PSCustomType]@{PSTypeName='StackOverflow.Example.Person'}</code></li>\n<li>Initialise your type using the script method you defined in the XML: <code>$p.Initialize('Anne', 'Droid')</code></li>\n<li>Look at it; you'll see all properties defined: <code>$p | Format-Table -AutoSize</code></li>\n<li>Type calling a mutator to update a property's value: <code>$p.SetGivenName('Dan')</code></li>\n<li>Look at it again to see the updated value: <code>$p | Format-Table -AutoSize</code></li>\n</ol>\n\n<h1>Explanation</h1>\n\n<ul>\n<li>The PS1XML file allows you to define custom properties on types.</li>\n<li>It is not restricted to .net types as the documentation implies; so you can put what you like in '/Types/Type/Name' any object created with a matching 'PSTypeName' will inherit the members defined for this type.</li>\n<li>Members added through <code>PS1XML</code> or <code>Add-Member</code> are restricted to <code>NoteProperty</code>, <code>AliasProperty</code>, <code>ScriptProperty</code>, <code>CodeProperty</code>, <code>ScriptMethod</code>, and <code>CodeMethod</code> (or <code>PropertySet</code>/<code>MemberSet</code>; though those are subject to the same restrictions). All of these properties are read only.</li>\n<li>By defining a <code>ScriptMethod</code> we can cheat the above restriction. E.g. We can define a method (e.g. <code>Initialize</code>) which creates new properties, setting their values for us; thus ensuring our object has all the properties we need for our other scripts to work.</li>\n<li>We can use this same trick to allow the properties to be updatable (albeit via method rather than direct assignment), as shown in the example's <code>SetGivenName</code>.</li>\n</ul>\n\n<p>This approach isn't ideal for all scenarios; but is useful for adding class-like behaviors to custom types / can be used in conjunction with other methods mentioned in the other answers. E.g. in the real world I'd probably only define the <code>FullName</code> property in the PS1XML, then use a function to create the object with the required values, like so:</p>\n\n<h1>More Info</h1>\n\n<p>Take a look at the <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_types.ps1xml?view=powershell-6\" rel=\"nofollow noreferrer\">documentation</a>, or the OOTB type file <code>Get-Content \n$PSHome\\types.ps1xml</code> for inspiration.</p>\n\n<pre><code># have something like this defined in my script so we only try to import the definition once.\n# the surrounding if statement may be useful if we're dot sourcing the script in an existing \n# session / running in ISE / something like that\nif (!(Get-TypeData 'StackOverflow.Example.Person')) {\n Update-TypeData '.\\Person.Types.ps1xml'\n}\n\n# have a function to create my objects with all required parameters\n# creating them from the hash table means they're PROPERties; i.e. updatable without calling a \n# setter method (note: recall I said above that in this scenario I'd remove their definition \n# from the PS1XML)\nfunction New-SOPerson {\n [CmdletBinding()]\n [OutputType('StackOverflow.Example.Person')]\n Param (\n [Parameter(Mandatory)]\n [string]$GivenName\n ,\n [Parameter(Mandatory)]\n [string]$Surname\n )\n ([PSCustomObject][Ordered]@{\n PSTypeName = 'StackOverflow.Example.Person'\n GivenName = $GivenName\n Surname = $Surname\n })\n}\n\n# then use my new function to generate the new object\n$p = New-SOPerson -GivenName 'Simon' -Surname 'Borg'\n\n# and thanks to the type magic... FullName exists :)\nWrite-Information \"$($p.FullName) was created successfully!\" -InformationAction Continue\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure: ``` Contact { string First string Last string Phone } ``` How would I go about creating this so that I could use it in function like the following: ``` function PrintContact { param( [Contact]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } ``` Is something like this possible, or even recommended in PowerShell?
Prior to PowerShell 3 --------------------- PowerShell's Extensible Type System didn't originally let you create concrete types you can test against the way you did in your parameter. If you don't need that test, you're fine with any of the other methods mentioned above. If you want an actual type that you can cast to or type-check with, as in your example script ... it **cannot** be done without writing it in C# or VB.net and compiling. In PowerShell 2, you can use the "Add-Type" command to do it quite simmple: ``` add-type @" public struct contact { public string First; public string Last; public string Phone; } "@ ``` ***Historical Note***: In PowerShell 1 it was even harder. You had to manually use CodeDom, there is a very old function [new-struct](http://poshcode.org/scripts/190) script on PoshCode.org which will help. Your example becomes: ``` New-Struct Contact @{ First=[string]; Last=[string]; Phone=[string]; } ``` Using `Add-Type` or `New-Struct` will let you actually test the class in your `param([Contact]$contact)` and make new ones using `$contact = new-object Contact` and so on... In PowerShell 3 =============== If you don't need a "real" class that you can cast to, you don't have to use the Add-Member way that [Steven and others have demonstrated](https://stackoverflow.com/a/59980/8718) above. Since PowerShell 2 you could use the -Property parameter for New-Object: ``` $Contact = New-Object PSObject -Property @{ First=""; Last=""; Phone="" } ``` And in PowerShell 3, we got the ability to use the `PSCustomObject` accelerator to add a TypeName: ``` [PSCustomObject]@{ PSTypeName = "Contact" First = $First Last = $Last Phone = $Phone } ``` You're still only getting a single object, so you should make a `New-Contact` function to make sure that every object comes out the same, but you can now easily verify a parameter "is" one of those type by decorating a parameter with the `PSTypeName` attribute: ``` function PrintContact { param( [PSTypeName("Contact")]$contact ) "Customer Name is " + $contact.First + " " + $contact.Last "Customer Phone is " + $contact.Phone } ``` In PowerShell 5 =============== In PowerShell 5 everything changes, and we finally got `class` and `enum` as language keywords for defining types (there's no `struct` but that's ok): ``` class Contact { # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone # optionally, have a constructor to # force properties to be set: Contact($First, $Last, $Phone) { $this.First = $First $this.Last = $Last $this.Phone = $Phone } } ``` We also got a new way to create objects without using `New-Object`: `[Contact]::new()` -- in fact, if you kept your class simple and don't define a constructor, you can create objects by casting a hashtable (although without a constructor, there would be no way to enforce that all properties must be set): ``` class Contact { # Optionally, add attributes to prevent invalid values [ValidateNotNullOrEmpty()][string]$First [ValidateNotNullOrEmpty()][string]$Last [ValidateNotNullOrEmpty()][string]$Phone } $C = [Contact]@{ First = "Joel" Last = "Bennett" } ```
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt; s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and dirty:</p> <pre><code>&gt;&gt;&gt; elem = s.pop() &gt;&gt;&gt; s.add(elem) </code></pre> <p>But do you know of a better way? Ideally in constant time.</p>
[ { "answer_id": 59841, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 11, "selected": true, "text": "<p>Two options that don't require copying the whole set:</p>\n\n<pre><code>for e in s:\n break\n# e is now an element from s\n</code></pre>\n\n<p>Or...</p>\n\n<pre><code>e = next(iter(s))\n</code></pre>\n\n<p>But in general, sets don't support indexing or slicing.</p>\n" }, { "answer_id": 59928, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": -1, "selected": false, "text": "<p>Another option is to use a dictionary with values you don't care about. E.g.,</p>\n\n<pre><code>\npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\n...\n</code></pre>\n\n<p>You can treat the keys as a set except that they're just an array:</p>\n\n<pre><code>\nkeys = poor_man_set.keys()\nprint \"Some key = %s\" % keys[0]\n</code></pre>\n\n<p>A side effect of this choice is that your code will be backwards compatible with older, pre-<code>set</code> versions of Python. It's maybe not the best answer but it's another option.</p>\n\n<p>Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:</p>\n\n<pre><code>\npoor_man_set = {}\npoor_man_set[1] = None\npoor_man_set[2] = None\npoor_man_set[3] = None\npoor_man_set = poor_man_set.keys()\n</code></pre>\n" }, { "answer_id": 60027, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 5, "selected": false, "text": "<p>Since you want a random element, this will also work:</p>\n\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; s = set([1,2,3])\n&gt;&gt;&gt; random.sample(s, 1)\n[2]\n</code></pre>\n\n<p>The documentation doesn't seem to mention performance of <code>random.sample</code>. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:</p>\n\n<pre><code>&gt;&gt;&gt; list(set(range(10))) == range(10)\nTrue \n</code></pre>\n\n<p>If randomness is important and you need a bunch of elements in constant time (large sets), I'd use <code>random.sample</code> and convert to a list first:</p>\n\n<pre><code>&gt;&gt;&gt; lst = list(s) # once, O(len(s))?\n...\n&gt;&gt;&gt; e = random.sample(lst, 1)[0] # constant time\n</code></pre>\n" }, { "answer_id": 60233, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 8, "selected": false, "text": "<p>Least code would be:</p>\n\n<pre><code>&gt;&gt;&gt; s = set([1, 2, 3])\n&gt;&gt;&gt; list(s)[0]\n1\n</code></pre>\n\n<p>Obviously this would create a new list which contains each member of the set, so not great if your set is very large.</p>\n" }, { "answer_id": 61140, "author": "Nick", "author_id": 5222, "author_profile": "https://Stackoverflow.com/users/5222", "pm_score": 3, "selected": false, "text": "<p>I use a utility function I wrote. Its name is somewhat misleading because it kind of implies it might be a random item or something like that.</p>\n\n<pre><code>def anyitem(iterable):\n try:\n return iter(iterable).next()\n except StopIteration:\n return None\n</code></pre>\n" }, { "answer_id": 1612654, "author": "wr.", "author_id": 101430, "author_profile": "https://Stackoverflow.com/users/101430", "pm_score": 5, "selected": false, "text": "<p>To provide some timing figures behind the different approaches, consider the following code.\n<em>The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.</em></p>\n\n<pre><code>from timeit import *\n\nstats = [\"for i in xrange(1000): iter(s).next() \",\n \"for i in xrange(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in xrange(1000): s.add(s.pop()) \",\n \"for i in xrange(1000): s.get() \"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100))\")\n try:\n print \"Time for %s:\\t %f\"%(stat, t.timeit(number=1000))\n except:\n t.print_exc()\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>$ ./test_get.py\nTime for for i in xrange(1000): iter(s).next() : 0.433080\nTime for for i in xrange(1000):\n for x in s:\n break: 0.148695\nTime for for i in xrange(1000): s.add(s.pop()) : 0.317418\nTime for for i in xrange(1000): s.get() : 0.146673\n</code></pre>\n\n<p>This means that the <strong><em>for/break</em></strong> solution is the fastest (sometimes faster than the custom get() solution).</p>\n" }, { "answer_id": 34973737, "author": "AChampion", "author_id": 2750492, "author_profile": "https://Stackoverflow.com/users/2750492", "pm_score": 3, "selected": false, "text": "<p>Following @wr. post, I get similar results (for Python3.5)</p>\n\n<pre><code>from timeit import *\n\nstats = [\"for i in range(1000): next(iter(s))\",\n \"for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in range(1000): s.add(s.pop())\"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100000))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Time for for i in range(1000): next(iter(s)): 0.205888\nTime for for i in range(1000): \n for x in s: \n break: 0.083397\nTime for for i in range(1000): s.add(s.pop()): 0.226570\n</code></pre>\n\n<p>However, when changing the underlying set (e.g. call to <code>remove()</code>) things go badly for the iterable examples (<code>for</code>, <code>iter</code>):</p>\n\n<pre><code>from timeit import *\n\nstats = [\"while s:\\n\\ta = next(iter(s))\\n\\ts.remove(a)\",\n \"while s:\\n\\tfor x in s: break\\n\\ts.remove(x)\",\n \"while s:\\n\\tx=s.pop()\\n\\ts.add(x)\\n\\ts.remove(x)\"]\n\nfor stat in stats:\n t = Timer(stat, setup=\"s=set(range(100000))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>Time for while s:\n a = next(iter(s))\n s.remove(a): 2.938494\nTime for while s:\n for x in s: break\n s.remove(x): 2.728367\nTime for while s:\n x=s.pop()\n s.add(x)\n s.remove(x): 0.030272\n</code></pre>\n" }, { "answer_id": 40054478, "author": "Cecil Curry", "author_id": 2809027, "author_profile": "https://Stackoverflow.com/users/2809027", "pm_score": 6, "selected": false, "text": "<h2>tl;dr</h2>\n\n<p><code>for first_item in muh_set: break</code> remains the optimal approach in Python 3.x. <sup><em>Curse you, Guido.</em></sup></p>\n\n<h2>y u do this</h2>\n\n<p>Welcome to yet another set of Python 3.x timings, extrapolated from <a href=\"https://stackoverflow.com/users/101430/wr\">wr.</a>'s excellent <a href=\"https://stackoverflow.com/a/1612654/2809027\">Python 2.x-specific response</a>. Unlike <a href=\"https://stackoverflow.com/users/2750492/achampion\">AChampion</a>'s equally helpful <a href=\"https://stackoverflow.com/a/34973737/2809027\">Python 3.x-specific response</a>, the timings below <em>also</em> time outlier solutions suggested above – including:</p>\n\n<ul>\n<li><code>list(s)[0]</code>, <a href=\"https://stackoverflow.com/users/2168/john\">John</a>'s novel <a href=\"https://stackoverflow.com/a/60233/2809027\">sequence-based solution</a>.</li>\n<li><code>random.sample(s, 1)</code>, <a href=\"https://stackoverflow.com/users/3002/df\">dF.</a>'s eclectic <a href=\"https://stackoverflow.com/a/60027/2809027\">RNG-based solution</a>.</li>\n</ul>\n\n<h2>Code Snippets for Great Joy</h2>\n\n<p>Turn on, tune in, time it:</p>\n\n<pre><code>from timeit import Timer\n\nstats = [\n \"for i in range(1000): \\n\\tfor x in s: \\n\\t\\tbreak\",\n \"for i in range(1000): next(iter(s))\",\n \"for i in range(1000): s.add(s.pop())\",\n \"for i in range(1000): list(s)[0]\",\n \"for i in range(1000): random.sample(s, 1)\",\n]\n\nfor stat in stats:\n t = Timer(stat, setup=\"import random\\ns=set(range(100))\")\n try:\n print(\"Time for %s:\\t %f\"%(stat, t.timeit(number=1000)))\n except:\n t.print_exc()\n</code></pre>\n\n<h2>Quickly Obsoleted Timeless Timings</h2>\n\n<p><strong>Behold!</strong> Ordered by fastest to slowest snippets:</p>\n\n<pre><code>$ ./test_get.py\nTime for for i in range(1000): \n for x in s: \n break: 0.249871\nTime for for i in range(1000): next(iter(s)): 0.526266\nTime for for i in range(1000): s.add(s.pop()): 0.658832\nTime for for i in range(1000): list(s)[0]: 4.117106\nTime for for i in range(1000): random.sample(s, 1): 21.851104\n</code></pre>\n\n<h2>Faceplants for the Whole Family</h2>\n\n<p>Unsurprisingly, <strong>manual iteration remains at least twice as fast</strong> as the next fastest solution. Although the gap has decreased from the Bad Old Python 2.x days (in which manual iteration was at least four times as fast), it disappoints the <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">PEP 20</a> zealot in me that the most verbose solution is the best. At least converting a set into a list just to extract the first element of the set is as horrible as expected. <em>Thank Guido, may his light continue to guide us.</em></p>\n\n<p>Surprisingly, the <strong>RNG-based solution is absolutely horrible.</strong> List conversion is bad, but <code>random</code> <em>really</em> takes the awful-sauce cake. So much for the <a href=\"http://catb.org/esr/jargon/html/R/Random-Number-God.html\" rel=\"noreferrer\">Random Number God</a>.</p>\n\n<p>I just wish the amorphous They would PEP up a <code>set.get_first()</code> method for us already. If you're reading this, They: \"Please. Do something.\"</p>\n" }, { "answer_id": 45803038, "author": "skovorodkin", "author_id": 847552, "author_profile": "https://Stackoverflow.com/users/847552", "pm_score": 4, "selected": false, "text": "<p>Seemingly the <strong>most compact</strong> (6 symbols) though <strong>very slow</strong> way to get a set element (made possible by <a href=\"https://www.python.org/dev/peps/pep-3132/\" rel=\"noreferrer\">PEP 3132</a>):</p>\n\n<pre><code>e,*_=s\n</code></pre>\n\n<p>With Python 3.5+ you can also use this 7-symbol expression (thanks to <a href=\"https://www.python.org/dev/peps/pep-0448/\" rel=\"noreferrer\">PEP 448</a>):</p>\n\n<pre><code>[*s][0]\n</code></pre>\n\n<p>Both options are roughly 1000 times slower on my machine than the for-loop method.</p>\n" }, { "answer_id": 48874729, "author": "MSeifert", "author_id": 5393381, "author_profile": "https://Stackoverflow.com/users/5393381", "pm_score": 7, "selected": false, "text": "<p>I wondered how the functions will perform for different sets, so I did a benchmark:</p>\n\n<pre><code>from random import sample\n\ndef ForLoop(s):\n for e in s:\n break\n return e\n\ndef IterNext(s):\n return next(iter(s))\n\ndef ListIndex(s):\n return list(s)[0]\n\ndef PopAdd(s):\n e = s.pop()\n s.add(e)\n return e\n\ndef RandomSample(s):\n return sample(s, 1)\n\ndef SetUnpacking(s):\n e, *_ = s\n return e\n\nfrom simple_benchmark import benchmark\n\nb = benchmark([ForLoop, IterNext, ListIndex, PopAdd, RandomSample, SetUnpacking],\n {2**i: set(range(2**i)) for i in range(1, 20)},\n argument_name='set size',\n function_aliases={first: 'First'})\n\nb.plot()\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/7oqB6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7oqB6.png\" alt=\"enter image description here\"></a></p>\n\n<p>This plot clearly shows that some approaches (<code>RandomSample</code>, <code>SetUnpacking</code> and <code>ListIndex</code>) depend on the size of the set and should be avoided in the general case (at least if performance <em>might</em> be important). As already shown by the other answers the fastest way is <code>ForLoop</code>.</p>\n\n<p>However as long as one of the constant time approaches is used the performance difference will be negligible.</p>\n\n<hr>\n\n<p><a href=\"https://iteration-utilities.readthedocs.io/en/latest/index.html\" rel=\"noreferrer\"><code>iteration_utilities</code></a> (Disclaimer: I'm the author) contains a convenience function for this use-case: <a href=\"https://iteration-utilities.readthedocs.io/en/latest/generated/first.html\" rel=\"noreferrer\"><code>first</code></a>:</p>\n\n<pre><code>&gt;&gt;&gt; from iteration_utilities import first\n&gt;&gt;&gt; first({1,2,3,4})\n1\n</code></pre>\n\n<p>I also included it in the benchmark above. It can compete with the other two \"fast\" solutions but the difference isn't much either way.</p>\n" }, { "answer_id": 49138346, "author": "Solomon Ucko", "author_id": 5445670, "author_profile": "https://Stackoverflow.com/users/5445670", "pm_score": -1, "selected": false, "text": "<p>How about <code>s.copy().pop()</code>? I haven't timed it, but it should work and it's simple. It works best for small sets however, as it copies the whole set.</p>\n" }, { "answer_id": 60803131, "author": "Josué Carvajal", "author_id": 5911191, "author_profile": "https://Stackoverflow.com/users/5911191", "pm_score": 2, "selected": false, "text": "<p>What I usually do for small collections is to create kind of parser/converter method like this</p>\n\n<pre><code>def convertSetToList(setName):\nreturn list(setName)\n</code></pre>\n\n<p>Then I can use the new list and access by index number</p>\n\n<pre><code>userFields = convertSetToList(user)\nname = request.json[userFields[0]]\n</code></pre>\n\n<p>As a list you will have all the other methods that you may need to work with</p>\n" }, { "answer_id": 64224698, "author": "seralouk", "author_id": 5025009, "author_profile": "https://Stackoverflow.com/users/5025009", "pm_score": 2, "selected": false, "text": "<p><strong>You can unpack the values to access the elements:</strong></p>\n<pre><code>s = set([1, 2, 3])\n\nv1, v2, v3 = s\n\nprint(v1,v2,v3)\n#1 2 3\n</code></pre>\n" }, { "answer_id": 64352862, "author": "dzang", "author_id": 7812912, "author_profile": "https://Stackoverflow.com/users/7812912", "pm_score": 4, "selected": false, "text": "<p>Yet another way in Python 3:</p>\n<pre><code>next(iter(s))\n</code></pre>\n<p>or</p>\n<pre><code>s.__iter__().__next__()\n</code></pre>\n" }, { "answer_id": 65430015, "author": "Necho", "author_id": 3558704, "author_profile": "https://Stackoverflow.com/users/3558704", "pm_score": 0, "selected": false, "text": "<p>I f you want just the first element try this:\nb = (a-set()).pop()</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
Suppose the following: ``` >>> s = set([1, 2, 3]) ``` How do I get a value (any value) out of `s` without doing `s.pop()`? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: ``` >>> elem = s.pop() >>> s.add(elem) ``` But do you know of a better way? Ideally in constant time.
Two options that don't require copying the whole set: ``` for e in s: break # e is now an element from s ``` Or... ``` e = next(iter(s)) ``` But in general, sets don't support indexing or slicing.
59,832
<p>I am currently calling the following line of code:</p> <pre><code>java.net.URL connection_url = new java.net.URL("http://&lt;ip address&gt;:&lt;port&gt;/path"); </code></pre> <p>and I get the exception above when it executes. Any ideas as to why this is happening?</p>
[ { "answer_id": 59851, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 2, "selected": false, "text": "<p>As a side note, you should be using <a href=\"http://java.sun.com/javase/6/docs/api/java/net/URI.html\" rel=\"nofollow noreferrer\">URI</a> because Java URL class is screwed up. (The equals method I believe)</p>\n" }, { "answer_id": 59864, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>That url string looks like it's invalid. Sure it's not supposed to be '<a href=\"http://path\" rel=\"nofollow noreferrer\">http://path</a>'? Or are the server &amp; port blank?</p>\n" }, { "answer_id": 59960, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": true, "text": "<p>Your code works perfectly fine for me:</p>\n\n<pre><code>public static void main(String[] args) {\n try {\n java.net.URL connection_url = new java.net.URL(\"http://:/path\");\n System.out.println(\"Instantiated new URL: \" + connection_url);\n }\n catch (MalformedURLException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Instantiated new URL: <a href=\"http://:/path\" rel=\"nofollow noreferrer\">http://:/path</a></p>\n</blockquote>\n\n<p>Sure you have the right line of code?</p>\n" }, { "answer_id": 7876198, "author": "Pavan", "author_id": 1010917, "author_profile": "https://Stackoverflow.com/users/1010917", "pm_score": 1, "selected": false, "text": "<p>I have also had the same exception, but in my case the URL which I was trying to execute had a space appended. After removing the space it worked fine for me. Check that the URL does not have any trailing spaces in your case.</p>\n" }, { "answer_id": 13266214, "author": "Jyoti", "author_id": 1805539, "author_profile": "https://Stackoverflow.com/users/1805539", "pm_score": 1, "selected": false, "text": "<p>I had the same error and it got resolved by the below :</p>\n\n<p>The jar files (JFree) which I added few days back got corrupted automatically and was causing this error. I downloaded the same files again from net and it worked fine for me.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
I am currently calling the following line of code: ``` java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path"); ``` and I get the exception above when it executes. Any ideas as to why this is happening?
Your code works perfectly fine for me: ``` public static void main(String[] args) { try { java.net.URL connection_url = new java.net.URL("http://:/path"); System.out.println("Instantiated new URL: " + connection_url); } catch (MalformedURLException e) { e.printStackTrace(); } } ``` > > Instantiated new URL: <http://:/path> > > > Sure you have the right line of code?
59,838
<p>What command checks if a directory exists or not within a Bash shell script?</p>
[ { "answer_id": 59839, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 13, "selected": true, "text": "<p>To check if a directory exists:</p>\n<pre><code>if [ -d &quot;$DIRECTORY&quot; ]; then\n echo &quot;$DIRECTORY does exist.&quot;\nfi\n</code></pre>\n<p>To check if a directory does not exist:</p>\n<pre><code>if [ ! -d &quot;$DIRECTORY&quot; ]; then\n echo &quot;$DIRECTORY does not exist.&quot;\nfi\n</code></pre>\n<hr />\n<p>However, as <a href=\"https://stackoverflow.com/users/1438/jon-ericson\">Jon Ericson</a> points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.\nE.g. running this:</p>\n<pre><code>ln -s &quot;$ACTUAL_DIR&quot; &quot;$SYMLINK&quot;\nif [ -d &quot;$SYMLINK&quot; ]; then \n rmdir &quot;$SYMLINK&quot; \nfi\n</code></pre>\n<p>Will produce the error message:</p>\n<pre class=\"lang-none prettyprint-override\"><code>rmdir: failed to remove `symlink': Not a directory\n</code></pre>\n<p>So symbolic links may have to be treated differently, if subsequent commands expect directories:</p>\n<pre><code>if [ -d &quot;$LINK_OR_DIR&quot; ]; then \n if [ -L &quot;$LINK_OR_DIR&quot; ]; then\n # It is a symlink!\n # Symbolic link specific commands go here.\n rm &quot;$LINK_OR_DIR&quot;\n else\n # It's a directory!\n # Directory command goes here.\n rmdir &quot;$LINK_OR_DIR&quot;\n fi\nfi\n</code></pre>\n<hr />\n<p>Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean <a href=\"https://stackoverflow.com/a/67458/102401\">in another answer</a>.</p>\n<p>If the variables contain spaces or other unusual characters it will probably cause the script to fail.</p>\n" }, { "answer_id": 59853, "author": "Neil Neyman", "author_id": 3240, "author_profile": "https://Stackoverflow.com/users/3240", "pm_score": 5, "selected": false, "text": "<h2>More features using <code>find</code></h2>\n<ul>\n<li><p>Check existence of the folder within sub-directories:</p>\n<pre><code> found=`find -type d -name &quot;myDirectory&quot;`\n if [ -n &quot;$found&quot; ]\n then\n # The variable 'found' contains the full path where &quot;myDirectory&quot; is.\n # It may contain several lines if there are several folders named &quot;myDirectory&quot;.\n fi\n</code></pre>\n</li>\n<li><p>Check existence of one or several folders based on a pattern within the current directory:</p>\n<pre><code> found=`find -maxdepth 1 -type d -name &quot;my*&quot;`\n if [ -n &quot;$found&quot; ]\n then\n # The variable 'found' contains the full path where folders &quot;my*&quot; have been found.\n fi\n</code></pre>\n</li>\n<li><p>Both combinations. In the following example, it checks the existence of the folder in the current directory:</p>\n<pre><code> found=`find -maxdepth 1 -type d -name &quot;myDirectory&quot;`\n if [ -n &quot;$found&quot; ]\n then\n # The variable 'found' is not empty =&gt; &quot;myDirectory&quot;` exists.\n fi\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 59871, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 8, "selected": false, "text": "<p>Note the <strong>-d</strong> test can produce some surprising results:</p>\n\n<pre><code>$ ln -s tmp/ t\n$ if [ -d t ]; then rmdir t; fi\nrmdir: directory \"t\": Path component not a directory\n</code></pre>\n\n<p>File under: \"When is a directory not a directory?\" The answer: \"When it's a symlink to a directory.\" A slightly more thorough test:</p>\n\n<pre><code>if [ -d t ]; then \n if [ -L t ]; then \n rm t\n else \n rmdir t\n fi\nfi\n</code></pre>\n\n<p>You can find more information in the Bash manual on <a href=\"https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions\" rel=\"noreferrer\">Bash conditional expressions</a> and the <a href=\"https://www.gnu.org/software/bash/manual/bash.html#index-_005b\" rel=\"noreferrer\"><code>[</code> builtin command</a> and the <a href=\"https://www.gnu.org/software/bash/manual/bash.html#index-_005b_005b\" rel=\"noreferrer\"><code>[[</code> compound commmand</a>.</p>\n" }, { "answer_id": 59969, "author": "elmarco", "author_id": 1277510, "author_profile": "https://Stackoverflow.com/users/1277510", "pm_score": 8, "selected": false, "text": "<p>Shorter form:</p>\n<pre class=\"lang-sh prettyprint-override\"><code># if $DIR is a directory, then print yes\n[ -d &quot;$DIR&quot; ] &amp;&amp; echo &quot;Yes&quot;\n</code></pre>\n" }, { "answer_id": 60014, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 8, "selected": false, "text": "<p>I find the <a href=\"http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS\" rel=\"noreferrer\">double-bracket</a> version of <code>test</code> makes writing logic tests more natural:</p>\n\n<pre><code>if [[ -d \"${DIRECTORY}\" &amp;&amp; ! -L \"${DIRECTORY}\" ]] ; then\n echo \"It's a bona-fide directory\"\nfi\n</code></pre>\n" }, { "answer_id": 67458, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 9, "selected": false, "text": "<p>Always wrap variables in double quotes when referencing them in a Bash script.</p>\n<pre><code>if [ -d &quot;$DIRECTORY&quot; ]; then\n # Will enter here if $DIRECTORY exists, even if it contains spaces\nfi\n</code></pre>\n<p>Kids these days put spaces and lots of other funny characters in their directory names. (Spaces! Back in my day, we didn't have no fancy spaces!)\nOne day, one of those kids will run your script with <code>$DIRECTORY</code> set to <code>&quot;My M0viez&quot;</code> and your script will blow up. You don't want that. So use double quotes.</p>\n" }, { "answer_id": 1288121, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Or for something completely useless:</p>\n\n<pre><code>[ -d . ] || echo \"No\"\n</code></pre>\n" }, { "answer_id": 2283055, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 5, "selected": false, "text": "<p>Actually, you should use several tools to get a bulletproof approach:</p>\n\n<pre><code>DIR_PATH=`readlink -f \"${the_stuff_you_test}\"` # Get rid of symlinks and get abs path\nif [[ -d \"${DIR_PATH}\" ]] ; Then # Now you're testing\n echo \"It's a dir\";\nfi\n</code></pre>\n\n<p>There isn't any need to worry about spaces and special characters as long as you use <code>\"${}\"</code>.</p>\n\n<p>Note that <code>[[]]</code> is not as portable as <code>[]</code>, but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.</p>\n" }, { "answer_id": 2469169, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>if [ -d \"$DIRECTORY\" ]; then\n # Will enter here if $DIRECTORY exists\nfi\n</code></pre>\n\n<p>This is not completely true...</p>\n\n<p>If you want to go to that directory, you also need to have the execute rights on the directory. Maybe you need to have write rights as well.</p>\n\n<p>Therefore:</p>\n\n<pre><code>if [ -d \"$DIRECTORY\" ] &amp;&amp; [ -x \"$DIRECTORY\" ] ; then\n # ... to go to that directory (even if DIRECTORY is a link)\n cd $DIRECTORY\n pwd\nfi\n</code></pre>\n\n<hr>\n\n<pre><code>if [ -d \"$DIRECTORY\" ] &amp;&amp; [ -w \"$DIRECTORY\" ] ; then\n # ... to go to that directory and write something there (even if DIRECTORY is a link)\n cd $DIRECTORY\n touch foobar\nfi\n</code></pre>\n" }, { "answer_id": 2680681, "author": "muralikrishna", "author_id": 321968, "author_profile": "https://Stackoverflow.com/users/321968", "pm_score": 5, "selected": false, "text": "<pre><code>if [ -d \"$Directory\" -a -w \"$Directory\" ]\nthen\n #Statements\nfi\n</code></pre>\n\n<p>The above code checks if the directory exists and if it is writable.</p>\n" }, { "answer_id": 7436646, "author": "ztank1013", "author_id": 938615, "author_profile": "https://Stackoverflow.com/users/938615", "pm_score": 3, "selected": false, "text": "<p>The <code>ls</code> command in conjunction with <code>-l</code> (long listing) option returns attributes information about files and directories.<br>\nIn particular the first character of <code>ls -l</code> output it is usually a <code>d</code> or a <code>-</code> (dash). In case of a <code>d</code> the one listed is a directory for sure.</p>\n\n<p>The following command in just one line will tell you if the given <strong><code>ISDIR</code></strong> variable contains a path to a directory or not:</p>\n\n<pre><code>[[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] &amp;&amp;\n echo \"YES, $ISDIR is a directory.\" || \n echo \"Sorry, $ISDIR is not a directory\"\n</code></pre>\n\n<p>Practical usage:</p>\n\n<pre><code> [claudio@nowhere ~]$ ISDIR=\"$HOME/Music\" \n [claudio@nowhere ~]$ ls -ld \"$ISDIR\"\n drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music\n [claudio@nowhere ~]$ [[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] &amp;&amp; \n echo \"YES, $ISDIR is a directory.\" ||\n echo \"Sorry, $ISDIR is not a directory\"\n YES, /home/claudio/Music is a directory.\n\n [claudio@nowhere ~]$ touch \"empty file.txt\"\n [claudio@nowhere ~]$ ISDIR=\"$HOME/empty file.txt\" \n [claudio@nowhere ~]$ [[ $(ls -ld \"$ISDIR\" | cut -c1) == 'd' ]] &amp;&amp; \n echo \"YES, $ISDIR is a directory.\" || \n echo \"Sorry, $ISDIR is not a directoy\"\n Sorry, /home/claudio/empty file.txt is not a directory\n</code></pre>\n" }, { "answer_id": 8480518, "author": "dromichaetes", "author_id": 1094365, "author_profile": "https://Stackoverflow.com/users/1094365", "pm_score": 3, "selected": false, "text": "<p>There are great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:</p>\n\n<pre><code>if [ -d \"$LINK_OR_DIR\" ]; then\nif [ -L \"$LINK_OR_DIR\" ]; then\n # It is a symlink!\n # Symbolic link specific commands go here\n rm \"$LINK_OR_DIR\"\nelse\n # It's a directory!\n # Directory command goes here\n rmdir \"$LINK_OR_DIR\"\nfi\nfi\n</code></pre>\n\n<p>will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.</p>\n\n<p>I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:</p>\n\n<pre><code>dir=\" \"\necho \"Input directory name to search for:\"\nread dir\nfind $HOME -name $dir -type d\n</code></pre>\n\n<p>This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29\" rel=\"nofollow noreferrer\">standard output</a> (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.</p>\n" }, { "answer_id": 11892411, "author": "Henk Langeveld", "author_id": 667820, "author_profile": "https://Stackoverflow.com/users/667820", "pm_score": 6, "selected": false, "text": "<p>Here's a very pragmatic idiom:</p>\n\n<pre><code>(cd $dir) || return # Is this a directory,\n # and do we have access?\n</code></pre>\n\n<p>I typically wrap it in a function:</p>\n\n<pre><code>can_use_as_dir() {\n (cd ${1:?pathname expected}) || return\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>assert_dir_access() {\n (cd ${1:?pathname expected}) || exit\n}\n</code></pre>\n\n<p>The nice thing about this approach is that I do not have to think of a good error message.</p>\n\n<p><code>cd</code> will give me a standard one line message to <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)\" rel=\"noreferrer\">standard error</a> already. It will also give more information than I will be able to provide. By performing the <code>cd</code> inside a subshell <code>( ... )</code>, the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.</p>\n\n<p>Next is the argument that we pass to <code>cd</code>: <code>${1:?pathname expected}</code>. This is a more elaborate form of parameter substitution which is explained in more detail below.</p>\n\n<p>Tl;dr: If the string passed into this function is empty, we again exit from the subshell <code>( ... )</code> and return from the function with the given error message.</p>\n\n<hr>\n\n<p>Quoting from the <code>ksh93</code> man page:</p>\n\n<pre><code>${parameter:?word}\n</code></pre>\n\n<blockquote>\n <p>If <code>parameter</code> is set and is non-null then substitute its value;\n otherwise, print <code>word</code> and exit from the shell (if not interactive).\n If <code>word</code> is omitted then a standard message is printed.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>If the colon <code>:</code> is omitted from the above expressions, then the\n shell only checks whether parameter is set or not.</p>\n</blockquote>\n\n<p>The phrasing here is peculiar to the shell documentation, as <code>word</code> may refer to any reasonable string, including whitespace.</p>\n\n<p>In this particular case, I know that the standard error message <code>1: parameter not set</code> is not sufficient, so I zoom in on the type of value that we expect here - the <code>pathname</code> of a directory.</p>\n\n<p>A philosophical note:</p>\n\n<p>The shell is not an object oriented language, so the message says <code>pathname</code>, not <code>directory</code>. At this level, I'd rather keep it simple - the arguments to a function are just strings.</p>\n" }, { "answer_id": 15015952, "author": "ajmartin", "author_id": 477522, "author_profile": "https://Stackoverflow.com/users/477522", "pm_score": 3, "selected": false, "text": "<pre><code>file=\"foo\" \nif [[ -e \"$file\" ]]; then echo \"File Exists\"; fi;\n</code></pre>\n" }, { "answer_id": 16093972, "author": "Juan Carlos Kuri Pinto", "author_id": 1408995, "author_profile": "https://Stackoverflow.com/users/1408995", "pm_score": 4, "selected": false, "text": "<pre><code>[ -d ~/Desktop/TEMPORAL/ ] &amp;&amp; echo \"DIRECTORY EXISTS\" || echo \"DIRECTORY DOES NOT EXIST\"\n</code></pre>\n" }, { "answer_id": 17859049, "author": "bailey86", "author_id": 450406, "author_profile": "https://Stackoverflow.com/users/450406", "pm_score": 4, "selected": false, "text": "<p>Using the <code>-e</code> check will check for files and this includes directories.</p>\n\n<pre><code>if [ -e ${FILE_PATH_AND_NAME} ]\nthen\n echo \"The file or directory exists.\"\nfi\n</code></pre>\n" }, { "answer_id": 20978574, "author": "derFunk", "author_id": 591004, "author_profile": "https://Stackoverflow.com/users/591004", "pm_score": 3, "selected": false, "text": "<p>If you want to check if a directory exists, regardless if it's a real directory or a symlink, use this:</p>\n\n<pre><code>ls $DIR\nif [ $? != 0 ]; then\n echo \"Directory $DIR already exists!\"\n exit 1;\nfi\necho \"Directory $DIR does not exist...\"\n</code></pre>\n\n<p>Explanation: The \"ls\" command gives an error \"ls: /x: No such file or directory\" if the directory or symlink does not exist, and also sets the return code, which you can retrieve via \"$?\", to non-null (normally \"1\").\nBe sure that you check the return code directly after calling \"ls\".</p>\n" }, { "answer_id": 25287796, "author": "Sadhun", "author_id": 3455684, "author_profile": "https://Stackoverflow.com/users/3455684", "pm_score": 3, "selected": false, "text": "<p>The below <code>find</code> can be used,</p>\n\n<pre><code>find . -type d -name dirname -prune -print\n</code></pre>\n" }, { "answer_id": 29505062, "author": "Jorge Barroso", "author_id": 4761359, "author_profile": "https://Stackoverflow.com/users/4761359", "pm_score": 7, "selected": false, "text": "<p>To check if a directory exists you can use a simple <code>if</code> structure like this:</p>\n\n<pre><code>if [ -d directory/path to a directory ] ; then\n# Things to do\n\nelse #if needed #also: elif [new condition]\n# Things to do\nfi\n</code></pre>\n\n<p>You can also do it in the negative:</p>\n\n<pre><code>if [ ! -d directory/path to a directory ] ; then\n# Things to do when not an existing directory\n</code></pre>\n\n<p><strong>Note</strong>: Be careful. Leave empty spaces on either side of both opening and closing braces.</p>\n\n<p>With the same syntax you can use:</p>\n\n<pre><code>-e: any kind of archive\n\n-f: file\n\n-h: symbolic link\n\n-r: readable file\n\n-w: writable file\n\n-x: executable file\n\n-s: file size greater than zero\n</code></pre>\n" }, { "answer_id": 29724604, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 4, "selected": false, "text": "<pre><code>[[ -d \"$DIR\" &amp;&amp; ! -L \"$DIR\" ]] &amp;&amp; echo \"It's a directory and not a symbolic link\"\n</code></pre>\n\n<blockquote>\n <p>N.B: Quoting variables is a good practice.</p>\n</blockquote>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li><code>-d</code>: check if it's a directory</li>\n<li><code>-L</code>: check if it's a symbolic link</li>\n</ul>\n" }, { "answer_id": 30208219, "author": "Piyush Baijal", "author_id": 2458462, "author_profile": "https://Stackoverflow.com/users/2458462", "pm_score": 3, "selected": false, "text": "<p>(1)</p>\n\n<pre><code>[ -d Piyush_Drv1 ] &amp;&amp; echo \"\"Exists\"\" || echo \"Not Exists\"\n</code></pre>\n\n<p>(2)</p>\n\n<pre><code>[ `find . -type d -name Piyush_Drv1 -print | wc -l` -eq 1 ] &amp;&amp; echo Exists || echo \"Not Exists\"\n</code></pre>\n\n<p>(3)</p>\n\n<pre><code>[[ -d run_dir &amp;&amp; ! -L run_dir ]] &amp;&amp; echo Exists || echo \"Not Exists\"\n</code></pre>\n\n<p>If an issue is found with one of the approaches provided above:</p>\n\n<p>With the <code>ls</code> command; the cases when a directory does not exists - an error message is shown</p>\n\n<pre><code>[[ `ls -ld SAMPLE_DIR| grep ^d | wc -l` -eq 1 ]] &amp;&amp; echo exists || not exists\n</code></pre>\n\n<blockquote>\n <p>-ksh: not: not found [No such file or directory]</p>\n</blockquote>\n" }, { "answer_id": 32543846, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<p>As per <a href=\"https://stackoverflow.com/users/15168/jonathan-leffler\">Jonathan</a>'s comment:</p>\n\n<p>If you want to create the directory and it does not exist yet, then the simplest technique is to use <code>mkdir -p</code> which creates the directory — and any missing directories up the path — and does not fail if the directory already exists, so you can do it all at once with:</p>\n\n<pre><code>mkdir -p /some/directory/you/want/to/exist || exit 1\n</code></pre>\n" }, { "answer_id": 32543895, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 7, "selected": false, "text": "<p>You can use <code>test -d</code> (see <code>man test</code>).</p>\n\n<blockquote>\n <p><code>-d file</code> True if file exists and is a directory.</p>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>test -d \"/etc\" &amp;&amp; echo Exists || echo Does not exist\n</code></pre>\n\n<p>Note: The <code>test</code> command is same as conditional expression <code>[</code> (see: <code>man [</code>), so it's portable across shell scripts.</p>\n\n<blockquote>\n <p><code>[</code> - This is a synonym for the <code>test</code> builtin, but the last argument must, be a literal <code>]</code>, to match the opening <code>[</code>.</p>\n</blockquote>\n\n<p>For possible options or further help, check:</p>\n\n<ul>\n<li><code>help [</code></li>\n<li><code>help test</code></li>\n<li><code>man test</code> or <code>man [</code></li>\n</ul>\n" }, { "answer_id": 34508422, "author": "Raamesh Keerthi", "author_id": 1116081, "author_profile": "https://Stackoverflow.com/users/1116081", "pm_score": 4, "selected": false, "text": "<p>To check more than one directory use this code:</p>\n\n<pre><code>if [ -d \"$DIRECTORY1\" ] &amp;&amp; [ -d \"$DIRECTORY2\" ] then\n # Things to do\nfi\n</code></pre>\n" }, { "answer_id": 36172057, "author": "David Okwii", "author_id": 547050, "author_profile": "https://Stackoverflow.com/users/547050", "pm_score": 4, "selected": false, "text": "<p>Check if the directory exists, else make one:</p>\n\n<pre><code>[ -d \"$DIRECTORY\" ] || mkdir $DIRECTORY\n</code></pre>\n" }, { "answer_id": 36654179, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/59871/26510\">This answer</a> wrapped up as a shell script</p>\n\n<h3>Examples</h3>\n\n<pre><code>$ is_dir ~ \nYES\n\n$ is_dir /tmp \nYES\n\n$ is_dir ~/bin \nYES\n\n$ mkdir '/tmp/test me'\n\n$ is_dir '/tmp/test me'\nYES\n\n$ is_dir /asdf/asdf \nNO\n\n# Example of calling it in another script\nDIR=~/mydata\nif [ $(is_dir $DIR) == \"NO\" ]\nthen\n echo \"Folder doesnt exist: $DIR\";\n exit;\nfi\n</code></pre>\n\n<h3>is_dir</h3>\n\n<pre><code>function show_help()\n{\n IT=$(CAT &lt;&lt;EOF\n\n usage: DIR\n output: YES or NO, depending on whether or not the directory exists.\n\n )\n echo \"$IT\"\n exit\n}\n\nif [ \"$1\" == \"help\" ]\nthen\n show_help\nfi\nif [ -z \"$1\" ]\nthen\n show_help\nfi\n\nDIR=$1\nif [ -d $DIR ]; then \n echo \"YES\";\n exit;\nfi\necho \"NO\";\n</code></pre>\n" }, { "answer_id": 43426718, "author": "Abhishek Gurjar", "author_id": 5345150, "author_profile": "https://Stackoverflow.com/users/5345150", "pm_score": 3, "selected": false, "text": "<p>In kind of a <a href=\"https://en.wikipedia.org/wiki/%3F:\" rel=\"noreferrer\">ternary</a> form,</p>\n\n<pre><code>[ -d \"$directory\" ] &amp;&amp; echo \"exist\" || echo \"not exist\"\n</code></pre>\n\n<p>And with <a href=\"https://linux.die.net/man/1/test\" rel=\"noreferrer\"><code>test</code></a>:</p>\n\n<pre><code>test -d \"$directory\" &amp;&amp; echo \"exist\" || echo \"not exist\"\n</code></pre>\n" }, { "answer_id": 44835790, "author": "Gene", "author_id": 2057089, "author_profile": "https://Stackoverflow.com/users/2057089", "pm_score": 2, "selected": false, "text": "<p>From script file <em>myScript.sh</em>:</p>\n\n<pre><code>if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\\ Directory ]; then\n echo \"Directory exists!\"\n echo \"Great\"\nfi\n</code></pre>\n\n<p><em>Or</em></p>\n\n<pre><code>if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then\n echo \"Directory exists!\"\n echo \"Great\"\nfi\n</code></pre>\n" }, { "answer_id": 46205746, "author": "KANJICODER", "author_id": 1740154, "author_profile": "https://Stackoverflow.com/users/1740154", "pm_score": 2, "selected": false, "text": "<p><strong>Git Bash + Dropbox + Windows:</strong></p>\n\n<p>None of the other solutions worked for my Dropbox folder,\nwhich was weird because I can Git push to a Dropbox symbolic path.</p>\n\n<pre><code>#!/bin/bash\n\ndbox=\"~/Dropbox/\"\nresult=0\nprv=$(pwd) &amp;&amp; eval \"cd $dbox\" &amp;&amp; result=1 &amp;&amp; cd \"$prv\"\necho $result\n\nread -p \"Press Enter To Continue:\"\n</code></pre>\n\n<p>You'll probably want to know how to successfully navigate to Dropbox from Bash as well. So here is the script in its entirety.</p>\n\n<p><a href=\"https://pastebin.com/QF2Exmpn\" rel=\"nofollow noreferrer\">https://pastebin.com/QF2Exmpn</a></p>\n" }, { "answer_id": 47699462, "author": "ArtOfWarfare", "author_id": 901641, "author_profile": "https://Stackoverflow.com/users/901641", "pm_score": 5, "selected": false, "text": "<p>Have you considered just doing whatever you want to do in the <code>if</code> rather than looking before you leap?</p>\n\n<p>I.e., if you want to check for the existence of a directory before you enter it, try just doing this:</p>\n\n<pre><code>if pushd /path/you/want/to/enter; then\n # Commands you want to run in this directory\n popd\nfi\n</code></pre>\n\n<p>If the path you give to <code>pushd</code> exists, you'll enter it and it'll exit with <code>0</code>, which means the <code>then</code> portion of the statement will execute. If it doesn't exist, nothing will happen (other than some output saying the directory doesn't exist, which is probably a helpful side-effect anyways for debugging).</p>\n\n<p>It seems better than this, which requires repeating yourself:</p>\n\n<pre><code>if [ -d /path/you/want/to/enter ]; then\n pushd /path/you/want/to/enter\n # Commands you want to run in this directory\n popd\nfi\n</code></pre>\n\n<p>The same thing works with <code>cd</code>, <code>mv</code>, <code>rm</code>, etc... if you try them on files that don't exist, they'll exit with an error and print a message saying it doesn't exist, and your <code>then</code> block will be skipped. If you try them on files that do exist, the command will execute and exit with a status of <code>0</code>, allowing your <code>then</code> block to execute.</p>\n" }, { "answer_id": 50342967, "author": "yoctotutor.com", "author_id": 6484851, "author_profile": "https://Stackoverflow.com/users/6484851", "pm_score": 7, "selected": false, "text": "<ol>\n<li><p>A simple script to test if a directory or file is present or not:</p>\n<pre><code> if [ -d /home/ram/dir ] # For file &quot;if [ -f /home/rama/file ]&quot;\n then\n echo &quot;dir present&quot;\n else\n echo &quot;dir not present&quot;\n fi\n</code></pre>\n</li>\n<li><p>A simple script to check whether the directory is present or not:</p>\n<pre><code> mkdir tempdir # If you want to check file use touch instead of mkdir\n ret=$?\n if [ &quot;$ret&quot; == &quot;0&quot; ]\n then\n echo &quot;dir present&quot;\n else\n echo &quot;dir not present&quot;\n fi\n</code></pre>\n<p>The above scripts will check if the directory is present or not</p>\n<p><code>$?</code> if the last command is a success it returns &quot;0&quot;, else a non-zero value.\nSuppose <code>tempdir</code> is already present. Then <code>mkdir tempdir</code> will give an error like below:</p>\n<blockquote>\n<p>mkdir: cannot create directory ‘tempdir’: File exists</p>\n</blockquote>\n</li>\n</ol>\n" }, { "answer_id": 51017848, "author": "Sudip Bhandari", "author_id": 4589003, "author_profile": "https://Stackoverflow.com/users/4589003", "pm_score": 3, "selected": false, "text": "<p>Use the <code>file</code> program.\nConsidering all directories are also files in Linux, issuing the following command would suffice:</p>\n\n<p><code>file $directory_name</code></p>\n\n<p>Checking a nonexistent file: <code>file blah</code></p>\n\n<p><strong>Output:</strong> <code>cannot open 'blah' (No such file or directory)</code></p>\n\n<p>Checking an existing directory: <code>file bluh</code></p>\n\n<p><strong>Output:</strong> <code>bluh: directory</code></p>\n" }, { "answer_id": 57223290, "author": "Bayou", "author_id": 8382929, "author_profile": "https://Stackoverflow.com/users/8382929", "pm_score": 2, "selected": false, "text": "<p>Just as an alternative to the '[ -d ]' and '[ -h ]' options, you can make use of <code>stat</code> to obtain the file type and parse it.</p>\n\n<pre><code>#! /bin/bash\nMY_DIR=$1\nNODE_TYPE=$(stat -c '%F' ${MY_DIR} 2&gt;/dev/null)\ncase \"${NODE_TYPE}\" in\n \"directory\") echo $MY_DIR;;\n \"symbolic link\") echo $(readlink $MY_DIR);;\n \"\") echo \"$MY_DIR does not exist\";;\n *) echo \"$NODE_TYPE is unsupported\";;\nesac\nexit 0\n</code></pre>\n\n<p>Test data:</p>\n\n<pre><code>$ mkdir tmp\n$ ln -s tmp derp\n$ touch a.txt\n$ ./dir.sh tmp\ntmp\n$ ./dir.sh derp\ntmp\n$ ./dir.sh a.txt\nregular file is unsupported\n$ ./dir.sh god\ngod does not exist\n</code></pre>\n" }, { "answer_id": 58297948, "author": "Vishal", "author_id": 197473, "author_profile": "https://Stackoverflow.com/users/197473", "pm_score": 5, "selected": false, "text": "<pre class=\"lang-sh prettyprint-override\"><code>DIRECTORY=/tmp\n\nif [ -d \"$DIRECTORY\" ]; then\n echo \"Exists\"\nfi\n</code></pre>\n\n<p><strong><a href=\"https://code.labstack.com/7GMFlEaC\" rel=\"noreferrer\">Try online</a></strong></p>\n" }, { "answer_id": 71447129, "author": "Aybak3k", "author_id": 16146522, "author_profile": "https://Stackoverflow.com/users/16146522", "pm_score": 3, "selected": false, "text": "<p>One Liner:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>[[ -d $Directory ]] &amp;&amp; echo true\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
What command checks if a directory exists or not within a Bash shell script?
To check if a directory exists: ``` if [ -d "$DIRECTORY" ]; then echo "$DIRECTORY does exist." fi ``` To check if a directory does not exist: ``` if [ ! -d "$DIRECTORY" ]; then echo "$DIRECTORY does not exist." fi ``` --- However, as [Jon Ericson](https://stackoverflow.com/users/1438/jon-ericson) points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this: ``` ln -s "$ACTUAL_DIR" "$SYMLINK" if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fi ``` Will produce the error message: ```none rmdir: failed to remove `symlink': Not a directory ``` So symbolic links may have to be treated differently, if subsequent commands expect directories: ``` if [ -d "$LINK_OR_DIR" ]; then if [ -L "$LINK_OR_DIR" ]; then # It is a symlink! # Symbolic link specific commands go here. rm "$LINK_OR_DIR" else # It's a directory! # Directory command goes here. rmdir "$LINK_OR_DIR" fi fi ``` --- Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean [in another answer](https://stackoverflow.com/a/67458/102401). If the variables contain spaces or other unusual characters it will probably cause the script to fail.
59,840
<p>I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround.</p> <p>If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best.</p> <p>If you look at the raw query, the parameters look like this:</p> <pre><code>@P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... [@P3 through @P9] @P10 = '111' @P11 = '222' ... [@p12 through @P19] @P20 = 'sss' ... [@P21 through @P99] @P100 = 'qqq' </code></pre> <p>when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed:</p> <pre><code>@P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... @P10 = 'bbb'0 @P11 = 'bbb'1 ... @P20 = 'ccc'0 ... @P100 = 'bbb'00 </code></pre> <p>So it looks like the parameter resolving looks at the first digit only after the <code>@P</code> and resolves that, then adds on anything left at the end of the parameter name.</p> <p>At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing.</p> <p>Really strange.</p> <p>So if any one has advice please share. Thanks!</p> <p><strong>Update:</strong><br> I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue.</p>
[ { "answer_id": 59854, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 2, "selected": true, "text": "<p>The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer plugin for Visual Studio, not actually in Linq to SQL itself. So it is not nearly as bad a situation as I thought - the query will return the right results, but you can't trust what the Visualizer is showing. Not great, but better than what I thought was going on.</p>\n" }, { "answer_id": 60025, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Try actually looking at the output from your datacontext before you pass judgement.</p>\n\n<p>DataContext.Log() will give you the generated SQL.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215/" ]
I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround. If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best. If you look at the raw query, the parameters look like this: ``` @P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... [@P3 through @P9] @P10 = '111' @P11 = '222' ... [@p12 through @P19] @P20 = 'sss' ... [@P21 through @P99] @P100 = 'qqq' ``` when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed: ``` @P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... @P10 = 'bbb'0 @P11 = 'bbb'1 ... @P20 = 'ccc'0 ... @P100 = 'bbb'00 ``` So it looks like the parameter resolving looks at the first digit only after the `@P` and resolves that, then adds on anything left at the end of the parameter name. At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing. Really strange. So if any one has advice please share. Thanks! **Update:** I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue.
The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer plugin for Visual Studio, not actually in Linq to SQL itself. So it is not nearly as bad a situation as I thought - the query will return the right results, but you can't trust what the Visualizer is showing. Not great, but better than what I thought was going on.
59,850
<p>I'd like to create a spring bean that holds the value of a double. Something like:</p> <pre><code>&lt;bean id="doubleValue" value="3.7"/&gt; </code></pre>
[ { "answer_id": 59852, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>Why don't you just use a <strong>Double</strong>? any reason?</p>\n" }, { "answer_id": 59875, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 5, "selected": true, "text": "<p>Declare it like this:</p>\n\n<pre><code>&lt;bean id=\"doubleValue\" class=\"java.lang.Double\"&gt;\n &lt;constructor-arg index=\"0\" value=\"3.7\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>And use like this:</p>\n\n<pre><code>&lt;bean id=\"someOtherBean\" ...&gt;\n &lt;property name=\"value\" ref=\"doubleValue\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n" }, { "answer_id": 73838, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 3, "selected": false, "text": "<p>It's also worth noting that depending on your need defining your own bean may not be the best bet for you.</p>\n\n<pre><code>&lt;util:constant static-field=\"org.example.Constants.FOO\"/&gt;\n</code></pre>\n\n<p>is a good way to access a constant value stored in a class and default binders also work very well for conversions e.g. </p>\n\n<pre><code>&lt;bean class=\"Foo\" p:doubleValue=\"123.00\"/&gt;\n</code></pre>\n\n<p>I've found myself replacing many of my beans in this manner, coupled with a properties file defining my values (for reuse purposes). What used to look like this</p>\n\n<pre><code>&lt;bean id=\"d1\" class=\"java.lang.Double\"&gt;\n &lt;constructor-arg value=\"3.7\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"foo\" class=\"Foo\"&gt;\n &lt;property name=\"doubleVal\" ref=\"d1\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>gets refactored into this:</p>\n\n<pre><code>&lt;bean\n id=\"propertyFile\"\n class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"\n p:location=\"classpath:my.properties\"\n/&gt;\n&lt;bean id=\"foo\" class=\"Foo\" p:doubleVal=\"${d1}\"/&gt;\n</code></pre>\n" }, { "answer_id": 48786968, "author": "Subin Chalil", "author_id": 2756662, "author_profile": "https://Stackoverflow.com/users/2756662", "pm_score": 0, "selected": false, "text": "<p>Spring 2.5+</p>\n\n<p><strong>You can define bean like this in Java config:</strong></p>\n\n<pre><code>@Configuration\npublic class BeanConfig {\n @Bean\n public Double doubleBean(){\n return new Double(3.7);\n }\n}\n</code></pre>\n\n<p><strong>You can use this bean like this in your program:</strong></p>\n\n<pre><code>@Autowired\nDouble doubleBean;\n\npublic void printDouble(){\n System.out.println(doubleBean); //sample usage\n}\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
I'd like to create a spring bean that holds the value of a double. Something like: ``` <bean id="doubleValue" value="3.7"/> ```
Declare it like this: ``` <bean id="doubleValue" class="java.lang.Double"> <constructor-arg index="0" value="3.7"/> </bean> ``` And use like this: ``` <bean id="someOtherBean" ...> <property name="value" ref="doubleValue"/> </bean> ```
59,857
<p>Should I use a dedicated network channel between the database and the application server?</p> <p>...or... </p> <p>Connecting both in the switch along with all other computer nodes makes no diference at all?</p> <p>The matter is <strong>performance!</strong></p>
[ { "answer_id": 59852, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>Why don't you just use a <strong>Double</strong>? any reason?</p>\n" }, { "answer_id": 59875, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 5, "selected": true, "text": "<p>Declare it like this:</p>\n\n<pre><code>&lt;bean id=\"doubleValue\" class=\"java.lang.Double\"&gt;\n &lt;constructor-arg index=\"0\" value=\"3.7\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>And use like this:</p>\n\n<pre><code>&lt;bean id=\"someOtherBean\" ...&gt;\n &lt;property name=\"value\" ref=\"doubleValue\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n" }, { "answer_id": 73838, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 3, "selected": false, "text": "<p>It's also worth noting that depending on your need defining your own bean may not be the best bet for you.</p>\n\n<pre><code>&lt;util:constant static-field=\"org.example.Constants.FOO\"/&gt;\n</code></pre>\n\n<p>is a good way to access a constant value stored in a class and default binders also work very well for conversions e.g. </p>\n\n<pre><code>&lt;bean class=\"Foo\" p:doubleValue=\"123.00\"/&gt;\n</code></pre>\n\n<p>I've found myself replacing many of my beans in this manner, coupled with a properties file defining my values (for reuse purposes). What used to look like this</p>\n\n<pre><code>&lt;bean id=\"d1\" class=\"java.lang.Double\"&gt;\n &lt;constructor-arg value=\"3.7\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"foo\" class=\"Foo\"&gt;\n &lt;property name=\"doubleVal\" ref=\"d1\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>gets refactored into this:</p>\n\n<pre><code>&lt;bean\n id=\"propertyFile\"\n class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"\n p:location=\"classpath:my.properties\"\n/&gt;\n&lt;bean id=\"foo\" class=\"Foo\" p:doubleVal=\"${d1}\"/&gt;\n</code></pre>\n" }, { "answer_id": 48786968, "author": "Subin Chalil", "author_id": 2756662, "author_profile": "https://Stackoverflow.com/users/2756662", "pm_score": 0, "selected": false, "text": "<p>Spring 2.5+</p>\n\n<p><strong>You can define bean like this in Java config:</strong></p>\n\n<pre><code>@Configuration\npublic class BeanConfig {\n @Bean\n public Double doubleBean(){\n return new Double(3.7);\n }\n}\n</code></pre>\n\n<p><strong>You can use this bean like this in your program:</strong></p>\n\n<pre><code>@Autowired\nDouble doubleBean;\n\npublic void printDouble(){\n System.out.println(doubleBean); //sample usage\n}\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
Should I use a dedicated network channel between the database and the application server? ...or... Connecting both in the switch along with all other computer nodes makes no diference at all? The matter is **performance!**
Declare it like this: ``` <bean id="doubleValue" class="java.lang.Double"> <constructor-arg index="0" value="3.7"/> </bean> ``` And use like this: ``` <bean id="someOtherBean" ...> <property name="value" ref="doubleValue"/> </bean> ```
59,880
<p>Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them <strong>ALL THE TIME</strong>.</p> <p>I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or &lt;<em>Insert_your_DB_here</em>&gt;. Is it overkill to have ALL access through stored procedures?</p>
[ { "answer_id": 59883, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 1, "selected": false, "text": "<p>I don't know that they are faster. I like using ORM for data access (to not re-invent the wheel) but I realize that's not always a viable option. </p>\n\n<p>Frans Bouma has a good article on this subject : <a href=\"http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx</a></p>\n" }, { "answer_id": 59884, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 0, "selected": false, "text": "<p>Stored procs are great for cases where the SQL code is run frequently because the database stores it tokenized in memory. If you repeatedly ran the same code outside of a stored proc, you will likey incur a performance hit from the database reparsing the same code over and over.</p>\n\n<p>I typically frequently called code as a stored proc or as a SqlCommand (.NET) object and execute as many times as needed.</p>\n" }, { "answer_id": 59885, "author": "Alvaro Rodriguez", "author_id": 1550, "author_profile": "https://Stackoverflow.com/users/1550", "pm_score": 2, "selected": false, "text": "<p>Read Frans Bouma's <a href=\"http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx\" rel=\"nofollow noreferrer\">excellent post</a> (if a bit biased) on that.</p>\n" }, { "answer_id": 59892, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 5, "selected": false, "text": "<p>In many cases, stored procedures are actually slower because they're more genaralized. While stored procedures can be highly tuned, in my experience there's enough development and institutional friction that they're left in place once they work, so stored procedures often tend to return a lot of columns \"just in case\" - because you don't want to deploy a new stored procedure every time you change your application. An OR/M, on the other hand, only requests the columns the application is using, which cuts down on network traffic, unnecessary joins, etc.</p>\n" }, { "answer_id": 59894, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 1, "selected": false, "text": "<p>All I can speak to is SQL server. In that platform, stored procedures are lovely because the server stores the execution plan, which in most cases speeds up performance a good bit. I say \"in most cases\", because if the SP has widely varying paths of execution you might get suboptimal performance. However, even in those cases, some enlightened refactoring of the SPs can speed things up.</p>\n" }, { "answer_id": 59901, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 3, "selected": false, "text": "<p>It's a debate that rages on and on (for instance, <a href=\"https://stackoverflow.com/questions/22907/which-is-better-ad-hoc-queries-or-stored-procedures\">here</a>).</p>\n\n<p>It's as easy to write bad stored procedures as it is to write bad data access logic in your app.</p>\n\n<p>My preference is for Stored Procs, but that's because I'm typically working with very large and complex apps in an enterprise environment where there are dedicated DBAs who are responsible for keeping the database servers running sweetly.</p>\n\n<p>In other situations, I'm happy enough for data access technologies such as LINQ to take care of the optimisation.</p>\n\n<p>Pure performance isn't the only consideration, though. Aspects such as security and configuration management are typically at least as important.</p> \n\n<p>Edit: While Frans Bouma's article is indeed verbose, it misses the point with regard to security by a mile. The fact that it's 5 years old doesn't help its relevance, either.</p>\n" }, { "answer_id": 59907, "author": "Flory", "author_id": 5551, "author_profile": "https://Stackoverflow.com/users/5551", "pm_score": 2, "selected": false, "text": "<p>I prefer to use SP's when it makes sense to use them. In SQL Server anyway there is no performance advantage to SP's over a parametrized query.</p>\n\n<p>However, at my current job my boss mentioned that we are forced to use SP's because our customer's require them. They feel that they are more secure. I have not been here long enough to see if we are implementing role based security but I have a feeling we do.</p>\n\n<p>So the customer's feelings trump all other arguments in this case.</p>\n" }, { "answer_id": 59920, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>There is no noticeable speed difference for stored procedures vs parameterized or prepared queries on most modern databases, because the database will also cache execution plans for those queries. </p>\n\n<p>Note that a parameterized query is not the same as ad hoc sql.</p>\n\n<p>The main reason imo to still favor stored procedures today has more to do with security. If you use stored procedures <em>exclusively</em>, you can disable INSERT, SELECT, UPDATE, DELETE, ALTER, DROP, and CREATE etc permissions for your application's user, only leaving it with EXECUTE. </p>\n\n<p>This provides a little extra protection against <em>2nd order</em> sql injection. Parameterized queries only protect against <em>1st order</em> injection.</p>\n" }, { "answer_id": 59923, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": false, "text": "<p>Obviously, actual performance ought to be measured in individual cases, not assumed. But even in cases where performance is <em>hampered</em> by a stored procedure, there are good reasons to use them:</p>\n\n<ol>\n<li><p>Application developers aren't always the best SQL coders. Stored procedures hides SQL from the application.</p></li>\n<li><p>Stored procedures automatically use bind variables. Application developers often avoid bind variables because they seem like unneeded code and show little benefit in small test systems. Later on, the failure to use bind variables can throttle RDBMS performance.</p></li>\n<li><p>Stored procedures create a layer of indirection that might be useful later on. It's possible to change implementation details (including table structure) on the database side without touching application code.</p></li>\n<li><p>The exercise of creating stored procedures can be useful for documenting all database interactions for a system. And it's easier to update the documentation when things change.</p></li>\n</ol>\n\n<p>That said, I usually stick raw SQL in my applications so that I can control it myself. It depends on your development team and philosophy.</p>\n" }, { "answer_id": 59932, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 9, "selected": true, "text": "<blockquote>\n <p><strong>NOTE</strong> that this is a general look at stored procedures not regulated to a specific\n DBMS. Some DBMS (and even, different\n versions of the same DBMS!) may operate\n contrary to this, so you'll want to\n double-check with your target DBMS\n before assuming all of this still holds.</p>\n \n <p>I've been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war.</p>\n</blockquote>\n\n<p>The historical performance benefit of stored procs have generally been from the following (in no particular order):</p>\n\n<ul>\n<li>Pre-parsed SQL</li>\n<li>Pre-generated query execution plan</li>\n<li>Reduced network latency</li>\n<li>Potential cache benefits</li>\n</ul>\n\n<p><strong>Pre-parsed SQL</strong> -- similar benefits to compiled vs. interpreted code, except on a very micro level. </p>\n\n<p><em>Still an advantage?</em> \nNot very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up.</p>\n\n<p><strong>Pre-generated query execution plan</strong>. \nIf you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I've seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the \"near best\" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead.</p>\n\n<p><em>Still an advantage?</em> \nMost DBMS' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn't the case, so you'll need to test on your target DBMS.</p>\n\n<p>Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!).</p>\n\n<blockquote>\n <p><strong>WARNING</strong> Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal.\n For example, if you send <code>SELECT *\n FROM table WHERE id BETWEEN 1 AND\n 99999999</code>, the DBMS may select a\n full-table scan instead of an index\n scan because you're grabbing every row\n in the table (so sayeth the\n statistics). If this is the cached\n version, then you can get poor\n performance when you later send\n <code>SELECT * FROM table WHERE id BETWEEN\n 1 AND 2</code>. The reasoning behind this is\n outside the scope of this posting, but\n for further reading see:\n <a href=\"http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx\" rel=\"noreferrer\">http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx</a>\n and\n <a href=\"http://msdn.microsoft.com/en-us/library/ms181055.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms181055.aspx</a>\n and <a href=\"http://www.simple-talk.com/sql/performance/execution-plan-basics/\" rel=\"noreferrer\">http://www.simple-talk.com/sql/performance/execution-plan-basics/</a></p>\n \n <p>\"In summary, they determined that\n supplying anything other than the\n common values when a compile or\n recompile was performed resulted in\n the optimizer compiling and caching\n the query plan for that particular\n value. Yet, when that query plan was\n reused for subsequent executions of\n the same query for the common values\n (‘M’, ‘R’, or ‘T’), it resulted in\n sub-optimal performance. This\n sub-optimal performance problem\n existed until the query was\n recompiled. At that point, based on\n the @P1 parameter value supplied, the\n query might or might not have a\n performance problem.\"</p>\n</blockquote>\n\n<p><strong>Reduced network latency</strong>\nA) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple \"exec foobar\" can really add up.\nB) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone's favorite WTF!)</p>\n\n<p><em>Still an advantage?</em>\nA) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible. \nB) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason?</p>\n\n<p><strong>Potential cache benefits</strong>\nPerforming server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server.</p>\n\n<p><em>Still an advantage?</em>\nUnless your app has shared memory access to DBMS data, the edge will always be to stored procs.</p>\n\n<p>Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL.</p>\n\n<p><strong>Parameterized / Prepared SQL</strong><br>\nKind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses \"parameters\" for query values, e.g.:</p>\n\n<pre><code>SELECT .. FROM yourtable WHERE foo = ? AND bar = ?\n</code></pre>\n\n<p>These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures.</p>\n\n<p><strong>Ad Hoc SQL</strong>\nJust open a console window to your DBMS and type in a SQL statement. In the past, these were the \"worst\" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method.</p>\n\n<p><em>Still a disadvantage?</em>\nNot necessarily. Most DBMS have the ability to \"abstract\" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: <a href=\"http://msdn.microsoft.com/en-us/library/ms175037.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms175037.aspx</a> , Oracle: <a href=\"http://www.praetoriate.com/oracle_tips_cursor_sharing.htm\" rel=\"noreferrer\">http://www.praetoriate.com/oracle_tips_cursor_sharing.htm</a>).</p>\n\n<p><strong>Lessons learned?</strong>\nMoore's law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it's not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of <em>massive</em> stored procedure use ** solely for \"performance reasons\"** sure sounds like premature optimization to me.</p>\n\n<p>Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won't notice a difference between ad hoc and stored procedures.</p>\n" }, { "answer_id": 59946, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 1, "selected": false, "text": "<p>Using stored procedures for CRUD operations is probably overkill, but it will depend on the tools be used and your own preferences (or requirements). I prefer inline SQL, but I make sure to use parameterized queries to prevent SQL injection attacks. I keep a print out of this <a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">xkcd comic</a> as a reminder of what can go wrong if you are not careful.</p>\n\n<p>Stored procedures can have real performance benefits when you are working with multiple sets of data to return a single set of data. It's usually more efficient to process sets of data in the stored procedure than sending them over the wire to be processed at the client end.</p>\n" }, { "answer_id": 59949, "author": "Jake Hackl", "author_id": 5247, "author_profile": "https://Stackoverflow.com/users/5247", "pm_score": 0, "selected": false, "text": "<p>Yes, they are faster most of time. SQL composition is a huge performance tuning area too. If I am doing a back office type app I may skip them but anything production facing I use them for sure for all the reasons others spoke too...namely security. </p>\n" }, { "answer_id": 60580, "author": "Evan", "author_id": 6277, "author_profile": "https://Stackoverflow.com/users/6277", "pm_score": 1, "selected": false, "text": "<p>Realising this is a bit off-topic to the question, but if you are using a lot of stored procedures, make sure there is a consistent way to put them under some sort of source control (e.g., subversion or git) and be able to migrate updates from your development system to the test system to the production system.</p>\n\n<p>When this is done by hand, with no way to easily audit what code is where, this quickly becomes a nightmare.</p>\n" }, { "answer_id": 60587, "author": "fuzzbone", "author_id": 5027, "author_profile": "https://Stackoverflow.com/users/5027", "pm_score": 3, "selected": false, "text": "<p>The one topic that no one has yet mentioned as a benefit of stored procedures is security. If you build the application exclusively with data access via stored procedures, you can lockdown the database so the ONLY access is via those stored procedures. Therefor, even if someone gets a database ID and password, they will be limited in what they can see or do against that database.</p>\n" }, { "answer_id": 60642, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 0, "selected": false, "text": "<p>IMHO...</p>\n\n<p>Restricting \"C_UD\" operations to stored procedures can keep the data integrity logic in one place. This can also be done by restricting\"C_UD\" operations to a single middle ware layer.</p>\n\n<p>Read operations can be provided to the application so they can join only the tables / columns they need.</p>\n" }, { "answer_id": 60964, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 0, "selected": false, "text": "<p>Stored procedures can also be used instead of parameterized queries (or ad-hoc queries) for some other advantages too :</p>\n\n<ul>\n<li>If you need to correct something (a sort order etc.) you don't need to recompile your app</li>\n<li>You could deny access to all tables for that user account, grant access only to stored procedures and route all access through stored procedures. This way you can have custom validation of all input much more flexible than table constraints.</li>\n</ul>\n" }, { "answer_id": 209094, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": false, "text": "<p>Reasons for using stored procedures:</p>\n\n<ul>\n<li><strong>Reduce network traffic</strong> -- you have to send the SQL statement across the network. With sprocs, you can execute SQL in batches, which is also more efficient.</li>\n<li><strong>Caching query plan</strong> -- the first time the sproc is executed, SQL Server creates an execution plan, which is cached for reuse. This is particularly performant for small queries run frequently.</li>\n<li><strong>Ability to use output parameters</strong> -- if you send inline SQL that returns one row, you can only get back a recordset. With sprocs you can get them back as output parameters, which is considerably faster.</li>\n<li><strong>Permissions</strong> -- when you send inline SQL, you have to grant permissions on the table(s) to the user, which is granting much more access than merely granting permission to execute a sproc</li>\n<li><strong>Separation of logic</strong> -- remove the SQL-generating code and segregate it in the database.</li>\n<li><strong>Ability to edit without recompiling</strong> -- this can be controversial. You can edit the SQL in a sproc without having to recompile the application.</li>\n<li><strong>Find where a table is used</strong> -- with sprocs, if you want to find all SQL statements referencing a particular table, you can export the sproc code and search it. This is much easier than trying to find it in code.</li>\n<li><strong>Optimization</strong> -- It's easier for a DBA to optimize the SQL and tune the database when sprocs are used. It's easier to find missing indexes and such.</li>\n<li><strong>SQL injection attacks</strong> -- properly written inline SQL can defend against attacks, but sprocs are better for this protection.</li>\n</ul>\n" }, { "answer_id": 234324, "author": "Will Dieterich", "author_id": 31233, "author_profile": "https://Stackoverflow.com/users/31233", "pm_score": -1, "selected": false, "text": "<p>Reduced network traffic -- SP are generally worse then Dynamic SQL. Because people don't create a new SP for every select, if you need just one column you are told use the SP that has the columns they need and ignore the rest. Get an extra column and any less network usage you had just went away. Also you tend to have a lot of client filtering when SP are used.</p>\n\n<p>caching -- MS-SQL does not treat them any differently, not since MS-SQL 2000 may of been 7 but I don't remember.</p>\n\n<p>permissions -- Not a problem since almost everything I do is web or have some middle application tier that does all the database access. The only software I work with that have direct client to database access are 3rd party products that are designed for users to have direct access and are based around giving users permissions. And yes MS-SQL permission security model SUCKS!!! (have not spent time on 2008 yet) As a final part to this would like to see a survey of how many people are still doing direct client/server programming vs web and middle application server programming; and if they are doing large projects why no ORM.</p>\n\n<p>Separation -- people would question why you are putting business logic outside of middle tier. Also if you are looking to separate data handling code there are ways of doing that without putting it in the database.</p>\n\n<p>Ability to edit -- What you have no testing and version control you have to worry about? Also only a problem with client/server, in the web world not problem.</p>\n\n<p>Find the table -- Only if you can identify the SP that use it, will stick with the tools of the version control system, agent ransack or visual studio to find.</p>\n\n<p>Optimization -- Your DBA should be using the tools of the database to find the queries that need optimization. Database can tell the DBA what statements are talking up the most time and resources and they can fix from there. For complex SQL statements the programmers should be told to talk to the DBA if simple selects don't worry about it.</p>\n\n<p>SQL injection attacks -- SP offer no better protection. The only thing they get the nod is that most of them teach using parameters vs dynamic SQL most examples ignore parameters.</p>\n" }, { "answer_id": 1797473, "author": "Dennis Decker Jensen", "author_id": 218656, "author_profile": "https://Stackoverflow.com/users/218656", "pm_score": 3, "selected": false, "text": "<p>In 2007 I was on a project, where we used MS SQL Server via an ORM. We had 2 big, growing tables which took up to 7-8 seconds of load time on the SQL Server. After making 2 large, stored SQL procedures, and optimizing them from the query planner, each DB load time got down to less than 20 milliseconds, so clearly there are still efficiency reasons to use stored SQL procedures.</p>\n\n<p>Having said that, we found out that the most important benefit of stored procedures was the added maintaince-ease, security, data-integrity, and decoupling business-logic from the middleware-logic, benefitting all middleware-logic from reuse of the 2 procedures.</p>\n\n<p>Our ORM vendor made the usual claim that firing off many small SQL queries were going to be more efficient than fetching large, joined data sets. Our experience (to our surprise) showed something else.</p>\n\n<p>This may of course vary between machines, networks, operating systems, SQL servers, application frameworks, ORM frameworks, and language implementations, so measure any benefit, you THINK you may get from doing something else.</p>\n\n<p>It wasn't until we benchmarked that we discovered the problem was between the ORM and the database taking all the load.</p>\n" }, { "answer_id": 7729253, "author": "jmt", "author_id": 989922, "author_profile": "https://Stackoverflow.com/users/989922", "pm_score": 2, "selected": false, "text": "<p>To me one advantage of stored procedures is to be host language agnostic: you can switch from a C, Python, PHP or whatever application to another programming language without rewriting your code. In addition, some features like bulk operations improve really performance and are not easily available (not at all?) in host languages.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them **ALL THE TIME**. I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or <*Insert\_your\_DB\_here*>. Is it overkill to have ALL access through stored procedures?
> > **NOTE** that this is a general look at stored procedures not regulated to a specific > DBMS. Some DBMS (and even, different > versions of the same DBMS!) may operate > contrary to this, so you'll want to > double-check with your target DBMS > before assuming all of this still holds. > > > I've been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war. > > > The historical performance benefit of stored procs have generally been from the following (in no particular order): * Pre-parsed SQL * Pre-generated query execution plan * Reduced network latency * Potential cache benefits **Pre-parsed SQL** -- similar benefits to compiled vs. interpreted code, except on a very micro level. *Still an advantage?* Not very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up. **Pre-generated query execution plan**. If you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I've seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the "near best" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead. *Still an advantage?* Most DBMS' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn't the case, so you'll need to test on your target DBMS. Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!). > > **WARNING** Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal. > For example, if you send `SELECT * > FROM table WHERE id BETWEEN 1 AND > 99999999`, the DBMS may select a > full-table scan instead of an index > scan because you're grabbing every row > in the table (so sayeth the > statistics). If this is the cached > version, then you can get poor > performance when you later send > `SELECT * FROM table WHERE id BETWEEN > 1 AND 2`. The reasoning behind this is > outside the scope of this posting, but > for further reading see: > <http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx> > and > <http://msdn.microsoft.com/en-us/library/ms181055.aspx> > and <http://www.simple-talk.com/sql/performance/execution-plan-basics/> > > > "In summary, they determined that > supplying anything other than the > common values when a compile or > recompile was performed resulted in > the optimizer compiling and caching > the query plan for that particular > value. Yet, when that query plan was > reused for subsequent executions of > the same query for the common values > (‘M’, ‘R’, or ‘T’), it resulted in > sub-optimal performance. This > sub-optimal performance problem > existed until the query was > recompiled. At that point, based on > the @P1 parameter value supplied, the > query might or might not have a > performance problem." > > > **Reduced network latency** A) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple "exec foobar" can really add up. B) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone's favorite WTF!) *Still an advantage?* A) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible. B) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason? **Potential cache benefits** Performing server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server. *Still an advantage?* Unless your app has shared memory access to DBMS data, the edge will always be to stored procs. Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL. **Parameterized / Prepared SQL** Kind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses "parameters" for query values, e.g.: ``` SELECT .. FROM yourtable WHERE foo = ? AND bar = ? ``` These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures. **Ad Hoc SQL** Just open a console window to your DBMS and type in a SQL statement. In the past, these were the "worst" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method. *Still a disadvantage?* Not necessarily. Most DBMS have the ability to "abstract" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: <http://msdn.microsoft.com/en-us/library/ms175037.aspx> , Oracle: <http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>). **Lessons learned?** Moore's law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it's not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of *massive* stored procedure use \*\* solely for "performance reasons"\*\* sure sounds like premature optimization to me. Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won't notice a difference between ad hoc and stored procedures.
59,895
<p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p> <p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p> <pre><code>$ ./application </code></pre>
[ { "answer_id": 59916, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 10, "selected": false, "text": "<p>Use <code>dirname &quot;$0&quot;</code>:</p>\n<pre><code>#!/usr/bin/env bash\n\necho &quot;The script you are running has basename $( basename -- &quot;$0&quot;; ), dirname $( dirname -- &quot;$0&quot;; )&quot;;\necho &quot;The present working directory is $( pwd; )&quot;;\n</code></pre>\n<p>Using <code>pwd</code> alone will not work if you are not running the script from the directory it is contained in.</p>\n<pre><code>[matt@server1 ~]$ pwd\n/home/matt\n[matt@server1 ~]$ ./test2.sh\nThe script you are running has basename test2.sh, dirname .\nThe present working directory is /home/matt\n[matt@server1 ~]$ cd /tmp\n[matt@server1 tmp]$ ~/test2.sh\nThe script you are running has basename test2.sh, dirname /home/matt\nThe present working directory is /tmp\n</code></pre>\n" }, { "answer_id": 59921, "author": "Mr Shark", "author_id": 6093, "author_profile": "https://Stackoverflow.com/users/6093", "pm_score": 7, "selected": false, "text": "<p>You can use <code>$BASH_SOURCE</code>:</p>\n<pre><code>#!/usr/bin/env bash\n\nscriptdir=&quot;$( dirname -- &quot;$BASH_SOURCE&quot;; )&quot;;\n</code></pre>\n<p>Note that you need to use <code>#!/bin/bash</code> and not <code>#!/bin/sh</code> since it's a Bash extension.</p>\n" }, { "answer_id": 60232, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I don't think this is as easy as others have made it out to be. <code>pwd</code> doesn't work, as the current directory is not necessarily the directory with the script. <code>$0</code> doesn't always have the information either. Consider the following three ways to invoke a script:</p>\n\n<pre><code>./script\n\n/usr/bin/script\n\nscript\n</code></pre>\n\n<p>In the first and third ways <code>$0</code> doesn't have the full path information. In the second and third, <code>pwd</code> does not work. The only way to get the directory in the third way would be to run through the path and find the file with the correct match. Basically the code would have to redo what the OS does.</p>\n\n<p>One way to do what you are asking would be to just hardcode the data in the <code>/usr/share</code> directory, and reference it by its full path. Data shoudn't be in the <code>/usr/bin</code> directory anyway, so this is probably the thing to do.</p>\n" }, { "answer_id": 60247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>#!/bin/sh\nPRG=\"$0\"\n\n# need this for relative symlinks\nwhile [ -h \"$PRG\" ] ; do\n PRG=`readlink \"$PRG\"`\ndone\n\nscriptdir=`dirname \"$PRG\"`\n</code></pre>\n" }, { "answer_id": 66271, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 6, "selected": false, "text": "<p><code>pwd</code> can be used to find the current working directory, and <code>dirname</code> to find the directory of a particular file (command that was run, is <code>$0</code>, so <code>dirname $0</code> should give you the directory of the current script).</p>\n<p>However, <code>dirname</code> gives precisely the directory portion of the filename, which more likely than not is going to be relative to the current working directory. If your script needs to change directory for some reason, then the output from <code>dirname</code> becomes meaningless.</p>\n<p>I suggest the following:</p>\n<pre><code>#!/usr/bin/env bash\n\nreldir=&quot;$( dirname -- &quot;$0&quot;; )&quot;;\ncd &quot;$reldir&quot;;\ndirectory=&quot;$( pwd; )&quot;;\n\necho &quot;Directory is ${directory}&quot;;\n</code></pre>\n<p>This way, you get an absolute, rather than a relative directory.</p>\n<p>Since the script will be run in a separate Bash instance, there isn't any need to restore the working directory afterwards, but if you do want to change back in your script for some reason, you can easily assign the value of <code>pwd</code> to a variable before you change directory, for future use.</p>\n<p>Although just</p>\n<pre><code>cd &quot;$( dirname -- &quot;$0&quot;; )&quot;;\n</code></pre>\n<p>solves the specific scenario in the question, I find having the absolute path to more more useful generally.</p>\n" }, { "answer_id": 76257, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 5, "selected": false, "text": "<p>This is Linux specific, but you could use:</p>\n\n<pre><code>SELF=$(readlink /proc/$$/fd/255)\n</code></pre>\n" }, { "answer_id": 179231, "author": "user25866", "author_id": 25866, "author_profile": "https://Stackoverflow.com/users/25866", "pm_score": 8, "selected": false, "text": "<pre><code>pushd . &gt; '/dev/null';\nSCRIPT_PATH=&quot;${BASH_SOURCE[0]:-$0}&quot;;\n\nwhile [ -h &quot;$SCRIPT_PATH&quot; ];\ndo\n cd &quot;$( dirname -- &quot;$SCRIPT_PATH&quot;; )&quot;;\n SCRIPT_PATH=&quot;$( readlink -f -- &quot;$SCRIPT_PATH&quot;; )&quot;;\ndone\n\ncd &quot;$( dirname -- &quot;$SCRIPT_PATH&quot;; )&quot; &gt; '/dev/null';\nSCRIPT_PATH=&quot;$( pwd; )&quot;;\npopd &gt; '/dev/null';\n</code></pre>\n<p>It works for all versions, including</p>\n<ul>\n<li>when called via multiple depth soft link,</li>\n<li>when the file it</li>\n<li>when script called by command &quot;<code>source</code>&quot; aka <code>.</code> (dot) operator.</li>\n<li>when arg <code>$0</code> is modified from caller.</li>\n<li><code>&quot;./script&quot;</code></li>\n<li><code>&quot;/full/path/to/script&quot;</code></li>\n<li><code>&quot;/some/path/../../another/path/script&quot;</code></li>\n<li><code>&quot;./some/folder/script&quot;</code></li>\n</ul>\n<p>Alternatively, if the Bash script itself is a <strong>relative symlink</strong> you <em>want</em> to follow it and return the full path of the linked-to script:</p>\n<pre><code>pushd . &gt; '/dev/null';\nSCRIPT_PATH=&quot;${BASH_SOURCE[0]:-$0}&quot;;\n\nwhile [ -h &quot;$SCRIPT_PATH&quot; ];\ndo\n cd &quot;$( dirname -- &quot;$SCRIPT_PATH&quot;; )&quot;;\n SCRIPT_PATH=&quot;$( readlink -f -- &quot;$SCRIPT_PATH&quot;; )&quot;;\ndone\n\ncd &quot;$( dirname -- &quot;$SCRIPT_PATH&quot;; )&quot; &gt; '/dev/null';\nSCRIPT_PATH=&quot;$( pwd; )&quot;;\npopd &gt; '/dev/null';\n</code></pre>\n<p><code>SCRIPT_PATH</code> is given in full path, no matter how it is called.</p>\n<p>Just make sure you locate this at start of the script.</p>\n" }, { "answer_id": 201915, "author": "Matt Tardiff", "author_id": 27925, "author_profile": "https://Stackoverflow.com/users/27925", "pm_score": 4, "selected": false, "text": "<p>This works in Bash 3.2:</p>\n<pre><code>path=&quot;$( dirname &quot;$( which &quot;$0&quot; )&quot; )&quot;\n</code></pre>\n<p>If you have a <code>~/bin</code> directory in your <code>$PATH</code>, you have <code>A</code> inside this directory. It sources the script <code>~/bin/lib/B</code>. You know where the included script is relative to the original one, in the <code>lib</code> subdirectory, but not where it is relative to the user's current directory.</p>\n<p>This is solved by the following (inside <code>A</code>):</p>\n<pre><code>source &quot;$( dirname &quot;$( which &quot;$0&quot; )&quot; )/lib/B&quot;\n</code></pre>\n<p>It doesn't matter where the user is or how he/she calls the script. This will always work.</p>\n" }, { "answer_id": 246128, "author": "dogbane", "author_id": 7412, "author_profile": "https://Stackoverflow.com/users/7412", "pm_score": 14, "selected": true, "text": "<pre><code>#!/usr/bin/env bash\n\nSCRIPT_DIR=$( cd -- &quot;$( dirname -- &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd )\n</code></pre>\n<p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p>\n<p>It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:</p>\n<pre><code>#!/usr/bin/env bash\n\nSOURCE=${BASH_SOURCE[0]}\nwhile [ -L &quot;$SOURCE&quot; ]; do # resolve $SOURCE until the file is no longer a symlink\n DIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )\n SOURCE=$(readlink &quot;$SOURCE&quot;)\n [[ $SOURCE != /* ]] &amp;&amp; SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )\n</code></pre>\n<p>This last one will work with any combination of aliases, <code>source</code>, <code>bash -c</code>, symlinks, etc.</p>\n<p><strong>Beware:</strong> if you <code>cd</code> to a different directory before running this snippet, the result may be incorrect!</p>\n<p>Also, watch out for <a href=\"http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/\" rel=\"noreferrer\"><code>$CDPATH</code> gotchas</a>, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling <code>update_terminal_cwd &gt;&amp;2</code> on Mac). Adding <code>&gt;/dev/null 2&gt;&amp;1</code> at the end of your <code>cd</code> command will take care of both possibilities.</p>\n<p>To understand how it works, try running this more verbose form:</p>\n<pre><code>#!/usr/bin/env bash\n\nSOURCE=${BASH_SOURCE[0]}\nwhile [ -L &quot;$SOURCE&quot; ]; do # resolve $SOURCE until the file is no longer a symlink\n TARGET=$(readlink &quot;$SOURCE&quot;)\n if [[ $TARGET == /* ]]; then\n echo &quot;SOURCE '$SOURCE' is an absolute symlink to '$TARGET'&quot;\n SOURCE=$TARGET\n else\n DIR=$( dirname &quot;$SOURCE&quot; )\n echo &quot;SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')&quot;\n SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\n fi\ndone\necho &quot;SOURCE is '$SOURCE'&quot;\nRDIR=$( dirname &quot;$SOURCE&quot; )\nDIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )\nif [ &quot;$DIR&quot; != &quot;$RDIR&quot; ]; then\n echo &quot;DIR '$RDIR' resolves to '$DIR'&quot;\nfi\necho &quot;DIR is '$DIR'&quot;\n</code></pre>\n<p>And it will print something like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')\nSOURCE is './sym2/scriptdir.sh'\nDIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'\nDIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'\n</code></pre>\n" }, { "answer_id": 337006, "author": "Fabien", "author_id": 21132, "author_profile": "https://Stackoverflow.com/users/21132", "pm_score": 7, "selected": false, "text": "<p>Short answer:</p>\n<pre><code>&quot;`dirname -- &quot;$0&quot;;`&quot;\n</code></pre>\n<p>or (<a href=\"http://mywiki.wooledge.org/BashFAQ/082\" rel=\"nofollow noreferrer\">preferably</a>):</p>\n<pre><code>&quot;$( dirname -- &quot;$0&quot;; )&quot;\n</code></pre>\n" }, { "answer_id": 476266, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I usually do:</p>\n\n<pre><code>LIBDIR=$(dirname \"$(readlink -f \"$(type -P $0 || echo $0)\")\")\nsource $LIBDIR/lib.sh\n</code></pre>\n" }, { "answer_id": 476333, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": false, "text": "<p>Hmm, if in the path, <a href=\"https://linux.die.net/man/1/basename\" rel=\"nofollow noreferrer\"><code>basename</code></a> and <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\"><code>dirname</code></a> are just not going to cut it and walking the path is hard (what if the parent didn't export PATH?!).</p>\n<p>However, the shell has to have an open handle to its script, and in Bash the handle is #255.</p>\n<pre><code>SELF=`readlink /proc/$$/fd/255`\n</code></pre>\n<p>works for me.</p>\n" }, { "answer_id": 541672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I want to make sure that the script is running in its directory. So</p>\n\n<pre><code>cd $(dirname $(which $0) )\n</code></pre>\n\n<p>After this, if you really want to know where the you are running then run the command below.</p>\n\n<pre><code>DIR=$(/usr/bin/pwd)\n</code></pre>\n" }, { "answer_id": 748265, "author": "BillTorpey", "author_id": 62513, "author_profile": "https://Stackoverflow.com/users/62513", "pm_score": 2, "selected": false, "text": "<p>This is the only way I've found to tell reliably:</p>\n\n<pre><code>SCRIPT_DIR=$(dirname $(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd))\n</code></pre>\n" }, { "answer_id": 1482133, "author": "phatblat", "author_id": 39207, "author_profile": "https://Stackoverflow.com/users/39207", "pm_score": 9, "selected": false, "text": "<p>The <a href=\"https://linux.die.net/man/1/dirname\" rel=\"noreferrer\"><code>dirname</code></a> command is the most basic, simply parsing the path up to the filename off of the <code>$0</code> (script name) variable:</p>\n<pre><code>dirname -- &quot;$0&quot;;\n</code></pre>\n<p>But, as <strong>matt b</strong> pointed out, the path returned is different depending on how the script is called. <code>pwd</code> doesn't do the job because that only tells you what the current directory is, not what directory the script resides in. Additionally, if a symbolic link to a script is executed, you're going to get a (probably relative) path to where the link resides, not the actual script.</p>\n<p>Some others have mentioned the <code>readlink</code> command, but at its simplest, you can use:</p>\n<pre><code>dirname -- &quot;$( readlink -f -- &quot;$0&quot;; )&quot;;\n</code></pre>\n<p><code>readlink</code> will resolve the script path to an absolute path from the root of the filesystem. So, any paths containing single or double dots, tildes and/or symbolic links will be resolved to a full path.</p>\n<p>Here's a script demonstrating each of these, <code>whatdir.sh</code>:</p>\n<pre><code>#!/usr/bin/env bash\n\necho &quot;pwd: `pwd`&quot;\necho &quot;\\$0: $0&quot;\necho &quot;basename: `basename -- &quot;$0&quot;`&quot;\necho &quot;dirname: `dirname -- &quot;$0&quot;`&quot;\necho &quot;dirname/readlink: $( dirname -- &quot;$( readlink -f -- &quot;$0&quot;; )&quot;; )&quot;\n</code></pre>\n<p>Running this script in my home dir, using a relative path:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;$ ./whatdir.sh\npwd: /Users/phatblat\n$0: ./whatdir.sh\nbasename: whatdir.sh\ndirname: .\ndirname/readlink: /Users/phatblat\n</code></pre>\n<p>Again, but using the full path to the script:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;$ /Users/phatblat/whatdir.sh\npwd: /Users/phatblat\n$0: /Users/phatblat/whatdir.sh\nbasename: whatdir.sh\ndirname: /Users/phatblat\ndirname/readlink: /Users/phatblat\n</code></pre>\n<p>Now changing directories:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;$ cd /tmp\n&gt;&gt;&gt;$ ~/whatdir.sh\npwd: /tmp\n$0: /Users/phatblat/whatdir.sh\nbasename: whatdir.sh\ndirname: /Users/phatblat\ndirname/readlink: /Users/phatblat\n</code></pre>\n<p>And finally using a symbolic link to execute the script:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;$ ln -s ~/whatdir.sh whatdirlink.sh\n&gt;&gt;&gt;$ ./whatdirlink.sh\npwd: /tmp\n$0: ./whatdirlink.sh\nbasename: whatdirlink.sh\ndirname: .\ndirname/readlink: /Users/phatblat\n</code></pre>\n<p>There is however one case where this doesn't work, when the script is sourced (instead of executed) in bash:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt;$ cd /tmp\n&gt;&gt;&gt;$ . ~/whatdir.sh \npwd: /tmp\n$0: bash\nbasename: bash\ndirname: .\ndirname/readlink: /tmp\n</code></pre>\n" }, { "answer_id": 1815323, "author": "Stefano Borini", "author_id": 78374, "author_profile": "https://Stackoverflow.com/users/78374", "pm_score": -1, "selected": false, "text": "<pre><code>function getScriptAbsoluteDir { # fold&gt;&gt;\n # @description used to get the script path\n # @param $1 the script $0 parameter\n local script_invoke_path=\"$1\"\n local cwd=`pwd`\n\n # absolute path ? if so, the first character is a /\n if test \"x${script_invoke_path:0:1}\" = 'x/'\n then\n RESULT=`dirname \"$script_invoke_path\"`\n else\n RESULT=`dirname \"$cwd/$script_invoke_path\"`\n fi\n} # &lt;&lt;fold\n</code></pre>\n" }, { "answer_id": 2633580, "author": "Fuwjax", "author_id": 315943, "author_profile": "https://Stackoverflow.com/users/315943", "pm_score": 4, "selected": false, "text": "<p>This is a slight revision to the solution e-satis and 3bcdnlklvc04a pointed out in <a href=\"https://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-in/179231#179231\" title=\"their answer\">their answer</a>:</p>\n<pre><code>SCRIPT_DIR=''\npushd &quot;$(dirname &quot;$(readlink -f &quot;$BASH_SOURCE&quot;)&quot;)&quot; &gt; /dev/null &amp;&amp; {\n SCRIPT_DIR=&quot;$PWD&quot;\n popd &gt; /dev/null\n}\n</code></pre>\n<p>This should still work in all the cases they listed.</p>\n<p>This will prevent <code>popd</code> after a failed <code>pushd</code>. Thanks to konsolebox.</p>\n" }, { "answer_id": 3674520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I tried all of these and none worked. One was very close, but it had a tiny bug that broke it badly; they forgot to wrap the path in quotation marks.</p>\n<p>Also a lot of people assume you're running the script from a shell, so they forget when you open a new script it defaults to your home.</p>\n<p>Try this directory on for size:</p>\n<pre><code>/var/No one/Thought/About Spaces Being/In a Directory/Name/And Here's your file.text\n</code></pre>\n<p>This gets it right regardless how or where you run it:</p>\n<pre><code>#!/bin/bash\necho &quot;pwd: `pwd`&quot;\necho &quot;\\$0: $0&quot;\necho &quot;basename: `basename &quot;$0&quot;`&quot;\necho &quot;dirname: `dirname &quot;$0&quot;`&quot;\n</code></pre>\n<p>So to make it actually useful, here's how to change to the directory of the running script:</p>\n<pre><code>cd &quot;`dirname &quot;$0&quot;`&quot;\n</code></pre>\n" }, { "answer_id": 3774351, "author": "tigfox", "author_id": 455644, "author_profile": "https://Stackoverflow.com/users/455644", "pm_score": 3, "selected": false, "text": "<p>None of these other answers worked for a Bash script launched by <a href=\"https://en.wikipedia.org/wiki/Finder_(software)\" rel=\"nofollow noreferrer\">Finder</a> in <a href=\"https://en.wikipedia.org/wiki/Mac_OS_X\" rel=\"nofollow noreferrer\">OS X</a>. I ended up using:</p>\n<pre><code>SCRIPT_LOC=&quot;`ps -p $$ | sed /PID/d | sed s:.*/Network/:/Network/: |\nsed s:.*/Volumes/:/Volumes/:`&quot;\n</code></pre>\n<p>It is not pretty, but it gets the job done.</p>\n" }, { "answer_id": 3884245, "author": "P M", "author_id": 396782, "author_profile": "https://Stackoverflow.com/users/396782", "pm_score": 5, "selected": false, "text": "<pre><code>SCRIPT_DIR=$( cd ${0%/*} &amp;&amp; pwd -P )\n</code></pre>\n" }, { "answer_id": 3921651, "author": "alanwj", "author_id": 60873, "author_profile": "https://Stackoverflow.com/users/60873", "pm_score": 3, "selected": false, "text": "<p>Use a combination of <a href=\"https://linux.die.net/man/1/readlink\" rel=\"nofollow noreferrer\">readlink</a> to canonicalize the name (with a bonus of following it back to its source if it is a symlink) and <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\">dirname</a> to extract the directory name:</p>\n<pre><code>script=&quot;`readlink -f &quot;${BASH_SOURCE[0]}&quot;`&quot;\ndir=&quot;`dirname &quot;$script&quot;`&quot;\n</code></pre>\n" }, { "answer_id": 4560790, "author": "Pubguy", "author_id": 558024, "author_profile": "https://Stackoverflow.com/users/558024", "pm_score": 5, "selected": false, "text": "<p>This gets the current working directory on <a href=\"https://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard\" rel=\"noreferrer\">Mac OS X v10.6.6</a> (Snow Leopard):</p>\n<pre><code>DIR=$(cd &quot;$(dirname &quot;$0&quot;)&quot;; pwd)\n</code></pre>\n" }, { "answer_id": 6840978, "author": "test11", "author_id": 864899, "author_profile": "https://Stackoverflow.com/users/864899", "pm_score": 5, "selected": false, "text": "<pre><code>$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")\n</code></pre>\n" }, { "answer_id": 7449270, "author": "hurrymaplelad", "author_id": 407845, "author_profile": "https://Stackoverflow.com/users/407845", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.gnu.org/s/bash/manual/bash.html#Environment\" rel=\"nofollow noreferrer\"><code>$_</code></a> is worth mentioning as an alternative to <code>$0</code>. If you're running a script from Bash, the accepted answer can be shortened to:</p>\n\n<pre><code>DIR=\"$( dirname \"$_\" )\"\n</code></pre>\n\n<p>Note that this has to be the first statement in your script.</p>\n" }, { "answer_id": 9158888, "author": "DarkPark", "author_id": 1192073, "author_profile": "https://Stackoverflow.com/users/1192073", "pm_score": 4, "selected": false, "text": "<p>Try using:</p>\n<pre><code>real=$(realpath &quot;$(dirname &quot;$0&quot;)&quot;)\n</code></pre>\n" }, { "answer_id": 13486116, "author": "Nicolas", "author_id": 1433151, "author_profile": "https://Stackoverflow.com/users/1433151", "pm_score": 4, "selected": false, "text": "<p>I would use something like this:</p>\n<pre><code># Retrieve the full pathname of the called script\nscriptPath=$(which $0)\n\n# Check whether the path is a link or not\nif [ -L $scriptPath ]; then\n\n # It is a link then retrieve the target path and get the directory name\n sourceDir=$(dirname $(readlink -f $scriptPath))\n\nelse\n\n # Otherwise just get the directory name of the script path\n sourceDir=$(dirname $scriptPath)\n\nfi\n</code></pre>\n" }, { "answer_id": 14881364, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 0, "selected": false, "text": "<p>Here is a pure Bash solution</p>\n\n<pre><code>$ cat a.sh\nBASENAME=${BASH_SOURCE/*\\/}\nDIRNAME=${BASH_SOURCE%$BASENAME}.\necho $DIRNAME\n\n$ a.sh\n/usr/local/bin/.\n\n$ ./a.sh\n./.\n\n$ . a.sh\n/usr/local/bin/.\n\n$ /usr/local/bin/a.sh\n/usr/local/bin/.\n</code></pre>\n" }, { "answer_id": 15255856, "author": "lamawithonel", "author_id": 2044979, "author_profile": "https://Stackoverflow.com/users/2044979", "pm_score": 5, "selected": false, "text": "<p>Here is a POSIX compliant one-liner:</p>\n\n<pre><code>SCRIPT_PATH=`dirname \"$0\"`; SCRIPT_PATH=`eval \"cd \\\"$SCRIPT_PATH\\\" &amp;&amp; pwd\"`\n\n# test\necho $SCRIPT_PATH\n</code></pre>\n" }, { "answer_id": 16131743, "author": "billyjmc", "author_id": 558709, "author_profile": "https://Stackoverflow.com/users/558709", "pm_score": 3, "selected": false, "text": "<p>I've compared many of the answers given, and came up with some more compact solutions. These seem to handle all of the crazy edge cases that arise from your favorite combination of:</p>\n<ul>\n<li>Absolute paths or relative paths</li>\n<li>File and directory soft links</li>\n<li>Invocation as <code>script</code>, <code>bash script</code>, <code>bash -c script</code>, <code>source script</code>, or <code>. script</code></li>\n<li>Spaces, tabs, newlines, Unicode, etc. in directories and/or filename</li>\n<li>Filenames beginning with a hyphen</li>\n</ul>\n<p>If you're running from Linux, it seems that using the <code>proc</code> handle is the best solution to locate the fully resolved source of the currently running script (in an interactive session, the link points to the respective <code>/dev/pts/X</code>):</p>\n<pre><code>resolved=&quot;$(readlink /proc/$$/fd/255 &amp;&amp; echo X)&quot; &amp;&amp; resolved=&quot;${resolved%$'\\nX'}&quot;\n</code></pre>\n<p>This has a small bit of ugliness to it, but the fix is compact and easy to understand. We aren't using bash primitives only, but I'm okay with that because <a href=\"https://linux.die.net/man/1/readlink\" rel=\"nofollow noreferrer\"><code>readlink</code></a> simplifies the task considerably. The <code>echo X</code> adds an <code>X</code> to the end of the variable string so that any trailing whitespace in the filename doesn't get eaten, and the parameter substitution <code>${VAR%X}</code> at the end of the line gets rid of the <code>X</code>. Because <code>readlink</code> adds a newline of its own (which would normally be eaten in the command substitution if not for our previous trickery), we have to get rid of that, too. This is most easily accomplished using the <code>$''</code> quoting scheme, which lets us use escape sequences such as <code>\\n</code> to represent newlines (this is also how you can easily make deviously named directories and files).</p>\n<p>The above should cover your needs for locating the currently running script on Linux, but if you don't have the <code>proc</code> filesystem at your disposal, or if you're trying to locate the fully resolved path of some other file, then maybe you'll find the below code helpful. It's only a slight modification from the above one-liner. If you're playing around with strange directory/filenames, checking the output with both <code>ls</code> and <code>readlink</code> is informative, as <code>ls</code> will output &quot;simplified&quot; paths, substituting <code>?</code> for things like newlines.</p>\n<pre><code>absolute_path=$(readlink -e -- &quot;${BASH_SOURCE[0]}&quot; &amp;&amp; echo x) &amp;&amp; absolute_path=${absolute_path%?x}\ndir=$(dirname -- &quot;$absolute_path&quot; &amp;&amp; echo x) &amp;&amp; dir=${dir%?x}\nfile=$(basename -- &quot;$absolute_path&quot; &amp;&amp; echo x) &amp;&amp; file=${file%?x}\n\nls -l -- &quot;$dir/$file&quot;\nprintf '$absolute_path: &quot;%s&quot;\\n' &quot;$absolute_path&quot;\n</code></pre>\n" }, { "answer_id": 17011222, "author": "mproffitt", "author_id": 2452553, "author_profile": "https://Stackoverflow.com/users/2452553", "pm_score": -1, "selected": false, "text": "<p>I usually include the following at the top of my scripts which works in the majority of cases:</p>\n<pre><code>[ &quot;$(dirname $0)&quot; = '.' ] &amp;&amp; SOURCE_DIR=$(pwd) || SOURCE_DIR=$(dirname $0);\nls -l $0 | grep -q ^l &amp;&amp; SOURCE_DIR=$(ls -l $0 | awk '{print $NF}');\n</code></pre>\n<p>The first line assigns source based on the value of <code>pwd</code> if run from the current path or <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\">dirname</a> if called from elsewhere.</p>\n<p>The second line examines the path to see if it is a symlink and if so, updates SOURCE_DIR to the location of the link itself.</p>\n<p>There are probably better solutions out there, but this is the cleanest I've managed to come up with myself.</p>\n" }, { "answer_id": 19153434, "author": "AsymLabs", "author_id": 2839332, "author_profile": "https://Stackoverflow.com/users/2839332", "pm_score": -1, "selected": false, "text": "<p>Try something like this:</p>\n<pre><code>function get_realpath() {\n\nif [[ -f &quot;$1&quot; ]]\nthen\n # The file *must* exist\n if cd &quot;$(echo &quot;${1%/*}&quot;)&quot; &amp;&gt;/dev/null\n then\n # The file *may* not be local.\n # The exception is ./file.ext\n # tTry 'cd .; cd -;' *works!*\n local tmppwd=&quot;$PWD&quot;\n cd - &amp;&gt;/dev/null\n else\n # file *must* be local\n local tmppwd=&quot;$PWD&quot;\n fi\nelse\n # The file *cannot* exist\n return 1 # Failure\nfi\n\n# Reassemble realpath\necho &quot;$tmppwd&quot;/&quot;${1##*/}&quot;\nreturn 0 # Success\n\n}\n\nfunction get_dirname(){\n\nlocal realpath=&quot;$(get_realpath &quot;$1&quot;)&quot;\nif (( $? )) # True when non-zero.\nthen\n return $? # Failure\nfi\necho &quot;${realpath%/*}&quot;\nreturn 0 # Success\n\n}\n\n# Then from the top level:\nget_dirname './script.sh'\n\n# Or within a script:\nget_dirname &quot;$0&quot;\n\n# Can even test the outcome!\nif (( $? )) # True when non-zero.\nthen\n exit 1 # Failure\nfi\n</code></pre>\n<p>These functions and related tools are part of our product that has been made available to the community for free and can be found at GitHub as <a href=\"http://asymlabs.github.io/realpath-lib/\" rel=\"nofollow noreferrer\">realpath-lib</a>. It's simple, clean and well documented (great for learning), pure Bash and has no dependencies. Good for cross-platform use too. So for the above example, within a script you could simply:</p>\n<pre><code>source '/path/to/realpath-lib'\n\nget_dirname &quot;$0&quot;\n\nif (( $? )) # True when non-zero.\nthen\n exit 1 # Failure\nfi\n</code></pre>\n" }, { "answer_id": 19250386, "author": "AsymLabs", "author_id": 2839332, "author_profile": "https://Stackoverflow.com/users/2839332", "pm_score": 3, "selected": false, "text": "<p>The best compact solution in my view would be:</p>\n<pre><code>&quot;$( cd &quot;$( echo &quot;${BASH_SOURCE[0]%/*}&quot; )&quot;; pwd )&quot;\n</code></pre>\n<p>There is no reliance on anything other than Bash. The use of <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\"><code>dirname</code></a>, <a href=\"https://linux.die.net/man/1/readlink\" rel=\"nofollow noreferrer\"><code>readlink</code></a> and <a href=\"https://linux.die.net/man/1/basename\" rel=\"nofollow noreferrer\"><code>basename</code></a> will eventually lead to compatibility issues, so they are best avoided if at all possible.</p>\n" }, { "answer_id": 20228026, "author": "mikeserv", "author_id": 2955202, "author_profile": "https://Stackoverflow.com/users/2955202", "pm_score": 0, "selected": false, "text": "<p>Here's an excerpt from my answer to <a href=\"https://stackoverflow.com/questions/12690085/shell-script-check-directory-name-and-convert-to-lowercase/20227287#20227287\">shell script: check directory name and convert to lowercase</a> in which I demonstrate not only how to solve this problem with very basic POSIX-specified utilities, I also address <em><strong>how to very simply store the function's results in a returned variable...</strong></em></p>\n<p>...Well, as you can see, with <strong>some help</strong>, I hit upon a pretty simple and very powerful solution:</p>\n<p>I can pass the function a sort of <em>messenger variable</em> and dereference any explicit use of the resulting function's argument's <code>$1</code> name with <code>eval</code> as necessary, and, upon the function routine's completion, I use <code>eval</code> and a backslashed quoting trick to assign my messenger variable the value I desire without ever having to know its name.</p>\n<p>In full disclosure, ... (I found the messenger variable portion of this) and at <a href=\"http://www.etalabs.net/sh_tricks.html\" rel=\"nofollow noreferrer\">Rich's sh tricks</a> and I have also excerpted the relevant portion of his page below my own answer's excerpt.</p>\n<p>...\n<strong>EXCERPT:</strong>\n...</p>\n<p>Though not strictly POSIX yet, <strong><a href=\"http://www.gnu.org/software/coreutils/manual/html_node/realpath-invocation.html\" rel=\"nofollow noreferrer\">realpath</a> is a GNU core application since 2012</strong>. Full disclosure: never heard of it before I noticed it in the <code>info coreutils</code> TOC and immediately thought of [the linked] question, but using the following function as demonstrated should reliably, (soon POSIXLY?), and, I hope, efficiently\nprovide its caller with an absolutely sourced <code>$0</code>:</p>\n<pre><code>% _abs_0() {\n&gt; o1=&quot;${1%%/*}&quot;; ${o1:=&quot;${1}&quot;}; ${o1:=`realpath -s &quot;${1}&quot;`}; eval &quot;$1=\\${o1}&quot;;\n&gt; }\n% _abs_0 ${abs0:=&quot;${0}&quot;} ; printf %s\\\\n &quot;${abs0}&quot;\n/no/more/dots/in/your/path2.sh\n</code></pre>\n<p>It may be worth highlighting that this solution uses <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02\" rel=\"nofollow noreferrer\">POSIX parameter expansion</a> to first check if the path actually needs expanding and resolving at all before attempting to do so. This should <strong>return an absolutely sourced <code>$0</code>via a messenger variable</strong> <em>(with the notable exception that it will preserve <code>symlinks</code>)</em> as <strong>efficiently</strong> as I could imagine it could be done <strong>whether or not the path is already absolute.</strong>\n...</p>\n<p>(<em><strong>minor edit</strong>: before finding <code>realpath</code> in the docs, I had at least pared down my version of (the version below) not to depend on the time field (as it does in the first <code>ps</code> command), but, fair warning, after testing some I'm less convinced <code>ps</code> is fully reliable in its command path expansion capacity</em>)</p>\n<p>On the other hand, you could do this:</p>\n<pre><code>ps ww -fp $$ | grep -Eo '/[^:]*'&quot;${0#*/}&quot;\n\neval &quot;abs0=${`ps ww -fp $$ | grep -Eo ' /'`#?}&quot;\n</code></pre>\n<p>...\n<strong>And from <a href=\"http://www.etalabs.net/sh_tricks.html\" rel=\"nofollow noreferrer\">Rich's sh tricks</a>:</strong>\n...</p>\n<p><strong>Returning strings from a shell function</strong></p>\n<p>As can be seen from the above pitfall of command substitution, standard output is not a good avenue for shell functions to return strings to their caller, unless the output is in a format where trailing newlines are insignificant. Certainly such practice is not acceptable for functions meant to deal with arbitrary strings. So, what can be done?</p>\n<p>Try this:</p>\n<pre><code>func () {\nbody here\neval &quot;$1=\\${foo}&quot;\n}\n</code></pre>\n<p>Of course, <code>${foo}</code> could be replaced by any sort of substitution. The key trick here is the eval line and the use of escaping. The <code>“$1”</code> is expanded when the argument to eval is constructed by the main command parser. But the <code>“${foo}”</code> is not expanded at this stage, because the <code>“$”</code> has been quoted. Instead, it’s expanded when eval evaluates its argument. If it’s not clear why this is important, consider how the following would be bad:</p>\n<pre><code>foo='hello ; rm -rf /'\ndest=bar\neval &quot;$dest=$foo&quot;\n</code></pre>\n<p>But of course the following version is perfectly safe:</p>\n<pre><code>foo='hello ; rm -rf /'\ndest=bar\neval &quot;$dest=\\$foo&quot;\n</code></pre>\n<p>Note that in the original example, <code>“$1”</code> was used to allow the caller to pass the destination variable name as an argument the function. If your function needs to use the shift command, for instance to handle the remaining arguments as <code>“$@”</code>, then it may be useful to save the value of <code>“$1”</code> in a temporary variable at the beginning of the function.</p>\n" }, { "answer_id": 20265752, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<p>Try the following cross-compatible solution:</p>\n<pre><code>CWD=&quot;$(cd -P -- &quot;$(dirname -- &quot;${BASH_SOURCE[0]}&quot;)&quot; &amp;&amp; pwd -P)&quot;\n</code></pre>\n<p>As the commands such as <code>realpath</code> or <code>readlink</code> could be not available (depending on the operating system).</p>\n<p>Note: In Bash, it's recommended to use <code>${BASH_SOURCE[0]}</code> instead of <code>$0</code>, otherwise path can break when sourcing the file (<code>source</code>/<code>.</code>).</p>\n<p>Alternatively you can try the following function in Bash:</p>\n<pre><code>realpath () {\n [[ $1 = /* ]] &amp;&amp; echo &quot;$1&quot; || echo &quot;$PWD/${1#./}&quot;\n}\n</code></pre>\n<p>This function takes one argument. If argument has already absolute path, print it as it is, otherwise print <code>$PWD</code> variable + filename argument (without <code>./</code> prefix).</p>\n<p>Related:</p>\n<ul>\n<li><em><a href=\"https://stackoverflow.com/questions/3349105/how-to-set-current-working-directory-to-the-directory-of-the-script\">How can I set the current working directory to the directory of the script in Bash?</a></em></li>\n<li><em><a href=\"https://stackoverflow.com/questions/3572030/bash-script-absolute-path-with-osx\">Bash script absolute path with OS X</a></em></li>\n<li><em><a href=\"https://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get-the-full-path-to-itself/20265654#20265654\">Reliable way for a Bash script to get the full path to itself</a></em></li>\n</ul>\n" }, { "answer_id": 20721819, "author": "Geoff Nixon", "author_id": 2351351, "author_profile": "https://Stackoverflow.com/users/2351351", "pm_score": 3, "selected": false, "text": "<p>I believe I've got this one. I'm late to the party, but I think some will appreciate it being here if they come across this thread. The comments should explain:</p>\n\n<pre><code>#!/bin/sh # dash bash ksh # !zsh (issues). G. Nixon, 12/2013. Public domain.\n\n## 'linkread' or 'fullpath' or (you choose) is a little tool to recursively\n## dereference symbolic links (ala 'readlink') until the originating file\n## is found. This is effectively the same function provided in stdlib.h as\n## 'realpath' and on the command line in GNU 'readlink -f'.\n\n## Neither of these tools, however, are particularly accessible on the many\n## systems that do not have the GNU implementation of readlink, nor ship\n## with a system compiler (not to mention the requisite knowledge of C).\n\n## This script is written with portability and (to the extent possible, speed)\n## in mind, hence the use of printf for echo and case statements where they\n## can be substituded for test, though I've had to scale back a bit on that.\n\n## It is (to the best of my knowledge) written in standard POSIX shell, and\n## has been tested with bash-as-bin-sh, dash, and ksh93. zsh seems to have\n## issues with it, though I'm not sure why; so probably best to avoid for now.\n\n## Particularly useful (in fact, the reason I wrote this) is the fact that\n## it can be used within a shell script to find the path of the script itself.\n## (I am sure the shell knows this already; but most likely for the sake of\n## security it is not made readily available. The implementation of \"$0\"\n## specificies that the $0 must be the location of **last** symbolic link in\n## a chain, or wherever it resides in the path.) This can be used for some\n## ...interesting things, like self-duplicating and self-modifiying scripts.\n\n## Currently supported are three errors: whether the file specified exists\n## (ala ENOENT), whether its target exists/is accessible; and the special\n## case of when a sybolic link references itself \"foo -&gt; foo\": a common error\n## for beginners, since 'ln' does not produce an error if the order of link\n## and target are reversed on the command line. (See POSIX signal ELOOP.)\n\n## It would probably be rather simple to write to use this as a basis for\n## a pure shell implementation of the 'symlinks' util included with Linux.\n\n## As an aside, the amount of code below **completely** belies the amount\n## effort it took to get this right -- but I guess that's coding for you.\n\n##===-------------------------------------------------------------------===##\n\nfor argv; do :; done # Last parameter on command line, for options parsing.\n\n## Error messages. Use functions so that we can sub in when the error occurs.\n\nrecurses(){ printf \"Self-referential:\\n\\t$argv -&gt;\\n\\t$argv\\n\" ;}\ndangling(){ printf \"Broken symlink:\\n\\t$argv -&gt;\\n\\t\"$(readlink \"$argv\")\"\\n\" ;}\nerrnoent(){ printf \"No such file: \"$@\"\\n\" ;} # Borrow a horrible signal name.\n\n# Probably best not to install as 'pathfull', if you can avoid it.\n\npathfull(){ cd \"$(dirname \"$@\")\"; link=\"$(readlink \"$(basename \"$@\")\")\"\n\n## 'test and 'ls' report different status for bad symlinks, so we use this.\n\n if [ ! -e \"$@\" ]; then if $(ls -d \"$@\" 2&gt;/dev/null) 2&gt;/dev/null; then\n errnoent 1&gt;&amp;2; exit 1; elif [ ! -e \"$@\" -a \"$link\" = \"$@\" ]; then\n recurses 1&gt;&amp;2; exit 1; elif [ ! -e \"$@\" ] &amp;&amp; [ ! -z \"$link\" ]; then\n dangling 1&gt;&amp;2; exit 1; fi\n fi\n\n## Not a link, but there might be one in the path, so 'cd' and 'pwd'.\n\n if [ -z \"$link\" ]; then if [ \"$(dirname \"$@\" | cut -c1)\" = '/' ]; then\n printf \"$@\\n\"; exit 0; else printf \"$(pwd)/$(basename \"$@\")\\n\"; fi; exit 0\n fi\n\n## Walk the symlinks back to the origin. Calls itself recursivly as needed.\n\n while [ \"$link\" ]; do\n cd \"$(dirname \"$link\")\"; newlink=\"$(readlink \"$(basename \"$link\")\")\"\n case \"$newlink\" in\n \"$link\") dangling 1&gt;&amp;2 &amp;&amp; exit 1 ;;\n '') printf \"$(pwd)/$(basename \"$link\")\\n\"; exit 0 ;;\n *) link=\"$newlink\" &amp;&amp; pathfull \"$link\" ;;\n esac\n done\n printf \"$(pwd)/$(basename \"$newlink\")\\n\"\n}\n\n## Demo. Install somewhere deep in the filesystem, then symlink somewhere \n## else, symlink again (maybe with a different name) elsewhere, and link\n## back into the directory you started in (or something.) The absolute path\n## of the script will always be reported in the usage, along with \"$0\".\n\nif [ -z \"$argv\" ]; then scriptname=\"$(pathfull \"$0\")\"\n\n# Yay ANSI l33t codes! Fancy.\n printf \"\\n\\033[3mfrom/as: \\033[4m$0\\033[0m\\n\\n\\033[1mUSAGE:\\033[0m \"\n printf \"\\033[4m$scriptname\\033[24m [ link | file | dir ]\\n\\n \"\n printf \"Recursive readlink for the authoritative file, symlink after \"\n printf \"symlink.\\n\\n\\n \\033[4m$scriptname\\033[24m\\n\\n \"\n printf \" From within an invocation of a script, locate the script's \"\n printf \"own file\\n (no matter where it has been linked or \"\n printf \"from where it is being called).\\n\\n\"\n\nelse pathfull \"$@\"\nfi\n</code></pre>\n" }, { "answer_id": 23846906, "author": "ideawu", "author_id": 427640, "author_profile": "https://Stackoverflow.com/users/427640", "pm_score": -1, "selected": false, "text": "<pre><code>cur_dir=`old=\\`pwd\\`; cd \\`dirname $0\\`; echo \\`pwd\\`; cd $old;`\n</code></pre>\n" }, { "answer_id": 23905052, "author": "user1338062", "author_id": 1338062, "author_profile": "https://Stackoverflow.com/users/1338062", "pm_score": 4, "selected": false, "text": "<p>For systems having GNU coreutils <code>readlink</code> (for example, Linux):</p>\n<pre><code>$(readlink -f &quot;$(dirname &quot;$0&quot;)&quot;)\n</code></pre>\n<p>There's no need to use <code>BASH_SOURCE</code> when <code>$0</code> contains the script filename.</p>\n" }, { "answer_id": 24545261, "author": "konsolebox", "author_id": 445221, "author_profile": "https://Stackoverflow.com/users/445221", "pm_score": -1, "selected": false, "text": "<p>No forks (besides subshell) and can handle \"alien\" pathname forms like those with newlines as some would claim:</p>\n\n<pre><code>IFS= read -rd '' DIR &lt; &lt;([[ $BASH_SOURCE != */* ]] || cd \"${BASH_SOURCE%/*}/\" &gt;&amp;- &amp;&amp; echo -n \"$PWD\")\n</code></pre>\n" }, { "answer_id": 25596764, "author": "gkb0986", "author_id": 1988435, "author_profile": "https://Stackoverflow.com/users/1988435", "pm_score": 2, "selected": false, "text": "<p>This solution applies only to Bash. Note that the commonly supplied answer <code>${BASH_SOURCE[0]}</code> won't work if you try to find the path from within a function.</p>\n<p>I've found this line to always work, regardless of whether the file is being sourced or run as a script.</p>\n<pre><code>dirname ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n</code></pre>\n<p>If you want to follow symlinks use <a href=\"https://linux.die.net/man/1/readlink\" rel=\"nofollow noreferrer\"><code>readlink</code></a> on the path you get above, recursively or non-recursively.</p>\n<p>Here's a script to try it out and compare it to other proposed solutions. Invoke it as <code>source test1/test2/test_script.sh</code> or <code>bash test1/test2/test_script.sh</code>.</p>\n<pre><code>#\n# Location: test1/test2/test_script.sh\n#\necho $0\necho $_\necho ${BASH_SOURCE}\necho ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n\ncur_file=&quot;${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}&quot;\ncur_dir=&quot;$(dirname &quot;${cur_file}&quot;)&quot;\nsource &quot;${cur_dir}/func_def.sh&quot;\n\nfunction test_within_func_inside {\n echo ${BASH_SOURCE}\n echo ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n}\n\necho &quot;Testing within function inside&quot;\ntest_within_func_inside\n\necho &quot;Testing within function outside&quot;\ntest_within_func_outside\n\n#\n# Location: test1/test2/func_def.sh\n#\nfunction test_within_func_outside {\n echo ${BASH_SOURCE}\n echo ${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\n}\n</code></pre>\n<p>The reason the one-liner works is explained by the use of the <code>BASH_SOURCE</code> environment variable and its associated <code>FUNCNAME</code>.</p>\n<blockquote>\n<p>BASH_SOURCE</p>\n</blockquote>\n<blockquote>\n<p>An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}.</p>\n</blockquote>\n<blockquote>\n<p>FUNCNAME</p>\n</blockquote>\n<blockquote>\n<p>An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is &quot;main&quot;. This variable exists only when a shell function is executing. Assignments to FUNCNAME doesn't have any effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.</p>\n</blockquote>\n<blockquote>\n<p>This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.</p>\n</blockquote>\n<p>[Source: Bash manual]</p>\n" }, { "answer_id": 26934693, "author": "Paul Savage", "author_id": 1901136, "author_profile": "https://Stackoverflow.com/users/1901136", "pm_score": -1, "selected": false, "text": "<pre><code>FOLDERNAME=${PWD##*/}\n</code></pre>\n<p>That is the quickest way I know.</p>\n" }, { "answer_id": 33033257, "author": "michaeljt", "author_id": 213180, "author_profile": "https://Stackoverflow.com/users/213180", "pm_score": -1, "selected": false, "text": "<p>The key part is that I am reducing the scope of the problem: I forbid indirect execution of the script via the path (as in <code>/bin/sh [script path relative to path component]</code>).</p>\n<p>This can be detected because <code>$0</code> will be a relative path which does not resolve to any file relative to the current folder. I believe that direct execution using the <code>#!</code> mechanism always results in an absolute <code>$0</code>, including when the script is found on the path.</p>\n<p>I also require that the pathname and any pathnames along a chain of symbolic links only contain a reasonable subset of characters, notably not <code>\\n</code>, <code>&gt;</code>, <code>*</code> or <code>?</code>. This is required for the parsing logic.</p>\n<p>There are a few more implicit expectations which I will not go into (look at <a href=\"https://stackoverflow.com/a/4794711/213180\">this answer</a>), and I do not attempt to handle deliberate sabotage of <code>$0</code> (so consider any security implications). I expect this to work on almost any Unix-like system with a Bourne-like <code>/bin/sh</code>.</p>\n<pre><code>#!/bin/sh\n(\n path=&quot;${0}&quot;\n while test -n &quot;${path}&quot;; do\n # Make sure we have at least one slash and no leading dash.\n expr &quot;${path}&quot; : / &gt; /dev/null || path=&quot;./${path}&quot;\n # Filter out bad characters in the path name.\n expr &quot;${path}&quot; : &quot;.*[*?&lt;&gt;\\\\]&quot; &gt; /dev/null &amp;&amp; exit 1\n # Catch embedded new-lines and non-existing (or path-relative) files.\n # $0 should always be absolute when scripts are invoked through &quot;#!&quot;.\n test &quot;`ls -l -d &quot;${path}&quot; 2&gt; /dev/null | wc -l`&quot; -eq 1 || exit 1\n # Change to the folder containing the file to resolve relative links.\n folder=`expr &quot;${path}&quot; : &quot;\\(.*/\\)[^/][^/]*/*$&quot;` || exit 1\n path=`expr &quot;x\\`ls -l -d &quot;${path}&quot;\\`&quot; : &quot;[^&gt;]* -&gt; \\(.*\\)&quot;`\n cd &quot;${folder}&quot;\n # If the last path was not a link then we are in the target folder.\n test -n &quot;${path}&quot; || pwd\n done\n)\n</code></pre>\n" }, { "answer_id": 35374073, "author": "Simon Rigét", "author_id": 3546836, "author_profile": "https://Stackoverflow.com/users/3546836", "pm_score": 7, "selected": false, "text": "<p>This should do it:</p>\n<pre><code>DIR=&quot;$(dirname &quot;$(realpath &quot;$0&quot;)&quot;)&quot;\n</code></pre>\n<p>This works with symlinks and spaces in path.</p>\n<p>Please see the man pages for <code>dirname</code> and <code>realpath</code>.</p>\n<p>Please add a comment on how to support MacOS. I'm sorry I can verify it.</p>\n" }, { "answer_id": 35514432, "author": "James Ko", "author_id": 4077294, "author_profile": "https://Stackoverflow.com/users/4077294", "pm_score": 4, "selected": false, "text": "<p>Here is the simple, correct way:</p>\n\n<pre><code>actual_path=$(readlink -f \"${BASH_SOURCE[0]}\")\nscript_dir=$(dirname \"$actual_path\")\n</code></pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li><p><strong><code>${BASH_SOURCE[0]}</code></strong> - the full path to the script. The value of this will be correct even when the script is being sourced, e.g. <code>source &lt;(echo 'echo $0')</code> prints <strong>bash</strong>, while replacing it with <code>${BASH_SOURCE[0]}</code> will print the full path of the script. (Of course, this assumes you're OK taking a dependency on Bash.)</p></li>\n<li><p><strong><code>readlink -f</code></strong> - Recursively resolves any symlinks in the specified path. This is a GNU extension, and not available on (for example) BSD systems. If you're running a Mac, you can use Homebrew to install GNU <code>coreutils</code> and supplant this with <strong><code>greadlink -f</code></strong>.</p></li>\n<li><p>And of course <strong><code>dirname</code></strong> gets the parent directory of the path.</p></li>\n</ul>\n" }, { "answer_id": 36322330, "author": "Jay jargot", "author_id": 6010343, "author_profile": "https://Stackoverflow.com/users/6010343", "pm_score": -1, "selected": false, "text": "<p>Look at the test at bottom with weird directory names. </p>\n\n<p>To change the working directory to the one where the Bash script is located, you should try this simple, <strong>tested</strong> and verified with <strong>shellcheck</strong> solution:</p>\n\n<pre><code>#!/bin/bash --\ncd \"$(dirname \"${0}\")\"/. || exit 2\n</code></pre>\n\n<p>The test:</p>\n\n<pre><code>$ ls \napplication\n$ mkdir \"$(printf \"\\1\\2\\3\\4\\5\\6\\7\\10\\11\\12\\13\\14\\15\\16\\17\\20\\21\\22\\23\\24\\25\\26\\27\\30\\31\\32\\33\\34\\35\\36\\37\\40\\41\\42\\43\\44\\45\\46\\47testdir\" \"\")\"\n$ mv application *testdir\n$ ln -s *testdir \"$(printf \"\\1\\2\\3\\4\\5\\6\\7\\10\\11\\12\\13\\14\\15\\16\\17\\20\\21\\22\\23\\24\\25\\26\\27\\30\\31\\32\\33\\34\\35\\36\\37\\40\\41\\42\\43\\44\\45\\46\\47symlink\" \"\")\"\n$ ls -lb\ntotal 4\nlrwxrwxrwx 1 jay stacko 46 Mar 30 20:44 \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&amp;'symlink -&gt; \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&amp;'testdir\ndrwxr-xr-x 2 jay stacko 4096 Mar 30 20:44 \\001\\002\\003\\004\\005\\006\\a\\b\\t\\n\\v\\f\\r\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\\ !\"#$%&amp;'testdir\n$ *testdir/application &amp;&amp; printf \"SUCCESS\\n\" \"\"\nSUCCESS\n$ *symlink/application &amp;&amp; printf \"SUCCESS\\n\" \"\"\nSUCCESS\n</code></pre>\n" }, { "answer_id": 40217561, "author": "Nam G VU", "author_id": 248616, "author_profile": "https://Stackoverflow.com/users/248616", "pm_score": -1, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/questions/59895/can-a-bash-script-tell-which-directory-it-is-stored-in/246128#246128\">this answer</a>, I suggest the clarified version that gets <code>SCRIPT_HOME</code> as the containing folder of any currently-running Bash script:</p>\n<pre><code>s=${BASH_SOURCE[0]} ; s=`dirname $s` ; SCRIPT_HOME=`cd $s ; pwd`\necho $SCRIPT_HOME\n</code></pre>\n" }, { "answer_id": 42025938, "author": "ankostis", "author_id": 548792, "author_profile": "https://Stackoverflow.com/users/548792", "pm_score": -1, "selected": false, "text": "<p>This <em>one-liner</em> works on <a href=\"https://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> even if the script has been called from <em>Windows</em> with <code>bash -c &lt;script&gt;</code>:</p>\n<pre><code>set mydir=&quot;$(cygpath &quot;$(dirname &quot;$0&quot;)&quot;)&quot;\n</code></pre>\n" }, { "answer_id": 42038422, "author": "puchu", "author_id": 404949, "author_profile": "https://Stackoverflow.com/users/404949", "pm_score": 2, "selected": false, "text": "<p><code>$0</code> is not a reliable way to get the current script path. For example, this is my <code>.xprofile</code>:</p>\n<pre><code>#!/bin/bash\necho &quot;$0 $1 $2&quot;\necho &quot;${BASH_SOURCE[0]}&quot;\n# $dir/my_script.sh &amp;\n</code></pre>\n<blockquote>\n<p>cd /tmp &amp;&amp; ~/.xprofile &amp;&amp; source ~/.xprofile</p>\n</blockquote>\n<pre><code>/home/puchuu/.xprofile\n/home/puchuu/.xprofile\n-bash\n/home/puchuu/.xprofile\n</code></pre>\n<p>So please use <code>BASH_SOURCE</code> instead.</p>\n" }, { "answer_id": 43333425, "author": "BuvinJ", "author_id": 3220983, "author_profile": "https://Stackoverflow.com/users/3220983", "pm_score": 3, "selected": false, "text": "<p>This worked for me when the other answers here did not:</p>\n\n<pre><code>thisScriptPath=`realpath $0`\nthisDirPath=`dirname $thisScriptPath`\necho $thisDirPath\n</code></pre>\n" }, { "answer_id": 49194320, "author": "User8461", "author_id": 8594421, "author_profile": "https://Stackoverflow.com/users/8594421", "pm_score": 4, "selected": false, "text": "<p>These are short ways to get script information:</p>\n\n<p>Folders and files:</p>\n\n<pre><code> Script: \"/tmp/src dir/test.sh\"\n Calling folder: \"/tmp/src dir/other\"\n</code></pre>\n\n<p>Using these commands:</p>\n\n<pre><code> echo Script-Dir : `dirname \"$(realpath $0)\"`\n echo Script-Dir : $( cd ${0%/*} &amp;&amp; pwd -P )\n echo Script-Dir : $(dirname \"$(readlink -f \"$0\")\")\n echo\n echo Script-Name : `basename \"$(realpath $0)\"`\n echo Script-Name : `basename $0`\n echo\n echo Script-Dir-Relative : `dirname \"$BASH_SOURCE\"`\n echo Script-Dir-Relative : `dirname $0`\n echo\n echo Calling-Dir : `pwd`\n</code></pre>\n\n<p>And I got this output:</p>\n\n<pre><code> Script-Dir : /tmp/src dir\n Script-Dir : /tmp/src dir\n Script-Dir : /tmp/src dir\n\n Script-Name : test.sh\n Script-Name : test.sh\n\n Script-Dir-Relative : ..\n Script-Dir-Relative : ..\n\n Calling-Dir : /tmp/src dir/other\n</code></pre>\n\n<p>Also see: <a href=\"https://pastebin.com/J8KjxrPF\" rel=\"noreferrer\">https://pastebin.com/J8KjxrPF</a></p>\n" }, { "answer_id": 49867891, "author": "Rawstring", "author_id": 2693082, "author_profile": "https://Stackoverflow.com/users/2693082", "pm_score": 2, "selected": false, "text": "<p>This is how I work it on my scripts:</p>\n<pre><code>pathvar=&quot;$( cd &quot;$( dirname $0 )&quot; &amp;&amp; pwd )&quot;\n</code></pre>\n<p>This will tell you which directory the Launcher (current script) is being executed from.</p>\n" }, { "answer_id": 50635459, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 2, "selected": false, "text": "<p><em>If your Bash script is a symlink</em>, then this is the way to do it:</p>\n<pre><code>#!/usr/bin/env bash\n\ndirn=&quot;$(dirname &quot;$0&quot;)&quot;\nrl=&quot;$(readlink &quot;$0&quot;)&quot;;\nexec_dir=&quot;$(dirname $(dirname &quot;$rl&quot;))&quot;;\nmy_path=&quot;$dirn/$exec_dir&quot;;\nX=&quot;$(cd $(dirname ${my_path}) &amp;&amp; pwd)/$(basename ${my_path})&quot;\n</code></pre>\n<p>X is the directory that contains your Bash script (the original file, not the symlink). I swear to God this works, and it is the only way I know of doing this properly.</p>\n" }, { "answer_id": 53183593, "author": "Thamme Gowda", "author_id": 1506477, "author_profile": "https://Stackoverflow.com/users/1506477", "pm_score": 7, "selected": false, "text": "<p>Here is an easy-to-remember script:</p>\n<pre><code>DIR=&quot;$( dirname -- &quot;${BASH_SOURCE[0]}&quot;; )&quot;; # Get the directory name\nDIR=&quot;$( realpath -e -- &quot;$DIR&quot;; )&quot;; # Resolve its full path if need be\n</code></pre>\n" }, { "answer_id": 54133107, "author": "danemacmillan", "author_id": 2973534, "author_profile": "https://Stackoverflow.com/users/2973534", "pm_score": -1, "selected": false, "text": "<p>The <a href=\"https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel/246128#246128\">chosen answer</a> works very well. I'm posting my solution for anyone looking for shorter alternatives that still addresses sourcing, executing, full paths, relative paths, and symlinks. Finally, this will work on <a href=\"https://en.wikipedia.org/wiki/MacOS\" rel=\"nofollow noreferrer\">macOS</a>, given that it cannot be assumed that GNU's coreutils' version of <a href=\"https://linux.die.net/man/1/readlink\" rel=\"nofollow noreferrer\">readlink</a> is available.</p>\n<p>The gotcha is that it's not using Bash, but it is easy to use in a Bash script. While the OP did not place any constraints on the language of the solution, it's probably best that most have stayed within the Bash world. This is just an alternative, and possibly an unpopular one.</p>\n<p>PHP is available on macOS by default, and installed on a number of other platforms, though not necessarily by default. I realize this is a shortcoming, but I'll leave this here for any people coming from search engines, anyway.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>export SOURCE_DIRECTORY=&quot;$(php -r 'echo dirname(realpath($argv[1]));' -- &quot;${BASH_SOURCE[0]}&quot;)&quot;\n</code></pre>\n" }, { "answer_id": 55352142, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 0, "selected": false, "text": "<p>The below stores the script's directory path in the <code>dir</code> variable.</p>\n<p>(It also tries to support being executed under <a href=\"https://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> in Windows.)</p>\n<p>And at last it runs the <code>my-sample-app</code> executable with all arguments passed to this script using <code>&quot;$@&quot;</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env sh\n\ndir=$(cd &quot;${0%[/\\\\]*}&quot; &gt; /dev/null &amp;&amp; pwd)\n\nif [ -d /proc/cygdrive ]; then\n case &quot;$(uname -s)&quot; in\n CYGWIN*|MINGW32*|MSYS*|MINGW*)\n # We are under Windows, so translate path to Windows format.\n dir=$(cygpath -m &quot;$dir&quot;);\n ;;\n esac\nfi\n\n# Runs the executable which is beside this script\n&quot;${dir}/my-sample-app&quot; &quot;$@&quot;\n</code></pre>\n" }, { "answer_id": 56031051, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": -1, "selected": false, "text": "<p>There is no 100% portable and reliable way to request a path to a current script directory. Especially between different backends like <a href=\"https://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a>, <a href=\"https://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow noreferrer\">MinGW</a>, <a href=\"https://en.wikipedia.org/wiki/MinGW#History\" rel=\"nofollow noreferrer\">MSYS</a>, Linux, etc. This issue was not properly and completely resolved in Bash for ages.</p>\n<p>For example, this could not be resolved if you want to request the path after the <code>source</code> command to make nested inclusion of another Bash script which is in turn use the same <code>source</code> command to include another Bash script and so on.</p>\n<p>In case of the <a href=\"https://linux.die.net/man/1/source\" rel=\"nofollow noreferrer\"><code>source</code></a> command, I suggest to replace the <code>source</code> command with something like this:</p>\n<pre><code>function include()\n{\n if [[ -n &quot;$CURRENT_SCRIPT_DIR&quot; ]]; then\n local dir_path=... get directory from `CURRENT_SCRIPT_DIR/$1`, depends if $1 is absolute path or relative ...\n local include_file_path=...\n else\n local dir_path=... request the directory from the &quot;$1&quot; argument using one of answered here methods...\n local include_file_path=...\n fi\n ... push $CURRENT_SCRIPT_DIR in to stack ...\n export CURRENT_SCRIPT_DIR=... export current script directory using $dir_path ...\n source &quot;$include_file_path&quot;\n ... pop $CURRENT_SCRIPT_DIR from stack ...\n}\n</code></pre>\n<p>From now on, the use of <code>include(...)</code> is based on previous <code>CURRENT_SCRIPT_DIR</code> in your script.</p>\n<p>This only works when you can replace all <code>source</code> commands by <code>include</code> command. If you can't, then you have no choice. At least until developers of the Bash interpreter make an explicit command to request the current running script directory path.</p>\n<p>My own closest implementation to this:\n<a href=\"https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/bash/tacklelib/bash_tacklelib\" rel=\"nofollow noreferrer\">https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/bash/tacklelib/bash_tacklelib</a><br />\n<a href=\"https://github.com/andry81/tacklelib/tree/trunk/bash/tacklelib/bash_tacklelib\" rel=\"nofollow noreferrer\">https://github.com/andry81/tacklelib/tree/trunk/bash/tacklelib/bash_tacklelib</a></p>\n<p>(search for the <code>tkl_include</code> function)</p>\n" }, { "answer_id": 56186126, "author": "cdonat", "author_id": 5053331, "author_profile": "https://Stackoverflow.com/users/5053331", "pm_score": 2, "selected": false, "text": "<p>I usually use:</p>\n<pre><code>dirname $(which $BASH_SOURCE)\n</code></pre>\n" }, { "answer_id": 56264110, "author": "Chaim Leib Halbert", "author_id": 1795125, "author_profile": "https://Stackoverflow.com/users/1795125", "pm_score": 2, "selected": false, "text": "<p>Here's a command that works under either Bash or zsh, and whether executed stand-alone or sourced:</p>\n<pre><code>[ -n &quot;$ZSH_VERSION&quot; ] &amp;&amp; this_dir=$(dirname &quot;${(%):-%x}&quot;) \\\n || this_dir=$(dirname &quot;${BASH_SOURCE[0]:-$0}&quot;)\n</code></pre>\n<h1>How it works</h1>\n<h2>The zsh current file expansion: <code>${(%):-%x}</code></h2>\n<p><code>${(%):-%x}</code> in zsh expands to the path of the currently-executing file.</p>\n<h3>The fallback substitution operator <code>:-</code></h3>\n<p>You know already that <code>${...}</code> substitutes variables inside of strings. You might not know that certain operations are possible (in both <a href=\"http://tldp.org/LDP/abs/html/parameter-substitution.html\" rel=\"nofollow noreferrer\">Bash</a> and <a href=\"http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion\" rel=\"nofollow noreferrer\">zsh</a>) on the variables during substitution, like the fallback expansion operator <code>:-</code>:</p>\n<pre><code>% x=ok\n% echo &quot;${x}&quot;\nok\n\n% echo &quot;${x:-fallback}&quot;\nok\n\n% x=\n% echo &quot;${x:-fallback}&quot;\nfallback\n\n% y=yvalue\n% echo &quot;${x:-$y}&quot;\nyvalue\n</code></pre>\n<h3>The <code>%x</code> prompt escape code</h3>\n<p>Next, we'll introduce prompt escape codes, a zsh-only feature. In zsh, <code>%x</code> will expand to the path of the file, but normally this is only when doing expansion for <a href=\"http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Shell-state\" rel=\"nofollow noreferrer\">prompt strings</a>. To enable those codes in our substitution, we can add a <code>(%)</code> flag before the variable name:</p>\n<pre><code>% cat apath/test.sh\nfpath=%x\necho &quot;${(%)fpath}&quot;\n\n% source apath/test.sh\napath/test.sh\n\n% cd apath\n% source test.sh\ntest.sh\n</code></pre>\n<h3>An unlikely match: the percent escape and the fallback</h3>\n<p>What we have so far works, but it would be tidier to avoid creating the extra <code>fpath</code> variable. Instead of putting <code>%x</code> in <code>fpath</code>, we can use <code>:-</code> and put <code>%x</code> in the fallback string:</p>\n<pre><code>% cat test.sh\necho &quot;${(%):-%x}&quot;\n\n% source test.sh\ntest.sh\n</code></pre>\n<p>Note that we normally would put a variable name between <code>(%)</code> and <code>:-</code>, but we left it blank. The variable with a blank name can't be declared or set, so the fallback is always triggered.</p>\n<h3>Finishing up: what about <code>print -P %x</code>?</h3>\n<p>Now we almost have the directory of our script. We could have used <code>print -P %x</code> to get the same file path with fewer hacks, but in our case, where we need to pass it as an argument to <code>dirname</code>, that would have required the overhead of a starting a new subshell:</p>\n<pre><code>% cat apath/test.sh\ndirname &quot;$(print -P %x)&quot; # $(...) runs a command in a new process\ndirname &quot;${(%):-%x}&quot;\n\n% source apath/test.sh\napath\napath\n</code></pre>\n<p>It turns out that the hacky way is both more performant and succinct.</p>\n" }, { "answer_id": 56694491, "author": "Atul", "author_id": 2881112, "author_profile": "https://Stackoverflow.com/users/2881112", "pm_score": 5, "selected": false, "text": "<p>The shortest and most elegant way to do this is:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\nDIRECTORY=$(cd `dirname $0` &amp;&amp; pwd)\necho $DIRECTORY\n</code></pre>\n\n<p>This would work on all platforms and is super clean.</p>\n\n<p>More details can be found in \"<a href=\"https://www.electrictoolbox.com/bash-script-directory/\" rel=\"noreferrer\">Which directory is that bash script in?</a>\". </p>\n" }, { "answer_id": 57505372, "author": "bestOfSong", "author_id": 5010054, "author_profile": "https://Stackoverflow.com/users/5010054", "pm_score": -1, "selected": false, "text": "<p>I want to comment on the previous answer up there (<em><a href=\"https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel/201915#201915\">How can I get the source directory of a Bash script from within the script itself?</a></em>), but don't have enough reputation to do that.</p>\n<p>I found a solution for this two years ago on Apple's documentation site: <a href=\"https://developer.apple.com/library/archive/documentation/OpenSource/Conceptual/ShellScripting/AdvancedTechniques/AdvancedTechniques.html\" rel=\"nofollow noreferrer\">https://developer.apple.com/library/archive/documentation/OpenSource/Conceptual/ShellScripting/AdvancedTechniques/AdvancedTechniques.html</a>. And I stuck to this method afterwards. It cannot handle soft link, but otherwise works pretty well for me. I'm posting it here for any who needs it and as a request for comment.</p>\n<pre><code>#!/bin/sh\n\n# Get an absolute path for the poem.txt file.\nPOEM=&quot;$PWD/../poem.txt&quot;\n\n# Get an absolute path for the script file.\nSCRIPT=&quot;$(which $0)&quot;\nif [ &quot;x$(echo $SCRIPT | grep '^\\/')&quot; = &quot;x&quot; ] ; then\n SCRIPT=&quot;$PWD/$SCRIPT&quot;\nfi\n</code></pre>\n<p>As shown by the code, after you get the absolute path of the script, then you can use the <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\"><code>dirname</code></a> command to get the path of the directory.</p>\n" }, { "answer_id": 57660444, "author": "LozanoMatheus", "author_id": 2868547, "author_profile": "https://Stackoverflow.com/users/2868547", "pm_score": 3, "selected": false, "text": "<p>You can do that just combining the script name (<code>$0</code>) with <a href=\"https://linux.die.net/man/1/realpath\" rel=\"nofollow noreferrer\"><code>realpath</code></a> and/or <a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\"><code>dirname</code></a>. It works for Bash and Shell.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env bash\n\nRELATIVE_PATH=&quot;${0}&quot;\nRELATIVE_DIR_PATH=&quot;$(dirname &quot;${0}&quot;)&quot;\nFULL_DIR_PATH=&quot;$(realpath &quot;${0}&quot; | xargs dirname)&quot;\nFULL_PATH=&quot;$(realpath &quot;${0}&quot;)&quot;\n\necho &quot;RELATIVE_PATH-&gt;${RELATIVE_PATH}&lt;-&quot;\necho &quot;RELATIVE_DIR_PATH-&gt;${RELATIVE_DIR_PATH}&lt;-&quot;\necho &quot;FULL_DIR_PATH-&gt;${FULL_DIR_PATH}&lt;-&quot;\necho &quot;FULL_PATH-&gt;${FULL_PATH}&lt;-&quot;\n</code></pre>\n<p>The output will be something like this:</p>\n<pre><code># RELATIVE_PATH-&gt;./bin/startup.sh&lt;-\n# RELATIVE_DIR_PATH-&gt;./bin&lt;-\n# FULL_DIR_PATH-&gt;/opt/my_app/bin&lt;-\n# FULL_PATH-&gt;/opt/my_app/bin/startup.sh&lt;-\n</code></pre>\n<blockquote>\n<p>$0 is the name of the script itself</p>\n</blockquote>\n<p><em><a href=\"https://www.tldp.org/LDP/abs/html/othertypesv.html\" rel=\"nofollow noreferrer\">4.4. Special Variable Types</a></em></p>\n<p>An example: <em><a href=\"https://gist.github.com/LozanoMatheus/da96b4e44b89b13ad4af10ac4602ad99\" rel=\"nofollow noreferrer\">LozanoMatheus/get_script_paths.sh</a></em></p>\n" }, { "answer_id": 57666344, "author": "MatteoBee", "author_id": 11004601, "author_profile": "https://Stackoverflow.com/users/11004601", "pm_score": -1, "selected": false, "text": "<p>This is what I crafted throughout the years to use as a header on my Bash scripts:</p>\n<pre><code>## BASE BRAIN - Get where you're from and who you are.\nMYPID=$$\nORIGINAL_DIR=&quot;$(pwd)&quot; # This is not a hot air balloon ride..\nfa=&quot;$0&quot; # First Assumption\nta= # Temporary Assumption\nwa= # Weighed Assumption\nwhile true; do\n [ &quot;${fa:0:1}&quot; = &quot;/&quot; ] &amp;&amp; wa=$0 &amp;&amp; break\n [ &quot;${fa:0:2}&quot; = &quot;./&quot; ] &amp;&amp; ta=&quot;${ORIGINAL_DIR}/${fa:2}&quot; &amp;&amp; [ -e &quot;$ta&quot; ] &amp;&amp; wa=&quot;$ta&quot; &amp;&amp; break\n ta=&quot;${ORIGINAL_DIR}/${fa}&quot; &amp;&amp; [ -e &quot;$ta&quot; ] &amp;&amp; wa=&quot;$ta&quot; &amp;&amp; break\ndone\nSW=&quot;$wa&quot;\nSWDIR=&quot;$(dirname &quot;$wa&quot;)&quot;\nSWBIN=&quot;$(basename &quot;$wa&quot;)&quot;\nunset ta fa wa\n( [ ! -e &quot;$SWDIR/$SWBIN&quot; ] || [ -z &quot;$SW&quot; ] ) &amp;&amp; echo &quot;I could not find my way around :( possible bug in the TOP script&quot; &amp;&amp; exit 1\n</code></pre>\n<p>At this point, your variables SW, SWDIR, and SWBIN contain what you need.</p>\n" }, { "answer_id": 58286511, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 2, "selected": false, "text": "<h3>The following will return the current directory of the script</h3>\n\n<ul>\n<li>works if it's sourced, or not sourced</li>\n<li>works if run in the current directory, or some other directory.</li>\n<li>works if relative directories are used.</li>\n<li>works with bash, not sure of other shells.</li>\n</ul>\n\n<pre><code>/tmp/a/b/c $ . ./test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ . /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ ./test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n/tmp/a/b/c $ cd\n\n~ $ . /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ . ../../tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ /tmp/a/b/c/test.sh\n/tmp/a/b/c\n\n~ $ ../../tmp/a/b/c/test.sh\n/tmp/a/b/c\n</code></pre>\n\n<h3>test.sh</h3>\n\n<pre><code>#!/usr/bin/env bash\n\n# snagged from: https://stackoverflow.com/a/51264222/26510\nfunction toAbsPath {\n local target\n target=\"$1\"\n\n if [ \"$target\" == \".\" ]; then\n echo \"$(pwd)\"\n elif [ \"$target\" == \"..\" ]; then\n echo \"$(dirname \"$(pwd)\")\"\n else\n echo \"$(cd \"$(dirname \"$1\")\"; pwd)/$(basename \"$1\")\"\n fi\n}\n\nfunction getScriptDir(){\n local SOURCED\n local RESULT\n (return 0 2&gt;/dev/null) &amp;&amp; SOURCED=1 || SOURCED=0\n\n if [ \"$SOURCED\" == \"1\" ]\n then\n RESULT=$(dirname \"$1\")\n else\n RESULT=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )\"\n fi\n toAbsPath \"$RESULT\"\n}\n\nSCRIPT_DIR=$(getScriptDir \"$0\")\necho \"$SCRIPT_DIR\"\n</code></pre>\n" }, { "answer_id": 58562442, "author": "Alexander Stohr", "author_id": 3423146, "author_profile": "https://Stackoverflow.com/users/3423146", "pm_score": 3, "selected": false, "text": "<p>The top response does not work in all cases...</p>\n<p>As I had problems with the BASH_SOURCE with the included 'cd' approach on some very fresh and also on less fresh installed <a href=\"https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_16.04_LTS_.28Xenial_Xerus.29\" rel=\"nofollow noreferrer\">Ubuntu 16.04</a> (Xenial Xerus) systems when invoking the shell script by means of &quot;sh my_script.sh&quot;, I tried out something different that as of now seems to run quite smoothly for my purposes. The approach is a bit more compact in the script and is further much lesser cryptic feeling.</p>\n<p>This alternate approach uses the external applications '<a href=\"https://linux.die.net/man/1/realpath\" rel=\"nofollow noreferrer\">realpath</a>' and '<a href=\"https://linux.die.net/man/1/dirname\" rel=\"nofollow noreferrer\">dirname</a>' from the coreutils package. (Okay, not anyone likes the overhead of invoking secondary processes - but when seeing the multi-line scripting for resolving the true object it won't be that bad either having it solve in a single binary usage.)</p>\n<p>So let’s see one example of those alternate solution for the described task of querying the true absolute path to a certain file:</p>\n<pre><code>PATH_TO_SCRIPT=`realpath -s $0`\nPATH_TO_SCRIPT_DIR=`dirname $PATH_TO_SCRIPT`\n</code></pre>\n<p>But preferably you should use this evolved version to also support the use of paths with spaces (or maybe even some other special characters):</p>\n<pre><code>PATH_TO_SCRIPT=`realpath -s &quot;$0&quot;`\nPATH_TO_SCRIPT_DIR=`dirname &quot;$PATH_TO_SCRIPT&quot;`\n</code></pre>\n<p>Indeed, if you don’t need the value of the SCRIPT variable then you might be able to merge this two-liner into even a single line. But why really shall you spend the effort for this?</p>\n" }, { "answer_id": 59485855, "author": "Domi", "author_id": 2228771, "author_profile": "https://Stackoverflow.com/users/2228771", "pm_score": 2, "selected": false, "text": "<p>Python was mentioned a few times. Here is the JavaScript (i.e., <a href=\"https://en.wikipedia.org/wiki/Node.js\" rel=\"nofollow noreferrer\">Node.js</a>) alternative:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>baseDirRelative=$(dirname &quot;$0&quot;)\nbaseDir=$(node -e &quot;console.log(require('path').resolve('$baseDirRelative'))&quot;) # Get absolute path using Node.js\n\necho $baseDir\n</code></pre>\n" }, { "answer_id": 60157372, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 4, "selected": false, "text": "<h2>Summary:</h2>\n<pre class=\"lang-sh prettyprint-override\"><code>FULL_PATH_TO_SCRIPT=&quot;$(realpath &quot;${BASH_SOURCE[-1]}&quot;)&quot;\n\n# OR, if you do NOT need it to work for **sourced** scripts too:\n# FULL_PATH_TO_SCRIPT=&quot;$(realpath &quot;$0&quot;)&quot;\n\n# OR, depending on which path you want, in case of nested `source` calls\n# FULL_PATH_TO_SCRIPT=&quot;$(realpath &quot;${BASH_SOURCE[0]}&quot;)&quot;\n\n# OR, add `-s` to NOT expand symlinks in the path:\n# FULL_PATH_TO_SCRIPT=&quot;$(realpath -s &quot;${BASH_SOURCE[-1]}&quot;)&quot;\n\nSCRIPT_DIRECTORY=&quot;$(dirname &quot;$FULL_PATH_TO_SCRIPT&quot;)&quot;\nSCRIPT_FILENAME=&quot;$(basename &quot;$FULL_PATH_TO_SCRIPT&quot;)&quot;\n</code></pre>\n<h2>Details:</h2>\n<h2>How to obtain the <em>full file path</em>, <em>full directory</em>, and <em>base filename</em> of any script being <em>run</em> OR <em>sourced</em>...</h2>\n<p>...even when the called script is called from within another bash function or script, or when nested sourcing is being used!</p>\n<p>For many cases, all you need to acquire is the full path to the script you just called. This can be easily accomplished using <code>realpath</code>. Note that <code>realpath</code> is part of <strong>GNU coreutils</strong>. If you don't have it already installed (it comes default on Ubuntu), you can install it with <code>sudo apt update &amp;&amp; sudo apt install coreutils</code>.</p>\n<p><strong>get_script_path.sh</strong> (for the latest version of this script, see <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/bash/get_script_path.sh\" rel=\"noreferrer\">get_script_path.sh</a> in my <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world\" rel=\"noreferrer\">eRCaGuy_hello_world</a> repo):</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\n# A. Obtain the full path, and expand (walk down) symbolic links\n# A.1. `&quot;$0&quot;` works only if the file is **run**, but NOT if it is **sourced**.\n# FULL_PATH_TO_SCRIPT=&quot;$(realpath &quot;$0&quot;)&quot;\n# A.2. `&quot;${BASH_SOURCE[-1]}&quot;` works whether the file is sourced OR run, and even\n# if the script is called from within another bash function!\n# NB: if `&quot;${BASH_SOURCE[-1]}&quot;` doesn't give you quite what you want, use\n# `&quot;${BASH_SOURCE[0]}&quot;` instead in order to get the first element from the array.\nFULL_PATH_TO_SCRIPT=&quot;$(realpath &quot;${BASH_SOURCE[-1]}&quot;)&quot;\n# B.1. `&quot;$0&quot;` works only if the file is **run**, but NOT if it is **sourced**.\n# FULL_PATH_TO_SCRIPT_KEEP_SYMLINKS=&quot;$(realpath -s &quot;$0&quot;)&quot;\n# B.2. `&quot;${BASH_SOURCE[-1]}&quot;` works whether the file is sourced OR run, and even\n# if the script is called from within another bash function!\n# NB: if `&quot;${BASH_SOURCE[-1]}&quot;` doesn't give you quite what you want, use\n# `&quot;${BASH_SOURCE[0]}&quot;` instead in order to get the first element from the array.\nFULL_PATH_TO_SCRIPT_KEEP_SYMLINKS=&quot;$(realpath -s &quot;${BASH_SOURCE[-1]}&quot;)&quot;\n\n# You can then also get the full path to the directory, and the base\n# filename, like this:\nSCRIPT_DIRECTORY=&quot;$(dirname &quot;$FULL_PATH_TO_SCRIPT&quot;)&quot;\nSCRIPT_FILENAME=&quot;$(basename &quot;$FULL_PATH_TO_SCRIPT&quot;)&quot;\n\n# Now print it all out\necho &quot;FULL_PATH_TO_SCRIPT = \\&quot;$FULL_PATH_TO_SCRIPT\\&quot;&quot;\necho &quot;SCRIPT_DIRECTORY = \\&quot;$SCRIPT_DIRECTORY\\&quot;&quot;\necho &quot;SCRIPT_FILENAME = \\&quot;$SCRIPT_FILENAME\\&quot;&quot;\n</code></pre>\n<p><strong>IMPORTANT note on <em>nested <code>source</code> calls</em>:</strong> if <code>&quot;${BASH_SOURCE[-1]}&quot;</code> above doesn't give you quite what you want, try using <code>&quot;${BASH_SOURCE[0]}&quot;</code> instead. The first (<code>0</code>) index gives you the first entry in the array, and the last (<code>-1</code>) index gives you the last last entry in the array. Depending on what it is you're after, you may actually want the first entry. I discovered this to be the case when I sourced <code>~/.bashrc</code> with <code>. ~/.bashrc</code>, which sourced <code>~/.bash_aliases</code> with <code>. ~/.bash_aliases</code>, and I wanted the <code>realpath</code> (with expanded symlinks) to the <code>~/.bash_aliases</code> file, NOT to the <code>~/.bashrc</code> file. Since these are <em>nested</em> <code>source</code> calls, using <code>&quot;${BASH_SOURCE[0]}&quot;</code> gave me what I wanted: the expanded path to <code>~/.bash_aliases</code>! Using <code>&quot;${BASH_SOURCE[-1]}&quot;</code>, however, gave me what I did <em>not</em> want: the expanded path to <code>~/.bashrc</code>.</p>\n<p><strong>Example command and output:</strong></p>\n<ol>\n<li><em>Running</em> the script:\n<pre class=\"lang-sh prettyprint-override\"><code>~/GS/dev/eRCaGuy_hello_world/bash$ ./get_script_path.sh \nFULL_PATH_TO_SCRIPT = &quot;/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh&quot;\nSCRIPT_DIRECTORY = &quot;/home/gabriel/GS/dev/eRCaGuy_hello_world/bash&quot;\nSCRIPT_FILENAME = &quot;get_script_path.sh&quot;\n</code></pre>\n</li>\n<li><em>Sourcing</em> the script with <code>. get_script_path.sh</code> or <code>source get_script_path.sh</code> (the result is the exact same as above because I used <code>&quot;${BASH_SOURCE[-1]}&quot;</code> in the script instead of <code>&quot;$0&quot;</code>):\n<pre class=\"lang-sh prettyprint-override\"><code>~/GS/dev/eRCaGuy_hello_world/bash$ . get_script_path.sh \nFULL_PATH_TO_SCRIPT = &quot;/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh&quot;\nSCRIPT_DIRECTORY = &quot;/home/gabriel/GS/dev/eRCaGuy_hello_world/bash&quot;\nSCRIPT_FILENAME = &quot;get_script_path.sh&quot;\n</code></pre>\n</li>\n</ol>\n<p>If you use <code>&quot;$0&quot;</code> in the script instead of <code>&quot;${BASH_SOURCE[-1]}&quot;</code>, you'll get the same output as above when <em>running</em> the script, but this <em>undesired</em> output instead when <em>sourcing</em> the script:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>~/GS/dev/eRCaGuy_hello_world/bash$ . get_script_path.sh \nFULL_PATH_TO_SCRIPT = &quot;/bin/bash&quot;\nSCRIPT_DIRECTORY = &quot;/bin&quot;\nSCRIPT_FILENAME = &quot;bash&quot;\n</code></pre>\n<p>And, apparently if you use <code>&quot;$BASH_SOURCE&quot;</code> instead of <code>&quot;${BASH_SOURCE[-1]}&quot;</code>, it will <em>not</em> work if the script is called from within another bash function. So, using <code>&quot;${BASH_SOURCE[-1]}&quot;</code> is therefore the best way to do it, as it solves both of these problems! See the references below.</p>\n<p><strong>Difference between <code>realpath</code> and <code>realpath -s</code>:</strong></p>\n<p>Note that <code>realpath</code> also successfully walks down symbolic links to determine and point to their targets rather than pointing to the symbolic link. If you do NOT want this behavior (sometimes I don't), then add <code>-s</code> to the <code>realpath</code> command above, making that line look like this instead:</p>\n<pre class=\"lang-sh prettyprint-override\"><code># Obtain the full path, but do NOT expand (walk down) symbolic links; in\n# other words: **keep** the symlinks as part of the path!\nFULL_PATH_TO_SCRIPT=&quot;$(realpath -s &quot;${BASH_SOURCE[-1]}&quot;)&quot;\n</code></pre>\n<p>This way, symbolic links are NOT expanded. Rather, they are left as-is, as symbolic links in the full path.</p>\n<p>The code above is now part of my <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world\" rel=\"noreferrer\">eRCaGuy_hello_world</a> repo in this file here: <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/bash/get_script_path.sh\" rel=\"noreferrer\">bash/get_script_path.sh</a>. Reference and run this file for full examples both with and withOUT symlinks in the paths. See the bottom of the file for example output in both cases.</p>\n<h2>References:</h2>\n<ol>\n<li><a href=\"https://stackoverflow.com/a/14892459/4561887\">How to retrieve absolute path given relative</a></li>\n<li>taught me about the <code>BASH_SOURCE</code> variable: <a href=\"https://unix.stackexchange.com/a/4653/114401\">Unix &amp; Linux: determining path to sourced shell script</a></li>\n<li>taught me that <code>BASH_SOURCE</code> is actually an array, and we want the last element from it for it to work as expected inside a function (hence why I used <code>&quot;${BASH_SOURCE[-1]}&quot;</code> in my code here): <a href=\"https://unix.stackexchange.com/a/153061/114401\">Unix &amp; Linux: determining path to sourced shell script</a></li>\n<li><code>man bash</code> --&gt; search for <code>BASH_SOURCE</code>:\n<blockquote>\n<p><strong><code>BASH_SOURCE</code></strong></p>\n<p>An array variable whose members are the source filenames where the corresponding shell function names in the <code>FUNCNAME</code> array variable are defined. The shell function <code>${FUNCNAME[$i]}</code> is defined in the file <code>${BASH_SOURCE[$i]}</code> and called from <code>${BASH_SOURCE[$i+1]}</code>.</p>\n</blockquote>\n</li>\n</ol>\n<h2>See also:</h2>\n<ol>\n<li>[my answer] <a href=\"https://unix.stackexchange.com/a/692485/114401\">Unix &amp; Linux: determining path to sourced shell script</a></li>\n</ol>\n" }, { "answer_id": 60381515, "author": "Muhammad Adeel", "author_id": 2407041, "author_profile": "https://Stackoverflow.com/users/2407041", "pm_score": -1, "selected": false, "text": "<p>Keep it simple.</p>\n\n<pre><code>#!/usr/bin/env bash\nsourceDir=`pwd`\necho $sourceDir\n</code></pre>\n" }, { "answer_id": 62396544, "author": "todd_dsm", "author_id": 1778702, "author_profile": "https://Stackoverflow.com/users/1778702", "pm_score": 0, "selected": false, "text": "<p>I think the simplest answer is a parameter expansion of the original variable:</p>\n<pre><code>#!/usr/bin/env bash\n\nDIR=&quot;$( cd &quot;$( dirname &quot;${BASH_SOURCE[0]}&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )&quot;\necho &quot;opt1; original answer: $DIR&quot;\necho ''\n\necho &quot;opt2; simple answer : ${BASH_SOURCE[0]%/*}&quot;\n</code></pre>\n<p>It should produce output like:</p>\n<pre><code>$ /var/tmp/test.sh\nopt1; original answer: /var/tmp\n\nopt2; simple answer : /var/tmp\n</code></pre>\n<p>The variable/parameter expansion <code>${BASH_SOURCE[0]%/*}&quot;</code> seems much easier to maintain.</p>\n" }, { "answer_id": 65430829, "author": "Thomas Guyot-Sionnest", "author_id": 969196, "author_profile": "https://Stackoverflow.com/users/969196", "pm_score": 2, "selected": false, "text": "<p>One advantage of this method is that it doesn't involve anything outside Bash itself and does not fork any subshell neither.</p>\n<p>First, use pattern substitution to replace anything not starting with <code>/</code> (i.e., a relative path) with <code>$PWD/</code>. Since we use a substitution to <em>match the first character of <code>$0</code></em>, we also have to append it back (<code>${0:0:1}</code> in the substitution).</p>\n<p>Now we have a full path to the script; we can get the directory by removing the last <code>/</code> and anything the follows (i.e., the script name). That directory can then be used in <code>cd</code> or as a prefix to other paths relative to your script.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\nBIN=${0/#[!\\/]/&quot;$PWD/${0:0:1}&quot;}\nDIR=${BIN%/*}\n\ncd &quot;$DIR&quot;\n</code></pre>\n<p>If your script may be sourced rather than executed, you can of course replace <code>$0</code> with <code>${BASH_SOURCE[0]}</code>, such as:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>BIN=${BASH_SOURCE[0]/#[!\\/]/&quot;$PWD/${BASH_SOURCE[0]:0:1}&quot;}\n</code></pre>\n<p>This will work for executable scripts too. It's longer, but more polyvalent.</p>\n" }, { "answer_id": 65802617, "author": "ghchoi", "author_id": 4227175, "author_profile": "https://Stackoverflow.com/users/4227175", "pm_score": 2, "selected": false, "text": "<p>I tried the followings with 3 different executions.</p>\n<h3><code>echo $(realpath $_)</code></h3>\n<pre><code>. application # /correct/path/to/dir or /path/to/temporary_dir\nbash application # /path/to/bash\n/PATH/TO/application # /correct/path/to/dir\n</code></pre>\n<h3><code>echo $(realpath $(dirname $0))</code></h3>\n<pre><code>. application # failed with `realpath: missing operand`\nbash application # /correct/path/to/dir\n/PATH/TO/application # /correct/path/to/dir\n</code></pre>\n<h3><code>echo $(realpath $BASH_SOURCE)</code></h3>\n<p><code>$BASH_SOURCE</code> is basically the same with <code>${BASH_SOURCE[0]}</code>.</p>\n<pre><code>. application # /correct/path/to/dir\nbash application # /correct/path/to/dir\n/PATH/TO/application # /correct/path/to/dir\n</code></pre>\n<p>Only <code>$(realpath $BASH_SOURCE)</code> seems to be reliable.</p>\n" }, { "answer_id": 67105198, "author": "l0b0", "author_id": 96588, "author_profile": "https://Stackoverflow.com/users/96588", "pm_score": 3, "selected": false, "text": "<p>None of the current solutions work if there are any newlines at the end of the directory name - They will be stripped by the command substitution. To work around this you can append a non-newline character inside the command substitution and then strip just that character off:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>dir=&quot;$(cd &quot;$(dirname &quot;${BASH_SOURCE[0]}&quot;)&quot; &amp;&amp; pwd &amp;&amp; echo x)&quot;\ndir=&quot;${dir%x}&quot;\n</code></pre>\n<p>This protects against two very common situations: Accidents and sabotage. A script shouldn't fail in unpredictable ways just because someone, somewhere, did a <code>mkdir $'\\n'</code>.</p>\n" }, { "answer_id": 67149152, "author": "Binary Phile", "author_id": 75182, "author_profile": "https://Stackoverflow.com/users/75182", "pm_score": 2, "selected": false, "text": "<p>Most answers either don't handle files which are symlinked via a relative path, aren't one-liners or don't handle BSD (Mac). A solution which does all three is:</p>\n<pre><code>HERE=$(cd &quot;$(dirname &quot;$BASH_SOURCE&quot;)&quot;; cd -P &quot;$(dirname &quot;$(readlink &quot;$BASH_SOURCE&quot; || echo .)&quot;)&quot;; pwd)\n</code></pre>\n<p>First, cd to bash's conception of the script's directory. Then readlink the file to see if it is a symlink (relative or otherwise), and if so, cd to that directory. If not, cd to the current directory (necessary to keep things a one-liner). Then echo the current directory via <code>pwd</code>.</p>\n<p>You could add <code>--</code> to the arguments of cd and readlink to avoid issues of directories named like options, but I don't bother for most purposes.</p>\n<p>You can see the full explanation with illustrations here:</p>\n<p><a href=\"https://www.binaryphile.com/bash/2020/01/12/determining-the-location-of-your-script-in-bash.html\" rel=\"nofollow noreferrer\">https://www.binaryphile.com/bash/2020/01/12/determining-the-location-of-your-script-in-bash.html</a></p>\n" }, { "answer_id": 68056148, "author": "mrucci", "author_id": 133106, "author_profile": "https://Stackoverflow.com/users/133106", "pm_score": 3, "selected": false, "text": "<p>This is, annoyingly, the only one-liner I've found that works on both Linux and macOS when the executable script is a symlink:</p>\n<pre><code>SCRIPT_DIR=$(python -c &quot;import os; print(os.path.dirname(os.path.realpath('${BASH_SOURCE[0]}')))&quot;)\n</code></pre>\n<p>or, similarly, using python3 pathlib module:</p>\n<pre><code>SCRIPT_DIR=$(python3 -c &quot;from pathlib import Path; print(Path('${BASH_SOURCE[0]}').resolve().parent)&quot;)\n</code></pre>\n<p>Tested on Linux and macOS and compared to other solutions in this gist: <a href=\"https://gist.github.com/ptc-mrucci/61772387878ed53a6c717d51a21d9371\" rel=\"nofollow noreferrer\">https://gist.github.com/ptc-mrucci/61772387878ed53a6c717d51a21d9371</a></p>\n" }, { "answer_id": 72077148, "author": "M Imam Pratama", "author_id": 9157799, "author_profile": "https://Stackoverflow.com/users/9157799", "pm_score": 0, "selected": false, "text": "<p>If <strong>not sourced</strong> by parent script and <strong>not symlinked</strong>, <code>$0</code> is enough:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>script_path=&quot;$0&quot;\n</code></pre>\n<p>If <strong>sourced</strong> by parent script and <strong>not symlinked</strong>, use <a href=\"https://stackoverflow.com/a/35006505/9157799\"><code>$BASH_SOURCE</code> or <code>${BASH_SOURCE[0]}</code></a>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>script_path=&quot;$BASH_SOURCE&quot;\n</code></pre>\n<p>If <strong>symlinked</strong>, use <code>$BASH_SOURCE</code> with <a href=\"https://unix.stackexchange.com/q/136494/307359\"><code>realpath</code> or <code>readlink -f</code></a> to get the real file path:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>script_path=&quot;$(realpath &quot;$BASH_SOURCE&quot;)&quot;\n</code></pre>\n<p>In addition, <code>realpath</code> or <code>readlink -f</code> returns the <strong>absolute path</strong>.</p>\n<p>To get <strong>the directory</strong> of the script, use <code>dirname</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>script_directory=&quot;$(dirname &quot;$script_path&quot;)&quot;\n</code></pre>\n<h4>Note</h4>\n<ul>\n<li>For MacOS, get an alternative of <code>realpath</code> or <code>readlink -f</code> <a href=\"https://stackoverflow.com/q/1055671/9157799\">here</a> or <a href=\"https://stackoverflow.com/q/3572030/9157799\">here</a>.</li>\n<li>To make the code compatible with shells other than Bash, use <a href=\"https://stackoverflow.com/a/66026711/9157799\">the <code>${var-string}</code> parameter expansion</a>. Example: <a href=\"https://stackoverflow.com/a/54755784/9157799\">Make it compatible with Zsh</a>.</li>\n</ul>\n" }, { "answer_id": 72195658, "author": "Alfred.37", "author_id": 16931965, "author_profile": "https://Stackoverflow.com/users/16931965", "pm_score": 0, "selected": false, "text": "<p>You can get the source directory of a Bash script from within the script itself on follow short way:</p>\n<pre><code>script_path=$(dirname &quot;$(readlink -f &quot;$0&quot;)&quot;)&quot;/&quot;\necho &quot;$script_path&quot;\n</code></pre>\n<p>Sample output:</p>\n<pre><code>/home/username/desktop/\n</code></pre>\n" }, { "answer_id": 74638215, "author": "digory doo", "author_id": 1823332, "author_profile": "https://Stackoverflow.com/users/1823332", "pm_score": 0, "selected": false, "text": "<p>Yet another variant:</p>\n<pre><code>SELF=$(SELF=$(dirname &quot;$0&quot;) &amp;&amp; bash -c &quot;cd \\&quot;$SELF\\&quot; &amp;&amp; pwd&quot;)\necho &quot;$SELF&quot;\n</code></pre>\n<p>This works on macOS as well, determines the canonical path, and does not change the current directory.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
How do I get the path of the directory in which a [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) script is located, *inside* that script? I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so: ``` $ ./application ```
``` #!/usr/bin/env bash SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) ``` is a useful one-liner which will give you the full directory name of the script no matter where it is being called from. It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution: ``` #!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) SOURCE=$(readlink "$SOURCE") [[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) ``` This last one will work with any combination of aliases, `source`, `bash -c`, symlinks, etc. **Beware:** if you `cd` to a different directory before running this snippet, the result may be incorrect! Also, watch out for [`$CDPATH` gotchas](http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/), and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling `update_terminal_cwd >&2` on Mac). Adding `>/dev/null 2>&1` at the end of your `cd` command will take care of both possibilities. To understand how it works, try running this more verbose form: ``` #!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE=$TARGET else DIR=$( dirname "$SOURCE" ) echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done echo "SOURCE is '$SOURCE'" RDIR=$( dirname "$SOURCE" ) DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'" fi echo "DIR is '$DIR'" ``` And it will print something like: ```none SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2' ```
59,896
<p>I have a page that uses </p> <pre><code>$(id).show("highlight", {}, 2000); </code></pre> <p>to highlight an element when I start a ajax request, that might fail so that I want to use something like</p> <pre><code>$(id).show("highlight", {color: "#FF0000"}, 2000); </code></pre> <p>in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?</p>
[ { "answer_id": 59904, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 5, "selected": true, "text": "<p>From the jQuery docs: </p>\n\n<p><a href=\"http://docs.jquery.com/Effects/stop\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Effects/stop</a></p>\n\n<blockquote>\n <p><em>Stop the currently-running animation on the matched elements.</em>...</p>\n \n <p>When <code>.stop()</code> is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with <code>.slideUp()</code> when <code>.stop()</code> is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.</p>\n \n <p>If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When <code>.stop()</code> is called, the next animation in the queue begins immediately. If the <code>clearQueue</code> parameter is provided with a value of <code>true</code>, then the rest of the animations in the queue are removed and never run.</p>\n \n <p>If the <code>jumpToEnd</code> argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above <code>.slideUp()</code> example, the element would be immediately hidden. The callback function is then immediately called, if provided...</p>\n</blockquote>\n" }, { "answer_id": 10280784, "author": "Dutchie432", "author_id": 83809, "author_profile": "https://Stackoverflow.com/users/83809", "pm_score": 4, "selected": false, "text": "<p><strong>I listed this as a comment for the accepted answer, but I thought it would be a good idea to post it as a standalone answer as it seems to be helping some people having problems with <code>.stop()</code></strong></p>\n\n<hr>\n\n<p>FYI - I was looking for this answer as well (trying to stop a Pulsate Effect), but I did have a <code>.stop()</code> in my code. </p>\n\n<p>After reviewing the docs, I needed <code>.stop(true, true)</code></p>\n" }, { "answer_id": 35552097, "author": "fireydude", "author_id": 869290, "author_profile": "https://Stackoverflow.com/users/869290", "pm_score": 2, "selected": false, "text": "<p><strong>.stop(true,true)</strong> will freeze the effect so if it's invisible at the time then it remains invisible. This could be a problem if you are using the pulsate effect.</p>\n\n<pre><code>$('#identifier').effect(\"pulsate\", {times:5}, 1000);\n</code></pre>\n\n<p>To get around this I added </p>\n\n<pre><code>$('#identifier').stop(true, true).effect(\"pulsate\", { times: 1 }, 1);\n</code></pre>\n" }, { "answer_id": 57123012, "author": "mike85", "author_id": 5137862, "author_profile": "https://Stackoverflow.com/users/5137862", "pm_score": 0, "selected": false, "text": "<p>In my case, using below code does not work and keep your opacity value remain: </p>\n\n<pre><code>$('#identifier').stop(true, true).effect(\"pulsate\", { times: 1 }, 1);\n</code></pre>\n\n<p>For me just remove opacity are working:</p>\n\n<pre><code>$('#identifier').stop(true, true).css('opacity','');\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6093/" ]
I have a page that uses ``` $(id).show("highlight", {}, 2000); ``` to highlight an element when I start a ajax request, that might fail so that I want to use something like ``` $(id).show("highlight", {color: "#FF0000"}, 2000); ``` in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?
From the jQuery docs: <http://docs.jquery.com/Effects/stop> > > *Stop the currently-running animation on the matched elements.*... > > > When `.stop()` is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with `.slideUp()` when `.stop()` is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called. > > > If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When `.stop()` is called, the next animation in the queue begins immediately. If the `clearQueue` parameter is provided with a value of `true`, then the rest of the animations in the queue are removed and never run. > > > If the `jumpToEnd` argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above `.slideUp()` example, the element would be immediately hidden. The callback function is then immediately called, if provided... > > >
59,986
<p>I have a simple type that explicitly implemets an Interface.</p> <pre><code>public interface IMessageHeader { string FromAddress { get; set; } string ToAddress { get; set; } } [Serializable] public class MessageHeader:IMessageHeader { private string from; private string to; [XmlAttribute("From")] string IMessageHeade.FromAddress { get { return this.from;} set { this.from = value;} } [XmlAttribute("To")] string IMessageHeade.ToAddress { get { return this.to;} set { this.to = value;} } } </code></pre> <p>Is there a way to Serialize and Deserialize objects of type IMessageHeader??</p> <p>I got the following error when tried</p> <p>"Cannot serialize interface IMessageHeader"</p>
[ { "answer_id": 59992, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>You can create an abstract base class the implements IMessageHeader and also inherits MarshalByRefObject</p>\n" }, { "answer_id": 59993, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 0, "selected": false, "text": "<p>No, because the serializer needs a concrete class that it can instantiate.</p>\n\n<p>Given the following code:</p>\n\n<pre><code>XmlSerializer ser = new XmlSerializer(typeof(IMessageHeader));\n\nIMessageHeader header = (IMessageHeader)ser.Deserialize(data);\n</code></pre>\n\n<p>What class does the serializer create to return from Deserialize()?</p>\n\n<p>In theory it's possible to serialize/deserialize an interface, just not with XmlSerializer.</p>\n" }, { "answer_id": 59994, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 0, "selected": false, "text": "<p>Try adding IXmlSerializable to your IMessageHeader declaration, although I don't think that will work.</p>\n\n<p>From what I recall, the .net xml serializer only works for concrete classes that have a default constructor.</p>\n" }, { "answer_id": 60005, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 0, "selected": false, "text": "<p>The issue stems from the fact that you can't deserialize an interface but need to instantiate a concrete class.</p>\n\n<p>The XmlInclude attribute can be used to tell the serializer what concrete classes implement the interface.</p>\n" }, { "answer_id": 60043, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": true, "text": "<p>You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type.</p>\n\n<p>You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do </p>\n\n<pre><code>XmlSerializer serializer = new XmlSerializer(instance.GetType())\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/59986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647/" ]
I have a simple type that explicitly implemets an Interface. ``` public interface IMessageHeader { string FromAddress { get; set; } string ToAddress { get; set; } } [Serializable] public class MessageHeader:IMessageHeader { private string from; private string to; [XmlAttribute("From")] string IMessageHeade.FromAddress { get { return this.from;} set { this.from = value;} } [XmlAttribute("To")] string IMessageHeade.ToAddress { get { return this.to;} set { this.to = value;} } } ``` Is there a way to Serialize and Deserialize objects of type IMessageHeader?? I got the following error when tried "Cannot serialize interface IMessageHeader"
You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type. You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do ``` XmlSerializer serializer = new XmlSerializer(instance.GetType()) ```
60,000
<p>In C++, can member function pointers be used to point to derived (or even base) class members? </p> <p>EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes <code>X</code>, <code>Y</code>, <code>Z</code> in order of inheritance. <code>Y</code> therefore has a base class <code>X</code> and a derived class <code>Z</code>.</p> <p>Now we can define a member function pointer <code>p</code> for class <code>Y</code>. This is written as:</p> <pre><code>void (Y::*p)(); </code></pre> <p>(For simplicity, I'll assume we're only interested in functions with the signature <code>void f()</code> ) </p> <p>This pointer <code>p</code> can now be used to point to member functions of class <code>Y</code>.</p> <p>This question (two questions, really) is then:</p> <ol> <li>Can <code>p</code> be used to point to a function in the derived class <code>Z</code>?</li> <li>Can <code>p</code> be used to point to a function in the base class <code>X</code>?</li> </ol>
[ { "answer_id": 60010, "author": "Steve Duitsman", "author_id": 4575, "author_profile": "https://Stackoverflow.com/users/4575", "pm_score": 1, "selected": false, "text": "<p>I believe so. Since the function pointer uses the signature to identify itself, the base/derived behavior would rely on whatever object you called it on.</p>\n" }, { "answer_id": 60016, "author": "dagorym", "author_id": 171, "author_profile": "https://Stackoverflow.com/users/171", "pm_score": 2, "selected": false, "text": "<p>You might want to check out this article <a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"nofollow noreferrer\">Member Function Pointers and the Fastest Possible C++ Delegates</a> The short answer seems to be yes, in some cases.</p>\n" }, { "answer_id": 60023, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 4, "selected": false, "text": "<p>I'm not 100% sure what you are asking, but here is an example that works with virtual functions:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass A { \npublic:\n virtual void foo() { cout &lt;&lt; \"A::foo\\n\"; }\n};\nclass B : public A {\npublic:\n virtual void foo() { cout &lt;&lt; \"B::foo\\n\"; }\n};\n\nint main()\n{\n void (A::*bar)() = &amp;A::foo;\n (A().*bar)();\n (B().*bar)();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 1130707, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 1, "selected": false, "text": "<p>My experimentation revealed the following: Warning - this might be undefined behaviour. It would be helpful if someone could provide a definitive reference.</p>\n\n<ol>\n<li>This worked, but required a cast when assigning the derived member function to <code>p</code>.</li>\n<li>This also worked, but required extra casts when dereferencing <code>p</code>.</li>\n</ol>\n\n<p>If we're feeling really ambitious we could ask if <code>p</code> can be used to point to member functions of unrelated classes. I didn't try it, but the <a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"nofollow noreferrer\">FastDelegate</a> page linked in dagorym's answer suggests it's possible.</p>\n\n<p>In conclusion, I'll try to avoid using member function pointers in this way. Passages like the following don't inspire confidence:</p>\n\n<blockquote>\n <p>Casting between member function\n pointers is an extremely murky area.\n During the standardization of C++,\n there was a lot of discussion about\n whether you should be able to cast a\n member function pointer from one class\n to a member function pointer of a base\n or derived class, and whether you\n could cast between unrelated classes.\n By the time the standards committee\n made up their mind, different compiler\n vendors had already made\n implementation decisions which had\n locked them into different answers to\n these questions. [<a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"nofollow noreferrer\">FastDelegate article</a>]</p>\n</blockquote>\n" }, { "answer_id": 2688154, "author": "Winston Ewert", "author_id": 322806, "author_profile": "https://Stackoverflow.com/users/322806", "pm_score": 1, "selected": false, "text": "<p>Assume that we have <code>class X, class Y : public X, and class Z : public Y</code></p>\n\n<p>You should be able to assign methods for both X, Y to pointers of type void (Y::*p)() but not methods for Z. To see why consider the following:</p>\n\n<pre><code>void (Y::*p)() = &amp;Z::func; // we pretend this is legal\nY * y = new Y; // clearly legal\n(y-&gt;*p)(); // okay, follows the rules, but what would this mean?\n</code></pre>\n\n<p>By allowing that assignment we permit the invocation of a method for Z on a Y object which could lead to who knows what. You can make it all work by casting the pointers but that is not safe or guaranteed to work.</p>\n" }, { "answer_id": 2688631, "author": "outis", "author_id": 90527, "author_profile": "https://Stackoverflow.com/users/90527", "pm_score": 6, "selected": true, "text": "<p>C++03 std, <a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem\" rel=\"noreferrer\">§4.11 2 Pointer to member conversions</a>:</p>\n\n<blockquote>\n <p>An rvalue of type “pointer to member of B of type <i>cv</i> T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type <i>cv</i> T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type <i>cv</i> T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. <sup>52)</sup></p>\n \n <p><sup>52)</sup>The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void*.</p>\n</blockquote>\n\n<p>In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. </p>\n\n<pre><code>class A {\npublic: \n void foo();\n};\nclass B : public A {};\nclass C {\npublic:\n void bar();\n};\nclass D {\npublic:\n void baz();\n};\nclass E : public A, public B, private C, public virtual D {\npublic: \n typedef void (E::*member)();\n};\nclass F:public E {\npublic:\n void bam();\n};\n...\nint main() {\n E::member mbr;\n mbr = &amp;A::foo; // invalid: ambiguous; E's A or B's A?\n mbr = &amp;C::bar; // invalid: C is private \n mbr = &amp;D::baz; // invalid: D is virtual\n mbr = &amp;F::bam; // invalid: conversion isn't defined by the standard\n ...\n</code></pre>\n\n<p>Conversion in the other direction (via <code>static_cast</code>) is governed by <a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast\" rel=\"noreferrer\">§ 5.2.9</a> 9:</p>\n\n<blockquote>\n <p>An rvalue of type \"pointer to member of D of type <i>cv1</i> T\" can be converted to an rvalue of type \"pointer to member of B of type <i>cv2</i> T\", where B is a base class (clause <a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived\" rel=\"noreferrer\">10 class.derived</a>) of D, if a valid standard conversion from \"pointer to member of B of type T\" to \"pointer to member of D of type T\" exists (<a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem\" rel=\"noreferrer\">4.11 conv.mem</a>), and <i>cv2</i> is the same cv-qualification as, or greater cv-qualification than, <i>cv1</i>.<sup>11)</sup> The null member pointer value (<a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem\" rel=\"noreferrer\">4.11 conv.mem</a>) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see <a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper\" rel=\"noreferrer\">5.5 expr.mptr.oper</a>.]</p>\n \n <p><sup>11)</sup> Function types (including those used in pointer to member function\n types) are never cv-qualified; see <a href=\"http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct\" rel=\"noreferrer\">8.3.5 dcl.fct</a>.</p>\n</blockquote>\n\n<p>In short, you can convert from a derived <code>D::*</code> to a base <code>B::*</code> if you can convert from a <code>B::*</code> to a <code>D::*</code>, though you can only use the <code>B::*</code> on objects that are of type D or are descended from D.</p>\n" }, { "answer_id": 2688793, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 3, "selected": false, "text": "<p>The critical issue with pointers to members is that they can be applied to any reference or pointer to a class of the correct type. This means that because <code>Z</code> is derived from <code>Y</code> a pointer (or reference) of type pointer (or reference) to <code>Y</code> may actually point (or refer) to the base class sub-object of <code>Z</code> or <em>any other class</em> derived from <code>Y</code>.</p>\n\n<pre><code>void (Y::*p)() = &amp;Z::z_fn; // illegal\n</code></pre>\n\n<p>This means that anything assigned to a pointer to member of <code>Y</code> must actually work with any <code>Y</code>. If it was allowed to point to a member of <code>Z</code> (that wasn't a member of <code>Y</code>) then it would be possible to call a member function of <code>Z</code> on some thing that wasn't actually a <code>Z</code>.</p>\n\n<p>On the other hand, any pointer to member of <code>Y</code> also points the member of <code>Z</code> (inheritance means that <code>Z</code> has all the attributes and methods of its base) is it is legal to convert a pointer to member of <code>Y</code> to a pointer to member of <code>Z</code>. This is inherently safe.</p>\n\n<pre><code>void (Y::*p)() = &amp;Y::y_fn;\nvoid (Z::*q)() = p; // legal and safe\n</code></pre>\n" }, { "answer_id": 28506633, "author": "Gena Batsyan", "author_id": 1427063, "author_profile": "https://Stackoverflow.com/users/1427063", "pm_score": 0, "selected": false, "text": "<p>Here is an example of what works.\nYou can override a method in derived class, and another method of base class that uses pointer to this overridden method indeed calls the derived class's method.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nclass A {\npublic:\n virtual void traverse(string arg) {\n find(&amp;A::visit, arg);\n }\n\nprotected:\n virtual void find(void (A::*method)(string arg), string arg) {\n (this-&gt;*method)(arg);\n }\n\n virtual void visit(string arg) {\n cout &lt;&lt; \"A::visit, arg:\" &lt;&lt; arg &lt;&lt; endl;\n }\n};\n\nclass B : public A {\nprotected:\n virtual void visit(string arg) {\n cout &lt;&lt; \"B::visit, arg:\" &lt;&lt; arg &lt;&lt; endl;\n }\n};\n\nint main()\n{\n A a;\n B b;\n a.traverse(\"one\");\n b.traverse(\"two\");\n return 0;\n}\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077/" ]
In C++, can member function pointers be used to point to derived (or even base) class members? EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes `X`, `Y`, `Z` in order of inheritance. `Y` therefore has a base class `X` and a derived class `Z`. Now we can define a member function pointer `p` for class `Y`. This is written as: ``` void (Y::*p)(); ``` (For simplicity, I'll assume we're only interested in functions with the signature `void f()` ) This pointer `p` can now be used to point to member functions of class `Y`. This question (two questions, really) is then: 1. Can `p` be used to point to a function in the derived class `Z`? 2. Can `p` be used to point to a function in the base class `X`?
C++03 std, [§4.11 2 Pointer to member conversions](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem): > > An rvalue of type “pointer to member of B of type *cv* T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type *cv* T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type *cv* T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. 52) > > > 52)The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void\*. > > > In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. ``` class A { public: void foo(); }; class B : public A {}; class C { public: void bar(); }; class D { public: void baz(); }; class E : public A, public B, private C, public virtual D { public: typedef void (E::*member)(); }; class F:public E { public: void bam(); }; ... int main() { E::member mbr; mbr = &A::foo; // invalid: ambiguous; E's A or B's A? mbr = &C::bar; // invalid: C is private mbr = &D::baz; // invalid: D is virtual mbr = &F::bam; // invalid: conversion isn't defined by the standard ... ``` Conversion in the other direction (via `static_cast`) is governed by [§ 5.2.9](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast) 9: > > An rvalue of type "pointer to member of D of type *cv1* T" can be converted to an rvalue of type "pointer to member of B of type *cv2* T", where B is a base class (clause [10 class.derived](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived)) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)), and *cv2* is the same cv-qualification as, or greater cv-qualification than, *cv1*.11) The null member pointer value ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see [5.5 expr.mptr.oper](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper).] > > > 11) Function types (including those used in pointer to member function > types) are never cv-qualified; see [8.3.5 dcl.fct](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct). > > > In short, you can convert from a derived `D::*` to a base `B::*` if you can convert from a `B::*` to a `D::*`, though you can only use the `B::*` on objects that are of type D or are descended from D.
60,019
<p>I am wanting to use ActiveScaffold to create <em>assignment</em> records for several <em>students</em> in a single step. The records will all contain identical data, with the exception of the student_id.</p> <p>I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want. That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.</p> <p>Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?</p> <hr> <p>Update: I still haven't found a good answer to this problem.</p>
[ { "answer_id": 60366, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 0, "selected": false, "text": "<p>if your assingnments have <code>has_many :students</code> or <code>has_and_belongs_to_many :students</code>, then you can change the id of the multi-select box to assignment_student_ids[], and it should work.</p>\n" }, { "answer_id": 62533, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 0, "selected": false, "text": "<p>I was referred to <a href=\"http://code.google.com/p/activescaffold-ext/wiki/BatchCreate\" rel=\"nofollow noreferrer\">BatchCreate</a>, an ActiveScaffold extension which looks like it might do the trick.</p>\n" }, { "answer_id": 295986, "author": "ARemesal", "author_id": 36599, "author_profile": "https://Stackoverflow.com/users/36599", "pm_score": 1, "selected": false, "text": "<p>I suppose you have defined your multi-select box adding :multiple => true to html parameters of select_tag. Then, in the controller, you need to access the list of names selected, what you can do like this:</p>\n\n<pre><code>params[:students].collect{|student| insert_student(student, params[:assignment_id]) }\n</code></pre>\n\n<p>With collect applied to an array or enum you can loop through each item of that array, and then do what you need with each student (in the example, to call a function for insert the students). Collect returns an array with the results of doing the code inside.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
I am wanting to use ActiveScaffold to create *assignment* records for several *students* in a single step. The records will all contain identical data, with the exception of the student\_id. I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want. That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record. Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code? --- Update: I still haven't found a good answer to this problem.
I suppose you have defined your multi-select box adding :multiple => true to html parameters of select\_tag. Then, in the controller, you need to access the list of names selected, what you can do like this: ``` params[:students].collect{|student| insert_student(student, params[:assignment_id]) } ``` With collect applied to an array or enum you can loop through each item of that array, and then do what you need with each student (in the example, to call a function for insert the students). Collect returns an array with the results of doing the code inside.
60,030
<p>In Firefox you can enter the following into the awesome bar and hit enter:</p> <pre><code>javascript:self.resizeTo(1024,768); </code></pre> <p>How do you do the same thing in IE?</p>
[ { "answer_id": 60038, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>javascript:resizeTo(1024,768);\n</code></pre>\n\n<p>This works in IE7 at least.</p>\n" }, { "answer_id": 60044, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<p>It works in IE6, but I think IE7 added some security around this?</p>\n" }, { "answer_id": 60045, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 3, "selected": false, "text": "<p>Maybe not directly related if you were looking for only a JavaScript solution but you can use the free Windows utility <a href=\"http://www.brianapps.net/sizer.html\" rel=\"nofollow noreferrer\">Sizer</a> to automatically resize any (browser) window to a predefined size like 800x600, 1024,768, etc.</p>\n\n<p><img src=\"https://i.stack.imgur.com/8v43d.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 60059, "author": "roman m", "author_id": 3661, "author_profile": "https://Stackoverflow.com/users/3661", "pm_score": 2, "selected": false, "text": "<p>Your code works in IE, you just need to \"Allow blocked Content\" in the Security Toolbar </p>\n\n<p><img src=\"https://i.stack.imgur.com/3LZ7b.jpg\" alt=\"http://i38.tinypic.com/20uahkl.jpg\"></p>\n" }, { "answer_id": 60209, "author": "Tolle", "author_id": 4260, "author_profile": "https://Stackoverflow.com/users/4260", "pm_score": 5, "selected": true, "text": "<pre><code>javascript:resizeTo(1024,768);\nvbscript:resizeto(1024,768)</code></pre>\n\n<p>Will work in IE7, But consider using something like</p>\n\n<pre><code>javascript:moveTo(0,0);resizeTo(1024,768);</code></pre>\n\n<p>because IE7 doesn't allow the window to \"resize\" beyond the screen borders. If you work on a 1024,768 desktop, this is what happens...<ul><li>Firefox: 1024x768 Window, going behind the taskbar. If you drop the moveTo part, the top left corner of the window won't change position.(You still get a 1024x768 window)</li>\n<li>IE7: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders.</li>\n<li>safari: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders, but you can ommit the moveTo part. Safari will move the top left corner of the window for you.</li>\n<li>Opera: Nothing happens.</li>\n<li>Chrome: Nothing happens.</li></p>\n\n<p></ul></p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1496/" ]
In Firefox you can enter the following into the awesome bar and hit enter: ``` javascript:self.resizeTo(1024,768); ``` How do you do the same thing in IE?
``` javascript:resizeTo(1024,768); vbscript:resizeto(1024,768) ``` Will work in IE7, But consider using something like ``` javascript:moveTo(0,0);resizeTo(1024,768); ``` because IE7 doesn't allow the window to "resize" beyond the screen borders. If you work on a 1024,768 desktop, this is what happens...* Firefox: 1024x768 Window, going behind the taskbar. If you drop the moveTo part, the top left corner of the window won't change position.(You still get a 1024x768 window) * IE7: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders. * safari: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders, but you can ommit the moveTo part. Safari will move the top left corner of the window for you. * Opera: Nothing happens. * Chrome: Nothing happens.
60,032
<p>How do I get the key of the current element in a <code>foreach</code> loop in C#?</p> <p>For example:</p> <h2>PHP</h2> <pre><code>foreach ($array as $key =&gt; $value) { echo("$value is assigned to key: $key"); } </code></pre> <h3>What I'm trying to do in C#:</h3> <pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 }; foreach (int val in values) { if(search &lt;= val &amp;&amp; !stop) { // Set key to a variable } } </code></pre>
[ { "answer_id": 60035, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 2, "selected": false, "text": "<p>Alas there is no built-in way to do this. Either use a for loop or create a temp variable that you increment on each pass.</p>\n" }, { "answer_id": 60047, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": -1, "selected": false, "text": "<p><code>myKey = Array.IndexOf(values, val);</code></p>\n" }, { "answer_id": 60058, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 5, "selected": false, "text": "<p>If you want to get at the key (read: index) then you'd have to use a for loop. If you actually want to have a collection that holds keys/values then I'd consider using a HashTable or a Dictionary (if you want to use Generics).</p>\n\n<pre><code>Dictionary&lt;int, string&gt; items = new Dictionary&lt;int, string&gt;();\n\nforeach (int key in items.Keys)\n{\n Console.WriteLine(\"Key: {0} has value: {1}\", key, items[key]);\n}\n</code></pre>\n\n<p>Hope that helps,\nTyler</p>\n" }, { "answer_id": 60062, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 2, "selected": false, "text": "<p>Actually you should use classic for (;;) loop if you want to loop through an array. But the similar functionality that you have achieved with your PHP code can be achieved in C# like this with a Dictionary:</p>\n\n<pre><code>Dictionary&lt;int, int&gt; values = new Dictionary&lt;int, int&gt;();\nvalues[0] = 5;\nvalues[1] = 14;\nvalues[2] = 29;\nvalues[3] = 49;\n// whatever...\n\nforeach (int key in values.Keys)\n{\n Console.WriteLine(\"{0} is assigned to key: {1}\", values[key], key);\n}\n</code></pre>\n" }, { "answer_id": 60089, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 6, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop#60035\">Grauenwolf's way</a> is the most straightforward and performant way of doing this with an array:</p>\n\n<blockquote>\n <p>Either use a for loop or create a temp variable that you increment on each pass.</p>\n</blockquote>\n\n<p>Which would of course look like this:</p>\n\n<pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 };\n\nfor (int key = 0; key &lt; values.Length; ++key)\n if (search &lt;= values[key] &amp;&amp; !stop)\n {\n // set key to a variable\n }\n</code></pre>\n\n<p>With .NET 3.5 you can take a more functional approach as well, but it is a little more verbose at the site, and would likely rely on a couple <a href=\"http://en.wikipedia.org/wiki/Apply\" rel=\"noreferrer\">support functions</a> for <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"noreferrer\">visiting</a> the elements in an IEnumerable. Overkill if this is all you need it for, but handy if you tend to do a lot of collection processing.</p>\n" }, { "answer_id": 60097, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>I answered this in another version of this question:</p>\n\n<blockquote>\n <p>Foreach is for iterating over\n collections that implement\n IEnumerable. It does this by calling\n GetEnumerator on the collection, which\n will return an Enumerator.</p>\n \n <p>This Enumerator has a method and a\n property:</p>\n\n<pre><code>* MoveNext()\n* Current\n</code></pre>\n \n <p>Current returns the object that\n Enumerator is currently on, MoveNext\n updates Current to the next object.</p>\n \n <p>Obviously, the concept of an index is\n foreign to the concept of enumeration,\n and cannot be done.</p>\n \n <p>Because of that, most collections are\n able to be traversed using an indexer\n and the for loop construct.</p>\n \n <p>I greatly prefer using a for loop in\n this situation compared to tracking\n the index with a local variable.</p>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/43021/c-get-index-of-current-foreach-iteration#43029\">How do you get the index of the current iteration of a foreach loop?</a></p>\n" }, { "answer_id": 1984058, "author": "mat3", "author_id": 173472, "author_profile": "https://Stackoverflow.com/users/173472", "pm_score": 0, "selected": false, "text": "<p>Here's a solution I just came up with for this problem</p>\n\n<p><strong>Original code:</strong></p>\n\n<pre><code>int index=0;\nforeach (var item in enumerable)\n{\n blah(item, index); // some code that depends on the index\n index++;\n}\n</code></pre>\n\n<p><strong>Updated code</strong></p>\n\n<pre><code>enumerable.ForEach((item, index) =&gt; blah(item, index));\n</code></pre>\n\n<p><strong>Extension Method:</strong></p>\n\n<pre><code> public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Action&lt;T, int&gt; action)\n {\n var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void\n enumerable.Select((item, i) =&gt; \n {\n action(item, i);\n return unit;\n }).ToList();\n\n return pSource;\n }\n</code></pre>\n" }, { "answer_id": 1984176, "author": "Craig Gidney", "author_id": 52239, "author_profile": "https://Stackoverflow.com/users/52239", "pm_score": 0, "selected": false, "text": "<p>You can implement this functionality yourself using an extension method. For example, here is an implementation of an extension method KeyValuePairs which works on lists:</p>\n\n<pre><code>public struct IndexValue&lt;T&gt; {\n public int Index {get; private set;}\n public T Value {get; private set;}\n public IndexValue(int index, T value) : this() {\n this.Index = index;\n this.Value = value;\n }\n}\n\npublic static class EnumExtension\n{\n public static IEnumerable&lt;IndexValue&lt;T&gt;&gt; KeyValuePairs&lt;T&gt;(this IList&lt;T&gt; list) {\n for (int i = 0; i &lt; list.Count; i++)\n yield return new IndexValue&lt;T&gt;(i, list[i]);\n }\n}\n</code></pre>\n" }, { "answer_id": 7366406, "author": "Guillaume Massé", "author_id": 449071, "author_profile": "https://Stackoverflow.com/users/449071", "pm_score": 4, "selected": false, "text": "<p>With DictionaryEntry and KeyValuePair:</p>\n\n<p>Based on<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx\" rel=\"noreferrer\">MSDN</a></p>\n\n<pre><code>IDictionary&lt;string,string&gt; openWith = new Dictionary&lt;string,string&gt;()\n{\n { \"txt\", \"notepad.exe\" }\n { \"bmp\", \"paint.exe\" }\n { \"rtf\", \"wordpad.exe\" }\n};\n\nforeach (DictionaryEntry de in openWith)\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", de.Key, de.Value);\n}\n\n// also\n\nforeach (KeyValuePair&lt;string,string&gt; de in openWith)\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", de.Key, de.Value);\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/905424/keyvaluepair-vs-dictionaryentry\">Releated SO question: KeyValuePair VS DictionaryEntry</a></p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
How do I get the key of the current element in a `foreach` loop in C#? For example: PHP --- ``` foreach ($array as $key => $value) { echo("$value is assigned to key: $key"); } ``` ### What I'm trying to do in C#: ``` int[] values = { 5, 14, 29, 49, 99, 150, 999 }; foreach (int val in values) { if(search <= val && !stop) { // Set key to a variable } } ```
[Grauenwolf's way](https://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop#60035) is the most straightforward and performant way of doing this with an array: > > Either use a for loop or create a temp variable that you increment on each pass. > > > Which would of course look like this: ``` int[] values = { 5, 14, 29, 49, 99, 150, 999 }; for (int key = 0; key < values.Length; ++key) if (search <= values[key] && !stop) { // set key to a variable } ``` With .NET 3.5 you can take a more functional approach as well, but it is a little more verbose at the site, and would likely rely on a couple [support functions](http://en.wikipedia.org/wiki/Apply) for [visiting](http://en.wikipedia.org/wiki/Visitor_pattern) the elements in an IEnumerable. Overkill if this is all you need it for, but handy if you tend to do a lot of collection processing.
60,033
<p>I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the <strong>id</strong>). What is the simplest way to accomplish this?</p> <p>I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.</p> <p>Perhaps something like this:</p> <pre class="lang-ruby prettyprint-override"><code> new_record = Record.copy(:id) </code></pre>
[ { "answer_id": 60053, "author": "Michael Sepcot", "author_id": 6033, "author_profile": "https://Stackoverflow.com/users/6033", "pm_score": 10, "selected": true, "text": "<p>To get a copy, use the <a href=\"https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup\" rel=\"noreferrer\">dup</a> (or clone for &lt; rails 3.1+) method:</p>\n<pre><code>#rails &gt;= 3.1\nnew_record = old_record.dup\n\n# rails &lt; 3.1\nnew_record = old_record.clone\n</code></pre>\n<p>Then you can change whichever fields you want.</p>\n<p><a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001363\" rel=\"noreferrer\">ActiveRecord overrides the built-in Object#clone</a> to give you a new (not saved to the DB) record with an unassigned ID.<br />\nNote that it does not copy associations, so you'll have to do this manually if you need to.</p>\n<p><a href=\"https://gist.github.com/994614\" rel=\"noreferrer\">Rails 3.1 clone is a shallow copy, use dup instead...</a></p>\n" }, { "answer_id": 62925, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 5, "selected": false, "text": "<p>I usually just copy the attributes, changing whatever I need changing:</p>\n\n<pre><code>new_user = User.new(old_user.attributes.merge(:login =&gt; \"newlogin\"))\n</code></pre>\n" }, { "answer_id": 63032, "author": "Phillip Koebbe", "author_id": 7283, "author_profile": "https://Stackoverflow.com/users/7283", "pm_score": 6, "selected": false, "text": "<p>Depending on your needs and programming style, you can also use a combination of the new method of the class and merge. For lack of a better <em>simple</em> example, suppose you have a task scheduled for a certain date and you want to duplicate it to another date. The actual attributes of the task aren't important, so:</p>\n\n<pre>\nold_task = Task.find(task_id)\nnew_task = Task.new(old_task.attributes.merge({:scheduled_on => some_new_date}))\n</pre>\n\n<p>will create a new task with <code>:id => nil</code>, <code>:scheduled_on => some_new_date</code>, and all other attributes the same as the original task. Using Task.new, you will have to explicitly call save, so if you want it saved automatically, change Task.new to Task.create.</p>\n\n<p>Peace. </p>\n" }, { "answer_id": 6957504, "author": "bradgonesurfing", "author_id": 158285, "author_profile": "https://Stackoverflow.com/users/158285", "pm_score": 5, "selected": false, "text": "<p>Use <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup\" rel=\"noreferrer\">ActiveRecord::Base#dup</a> if you don't want to copy the id</p>\n" }, { "answer_id": 7265525, "author": "raidfive", "author_id": 110315, "author_profile": "https://Stackoverflow.com/users/110315", "pm_score": 3, "selected": false, "text": "<p>If you need a deep copy with associations, I recommend the <a href=\"https://github.com/moiristo/deep_cloneable\">deep_cloneable</a> gem.</p>\n" }, { "answer_id": 9485535, "author": "Vaughn Draughon", "author_id": 1238269, "author_profile": "https://Stackoverflow.com/users/1238269", "pm_score": 5, "selected": false, "text": "<p>You may also like the <a href=\"https://rubygems.org/gems/amoeba\" rel=\"noreferrer\">Amoeba gem</a> for ActiveRecord 3.2.</p>\n\n<p>In your case, you probably want to make use of the <code>nullify</code>, <code>regex</code> or <code>prefix</code> options available in the configuration DSL.</p>\n\n<p>It supports easy and automatic recursive duplication of <code>has_one</code>, <code>has_many</code> and <code>has_and_belongs_to_many</code> associations, field preprocessing and a highly flexible and powerful configuration DSL that can be applied both to the model and on the fly.</p>\n\n<p>be sure to check out the <a href=\"https://github.com/rocksolidwebdesign/amoeba#readme\" rel=\"noreferrer\">Amoeba Documentation</a> but usage is pretty easy...</p>\n\n<p>just</p>\n\n<pre><code>gem install amoeba\n</code></pre>\n\n<p>or add </p>\n\n<pre><code>gem 'amoeba'\n</code></pre>\n\n<p>to your Gemfile</p>\n\n<p>then add the amoeba block to your model and run the <code>dup</code> method as usual</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n enable\n end\nend\n\nclass Comment &lt; ActiveRecord::Base\n belongs_to :post\nend\n\nclass Tag &lt; ActiveRecord::Base\n has_and_belongs_to_many :posts\nend\n\nclass PostsController &lt; ActionController\n def some_method\n my_post = Post.find(params[:id])\n new_post = my_post.dup\n new_post.save\n end\nend\n</code></pre>\n\n<p>You can also control which fields get copied in numerous ways, but for example, if you wanted to prevent comments from being duplicated but you wanted to maintain the same tags, you could do something like this:</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n exclude_field :comments\n end\nend\n</code></pre>\n\n<p>You can also preprocess fields to help indicate uniqueness with both prefixes and suffixes as well as regexes. In addition, there are also numerous options so you can write in the most readable style for your purpose:</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n has_many :comments\n has_and_belongs_to_many :tags\n\n amoeba do\n include_field :tags\n prepend :title =&gt; \"Copy of \"\n append :contents =&gt; \" (copied version)\"\n regex :contents =&gt; {:replace =&gt; /dog/, :with =&gt; \"cat\"}\n end\nend\n</code></pre>\n\n<p>Recursive copying of associations is easy, just enable amoeba on child models as well</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n has_many :comments\n\n amoeba do\n enable\n end\nend\n\nclass Comment &lt; ActiveRecord::Base\n belongs_to :post\n has_many :ratings\n\n amoeba do\n enable\n end\nend\n\nclass Rating &lt; ActiveRecord::Base\n belongs_to :comment\nend\n</code></pre>\n\n<p>The configuration DSL has yet more options, so be sure to check out the documentation.</p>\n\n<p>Enjoy! :)</p>\n" }, { "answer_id": 33379580, "author": "esbanarango", "author_id": 1136821, "author_profile": "https://Stackoverflow.com/users/1136821", "pm_score": 0, "selected": false, "text": "<p>You can also check the <a href=\"https://github.com/esbanarango/acts_as_inheritable\" rel=\"nofollow\">acts_as_inheritable</a> gem.</p>\n\n<p>\"Acts As Inheritable is a Ruby Gem specifically written for Rails/ActiveRecord models. It is meant to be used with the <a href=\"https://github.com/esbanarango/acts_as_inheritable#self-referential-association\" rel=\"nofollow\">Self-Referential Association</a>, or with a model having a parent that share the inheritable attributes. This will let you inherit any attribute or relation from the parent model.\"</p>\n\n<p>By adding <code>acts_as_inheritable</code> to your models you will have access to these methods:</p>\n\n<p><strong>inherit_attributes</strong></p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>class Person &lt; ActiveRecord::Base\n\n acts_as_inheritable attributes: %w(favorite_color last_name soccer_team)\n\n # Associations\n belongs_to :parent, class_name: 'Person'\n has_many :children, class_name: 'Person', foreign_key: :parent_id\nend\n\nparent = Person.create(last_name: 'Arango', soccer_team: 'Verdolaga', favorite_color:'Green')\n\nson = Person.create(parent: parent)\nson.inherit_attributes\nson.last_name # =&gt; Arango\nson.soccer_team # =&gt; Verdolaga\nson.favorite_color # =&gt; Green\n</code></pre>\n\n<p><strong>inherit_relations</strong></p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>class Person &lt; ActiveRecord::Base\n\n acts_as_inheritable associations: %w(pet)\n\n # Associations\n has_one :pet\nend\n\nparent = Person.create(last_name: 'Arango')\nparent_pet = Pet.create(person: parent, name: 'Mango', breed:'Golden Retriver')\nparent_pet.inspect #=&gt; #&lt;Pet id: 1, person_id: 1, name: \"Mango\", breed: \"Golden Retriver\"&gt;\n\nson = Person.create(parent: parent)\nson.inherit_relations\nson.pet.inspect # =&gt; #&lt;Pet id: 2, person_id: 2, name: \"Mango\", breed: \"Golden Retriver\"&gt;\n</code></pre>\n\n<p>Hope this can help you.</p>\n" }, { "answer_id": 40329894, "author": "ThienSuBS", "author_id": 4631412, "author_profile": "https://Stackoverflow.com/users/4631412", "pm_score": 2, "selected": false, "text": "<p>The easily way is:</p>\n\n<pre><code>#your rails &gt;= 3.1 (i was done it with Rails 5.0.0.1)\n o = Model.find(id)\n # (Range).each do |item|\n (1..109).each do |item|\n new_record = o.dup\n new_record.save\n end\n</code></pre>\n\n<p>Or </p>\n\n<pre><code># if your rails &lt; 3.1\n o = Model.find(id)\n (1..109).each do |item|\n new_record = o.clone\n new_record.save\n end \n</code></pre>\n" }, { "answer_id": 49322942, "author": "Paulo Fidalgo", "author_id": 1006863, "author_profile": "https://Stackoverflow.com/users/1006863", "pm_score": 0, "selected": false, "text": "<p>Since there could be more logic, when duplicating a model, I would suggest to create a new class, where you handle all the needed logic.\nTo ease that, there's a gem that can help: <a href=\"https://github.com/palkan/clowne\" rel=\"nofollow noreferrer\">clowne</a></p>\n\n<p>As per their documentation examples, for a User model:</p>\n\n<pre><code>class User &lt; ActiveRecord::Base\n # create_table :users do |t|\n # t.string :login\n # t.string :email\n # t.timestamps null: false\n # end\n\n has_one :profile\n has_many :posts\nend\n</code></pre>\n\n<p>You create your cloner class:</p>\n\n<pre><code>class UserCloner &lt; Clowne::Cloner\n adapter :active_record\n\n include_association :profile, clone_with: SpecialProfileCloner\n include_association :posts\n\n nullify :login\n\n # params here is an arbitrary Hash passed into cloner\n finalize do |_source, record, params|\n record.email = params[:email]\n end\nend\n\nclass SpecialProfileCloner &lt; Clowne::Cloner\n adapter :active_record\n\n nullify :name\nend\n</code></pre>\n\n<p>and then use it:</p>\n\n<pre><code>user = User.last\n#=&gt; &lt;#User(login: 'clown', email: '[email protected]')&gt;\n\ncloned = UserCloner.call(user, email: '[email protected]')\ncloned.persisted?\n# =&gt; false\n\ncloned.save!\ncloned.login\n# =&gt; nil\ncloned.email\n# =&gt; \"[email protected]\"\n\n# associations:\ncloned.posts.count == user.posts.count\n# =&gt; true\ncloned.profile.name\n# =&gt; nil\n</code></pre>\n\n<p>Example copied from the project, but it will give a clear vision of what you can achieve.</p>\n\n<p><strong>For a quick and simple record I would go with:</strong></p>\n\n<p><code>Model.new(Model.last.attributes.reject {|k,_v| k.to_s == 'id'}</code></p>\n" }, { "answer_id": 51925581, "author": "Zoran Majstorovic", "author_id": 3452582, "author_profile": "https://Stackoverflow.com/users/3452582", "pm_score": 2, "selected": false, "text": "<p>Here is a sample of overriding ActiveRecord <code>#dup</code> method to customize instance duplication and include relation duplication as well:</p>\n\n<pre><code>class Offer &lt; ApplicationRecord\n has_many :offer_items\n\n def dup\n super.tap do |new_offer|\n\n # change title of the new instance\n new_offer.title = \"Copy of #{@offer.title}\"\n\n # duplicate offer_items as well\n self.offer_items.each { |offer_item| new_offer.offer_items &lt;&lt; offer_item.dup }\n end\n end\nend\n</code></pre>\n\n<p>Note: this method doesn't require any external gem but it requires newer ActiveRecord version with <code>#dup</code> method implemented</p>\n" }, { "answer_id": 54035727, "author": "Foram", "author_id": 8649274, "author_profile": "https://Stackoverflow.com/users/8649274", "pm_score": 3, "selected": false, "text": "<p>In Rails 5 you can simply create duplicate object or record like this.</p>\n\n<pre><code>new_user = old_user.dup\n</code></pre>\n" }, { "answer_id": 66943947, "author": "Sachin Singh", "author_id": 13088705, "author_profile": "https://Stackoverflow.com/users/13088705", "pm_score": 0, "selected": false, "text": "<p>Try rails's <code>dup</code> method:</p>\n<pre><code>new_record = old_record.dup.save\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the **id**). What is the simplest way to accomplish this? I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this. Perhaps something like this: ```ruby new_record = Record.copy(:id) ```
To get a copy, use the [dup](https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup) (or clone for < rails 3.1+) method: ``` #rails >= 3.1 new_record = old_record.dup # rails < 3.1 new_record = old_record.clone ``` Then you can change whichever fields you want. [ActiveRecord overrides the built-in Object#clone](http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001363) to give you a new (not saved to the DB) record with an unassigned ID. Note that it does not copy associations, so you'll have to do this manually if you need to. [Rails 3.1 clone is a shallow copy, use dup instead...](https://gist.github.com/994614)
60,034
<p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>
[ { "answer_id": 60055, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>I don't think there's a way to do it with any built-in commands. I would suggest you download something like <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"noreferrer\">Gnuwin32</a> or <a href=\"http://unxutils.sourceforge.net/\" rel=\"noreferrer\">UnxUtils</a> and use the <code>sed</code> command (or download only <a href=\"http://gnuwin32.sourceforge.net/packages/sed.htm\" rel=\"noreferrer\"><code>sed</code></a>):</p>\n\n<pre><code>sed -c s/FOO/BAR/g filename\n</code></pre>\n" }, { "answer_id": 60065, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 8, "selected": false, "text": "<p>If you are on Windows version that supports .Net 2.0, I would replace your shell. <a href=\"http://en.wikipedia.org/wiki/Windows_PowerShell\" rel=\"noreferrer\">PowerShell</a> gives you the full power of .Net from the command line. There are many commandlets built in as well. The example below will solve your question. I'm using the full names of the commands, there are shorter aliases, but this gives you something to Google for.</p>\n\n<pre><code>(Get-Content test.txt) | ForEach-Object { $_ -replace \"foo\", \"bar\" } | Set-Content test2.txt\n</code></pre>\n" }, { "answer_id": 60084, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 0, "selected": false, "text": "<p>Download <a href=\"http://www.cygwin.com/\" rel=\"nofollow noreferrer\">Cygwin</a> (free) and use unix-like commands at the Windows command line.</p>\n\n<p>Your best bet: sed</p>\n" }, { "answer_id": 64816, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://www.dostips.com/DtCodeBatchFiles.php#Batch.FindAndReplace\" rel=\"noreferrer\"><code>BatchSubstitute.bat</code> on dostips.com</a> is an example of search and replace using a pure batch file.</p>\n<p>It uses a combination of <code>FOR</code>, <code>FIND</code> and <code>CALL SET</code>.</p>\n<p>Lines containing characters among <code>&quot;&amp;&lt;&gt;]|^</code> may be treated incorrectly.</p>\n<hr />\n" }, { "answer_id": 85886, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>This is one thing that batch scripting just does not do well.</p>\n\n<p>The script <strong>morechilli</strong> linked to will work for some files, but unfortunately it will choke on ones which contain characters such as pipes and ampersands.</p>\n\n<p>VBScript is a better built-in tool for this task. See this article for an example:\n<a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx</a></p>\n" }, { "answer_id": 202635, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<p>Take a look at <a href=\"https://stackoverflow.com/questions/127318/\">Is there any sed like utility for cmd.exe</a> which asked for a sed equivalent under Windows, should apply to this question as well. Executive summary: </p>\n\n<ul>\n<li>It can be done in batch file, but it's not pretty</li>\n<li>Lots of available third party executables that will do it for you, if you have the luxury of installing or just copying over an exe</li>\n<li>Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.</li>\n</ul>\n" }, { "answer_id": 1953773, "author": "Peter Schuetze", "author_id": 204042, "author_profile": "https://Stackoverflow.com/users/204042", "pm_score": 2, "selected": false, "text": "<p>May be a little bit late, but I am frequently looking for similar stuff, since I don't want to get through the pain of getting software approved.</p>\n\n<p>However, you usually use the FOR statement in various forms. Someone created a useful batch file that does a search and replace. Have a look <a href=\"http://www.dostips.com/?t=Batch.FindAndReplace\" rel=\"nofollow noreferrer\">here</a>. It is important to understand the limitations of the batch file provided. For this reason I don't copy the source code in this answer.</p>\n" }, { "answer_id": 2363075, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": false, "text": "<p>Just used <strong><a href=\"http://fart-it.sourceforge.net/\" rel=\"noreferrer\">FART</a></strong> (&quot;<strong>F</strong> ind <strong>A</strong> nd <strong>R</strong> eplace <strong>T</strong> ext&quot; command line utility):<br />\nexcellent little freeware for text replacement within a large set of files.</p>\n<p>The setup files <a href=\"http://sourceforge.net/projects/fart-it/files/\" rel=\"noreferrer\">are on SourceForge</a>.</p>\n<p>Usage example:</p>\n<pre><code>fart.exe -p -r -c -- C:\\tools\\perl-5.8.9\\* @@APP_DIR@@ C:\\tools\n</code></pre>\n<p>will preview the replacements to do recursively in the files of this Perl distribution.</p>\n<p>Only problem: the FART website icon isn't exactly tasteful, refined or elegant ;)</p>\n<hr />\n<p>Update 2017 (7 years later) <a href=\"https://stackoverflow.com/users/3217130/jagb\">jagb</a> points out <a href=\"https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir/2363075#comment72538743_2363075\">in the comments</a> to the 2011 article &quot;<a href=\"https://emtunc.org/blog/03/2011/farting-the-easy-way-find-and-replace-text/\" rel=\"noreferrer\">FARTing the Easy Way – Find And Replace Text</a>&quot; from <a href=\"https://emtunc.org/blog/about/\" rel=\"noreferrer\">Mikail Tunç</a></p>\n<hr />\n<p>As noted by <a href=\"https://stackoverflow.com/users/7058553/joe-jobs\">Joe Jobs</a> in <a href=\"https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir/2363075?noredirect=1#comment115826648_2363075\">the comments</a> (Dec. 2020), if you want to replace <code>&amp;A</code> for instance, you would need to use quotes in order to make sure <code>&amp;</code> is not interpreted by the shell:</p>\n<pre><code>fart in.txt &quot;&amp;A&quot; &quot;B&quot; \n</code></pre>\n" }, { "answer_id": 2419322, "author": "Chad", "author_id": 290782, "author_profile": "https://Stackoverflow.com/users/290782", "pm_score": 3, "selected": false, "text": "<p>Here's a solution that I found worked on Win XP. In my running batch file, I included the following:</p>\n\n<pre><code>set value=new_value\n\n:: Setup initial configuration\n:: I use &amp;&amp; as the delimiter in the file because it should not exist, thereby giving me the whole line\n::\necho --&gt; Setting configuration and properties.\nfor /f \"tokens=* delims=&amp;&amp;\" %%a in (config\\config.txt) do ( \n call replace.bat \"%%a\" _KEY_ %value% config\\temp.txt \n)\ndel config\\config.txt\nrename config\\temp.txt config.txt\n</code></pre>\n\n<p>The <code>replace.bat</code> file is as below. I did not find a way to include that function within the same batch file, because the <code>%%a</code> variable always seems to give the last value in the for loop.</p>\n\n<p><code>replace.bat</code>:</p>\n\n<pre><code>@echo off\n\n:: This ensures the parameters are resolved prior to the internal variable\n::\nSetLocal EnableDelayedExpansion\n\n:: Replaces Key Variables\n::\n:: Parameters:\n:: %1 = Line to search for replacement\n:: %2 = Key to replace\n:: %3 = Value to replace key with\n:: %4 = File in which to write the replacement\n::\n\n:: Read in line without the surrounding double quotes (use ~)\n::\nset line=%~1\n\n:: Write line to specified file, replacing key (%2) with value (%3)\n::\necho !line:%2=%3! &gt;&gt; %4\n\n:: Restore delayed expansion\n::\nEndLocal\n</code></pre>\n" }, { "answer_id": 3309448, "author": "kool_guy_here", "author_id": 399147, "author_profile": "https://Stackoverflow.com/users/399147", "pm_score": 3, "selected": false, "text": "<p>Power shell command works like a charm</p>\n\n<pre><code>(\ntest.txt | ForEach-Object { $_ -replace \"foo\", \"bar\" } | Set-Content test2.txt\n)\n</code></pre>\n" }, { "answer_id": 3801102, "author": "user459118", "author_id": 459118, "author_profile": "https://Stackoverflow.com/users/459118", "pm_score": 6, "selected": false, "text": "<p>Create file replace.vbs:</p>\n\n<pre><code>Const ForReading = 1 \nConst ForWriting = 2\n\nstrFileName = Wscript.Arguments(0)\nstrOldText = Wscript.Arguments(1)\nstrNewText = Wscript.Arguments(2)\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objFile = objFSO.OpenTextFile(strFileName, ForReading)\nstrText = objFile.ReadAll\nobjFile.Close\n\nstrNewText = Replace(strText, strOldText, strNewText)\nSet objFile = objFSO.OpenTextFile(strFileName, ForWriting)\nobjFile.Write strNewText 'WriteLine adds extra CR/LF\nobjFile.Close\n</code></pre>\n\n<p>To use this revised script (which we’ll call replace.vbs) just type a command similar to this from the command prompt:</p>\n\n<p><code>cscript replace.vbs \"C:\\Scripts\\Text.txt\" \"Jim \" \"James \"</code></p>\n" }, { "answer_id": 4402290, "author": "Faisal", "author_id": 536948, "author_profile": "https://Stackoverflow.com/users/536948", "pm_score": 4, "selected": false, "text": "<p>I have used perl, and that works marvelously.</p>\n\n<pre><code>perl -pi.orig -e \"s/&lt;textToReplace&gt;/&lt;textToReplaceWith&gt;/g;\" &lt;fileName&gt;\n</code></pre>\n\n<p>.orig is the extension it would append to the original file</p>\n\n<p>For a number of files matching such as *.html</p>\n\n<pre><code>for %x in (&lt;filePattern&gt;) do perl -pi.orig -e \"s/&lt;textToReplace&gt;/&lt;textToReplaceWith&gt;/g;\" %x\n</code></pre>\n" }, { "answer_id": 6159108, "author": "Bill Richardson", "author_id": 773948, "author_profile": "https://Stackoverflow.com/users/773948", "pm_score": 7, "selected": false, "text": "<p>Replace - Replace a substring using string substitution\nDescription: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences \"teh\" misspellings with \"the\" in the string variable str. </p>\n\n<pre><code>set str=teh cat in teh hat\necho.%str%\nset str=%str:teh=the%\necho.%str%\n</code></pre>\n\n<p>Script Output: </p>\n\n<pre><code>teh cat in teh hat\nthe cat in the hat\n</code></pre>\n\n<p>ref: <a href=\"http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace\" rel=\"noreferrer\">http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace</a></p>\n" }, { "answer_id": 10490757, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 4, "selected": false, "text": "<p>I played around with some of the existing answers here and prefer my improved solution...</p>\n\n<pre><code>type test.txt | powershell -Command \"$input | ForEach-Object { $_ -replace \\\"foo\\\", \\\"bar\\\" }\"\n</code></pre>\n\n<p>or if you want to save the output again to a file...</p>\n\n<pre><code>type test.txt | powershell -Command \"$input | ForEach-Object { $_ -replace \\\"foo\\\", \\\"bar\\\" }\" &gt; outputFile.txt\n</code></pre>\n\n<p>The benefit of this is that you can pipe in output from any program. Will look into using regular expressions with this too. Couldn't work out how to make it into a BAT file for easier use though... :-(</p>\n" }, { "answer_id": 14396154, "author": "Aman", "author_id": 173136, "author_profile": "https://Stackoverflow.com/users/173136", "pm_score": 5, "selected": false, "text": "<h1>Use FNR</h1>\n<p>Use the <code>fnr</code> utility. It's got some advantages over <code>fart</code>:</p>\n<ul>\n<li>Regular expressions</li>\n<li>Optional GUI. Has a &quot;Generate command line button&quot; to create command line text to put in batch file.</li>\n<li>Multi-line patterns: The GUI allows you to easily work with multi-line patterns. In FART you'd have to manually escape line breaks.</li>\n<li>Allows you to select text file encoding. Also has an auto detect option.</li>\n</ul>\n<p>Download FNR here: <a href=\"http://findandreplace.io/?z=codeplex\" rel=\"noreferrer\">http://findandreplace.io/?z=codeplex</a></p>\n<p>Usage example:\n<code>fnr --cl --dir &quot;&lt;Directory Path&gt;&quot; --fileMask &quot;hibernate.*&quot; --useRegEx --find &quot;find_str_expression&quot; --replace &quot;replace_string&quot;</code></p>\n" }, { "answer_id": 16735079, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 6, "selected": false, "text": "<p><strong><em>Note</em></strong> <em>- Be sure to see the update at the end of this answer for a link to the superior JREPL.BAT that supersedes REPL.BAT</em><br>\n<em><a href=\"http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044\" rel=\"noreferrer\">JREPL.BAT 7.0 and above</a> natively supports unicode (UTF-16LE) via the <code>/UTF</code> option, as well as any other character set, including UTF-8, via ADO!!!!</em></p>\n\n<hr>\n\n<p><a href=\"http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855\" rel=\"noreferrer\">I have written a small hybrid JScript/batch utility called REPL.BAT</a> that is very convenient for modifying ASCII (or extended ASCII) files via the command line or a batch file. The purely native script does not require installation of any 3rd party executeable, and it works on any modern Windows version from XP onward. It is also very fast, especially when compared to pure batch solutions.</p>\n\n<p>REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.</p>\n\n<p>Here is a trivial example of how to replace foo with bar in test.txt, assuming REPL.BAT is in your current folder, or better yet, somewhere within your PATH:</p>\n\n<pre><code>type test.txt|repl \"foo\" \"bar\" &gt;test.txt.new\nmove /y test.txt.new test.txt\n</code></pre>\n\n<p>The JScript regex capabilities make it very powerful, especially the ability of the replacement text to reference captured substrings from the search text.</p>\n\n<p>I've included a number of options in the utility that make it quite powerful. For example, combining the <code>M</code> and <code>X</code> options enable modification of binary files! The <code>M</code> Multi-line option allows searches across multiple lines. The <code>X</code> eXtended substitution pattern option provides escape sequences that enable inclusion of any binary value in the replacement text.</p>\n\n<p>The entire utility could have been written as pure JScript, but the hybrid batch file eliminates the need to explicitly specify CSCRIPT every time you want to use the utility.</p>\n\n<p>Here is the REPL.BAT script. Full documentation is embedded within the script.</p>\n\n<pre><code>@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment\n\n::************ Documentation ***********\n::REPL.BAT version 6.2\n:::\n:::REPL Search Replace [Options [SourceVar]]\n:::REPL /?[REGEX|REPLACE]\n:::REPL /V\n:::\n::: Performs a global regular expression search and replace operation on\n::: each line of input from stdin and prints the result to stdout.\n:::\n::: Each parameter may be optionally enclosed by double quotes. The double\n::: quotes are not considered part of the argument. The quotes are required\n::: if the parameter contains a batch token delimiter like space, tab, comma,\n::: semicolon. The quotes should also be used if the argument contains a\n::: batch special character like &amp;, |, etc. so that the special character\n::: does not need to be escaped with ^.\n:::\n::: If called with a single argument of /?, then prints help documentation\n::: to stdout. If a single argument of /?REGEX, then opens up Microsoft's\n::: JScript regular expression documentation within your browser. If a single\n::: argument of /?REPLACE, then opens up Microsoft's JScript REPLACE\n::: documentation within your browser.\n:::\n::: If called with a single argument of /V, case insensitive, then prints\n::: the version of REPL.BAT.\n:::\n::: Search - By default, this is a case sensitive JScript (ECMA) regular\n::: expression expressed as a string.\n:::\n::: JScript regex syntax documentation is available at\n::: http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx\n:::\n::: Replace - By default, this is the string to be used as a replacement for\n::: each found search expression. Full support is provided for\n::: substituion patterns available to the JScript replace method.\n:::\n::: For example, $&amp; represents the portion of the source that matched\n::: the entire search pattern, $1 represents the first captured\n::: submatch, $2 the second captured submatch, etc. A $ literal\n::: can be escaped as $$.\n:::\n::: An empty replacement string must be represented as \"\".\n:::\n::: Replace substitution pattern syntax is fully documented at\n::: http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx\n:::\n::: Options - An optional string of characters used to alter the behavior\n::: of REPL. The option characters are case insensitive, and may\n::: appear in any order.\n:::\n::: A - Only print altered lines. Unaltered lines are discarded.\n::: If the S options is present, then prints the result only if\n::: there was a change anywhere in the string. The A option is\n::: incompatible with the M option unless the S option is present.\n:::\n::: B - The Search must match the beginning of a line.\n::: Mostly used with literal searches.\n:::\n::: E - The Search must match the end of a line.\n::: Mostly used with literal searches.\n:::\n::: I - Makes the search case-insensitive.\n:::\n::: J - The Replace argument represents a JScript expression.\n::: The expression may access an array like arguments object\n::: named $. However, $ is not a true array object.\n:::\n::: The $.length property contains the total number of arguments\n::: available. The $.length value is equal to n+3, where n is the\n::: number of capturing left parentheses within the Search string.\n:::\n::: $[0] is the substring that matched the Search,\n::: $[1] through $[n] are the captured submatch strings,\n::: $[n+1] is the offset where the match occurred, and\n::: $[n+2] is the original source string.\n:::\n::: Arguments $[0] through $[10] may be abbreviated as\n::: $1 through $10. Argument $[11] and above must use the square\n::: bracket notation.\n:::\n::: L - The Search is treated as a string literal instead of a\n::: regular expression. Also, all $ found in the Replace string\n::: are treated as $ literals.\n:::\n::: M - Multi-line mode. The entire contents of stdin is read and\n::: processed in one pass instead of line by line, thus enabling\n::: search for \\n. This also enables preservation of the original\n::: line terminators. If the M option is not present, then every\n::: printed line is terminated with carriage return and line feed.\n::: The M option is incompatible with the A option unless the S\n::: option is also present.\n:::\n::: Note: If working with binary data containing NULL bytes,\n::: then the M option must be used.\n:::\n::: S - The source is read from an environment variable instead of\n::: from stdin. The name of the source environment variable is\n::: specified in the next argument after the option string. Without\n::: the M option, ^ anchors the beginning of the string, and $ the\n::: end of the string. With the M option, ^ anchors the beginning\n::: of a line, and $ the end of a line.\n:::\n::: V - Search and Replace represent the name of environment\n::: variables that contain the respective values. An undefined\n::: variable is treated as an empty string.\n:::\n::: X - Enables extended substitution pattern syntax with support\n::: for the following escape sequences within the Replace string:\n:::\n::: \\\\ - Backslash\n::: \\b - Backspace\n::: \\f - Formfeed\n::: \\n - Newline\n::: \\q - Quote\n::: \\r - Carriage Return\n::: \\t - Horizontal Tab\n::: \\v - Vertical Tab\n::: \\xnn - Extended ASCII byte code expressed as 2 hex digits\n::: \\unnnn - Unicode character expressed as 4 hex digits\n:::\n::: Also enables the \\q escape sequence for the Search string.\n::: The other escape sequences are already standard for a regular\n::: expression Search string.\n:::\n::: Also modifies the behavior of \\xnn in the Search string to work\n::: properly with extended ASCII byte codes.\n:::\n::: Extended escape sequences are supported even when the L option\n::: is used. Both Search and Replace support all of the extended\n::: escape sequences if both the X and L opions are combined.\n:::\n::: Return Codes: 0 = At least one change was made\n::: or the /? or /V option was used\n:::\n::: 1 = No change was made\n:::\n::: 2 = Invalid call syntax or incompatible options\n:::\n::: 3 = JScript runtime error, typically due to invalid regex\n:::\n::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini\n::: to get \\xnn to work properly with extended ASCII byte codes. Also assistance\n::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a\n::: workaround. REPL.BAT was originally posted at:\n::: http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855\n:::\n\n::************ Batch portion ***********\n@echo off\nif .%2 equ . (\n if \"%~1\" equ \"/?\" (\n &lt;\"%~f0\" cscript //E:JScript //nologo \"%~f0\" \"^:::\" \"\" a\n exit /b 0\n ) else if /i \"%~1\" equ \"/?regex\" (\n explorer \"http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx\"\n exit /b 0\n ) else if /i \"%~1\" equ \"/?replace\" (\n explorer \"http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx\"\n exit /b 0\n ) else if /i \"%~1\" equ \"/V\" (\n &lt;\"%~f0\" cscript //E:JScript //nologo \"%~f0\" \"^::(REPL\\.BAT version)\" \"$1\" a\n exit /b 0\n ) else (\n call :err \"Insufficient arguments\"\n exit /b 2\n )\n)\necho(%~3|findstr /i \"[^SMILEBVXAJ]\" &gt;nul &amp;&amp; (\n call :err \"Invalid option(s)\"\n exit /b 2\n)\necho(%~3|findstr /i \"M\"|findstr /i \"A\"|findstr /vi \"S\" &gt;nul &amp;&amp; (\n call :err \"Incompatible options\"\n exit /b 2\n)\ncscript //E:JScript //nologo \"%~f0\" %*\nexit /b %errorlevel%\n\n:err\n&gt;&amp;2 echo ERROR: %~1. Use REPL /? to get help.\nexit /b\n\n************* JScript portion **********/\nvar rtn=1;\ntry {\n var env=WScript.CreateObject(\"WScript.Shell\").Environment(\"Process\");\n var args=WScript.Arguments;\n var search=args.Item(0);\n var replace=args.Item(1);\n var options=\"g\";\n if (args.length&gt;2) options+=args.Item(2).toLowerCase();\n var multi=(options.indexOf(\"m\")&gt;=0);\n var alterations=(options.indexOf(\"a\")&gt;=0);\n if (alterations) options=options.replace(/a/g,\"\");\n var srcVar=(options.indexOf(\"s\")&gt;=0);\n if (srcVar) options=options.replace(/s/g,\"\");\n var jexpr=(options.indexOf(\"j\")&gt;=0);\n if (jexpr) options=options.replace(/j/g,\"\");\n if (options.indexOf(\"v\")&gt;=0) {\n options=options.replace(/v/g,\"\");\n search=env(search);\n replace=env(replace);\n }\n if (options.indexOf(\"x\")&gt;=0) {\n options=options.replace(/x/g,\"\");\n if (!jexpr) {\n replace=replace.replace(/\\\\\\\\/g,\"\\\\B\");\n replace=replace.replace(/\\\\q/g,\"\\\"\");\n replace=replace.replace(/\\\\x80/g,\"\\\\u20AC\");\n replace=replace.replace(/\\\\x82/g,\"\\\\u201A\");\n replace=replace.replace(/\\\\x83/g,\"\\\\u0192\");\n replace=replace.replace(/\\\\x84/g,\"\\\\u201E\");\n replace=replace.replace(/\\\\x85/g,\"\\\\u2026\");\n replace=replace.replace(/\\\\x86/g,\"\\\\u2020\");\n replace=replace.replace(/\\\\x87/g,\"\\\\u2021\");\n replace=replace.replace(/\\\\x88/g,\"\\\\u02C6\");\n replace=replace.replace(/\\\\x89/g,\"\\\\u2030\");\n replace=replace.replace(/\\\\x8[aA]/g,\"\\\\u0160\");\n replace=replace.replace(/\\\\x8[bB]/g,\"\\\\u2039\");\n replace=replace.replace(/\\\\x8[cC]/g,\"\\\\u0152\");\n replace=replace.replace(/\\\\x8[eE]/g,\"\\\\u017D\");\n replace=replace.replace(/\\\\x91/g,\"\\\\u2018\");\n replace=replace.replace(/\\\\x92/g,\"\\\\u2019\");\n replace=replace.replace(/\\\\x93/g,\"\\\\u201C\");\n replace=replace.replace(/\\\\x94/g,\"\\\\u201D\");\n replace=replace.replace(/\\\\x95/g,\"\\\\u2022\");\n replace=replace.replace(/\\\\x96/g,\"\\\\u2013\");\n replace=replace.replace(/\\\\x97/g,\"\\\\u2014\");\n replace=replace.replace(/\\\\x98/g,\"\\\\u02DC\");\n replace=replace.replace(/\\\\x99/g,\"\\\\u2122\");\n replace=replace.replace(/\\\\x9[aA]/g,\"\\\\u0161\");\n replace=replace.replace(/\\\\x9[bB]/g,\"\\\\u203A\");\n replace=replace.replace(/\\\\x9[cC]/g,\"\\\\u0153\");\n replace=replace.replace(/\\\\x9[dD]/g,\"\\\\u009D\");\n replace=replace.replace(/\\\\x9[eE]/g,\"\\\\u017E\");\n replace=replace.replace(/\\\\x9[fF]/g,\"\\\\u0178\");\n replace=replace.replace(/\\\\b/g,\"\\b\");\n replace=replace.replace(/\\\\f/g,\"\\f\");\n replace=replace.replace(/\\\\n/g,\"\\n\");\n replace=replace.replace(/\\\\r/g,\"\\r\");\n replace=replace.replace(/\\\\t/g,\"\\t\");\n replace=replace.replace(/\\\\v/g,\"\\v\");\n replace=replace.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n function($0,$1,$2){\n return String.fromCharCode(parseInt(\"0x\"+$0.substring(2)));\n }\n );\n replace=replace.replace(/\\\\B/g,\"\\\\\");\n }\n search=search.replace(/\\\\\\\\/g,\"\\\\B\");\n search=search.replace(/\\\\q/g,\"\\\"\");\n search=search.replace(/\\\\x80/g,\"\\\\u20AC\");\n search=search.replace(/\\\\x82/g,\"\\\\u201A\");\n search=search.replace(/\\\\x83/g,\"\\\\u0192\");\n search=search.replace(/\\\\x84/g,\"\\\\u201E\");\n search=search.replace(/\\\\x85/g,\"\\\\u2026\");\n search=search.replace(/\\\\x86/g,\"\\\\u2020\");\n search=search.replace(/\\\\x87/g,\"\\\\u2021\");\n search=search.replace(/\\\\x88/g,\"\\\\u02C6\");\n search=search.replace(/\\\\x89/g,\"\\\\u2030\");\n search=search.replace(/\\\\x8[aA]/g,\"\\\\u0160\");\n search=search.replace(/\\\\x8[bB]/g,\"\\\\u2039\");\n search=search.replace(/\\\\x8[cC]/g,\"\\\\u0152\");\n search=search.replace(/\\\\x8[eE]/g,\"\\\\u017D\");\n search=search.replace(/\\\\x91/g,\"\\\\u2018\");\n search=search.replace(/\\\\x92/g,\"\\\\u2019\");\n search=search.replace(/\\\\x93/g,\"\\\\u201C\");\n search=search.replace(/\\\\x94/g,\"\\\\u201D\");\n search=search.replace(/\\\\x95/g,\"\\\\u2022\");\n search=search.replace(/\\\\x96/g,\"\\\\u2013\");\n search=search.replace(/\\\\x97/g,\"\\\\u2014\");\n search=search.replace(/\\\\x98/g,\"\\\\u02DC\");\n search=search.replace(/\\\\x99/g,\"\\\\u2122\");\n search=search.replace(/\\\\x9[aA]/g,\"\\\\u0161\");\n search=search.replace(/\\\\x9[bB]/g,\"\\\\u203A\");\n search=search.replace(/\\\\x9[cC]/g,\"\\\\u0153\");\n search=search.replace(/\\\\x9[dD]/g,\"\\\\u009D\");\n search=search.replace(/\\\\x9[eE]/g,\"\\\\u017E\");\n search=search.replace(/\\\\x9[fF]/g,\"\\\\u0178\");\n if (options.indexOf(\"l\")&gt;=0) {\n search=search.replace(/\\\\b/g,\"\\b\");\n search=search.replace(/\\\\f/g,\"\\f\");\n search=search.replace(/\\\\n/g,\"\\n\");\n search=search.replace(/\\\\r/g,\"\\r\");\n search=search.replace(/\\\\t/g,\"\\t\");\n search=search.replace(/\\\\v/g,\"\\v\");\n search=search.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n function($0,$1,$2){\n return String.fromCharCode(parseInt(\"0x\"+$0.substring(2)));\n }\n );\n search=search.replace(/\\\\B/g,\"\\\\\");\n } else search=search.replace(/\\\\B/g,\"\\\\\\\\\");\n }\n if (options.indexOf(\"l\")&gt;=0) {\n options=options.replace(/l/g,\"\");\n search=search.replace(/([.^$*+?()[{\\\\|])/g,\"\\\\$1\");\n if (!jexpr) replace=replace.replace(/\\$/g,\"$$$$\");\n }\n if (options.indexOf(\"b\")&gt;=0) {\n options=options.replace(/b/g,\"\");\n search=\"^\"+search\n }\n if (options.indexOf(\"e\")&gt;=0) {\n options=options.replace(/e/g,\"\");\n search=search+\"$\"\n }\n var search=new RegExp(search,options);\n var str1, str2;\n\n if (srcVar) {\n str1=env(args.Item(3));\n str2=str1.replace(search,jexpr?replFunc:replace);\n if (!alterations || str1!=str2) if (multi) {\n WScript.Stdout.Write(str2);\n } else {\n WScript.Stdout.WriteLine(str2);\n }\n if (str1!=str2) rtn=0;\n } else if (multi){\n var buf=1024;\n str1=\"\";\n while (!WScript.StdIn.AtEndOfStream) {\n str1+=WScript.StdIn.Read(buf);\n buf*=2\n }\n str2=str1.replace(search,jexpr?replFunc:replace);\n WScript.Stdout.Write(str2);\n if (str1!=str2) rtn=0;\n } else {\n while (!WScript.StdIn.AtEndOfStream) {\n str1=WScript.StdIn.ReadLine();\n str2=str1.replace(search,jexpr?replFunc:replace);\n if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);\n if (str1!=str2) rtn=0;\n }\n }\n} catch(e) {\n WScript.Stderr.WriteLine(\"JScript runtime error: \"+e.message);\n rtn=3;\n}\nWScript.Quit(rtn);\n\nfunction replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {\n var $=arguments;\n return(eval(replace));\n}\n</code></pre>\n\n<p><br/>\n<strong><em>IMPORTANT UPDATE</em></strong></p>\n\n<p>I have ceased development of REPL.BAT, and replaced it with JREPL.BAT. This newer utility has all the same functionality of REPL.BAT, plus much more: </p>\n\n<ul>\n<li>Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.</li>\n<li>Read directly from / write directly to a file: no need for pipes, redirection, or move command.</li>\n<li>Incorporate user supplied JScript</li>\n<li>Translation facility similar to unix tr, only it also supports regex search and JScript replace</li>\n<li>Discard non-matching text</li>\n<li>Prefix output lines with line number</li>\n<li>and more...</li>\n</ul>\n\n<p>As always, full documentation is embedded within the script. </p>\n\n<p>The original trivial solution is now even simpler:</p>\n\n<pre><code>jrepl \"foo\" \"bar\" /f test.txt /o -\n</code></pre>\n\n<p><a href=\"http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044\" rel=\"noreferrer\">The current version of JREPL.BAT is available at DosTips</a>. Read all of the subsequent posts in the thread to see examples of usage and a history of the development.</p>\n" }, { "answer_id": 20999154, "author": "Rachel", "author_id": 302677, "author_profile": "https://Stackoverflow.com/users/302677", "pm_score": 10, "selected": true, "text": "<p>A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.</p>\n<p>I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:</p>\n<pre><code>powershell -Command &quot;(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt&quot;\n</code></pre>\n<p>To explain it:</p>\n<ul>\n<li><code>powershell</code> starts up powershell.exe, which is included in Windows 7</li>\n<li><code>-Command &quot;... &quot;</code> is a command line arg for powershell.exe containing the command to run</li>\n<li><code>(gc myFile.txt)</code> reads the content of <code>myFile.txt</code> (<code>gc</code> is short for the <code>Get-Content</code> command)</li>\n<li><code>-replace 'foo', 'bar'</code> simply runs the replace command to replace <code>foo</code> with <code>bar</code></li>\n<li><code>| Out-File myFile.txt</code> pipes the output to the file <code>myFile.txt</code></li>\n<li><code>-encoding ASCII</code> prevents transcribing the output file to unicode, as the comments point out</li>\n</ul>\n<p>Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is <code>C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0</code></p>\n<p><strong>Update</strong><br/>Apparently modern windows systems have PowerShell built in allowing you to access this directly using</p>\n<pre><code>(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt\n</code></pre>\n" }, { "answer_id": 24887951, "author": "foxidrive", "author_id": 2299431, "author_profile": "https://Stackoverflow.com/users/2299431", "pm_score": 3, "selected": false, "text": "<p>Two batch files that supply <code>search and replace</code> functions have been written by Stack Overflow members <code>dbenham</code> and <code>aacini</code> using <code>native built-in jscript</code> in Windows. </p>\n\n<p>They are both <code>robust</code> and <code>very swift with large files</code> compared to plain batch scripting, and also <code>simpler</code> to use for basic replacing of text. They both have <code>Windows regular expression</code> pattern matching.</p>\n\n<ol>\n<li><p>This<code>sed-like</code> helper batch file is called <a href=\"https://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855\" rel=\"nofollow noreferrer\"><code>repl.bat</code></a> (by dbenham).</p>\n\n<p>Example using the <code>L</code> literal switch:</p>\n\n<pre><code>echo This is FOO here|repl \"FOO\" \"BAR\" L\necho and with a file:\ntype \"file.txt\" |repl \"FOO\" \"BAR\" L &gt;\"newfile.txt\"\n</code></pre></li>\n<li><p>This <code>grep-like</code> helper batch file is called <a href=\"https://www.dostips.com/forum/viewtopic.php?t=4697\" rel=\"nofollow noreferrer\"><code>findrepl.bat</code></a> (by aacini).</p>\n\n<p>Example which has regular expressions active:</p>\n\n<pre><code>echo This is FOO here|findrepl \"FOO\" \"BAR\" \necho and with a file:\ntype \"file.txt\" |findrepl \"FOO\" \"BAR\" &gt;\"newfile.txt\"\n</code></pre></li>\n</ol>\n\n<p>Both become powerful system-wide utilities <code>when placed in a folder that is on the path</code>, or can be used in the same folder with a batch file, or from the cmd prompt.</p>\n\n<p>They both have <code>case-insensitive</code> switches and also many other functions.</p>\n" }, { "answer_id": 26894259, "author": "Leptonator", "author_id": 175063, "author_profile": "https://Stackoverflow.com/users/175063", "pm_score": 5, "selected": false, "text": "<p>I know I am late to the party..</p>\n\n<p>Personally, I like the solution at:\n - <a href=\"http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace\" rel=\"noreferrer\">http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace</a></p>\n\n<p>We also, use the Dedupe Function extensively to help us deliver approximately 500 e-mails daily via SMTP from:\n- <a href=\"https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o\" rel=\"noreferrer\">https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o</a></p>\n\n<p>and these both work natively with no extra tools or utilities needed.</p>\n\n<p>REPLACER:</p>\n\n<pre><code>DEL New.txt\nsetLocal EnableDelayedExpansion\nFor /f \"tokens=* delims= \" %%a in (OLD.txt) do (\nSet str=%%a\nset str=!str:FOO=BAR!\necho !str!&gt;&gt;New.txt\n)\nENDLOCAL\n</code></pre>\n\n<p>DEDUPLICATOR (note the use of -9 for an ABA number):</p>\n\n<pre><code>REM DE-DUPLICATE THE Mapping.txt FILE\nREM THE DE-DUPLICATED FILE IS STORED AS new.txt\n\nset MapFile=Mapping.txt\nset ReplaceFile=New.txt\n\ndel %ReplaceFile%\n::DelDupeText.bat\nrem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o\nsetLocal EnableDelayedExpansion\nfor /f \"tokens=1,2 delims=,\" %%a in (%MapFile%) do (\nset str=%%a\nrem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString\nset str=!str:~-9!\nset str2=%%a\nset str3=%%a,%%b\n\nfind /i ^\"!str!^\" %MapFile%\nfind /i ^\"!str!^\" %ReplaceFile%\nif errorlevel 1 echo !str3!&gt;&gt;%ReplaceFile%\n)\nENDLOCAL\n</code></pre>\n\n<p>Thanks!</p>\n" }, { "answer_id": 29260513, "author": "Nadjib", "author_id": 4712931, "author_profile": "https://Stackoverflow.com/users/4712931", "pm_score": -1, "selected": false, "text": "<p>I have faced this problem several times while coding under Visual C++.\nIf you have it, you can use Visual studio Find and Replace Utility. It allows you to select a folder and replace the contents of any file in that folder with any other text you want.</p>\n\n<p>Under Visual Studio: \nEdit -> Find and Replace \nIn the opened dialog, select your folder and fill in \"Find What\" and \"Replace With\" boxes.\nHope this will be helpful. </p>\n" }, { "answer_id": 31812389, "author": "madcorp", "author_id": 2883841, "author_profile": "https://Stackoverflow.com/users/2883841", "pm_score": 2, "selected": false, "text": "<p>Just faced a similar problem - \"Search and replace text within files\", but with the exception that for both filenames and search/repalce I need to use regex. Because I'm not familiar with Powershell and want to save my searches for later use I need something more \"user friendly\" (preferable if it has GUI). </p>\n\n<p>So, while Googling :) I found a great tool - <a href=\"http://findandreplace.sourceforge.net/\" rel=\"nofollow\">FAR (Find And Replace)</a> (not FART). </p>\n\n<p>That little program has nice GUI and support regex for searching in filenames and within files. Only disadventage is that if you want to save your settings you have to run the program as an administrator (at least on Win7).</p>\n" }, { "answer_id": 33149373, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 4, "selected": false, "text": "<p>With the <a href=\"https://github.com/npocmaka/batch.scripts/blob/master/hybrids/jscript/replacer.bat\">replacer.bat</a></p>\n\n<p>1) With <code>e?</code> option that will evaluate special character sequences like <code>\\n\\r</code> and unicode sequences. In this case will replace quoted <code>\"Foo\"</code> and <code>\"Bar\"</code>:</p>\n\n<pre><code>call replacer.bat \"e?C:\\content.txt\" \"\\u0022Foo\\u0022\" \"\\u0022Bar\\u0022\"\n</code></pre>\n\n<p>2) Straightforward replacing where the <code>Foo</code> and <code>Bar</code> are not quoted.</p>\n\n<pre><code>call replacer.bat \"C:\\content.txt\" \"Foo\" \"Bar\"\n</code></pre>\n" }, { "answer_id": 33762001, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 4, "selected": false, "text": "<p>When you work with <a href=\"https://git-for-windows.github.io/\" rel=\"noreferrer\"><strong>Git on Windows</strong></a> then simply fire up <strong><code>git-bash</code></strong> \nand use <strong><code>sed</code></strong>. Or, when using Windows 10, start \"Bash on Ubuntu on Windows\" (from the Linux subsystem) and use <strong><code>sed</code></strong>.</p>\n\n<p>Its a stream editor, but can edit files directly by using the following command:</p>\n\n<pre><code>sed -i -e 's/foo/bar/g' filename\n</code></pre>\n\n<ul>\n<li><code>-i</code> option is used to edit in place on filename.</li>\n<li><code>-e</code> option indicates a command to run.\n\n<ul>\n<li><code>s</code> is used to replace the found expression \"foo\" with \"bar\" and <code>g</code> is used to replace any found matches.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Note by ereOn: </p>\n\n<p>If you want to replace a string in versioned files only of a Git repository, you may want to use: </p>\n\n<p><code>git ls-files &lt;eventual subfolders &amp; filters&gt; | xargs sed -i -e 's/foo/bar/g'</code> </p>\n\n<p>which works wonders.</p>\n" }, { "answer_id": 44577233, "author": "Whome", "author_id": 185565, "author_profile": "https://Stackoverflow.com/users/185565", "pm_score": 2, "selected": false, "text": "<p>@Rachel gave an excellent answer but here is a variation of it to read content to a powershell <code>$data</code> variable. You may then easily manipulate content multiple times before writing to a output file. Also see how multi-line values are given in a .bat batch files.</p>\n\n<pre><code>@REM ASCII=7bit ascii(no bom), UTF8=with bom marker\nset cmd=^\n $old = '\\$Param1\\$'; ^\n $new = 'Value1'; ^\n [string[]]$data = Get-Content 'datafile.txt'; ^\n $data = $data -replace $old, $new; ^\n out-file -InputObject $data -encoding UTF8 -filepath 'datafile.txt';\npowershell -NoLogo -Noninteractive -InputFormat none -Command \"%cmd%\"\n</code></pre>\n" }, { "answer_id": 49675231, "author": "George Birbilis", "author_id": 903783, "author_profile": "https://Stackoverflow.com/users/903783", "pm_score": 0, "selected": false, "text": "<p>Can also see the Replace and ReplaceFilter tools at <a href=\"https://zoomicon.github.io/tranXform/\" rel=\"nofollow noreferrer\">https://zoomicon.github.io/tranXform/</a> (source included). The 2nd one is a filter. </p>\n\n<p>The tool that replaces strings in files is in VBScript (needs Windows Script Host [WSH] to run in old Windows versions)</p>\n\n<p>The filter is probably not working with Unicode unless you recompile with latest Delphi (or with FreePascal/Lazarus)</p>\n" }, { "answer_id": 49868359, "author": "Wagner Pereira", "author_id": 3954704, "author_profile": "https://Stackoverflow.com/users/3954704", "pm_score": 2, "selected": false, "text": "<p>Use powershell in .bat - for Windows 7+</p>\n\n<p>encoding utf8 is optional, good for web sites</p>\n\n<pre><code>@echo off\nset ffile='myfile.txt'\nset fold='FOO'\nset fnew='BAR'\npowershell -Command \"(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8\"\n</code></pre>\n" }, { "answer_id": 55664924, "author": "eQ19", "author_id": 4058484, "author_profile": "https://Stackoverflow.com/users/4058484", "pm_score": 3, "selected": false, "text": "<p>I'm prefer to use <code>sed</code> from <a href=\"http://unxutils.sourceforge.net/\" rel=\"noreferrer\">GNU utilities for Win32</a>, the followings need to be noted</p>\n\n<blockquote>\n <ul>\n <li>single quote <code>''</code> won't work in windows, use <code>\"\"</code> instead</li>\n <li><strong><code>sed -i</code></strong> won't work in windows, it will need file <strong>swapping</strong></li>\n </ul>\n</blockquote>\n\n<p>So the working code of <code>sed</code> to find and replace text in a file in windows is as below</p>\n\n<pre><code>sed -e \"s/foo/bar/g\" test.txt &gt; tmp.txt &amp;&amp; mv tmp.txt test.txt\n</code></pre>\n" }, { "answer_id": 68204080, "author": "Shivam Tyagi", "author_id": 8071857, "author_profile": "https://Stackoverflow.com/users/8071857", "pm_score": 0, "selected": false, "text": "<p>Powershell Command -</p>\n<p>Getting content of the file and replacing it with some other text and then storing into another file</p>\n<p><strong>Command -1</strong>\n(Get-Content filename.xml)| ForEach-Object { $_.replace(&quot;some_text&quot;,&quot;replace_text&quot;).replace(&quot;some_other_text&quot;,&quot;replace_text&quot;) } | Set-Content filename2.xml</p>\n<p>Copying another file into the original one file</p>\n<p><strong>Command2</strong></p>\n<p>Copy-Item -Path filename2.xml -Destination filename.xml -PassThru</p>\n<p>removing another one file</p>\n<p><strong>Command 3</strong></p>\n<p>Remove-Item filename2.xml</p>\n" }, { "answer_id": 69695302, "author": "Georgie", "author_id": 2344075, "author_profile": "https://Stackoverflow.com/users/2344075", "pm_score": 2, "selected": false, "text": "<p>For me, to be sure to not change the encoding (from UTF-8), keeping accents... the only way was to mention the default encoding before and after :</p>\n<pre><code>powershell -Command &quot;(gc 'My file.sql' -encoding &quot;Default&quot;) -replace 'String 1', 'String 2' | Out-File -encoding &quot;Default&quot; 'My file.sql'&quot;\n</code></pre>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?
A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution. I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file: ``` powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt" ``` To explain it: * `powershell` starts up powershell.exe, which is included in Windows 7 * `-Command "... "` is a command line arg for powershell.exe containing the command to run * `(gc myFile.txt)` reads the content of `myFile.txt` (`gc` is short for the `Get-Content` command) * `-replace 'foo', 'bar'` simply runs the replace command to replace `foo` with `bar` * `| Out-File myFile.txt` pipes the output to the file `myFile.txt` * `-encoding ASCII` prevents transcribing the output file to unicode, as the comments point out Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is `C:\WINDOWS\system32\WindowsPowerShell\v1.0` **Update** Apparently modern windows systems have PowerShell built in allowing you to access this directly using ``` (Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt ```
60,046
<p>I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below: </p> <pre><code>SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain. at flash.display::Loader/get content() at com.google.maps::ClientBootstrap/createFactory() at com.google.maps::ClientBootstrap/executeNextFrameCalls() </code></pre> <p>Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published.</p> <p>I've tried doing the following in the main application as well as the component:</p> <pre><code>Security.allowDomain('*') Security.allowDomain('maps.googleapis.com') Security.allowDomain('mydomain.com') </code></pre>
[ { "answer_id": 60453, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>This sounds like a <code>crossdomain.xml</code> related problem. I did a quick search and there seems to be many people with the same issue. Some proxy requests through XMLHttpRequest etc..</p>\n\n<p><a href=\"http://code.google.com/p/gdata-issues/issues/detail?id=406\" rel=\"nofollow noreferrer\">Issue 406: Add crossdomain.xml for Google Accounts</a></p>\n" }, { "answer_id": 62227, "author": "Adam Cuzzort", "author_id": 4760, "author_profile": "https://Stackoverflow.com/users/4760", "pm_score": 1, "selected": false, "text": "<p>Thanks for the help. Apparently this has something to do with including the Flex app on an ASP.NET page. When I moved it over to a flat HTML file, it worked fine. I don't have time to fully investigate right now, but that seems to have fixed it.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4760/" ]
I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below: ``` SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain. at flash.display::Loader/get content() at com.google.maps::ClientBootstrap/createFactory() at com.google.maps::ClientBootstrap/executeNextFrameCalls() ``` Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published. I've tried doing the following in the main application as well as the component: ``` Security.allowDomain('*') Security.allowDomain('maps.googleapis.com') Security.allowDomain('mydomain.com') ```
This sounds like a `crossdomain.xml` related problem. I did a quick search and there seems to be many people with the same issue. Some proxy requests through XMLHttpRequest etc.. [Issue 406: Add crossdomain.xml for Google Accounts](http://code.google.com/p/gdata-issues/issues/detail?id=406)
60,051
<p>My question is pertaining to the best practice for accessing a child object's parent. So let's say a class instantiates another class, that class instance is now referenced with an object. From that child object, what is the best way to reference back to the parent object? Currently I know of a couple ways that I use often, but I'm not sure if A) there is a better way to do it or B) which of them is the better practice</p> <p>The first method is to use getDefinitionByName, which would not instantiate that class, but allow access to anything inside of it that was publicly declared.</p> <pre><code>_class:Class = getDefinitionByName("com.site.Class") as Class; </code></pre> <p>And then reference that variable based on its parent to child hierarchy.<br> Example, if the child is attempting to reference a class that's two levels up from itself:</p> <pre><code>_class(parent.parent).function(); </code></pre> <p>This seems to work fine, but you are required to know the level at which the child is at compared to the level of the parent you are attempting to access.</p> <p>I can also get the following statement to trace out [object ClassName] into Flash's output.</p> <pre><code>trace(Class); </code></pre> <p>I'm not 100% on the implementation of that line, I haven't persued it as a way to reference an object outside of the current object I'm in.</p> <p>Another method I've seen used is to simply pass a reference to this into the class object you are creating and just catch it with a constructor argument</p> <pre><code>var class:Class = new Class(this); </code></pre> <p>and then in the Class file</p> <pre><code>public function Class(objectRef:Object) { _parentRef = objectRef; } </code></pre> <p>That reference also requires you to step back up using the child to parent hierarchy though.</p> <p>I could also import that class, and then use the direct filepath to reference a method inside of that class, regardless of its the parent or not.</p> <pre><code>import com.site.Class; com.site.Class.method(); </code></pre> <p>Of course there the parent to child relationship is irrelevant because I'm accessing the method or property directly through the imported class.</p> <p>I just feel like I'm missing something really obvious here. I'm basically looking for confirmation if these are the correct ways to reference the parent, and if so which is the most ideal, or am I over-looking something else?</p>
[ { "answer_id": 60074, "author": "dagorym", "author_id": 171, "author_profile": "https://Stackoverflow.com/users/171", "pm_score": 2, "selected": false, "text": "<p>I've always used your second method, passing a pointer to the parent object to the child and storing that pointer in a member variable in the child class. To me that seems to be the simplest method for the child to communicate back to the parent.</p>\n" }, { "answer_id": 60411, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 3, "selected": true, "text": "<p>It's generally good to have the class as it's own instance and reduce tight coupling to something else (as in this case, it's parent). If you do something like parent.doSomething() it's not possible to use that class in container that doesn't have the doSometing() method. I think it's definitely better to pass in whatever the class may need and then inside the class it doesn't have to do any parent.parent etc anymore.</p>\n\n<p>With this if you in the future want to change the structure, it's very easy to just pass in a new reference; the implementation of the child class doesn't have to change at all.</p>\n\n<p>The third alternative you have here is also very different, it's accessing a class level static method (you don't have to type the whole class path when accessing that method), not an instance method as in the first two.</p>\n" }, { "answer_id": 60427, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>I like to pass the parent as an interface (so the class can be contained in any parent implementing that interface) or implement the reference as an event/function pointer/delegate which the parent can hook onto.</p>\n" }, { "answer_id": 64085, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I like setting up a global class to handle references to classes that need to be accessed by any other class, not necessarily the child.</p>\n\n<p>The global class simply consists of static getters and setters like so:</p>\n\n<pre><code>private static const class:Class;\n\npublic static function setClass(_class:Class){\nclass = _class;\n}\npublic static function getClass(void):Class{\nreturn class;\n}\n</code></pre>\n\n<p>The nice thing about this is that you don't have to import the class you are returning from the global class, just the global class itself.</p>\n\n<p>The class that needs to be referenced adds itself to the global list.\nThe Other cool thing is that you can easily dispatch events from this centralized location.</p>\n\n<p>Most of the time if a class needs to be referenced by child classes or any other class, i do it through an interface.</p>\n" }, { "answer_id": 67526, "author": "mikechambers", "author_id": 10232, "author_profile": "https://Stackoverflow.com/users/10232", "pm_score": 3, "selected": false, "text": "<p>In general, if you need a child to communicate with a parent, you should look at having it do so by broadcasting events. This decouples the child for the parent, and makes it possible to have other classes work with the child.</p>\n\n<p>I would not recommend passing in a reference to the parent class into the child.</p>\n\n<p>Here is a a simple example (I have tested / compiled this so there may be some typos).</p>\n\n<pre><code>//Child.as\npackage\n{\n import flash.events.EventDispatcher;\n import flash.events.Event;\n\n public class Child extends EventDispatcher\n {\n public function doSomething():void\n {\n var e:Event = new Event(Event.COMPLETE);\n dispatchEvent(e);\n }\n\n public function foo():void\n {\n trace(\"foo\");\n }\n }\n}\n\n\n//Parent.as\npackage\n{\n import flash.display.Sprite;\n import flash.events.Event;\n public class Parent extends Sprite\n {\n private var child:Child;\n public function Parent():void\n {\n c = new Child();\n c.addEventListener(Event.COMPLETE, onComplete);\n c.foo();//traces foo\n\n c.doSomething()\n }\n\n public function onComplete(e:Event):void\n {\n trace(\"Child broadcast Event.COMPLETE\");\n }\n\n }\n}\n</code></pre>\n\n<p>In most cases, you would dispatch custom events and pass data with them.</p>\n\n<p>Basically:</p>\n\n<p>Parent has reference to Child and communicates via method calls.\nChild does not have reference to Parent, and communicates (to anyone) via dispatching events.</p>\n\n<p>hope that helps...</p>\n\n<p>mike chambers</p>\n\n<p>[email protected]</p>\n" }, { "answer_id": 1077501, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If these objects are in the DisplayList, then you have some more options. If I have a ParentClass and a ChildClass, in the child class, you seem to be able to access the parent if you cast the request as the ParentClass. e.g. </p>\n\n<pre><code>ParentClass(parent).parentFunction();\n</code></pre>\n\n<p>I know for sure it works if the ParentClass is the Document Class. As the Document Class is always the first item in the display list, this works:</p>\n\n<pre><code>ParentClass(stage.getChildAt(0)).parentFunction();\n</code></pre>\n\n<p>In my case, they were both members of the same package, so I did not even need to import anything. I haven't tested it in all circumstances, but it worked when I needed it to.</p>\n\n<p>Of course 'parent' and 'getChild...' only work if these objects are in the DisplayList, but that's been good enough for me.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945/" ]
My question is pertaining to the best practice for accessing a child object's parent. So let's say a class instantiates another class, that class instance is now referenced with an object. From that child object, what is the best way to reference back to the parent object? Currently I know of a couple ways that I use often, but I'm not sure if A) there is a better way to do it or B) which of them is the better practice The first method is to use getDefinitionByName, which would not instantiate that class, but allow access to anything inside of it that was publicly declared. ``` _class:Class = getDefinitionByName("com.site.Class") as Class; ``` And then reference that variable based on its parent to child hierarchy. Example, if the child is attempting to reference a class that's two levels up from itself: ``` _class(parent.parent).function(); ``` This seems to work fine, but you are required to know the level at which the child is at compared to the level of the parent you are attempting to access. I can also get the following statement to trace out [object ClassName] into Flash's output. ``` trace(Class); ``` I'm not 100% on the implementation of that line, I haven't persued it as a way to reference an object outside of the current object I'm in. Another method I've seen used is to simply pass a reference to this into the class object you are creating and just catch it with a constructor argument ``` var class:Class = new Class(this); ``` and then in the Class file ``` public function Class(objectRef:Object) { _parentRef = objectRef; } ``` That reference also requires you to step back up using the child to parent hierarchy though. I could also import that class, and then use the direct filepath to reference a method inside of that class, regardless of its the parent or not. ``` import com.site.Class; com.site.Class.method(); ``` Of course there the parent to child relationship is irrelevant because I'm accessing the method or property directly through the imported class. I just feel like I'm missing something really obvious here. I'm basically looking for confirmation if these are the correct ways to reference the parent, and if so which is the most ideal, or am I over-looking something else?
It's generally good to have the class as it's own instance and reduce tight coupling to something else (as in this case, it's parent). If you do something like parent.doSomething() it's not possible to use that class in container that doesn't have the doSometing() method. I think it's definitely better to pass in whatever the class may need and then inside the class it doesn't have to do any parent.parent etc anymore. With this if you in the future want to change the structure, it's very easy to just pass in a new reference; the implementation of the child class doesn't have to change at all. The third alternative you have here is also very different, it's accessing a class level static method (you don't have to type the whole class path when accessing that method), not an instance method as in the first two.
60,098
<p>I wrote a simple web service in C# using SharpDevelop (which I just got and I love).</p> <p>The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)</p> <p>But I get this error when I try to load the service now.</p> <pre> Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'. Source Error: Line 1: &lt;%@ WebService Class="flightinfo.Soap,flightinfo" %&gt; </pre> <p>I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.</p> <p>Any ideas?</p>
[ { "answer_id": 60108, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;%@ WebService Class=\"flightinfo.Soap,flightinfo\" %&gt;\n</code></pre>\n\n<p>What is the name of your class?</p>\n" }, { "answer_id": 72087, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 0, "selected": false, "text": "<p>The problem may be cause by VB.NET &amp; C# projects using different naming conventions for project assemblies and how the project namespace is used. At least that's were I would start looking.</p>\n" }, { "answer_id": 201092, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 2, "selected": true, "text": "<p>In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between <code>Namespace Z</code> and <code>End Namespace</code> will be in the X.Y.Z namespace.\nIn C# you have to provide the full namespace name, regardless of the default namespace of the project. \nSo if the C# project had the default namespace X.Y, the CS files would still include the <code>namespace X.Y</code> declaration. After converting to VB, if both the default namespace and the namespace declarations in the files stay the same you end up with classes in the X.Y.X.Y namespace.\nSo in your case, the Soap class is now in the flightinfo.flightinfo namespace. Thus there are three possible solutions:</p>\n\n<ul>\n<li><p>change the asmx file to</p>\n\n</li>\n<li><p>remove the default namespace from the project</p></li>\n<li>remove the namespace declarations from the vb files</li>\n</ul>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525/" ]
I wrote a simple web service in C# using SharpDevelop (which I just got and I love). The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.) But I get this error when I try to load the service now. ``` Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'. Source Error: Line 1: <%@ WebService Class="flightinfo.Soap,flightinfo" %> ``` I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#. Any ideas?
In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between `Namespace Z` and `End Namespace` will be in the X.Y.Z namespace. In C# you have to provide the full namespace name, regardless of the default namespace of the project. So if the C# project had the default namespace X.Y, the CS files would still include the `namespace X.Y` declaration. After converting to VB, if both the default namespace and the namespace declarations in the files stay the same you end up with classes in the X.Y.X.Y namespace. So in your case, the Soap class is now in the flightinfo.flightinfo namespace. Thus there are three possible solutions: * change the asmx file to * remove the default namespace from the project * remove the namespace declarations from the vb files
60,160
<p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
[ { "answer_id": 60161, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 10, "selected": true, "text": "<p>Since <a href=\"http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)\" rel=\"noreferrer\">Java 1.5, yes</a>:</p>\n\n<pre><code>Pattern.quote(\"$5\");\n</code></pre>\n" }, { "answer_id": 60164, "author": "Rob Oxspring", "author_id": 1867, "author_profile": "https://Stackoverflow.com/users/1867", "pm_score": 4, "selected": false, "text": "<p>I think what you're after is <code>\\Q$5\\E</code>. Also see <code>Pattern.quote(s)</code> introduced in Java5.</p>\n\n<p>See <a href=\"http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html\" rel=\"noreferrer\">Pattern</a> javadoc for details.</p>\n" }, { "answer_id": 60172, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 7, "selected": false, "text": "<p>Difference between <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#quote-java.lang.String-\" rel=\"noreferrer\"><code>Pattern.quote</code></a> and <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#quoteReplacement-java.lang.String-\" rel=\"noreferrer\"><code>Matcher.quoteReplacement</code></a> was not clear to me before I saw following example</p>\n\n<pre><code>s.replaceFirst(Pattern.quote(\"text to replace\"), \n Matcher.quoteReplacement(\"replacement text\"));\n</code></pre>\n" }, { "answer_id": 11955201, "author": "Meower68", "author_id": 251767, "author_profile": "https://Stackoverflow.com/users/251767", "pm_score": 3, "selected": false, "text": "<p>First off, if</p>\n\n<ul>\n<li>you use replaceAll()</li>\n<li>you DON'T use Matcher.quoteReplacement()</li>\n<li>the text to be substituted in includes a $1</li>\n</ul>\n\n<p>it won't put a 1 at the end. It will look at the search regex for the first matching group and sub THAT in. That's what $1, $2 or $3 means in the replacement text: matching groups from the search pattern.</p>\n\n<p>I frequently plug long strings of text into .properties files, then generate email subjects and bodies from those. Indeed, this appears to be the default way to do i18n in Spring Framework. I put XML tags, as placeholders, into the strings and I use replaceAll() to replace the XML tags with the values at runtime.</p>\n\n<p>I ran into an issue where a user input a dollars-and-cents figure, with a dollar sign. replaceAll() choked on it, with the following showing up in a stracktrace:</p>\n\n<pre><code>java.lang.IndexOutOfBoundsException: No group 3\nat java.util.regex.Matcher.start(Matcher.java:374)\nat java.util.regex.Matcher.appendReplacement(Matcher.java:748)\nat java.util.regex.Matcher.replaceAll(Matcher.java:823)\nat java.lang.String.replaceAll(String.java:2201)\n</code></pre>\n\n<p>In this case, the user had entered \"$3\" somewhere in their input and replaceAll() went looking in the search regex for the third matching group, didn't find one, and puked.</p>\n\n<p>Given:</p>\n\n<pre><code>// \"msg\" is a string from a .properties file, containing \"&lt;userInput /&gt;\" among other tags\n// \"userInput\" is a String containing the user's input\n</code></pre>\n\n<p>replacing</p>\n\n<pre><code>msg = msg.replaceAll(\"&lt;userInput \\\\/&gt;\", userInput);\n</code></pre>\n\n<p>with </p>\n\n<pre><code>msg = msg.replaceAll(\"&lt;userInput \\\\/&gt;\", Matcher.quoteReplacement(userInput));\n</code></pre>\n\n<p>solved the problem. The user could put in any kind of characters, including dollar signs, without issue. It behaved exactly the way you would expect.</p>\n" }, { "answer_id": 13405612, "author": "Moscow Boy", "author_id": 925098, "author_profile": "https://Stackoverflow.com/users/925098", "pm_score": 3, "selected": false, "text": "<p>To have protected pattern you may replace all symbols with \"\\\\\\\\\", except digits and letters. And after that you can put in that protected pattern your special symbols to make this pattern working not like stupid quoted text, but really like a patten, but your own. Without user special symbols.</p>\n\n<pre><code>public class Test {\n public static void main(String[] args) {\n String str = \"y z (111)\";\n String p1 = \"x x (111)\";\n String p2 = \".* .* \\\\(111\\\\)\";\n\n p1 = escapeRE(p1);\n\n p1 = p1.replace(\"x\", \".*\");\n\n System.out.println( p1 + \"--&gt;\" + str.matches(p1) ); \n //.*\\ .*\\ \\(111\\)--&gt;true\n System.out.println( p2 + \"--&gt;\" + str.matches(p2) ); \n //.* .* \\(111\\)--&gt;true\n }\n\n public static String escapeRE(String str) {\n //Pattern escaper = Pattern.compile(\"([^a-zA-z0-9])\");\n //return escaper.matcher(str).replaceAll(\"\\\\\\\\$1\");\n return str.replaceAll(\"([^a-zA-Z0-9])\", \"\\\\\\\\$1\");\n }\n}\n</code></pre>\n" }, { "answer_id": 35991060, "author": "Androidme", "author_id": 1014693, "author_profile": "https://Stackoverflow.com/users/1014693", "pm_score": 5, "selected": false, "text": "<p>It may be too late to respond, but you can also use <code>Pattern.LITERAL</code>, which would ignore all special characters while formatting:</p>\n\n<pre><code>Pattern.compile(textToFormat, Pattern.LITERAL);\n</code></pre>\n" }, { "answer_id": 45415931, "author": "Adam111p", "author_id": 3058581, "author_profile": "https://Stackoverflow.com/users/3058581", "pm_score": 3, "selected": false, "text": "<p>Pattern.quote(\"blabla\") works nicely.</p>\n\n<p>The Pattern.quote() works nicely. It encloses the sentence with the characters \"<strong>\\Q</strong>\" and \"<strong>\\E</strong>\", and if it does escape \"\\Q\" and \"\\E\".\nHowever, if you need to do a real regular expression escaping(or custom escaping), you can use this code:</p>\n\n<pre><code>String someText = \"Some/s/wText*/,**\";\nSystem.out.println(someText.replaceAll(\"[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]\", \"\\\\\\\\$0\"));\n</code></pre>\n\n<p>This method returns: <em>Some/\\s/wText*/\\,**</em></p>\n\n<p>Code for example and tests:</p>\n\n<pre><code>String someText = \"Some\\\\E/s/wText*/,**\";\nSystem.out.println(\"Pattern.quote: \"+ Pattern.quote(someText));\nSystem.out.println(\"Full escape: \"+someText.replaceAll(\"[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]\", \"\\\\\\\\$0\"));\n</code></pre>\n" }, { "answer_id": 50990732, "author": "Akhil Kathi", "author_id": 9717510, "author_profile": "https://Stackoverflow.com/users/9717510", "pm_score": -1, "selected": false, "text": "<p>^(Negation) symbol is used to match something that is not in the character group.</p>\n\n<p>This is the link to <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference\" rel=\"nofollow noreferrer\">Regular Expressions</a></p>\n\n<p>Here is the image info about negation:</p>\n\n<p><img src=\"https://i.stack.imgur.com/m5cXU.png\" alt=\"Info about negation\"></p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338/" ]
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
Since [Java 1.5, yes](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)): ``` Pattern.quote("$5"); ```
60,168
<p>Here is an example of what I've got going on:</p> <pre><code>CREATE TABLE Parent (id BIGINT NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB; CREATE TABLE Child (id BIGINT NOT NULL, parentid BIGINT NOT NULL, PRIMARY KEY (id), KEY (parentid), CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB; CREATE TABLE Uncle (id BIGINT NOT NULL, parentid BIGINT NOT NULL, childid BIGINT NOT NULL, PRIMARY KEY (id), KEY (parentid), KEY (childid), CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE, CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB; </code></pre> <p>Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.</p> <p>When I have a Parent and an Uncle with the same Child, and I delete the Parent, it <em>seems</em> like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following:</p> <pre><code> ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`)) </code></pre> <p>InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.</p> <p>Am I missing something? Is this <em>supposed</em> to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)?</p>
[ { "answer_id": 60185, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 3, "selected": false, "text": "<p>In the simpler case, what happens if a record is deleted from Child and it has a referencing Uncle? That's unspecified, so the constraints fail for that anyway.</p>\n\n<p>If deleting a Child does not delete its Uncles, then what happens instead? Uncle.childid cannot be null.</p>\n\n<p>What you want is one of these three things:</p>\n\n<ol>\n<li>Uncle.childid can be null, and you want ON DELETE SET NULL for childid.</li>\n<li>Uncle.childid cannot be null, and you want ON DELETE CASCADE for childid.</li>\n<li>Childid does not belong on Uncle, and you want a ChildsUncle relation with ON DELETE CASCADE foreign key constraints to both Child and Uncle. Uncleid would be a candidate key for that relation (i.e. it should be unique).</li>\n</ol>\n" }, { "answer_id": 60229, "author": "Tony BenBrahim", "author_id": 80075, "author_profile": "https://Stackoverflow.com/users/80075", "pm_score": -1, "selected": false, "text": "<p>the design is all wrong. You should have single table, with parent child relationship (literrally).\nThen you can figure out uncles (and aunts) with a query</p>\n\n<p><code>\nselect id from persons where -find all children of the grandparents<br>\nparent id in (<br>\n select parentid from persons --find the grandparents<br>\n where id in (<br>\n select parentid from persons --find the parents<br>\n where id=THECHILD)\n )<br>\nminus --and take out the child's parents<br>\nselect parentid from persons<br>\nwhere id=THECHILD<br>\n</code> </p>\n" }, { "answer_id": 78024, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 3, "selected": true, "text": "<p>The parent deletion is triggering the child deletion as you stated and I don't know why it goes to the child table before the uncle table. I imagine you would have to look at the dbms code to know for sure, but im sure there is an algorithm that picks which tables to cascade to first.</p>\n\n<p>The system does not really 'figure out' stuff the way you imply here and it is just following its constraint rules. The problem is the schema you created in that it encounters a constraint that will not let it pass further. </p>\n\n<p>I see what you are saying.. if it hit the uncle table first it would delete the record and then delete the child (and not hit the uncle cascade from the child deletion). But even so, I don't think a schema would be set up to rely on that kind of behavior in reality. I think the only way to know for sure what is going on is to look through the code or get one of the mysql/postgresql programmers in here to say how it processes fk constraints.</p>\n" }, { "answer_id": 16425452, "author": "sactiw", "author_id": 416369, "author_profile": "https://Stackoverflow.com/users/416369", "pm_score": 0, "selected": false, "text": "<p>@Matt Solnit first of all this is really a good question and as far as I know when a record from Parent is to be deleted then innodb first tries to identify which other tables holds references to it so that it can delete the record from them as well. In your case it is Child table and Uncle table, now it seems that in this case it decides to first delete record from Child table and thus it repeats the same process for Child and eventually fails as Uncle holds reference to Child table but neither \"ON DELETE CASCADE\" nor \"ON DELETE SET NULL\" is specified for fk_child FK in Uncle table. However, it does seems that <em>if</em> innodb first tries to delete record from the Uncle table then deletion should have happened smoothly. Well after giving a second thought I think that since innodb follows ACID model thus it chooses Child over Uncle to start the deletion process becuase if it starts with Uncle even then the deletion in Child might still have failed e.g. assume a Friend table that has fk_child key (similar to Uncle) without ON DELETE CASCADE, now this would still have caused the whole transaction to fail and therefore this looks right behaviour to me. In others words innodb starts with table that may cause a possible failure in the transaction but that is my theory in reality it might be a completely different story. :)</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6198/" ]
Here is an example of what I've got going on: ``` CREATE TABLE Parent (id BIGINT NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB; CREATE TABLE Child (id BIGINT NOT NULL, parentid BIGINT NOT NULL, PRIMARY KEY (id), KEY (parentid), CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB; CREATE TABLE Uncle (id BIGINT NOT NULL, parentid BIGINT NOT NULL, childid BIGINT NOT NULL, PRIMARY KEY (id), KEY (parentid), KEY (childid), CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE, CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB; ``` Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa. When I have a Parent and an Uncle with the same Child, and I delete the Parent, it *seems* like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following: ``` ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`)) ``` InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it. Am I missing something? Is this *supposed* to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)?
The parent deletion is triggering the child deletion as you stated and I don't know why it goes to the child table before the uncle table. I imagine you would have to look at the dbms code to know for sure, but im sure there is an algorithm that picks which tables to cascade to first. The system does not really 'figure out' stuff the way you imply here and it is just following its constraint rules. The problem is the schema you created in that it encounters a constraint that will not let it pass further. I see what you are saying.. if it hit the uncle table first it would delete the record and then delete the child (and not hit the uncle cascade from the child deletion). But even so, I don't think a schema would be set up to rely on that kind of behavior in reality. I think the only way to know for sure what is going on is to look through the code or get one of the mysql/postgresql programmers in here to say how it processes fk constraints.
60,174
<p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p> <pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); </code></pre> <p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p> <pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') </code></pre> <p>What can be done to prevent this from happening?</p>
[ { "answer_id": 60180, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 10, "selected": false, "text": "<p>I'd recommend using <a href=\"http://ca3.php.net/manual/en/book.pdo.php\" rel=\"noreferrer\">PDO</a> (PHP Data Objects) to run parameterized SQL queries. </p>\n\n<p>Not only does this protect against SQL injection, but it also speeds up queries. </p>\n\n<p>And by using PDO rather than <code>mysql_</code>, <code>mysqli_</code>, and <code>pgsql_</code> functions, you make your application a little more abstracted from the database, in the rare occurrence that you have to switch database providers.</p>\n" }, { "answer_id": 60195, "author": "Tanerax", "author_id": 567, "author_profile": "https://Stackoverflow.com/users/567", "pm_score": 9, "selected": false, "text": "<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk.</p>\n</blockquote>\n<p>You could do something basic like this:</p>\n<pre><code>$safe_variable = mysqli_real_escape_string($dbConnection, $_POST[&quot;user-input&quot;]);\nmysqli_query($dbConnection, &quot;INSERT INTO table (column) VALUES ('&quot; . $safe_variable . &quot;')&quot;);\n</code></pre>\n<p>This won't solve every problem, but it's a very good stepping stone. I left out obvious items such as checking the variable's existence, format (numbers, letters, etc.).</p>\n" }, { "answer_id": 60442, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 11, "selected": false, "text": "<p>To use the parameterized query, you need to use either Mysqli or PDO. To rewrite your example with mysqli, we would need something like the following.</p>\n<pre><code>&lt;?php\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(&quot;server&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database_name&quot;);\n\n$variable = $_POST[&quot;user-input&quot;];\n$stmt = $mysqli-&gt;prepare(&quot;INSERT INTO table (column) VALUES (?)&quot;);\n// &quot;s&quot; means the database expects a string\n$stmt-&gt;bind_param(&quot;s&quot;, $variable);\n$stmt-&gt;execute();\n</code></pre>\n<p>The key function you'll want to read up on there would be <a href=\"http://php.net/mysqli.prepare\" rel=\"noreferrer\"><code>mysqli::prepare</code></a>.</p>\n<p>Also, as others have suggested, you may find it useful/easier to step up a layer of abstraction with something like <a href=\"http://php.net/pdo\" rel=\"noreferrer\">PDO</a>.</p>\n<p>Please note that the case you asked about is a fairly simple one and that more complex cases may require more complex approaches. In particular:</p>\n<ul>\n<li>If you want to alter the structure of the SQL based on user input, parameterized queries are not going to help, and the escaping required is not covered by <code>mysql_real_escape_string</code>. In this kind of case, you would be better off passing the user's input through a whitelist to ensure only 'safe' values are allowed through.</li>\n</ul>\n" }, { "answer_id": 60496, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 14, "selected": true, "text": "<p>The <em>correct</em> way to avoid SQL injection attacks, no matter which database you use, is to <strong>separate the data from SQL</strong>, so that data stays data and will <strong>never be interpreted</strong> as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't <em>fully</em> understand the details, you should always <strong>use prepared statements and parameterized queries.</strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.</p>\n<p>You basically have two options to achieve this:</p>\n<ol>\n<li><p>Using <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"noreferrer\"><strong>PDO</strong></a> (for any supported database driver):</p>\n <pre class=\"lang-php prettyprint-override\"><code>$stmt = $pdo-&gt;prepare('SELECT * FROM employees WHERE name = :name');\n$stmt-&gt;execute([ 'name' =&gt; $name ]);\n\nforeach ($stmt as $row) {\n // Do something with $row\n}\n</code></pre>\n</li>\n<li><p>Using <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"noreferrer\"><strong>MySQLi</strong></a> (for MySQL):</p>\n <pre class=\"lang-php prettyprint-override\"><code>$stmt = $dbConnection-&gt;prepare('SELECT * FROM employees WHERE name = ?');\n$stmt-&gt;bind_param('s', $name); // 's' specifies the variable type =&gt; 'string'\n$stmt-&gt;execute();\n\n$result = $stmt-&gt;get_result();\nwhile ($row = $result-&gt;fetch_assoc()) {\n // Do something with $row\n}\n</code></pre>\n</li>\n</ol>\n<p>If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, <code>pg_prepare()</code> and <code>pg_execute()</code> for PostgreSQL). PDO is the universal option.</p>\n<hr />\n<h2>Correctly setting up the connection</h2>\n<h4>PDO</h4>\n<p>Note that when using <strong>PDO</strong> to access a MySQL database <em>real</em> prepared statements are <strong>not used by default</strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using <strong>PDO</strong> is:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');\n\n$dbConnection-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n</code></pre>\n<p>In the above example, the error mode isn't strictly necessary, <strong>but it is advised to add it</strong>. This way PDO will inform you of all MySQL errors by means of throwing the <code>PDOException</code>.</p>\n<p>What is <strong>mandatory</strong>, however, is the first <code>setAttribute()</code> line, which tells PDO to disable emulated prepared statements and use <em>real</em> prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).</p>\n<p>Although you can set the <code>charset</code> in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) <a href=\"http://php.net/manual/en/ref.pdo-mysql.connection.php\" rel=\"noreferrer\">silently ignored the charset parameter</a> in the DSN.</p>\n<h4>Mysqli</h4>\n<p>For mysqli we have to follow the same routine:</p>\n<pre class=\"lang-php prettyprint-override\"><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting\n$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');\n$dbConnection-&gt;set_charset('utf8mb4'); // charset\n</code></pre>\n<hr />\n<h2>Explanation</h2>\n<p>The SQL statement you pass to <code>prepare</code> is parsed and compiled by the database server. By specifying parameters (either a <code>?</code> or a named parameter like <code>:name</code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute</code>, the prepared statement is combined with the parameter values you specify.</p>\n<p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.</p>\n<p>Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name</code> variable contains <code>'Sarah'; DELETE FROM employees</code> the result would simply be a search for the string <code>&quot;'Sarah'; DELETE FROM employees&quot;</code>, and you will not end up with <a href=\"http://xkcd.com/327/\" rel=\"noreferrer\">an empty table</a>.</p>\n<p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.</p>\n<p>Oh, and since you asked about how to do it for an insert, here's an example (using PDO):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$preparedStatement = $db-&gt;prepare('INSERT INTO table (column) VALUES (:column)');\n\n$preparedStatement-&gt;execute([ 'column' =&gt; $unsafeValue ]);\n</code></pre>\n<hr />\n<h2>Can prepared statements be used for dynamic queries?</h2>\n<p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.</p>\n<p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.</p>\n<pre><code>// Value whitelist\n// $dir can only be 'DESC', otherwise it will be 'ASC'\nif (empty($dir) || $dir !== 'DESC') {\n $dir = 'ASC';\n}\n</code></pre>\n" }, { "answer_id": 60530, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 9, "selected": false, "text": "<p>Use <code>PDO</code> and prepared queries.</p>\n<p>(<code>$conn</code> is a <code>PDO</code> object)</p>\n<pre><code>$stmt = $conn-&gt;prepare(&quot;INSERT INTO tbl VALUES(:id, :name)&quot;);\n$stmt-&gt;bindValue(':id', $id);\n$stmt-&gt;bindValue(':name', $name);\n$stmt-&gt;execute();\n</code></pre>\n" }, { "answer_id": 348719, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 9, "selected": false, "text": "<p>Whatever you do end up using, make sure that you check your input hasn't already been mangled by <code>magic_quotes</code> or some other well-meaning rubbish, and if necessary, run it through <code>stripslashes</code> or whatever to sanitize it.</p>\n" }, { "answer_id": 1669109, "author": "Nikhil", "author_id": 14944, "author_profile": "https://Stackoverflow.com/users/14944", "pm_score": 8, "selected": false, "text": "<p>I favor <a href=\"http://en.wikipedia.org/wiki/Stored_procedure\" rel=\"noreferrer\">stored procedures</a> (<a href=\"http://dev.mysql.com/doc/refman/5.1/en/stored-routines-syntax.html\" rel=\"noreferrer\">MySQL has had stored procedures support since 5.0</a>) from a security point of view - the advantages are -</p>\n\n<ol>\n<li>Most databases (including <a href=\"http://dev.mysql.com/doc/refman/5.1/en/stored-routines-privileges.html\" rel=\"noreferrer\">MySQL</a>) enable user access to be restricted to executing stored procedures. The fine-grained security access control is useful to prevent escalation of privileges attacks. This prevents compromised applications from being able to run SQL directly against the database.</li>\n<li>They abstract the raw SQL query from the application so less information of the database structure is available to the application. This makes it harder for people to understand the underlying structure of the database and design suitable attacks.</li>\n<li>They accept only parameters, so the advantages of parameterized queries are there. Of course - IMO you still need to sanitize your input - especially if you are using dynamic SQL inside the stored procedure.</li>\n</ol>\n\n<p>The disadvantages are -</p>\n\n<ol>\n<li>They (stored procedures) are tough to maintain and tend to multiply very quickly. This makes managing them an issue.</li>\n<li>They are not very suitable for dynamic queries - if they are built to accept dynamic code as parameters then a lot of the advantages are negated.</li>\n</ol>\n" }, { "answer_id": 6381189, "author": "rahularyansharma", "author_id": 779158, "author_profile": "https://Stackoverflow.com/users/779158", "pm_score": 9, "selected": false, "text": "<blockquote>\n <p><strong>Deprecated Warning:</strong>\n This answer's sample code (like the question's sample code) uses PHP's <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n \n <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n \n <p><strong>IMPORTANT</strong></p>\n \n <p>The best way to prevent SQL Injection is to use <strong>Prepared Statements</strong> <em>instead of escaping</em>, as <a href=\"https://stackoverflow.com/a/60496/2224584\">the accepted answer</a> demonstrates. </p>\n \n <p>There are libraries such as <a href=\"https://github.com/auraphp/Aura.Sql\" rel=\"noreferrer\">Aura.Sql</a> and <a href=\"https://github.com/paragonie/easydb\" rel=\"noreferrer\">EasyDB</a> that allow developers to use prepared statements easier. To learn more about why prepared statements are better at <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">stopping SQL injection</a>, refer to <a href=\"https://stackoverflow.com/a/12118602/2224584\">this <code>mysql_real_escape_string()</code> bypass</a> and <a href=\"https://kraft.im/2015/05/how-emoji-saved-your-sites-hide/\" rel=\"noreferrer\">recently fixed Unicode SQL Injection vulnerabilities in WordPress</a>.</p>\n</blockquote>\n\n<p>Injection prevention - <a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"noreferrer\">mysql_real_escape_string()</a></p>\n\n<p>PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function, <code>mysql_real_escape_string</code>.</p>\n\n<p><code>mysql_real_escape_string</code> takes a string that is going to be used in a MySQL query and return the same string with all SQL injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \\'.</p>\n\n<p><strong>NOTE:</strong> you must be connected to the database to use this function!</p>\n\n<p>// Connect to MySQL</p>\n\n<pre><code>$name_bad = \"' OR 1'\"; \n\n$name_bad = mysql_real_escape_string($name_bad);\n\n$query_bad = \"SELECT * FROM customers WHERE username = '$name_bad'\";\necho \"Escaped Bad Injection: &lt;br /&gt;\" . $query_bad . \"&lt;br /&gt;\";\n\n\n$name_evil = \"'; DELETE FROM customers WHERE 1 or username = '\"; \n\n$name_evil = mysql_real_escape_string($name_evil);\n\n$query_evil = \"SELECT * FROM customers WHERE username = '$name_evil'\";\necho \"Escaped Evil Injection: &lt;br /&gt;\" . $query_evil;\n</code></pre>\n\n<p>You can find more details in <em><a href=\"http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php\" rel=\"noreferrer\">MySQL - SQL Injection Prevention</a></em>.</p>\n" }, { "answer_id": 6565763, "author": "Cedric", "author_id": 154607, "author_profile": "https://Stackoverflow.com/users/154607", "pm_score": 9, "selected": false, "text": "<blockquote>\n <p><strong>Deprecated Warning:</strong>\n This answer's sample code (like the question's sample code) uses PHP's <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n \n <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n\n<p>Parameterized query AND input validation is the way to go. There are many scenarios under which SQL injection may occur, even though <code>mysql_real_escape_string()</code> has been used.</p>\n\n<p>Those examples are vulnerable to SQL injection:</p>\n\n<pre><code>$offset = isset($_GET['o']) ? $_GET['o'] : 0;\n$offset = mysql_real_escape_string($offset);\nRunQuery(\"SELECT userid, username FROM sql_injection_test LIMIT $offset, 10\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$order = isset($_GET['o']) ? $_GET['o'] : 'userid';\n$order = mysql_real_escape_string($order);\nRunQuery(\"SELECT userid, username FROM sql_injection_test ORDER BY `$order`\");\n</code></pre>\n\n<p>In both cases, you can't use <code>'</code> to protect the encapsulation.</p>\n\n<p><a href=\"http://www.webappsec.org/projects/articles/091007.txt\" rel=\"noreferrer\">Source</a>: <em>The Unexpected SQL Injection (When Escaping Is Not Enough)</em></p>\n" }, { "answer_id": 8255054, "author": "Your Common Sense", "author_id": 285587, "author_profile": "https://Stackoverflow.com/users/285587", "pm_score": 10, "selected": false, "text": "<p>Every answer here covers only part of the problem.\nIn fact, there are <strong>four</strong> different query parts which we can add to SQL dynamically: -</p>\n<ul>\n<li>a string</li>\n<li>a number</li>\n<li>an identifier</li>\n<li>a syntax keyword</li>\n</ul>\n<p>And prepared statements cover only two of them.</p>\n<p>But sometimes we have to make our query even more dynamic, adding operators or identifiers as well.\nSo, we will need different protection techniques.</p>\n<p>In general, such a protection approach is based on <em>whitelisting</em>.</p>\n<p>In this case, every dynamic parameter should be hardcoded in your script and chosen from that set.\nFor example, to do dynamic ordering:</p>\n<pre><code>$orders = array(&quot;name&quot;, &quot;price&quot;, &quot;qty&quot;); // Field names\n$key = array_search($_GET['sort'], $orders)); // if we have such a name\n$orderby = $orders[$key]; // If not, first one will be set automatically. \n$query = &quot;SELECT * FROM `table` ORDER BY $orderby&quot;; // Value is safe\n</code></pre>\n<p>To ease the process I wrote a <a href=\"https://phpdelusions.net/pdo_examples/order_by\" rel=\"noreferrer\">whitelist helper function</a> that does all the job in one line:</p>\n<pre><code>$orderby = white_list($_GET['orderby'], &quot;name&quot;, [&quot;name&quot;,&quot;price&quot;,&quot;qty&quot;], &quot;Invalid field name&quot;);\n$query = &quot;SELECT * FROM `table` ORDER BY `$orderby`&quot;; // sound and safe\n</code></pre>\n<p>There is another way to secure identifiers - escaping but I rather stick to whitelisting as a more robust and explicit approach. Yet as long as you have an identifier quoted, you can escape the quote character to make it safe. For example, by default for mysql you have to <a href=\"https://dev.mysql.com/doc/refman/8.0/en/identifiers.html\" rel=\"noreferrer\">double the quote character to escape it</a>. For other other DBMS escaping rules would be different.</p>\n<p>Still, there is an issue with SQL syntax keywords (such as <code>AND</code>, <code>DESC</code> and such), but white-listing seems the only approach in this case.</p>\n<p>So, a general recommendation may be phrased as</p>\n<blockquote>\n<ul>\n<li>Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) must be added through a prepared statement. No Exceptions.</li>\n<li>Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.</li>\n</ul>\n</blockquote>\n<h3>Update</h3>\n<p>Although there is a general agreement on the best practices regarding SQL injection protection, there are <strong>still many bad practices as well.</strong> And some of them too deeply rooted in the minds of PHP users. For instance, on this very page there are (although invisible to most visitors) <strong>more than 80 deleted answers</strong> - all removed by the community due to bad quality or promoting bad and outdated practices. Worse yet, some of the bad answers aren't deleted, but rather prospering.</p>\n<p>For example, <a href=\"https://stackoverflow.com/a/11802479\">there(1)</a> <a href=\"https://stackoverflow.com/a/6381189\">are(2)</a> <a href=\"https://stackoverflow.com/a/60195/\">still(3)</a> <a href=\"https://stackoverflow.com/a/12426697/\">many(4)</a> <a href=\"https://stackoverflow.com/a/21179234\">answers(5)</a>, including the <a href=\"https://stackoverflow.com/a/60442\">second most upvoted answer</a> suggesting you manual string escaping - an outdated approach that is proven to be insecure.</p>\n<p>Or there is a slightly better answer that suggests just <a href=\"https://stackoverflow.com/a/12710285\">another method of string formatting</a> and even boasts it as the ultimate panacea. While of course, it is not. This method is no better than regular string formatting, yet it keeps all its drawbacks: it is applicable to strings only and, like any other manual formatting, it's essentially optional, non-obligatory measure, prone to human error of any sort.</p>\n<p>I think that all this because of one very old superstition, supported by such authorities like <a href=\"https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_4:_Escaping_All_User_Supplied_Input\" rel=\"noreferrer\">OWASP</a> or <a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php#refsect1-function.mysql-real-escape-string-description\" rel=\"noreferrer\">the PHP manual</a>, which proclaims equality between whatever &quot;escaping&quot; and protection from SQL injections.</p>\n<p>Regardless of what PHP manual said for ages, <strong><code>*_escape_string</code> by no means makes data safe</strong> and never has been intended to. Besides being useless for any SQL part other than string, manual escaping is wrong, because it is manual as opposite to automated.</p>\n<p>And OWASP makes it even worse, stressing on escaping <em>user input</em> which is an utter nonsense: there should be no such words in the context of injection protection. Every variable is potentially dangerous - no matter the source! Or, in other words - every variable has to be properly formatted to be put into a query - no matter the source again. It's the destination that matters. The moment a developer starts to separate the sheep from the goats (thinking whether some particular variable is &quot;safe&quot; or not) he/she takes his/her first step towards disaster. Not to mention that even the wording suggests bulk escaping at the entry point, resembling the very magic quotes feature - already despised, deprecated and removed.</p>\n<p>So, unlike whatever &quot;escaping&quot;, prepared statements <em>is</em> the measure that indeed protects from SQL injection (when applicable).</p>\n" }, { "answer_id": 10992656, "author": "devOp", "author_id": 842330, "author_profile": "https://Stackoverflow.com/users/842330", "pm_score": 8, "selected": false, "text": "<p>If possible, cast the types of your parameters. But it's only working on simple types like int, bool, and float.</p>\n\n<pre><code>$unsafe_variable = $_POST['user_id'];\n\n$safe_variable = (int)$unsafe_variable ;\n\nmysqli_query($conn, \"INSERT INTO table (column) VALUES ('\" . $safe_variable . \"')\");\n</code></pre>\n" }, { "answer_id": 11308776, "author": "Johannes Fahrenkrug", "author_id": 171933, "author_profile": "https://Stackoverflow.com/users/171933", "pm_score": 8, "selected": false, "text": "<p>In my opinion, the best way to generally prevent SQL injection in your PHP application (or any web application, for that matter) is to think about your application's architecture. If the only way to protect against SQL injection is to remember to use a special method or function that does The Right Thing every time you talk to the database, you are doing it wrong. That way, it's just a matter of time until you forget to correctly format your query at some point in your code.</p>\n\n<p>Adopting the MVC pattern and a framework like <a href=\"http://cakephp.org/\" rel=\"noreferrer\">CakePHP</a> or <a href=\"http://codeigniter.com/\" rel=\"noreferrer\">CodeIgniter</a> is probably the right way to go: Common tasks like creating secure database queries have been solved and centrally implemented in such frameworks. They help you to organize your web application in a sensible way and make you think more about loading and saving objects than about securely constructing single SQL queries. </p>\n" }, { "answer_id": 11610605, "author": "Manish Shrivastava", "author_id": 1133932, "author_profile": "https://Stackoverflow.com/users/1133932", "pm_score": 8, "selected": false, "text": "<p>There are many ways of preventing SQL injections and other SQL hacks. You can easily find it on the Internet (Google Search). Of course <strong>PDO is one of the good solutions.</strong> But I would like to suggest you some good links prevention from SQL injection.</p>\n\n<p><em><a href=\"http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php\" rel=\"noreferrer\">What is SQL injection and how to prevent</a></em></p>\n\n<p><em><a href=\"https://php.net/manual/en/security.database.sql-injection.php\" rel=\"noreferrer\">PHP manual for SQL injection</a></em></p>\n\n<p><em><a href=\"https://learn.microsoft.com/en-gb/archive/blogs/brian_swan/whats-the-right-way-to-prevent-sql-injection-in-php-scripts\" rel=\"noreferrer\">Microsoft explanation of SQL injection and prevention in PHP</a></em></p>\n\n<p>And some other like <em><a href=\"https://web.archive.org/web/20190221025712/http://www.digifuzz.net/archives/2007/07/preventing-sql-injection-with-php/\" rel=\"noreferrer\">Preventing SQL injection with MySQL and PHP</a></em>.</p>\n\n<p>Now, <strong>why you do you need to prevent your query from SQL injection?</strong></p>\n\n<p>I would like to let you know: Why do we try for preventing SQL injection with a short example below:</p>\n\n<p>Query for login authentication match:</p>\n\n<pre><code>$query=\"select * from users where email='\".$_POST['email'].\"' and password='\".$_POST['password'].\"' \";\n</code></pre>\n\n<p>Now, if someone (a hacker) puts</p>\n\n<pre><code>$_POST['email']= [email protected]' OR '1=1\n</code></pre>\n\n<p>and password anything....</p>\n\n<p>The query will be parsed into the system only up to:</p>\n\n<pre><code>$query=\"select * from users where email='[email protected]' OR '1=1';\n</code></pre>\n\n<p>The other part will be discarded. So, what will happen? A non-authorized user (hacker) will be able to log in as administrator without having his/her password. Now, he/she can do anything that the administrator/email person can do. See, it's very dangerous if SQL injection is not prevented.</p>\n" }, { "answer_id": 11802479, "author": "Nicolas Finelli", "author_id": 1720432, "author_profile": "https://Stackoverflow.com/users/1720432", "pm_score": 8, "selected": false, "text": "<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"nofollow noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n<blockquote>\n<p><strong>Warning</strong>: The mysql extension is removed at this time. we recommend using the <em>PDO extension</em></p>\n</blockquote>\n<p>Using this PHP function <code>mysql_escape_string()</code> you can get a good prevention in a fast way.</p>\n<p>For example:</p>\n<pre><code>SELECT * FROM users WHERE name = '&quot;.mysql_escape_string($name_from_html_form).&quot;'\n</code></pre>\n<p><code>mysql_escape_string</code> — Escapes a string for use in a mysql_query</p>\n<p>For more prevention, you can add at the end ...</p>\n<pre><code>wHERE 1=1 or LIMIT 1\n</code></pre>\n<p>Finally you get:</p>\n<pre><code>SELECT * FROM users WHERE name = '&quot;.mysql_escape_string($name_from_html_form).&quot;' LIMIT 1\n</code></pre>\n" }, { "answer_id": 12426697, "author": "Soumalya Banerjee", "author_id": 1019484, "author_profile": "https://Stackoverflow.com/users/1019484", "pm_score": 7, "selected": false, "text": "<blockquote>\n <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n \n <p><strong>Deprecated Warning</strong>: The mysql extension is deprecated at this time. we recommend using the <em>PDO extension</em></p>\n</blockquote>\n\n<p>I use three different ways to prevent my web application from being vulnerable to SQL injection.</p>\n\n<ol>\n<li>Use of <code>mysql_real_escape_string()</code>, which is a pre-defined function in <a href=\"http://en.wikipedia.org/wiki/PHP\" rel=\"noreferrer\">PHP</a>, and this code add backslashes to the following characters: <code>\\x00</code>, <code>\\n</code>, <code>\\r</code>, <code>\\</code>, <code>'</code>, <code>\"</code> and <code>\\x1a</code>. Pass the input values as parameters to minimize the chance of SQL injection.</li>\n<li>The most advanced way is to use PDOs.</li>\n</ol>\n\n<p>I hope this will help you.</p>\n\n<p>Consider the following query:</p>\n\n<p><code>$iId = mysql_real_escape_string(\"1 OR 1=1\");\n $sSql = \"SELECT * FROM table WHERE id = $iId\";</code></p>\n\n<p>mysql_real_escape_string() will not protect here. If you use single quotes (' ') around your variables inside your query is what protects you against this. Here is an solution below for this:</p>\n\n<p><code>$iId = (int) mysql_real_escape_string(\"1 OR 1=1\");\n $sSql = \"SELECT * FROM table WHERE id = $iId\";</code></p>\n\n<p>This <a href=\"https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string\">question</a> has some good answers about this.</p>\n\n<p>I suggest, using PDO is the best option.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p><code>mysql_real_escape_string()</code> is deprecated as of PHP 5.5.0. Use either mysqli or PDO.</p>\n\n<p>An alternative to mysql_real_escape_string() is </p>\n\n<pre><code>string mysqli_real_escape_string ( mysqli $link , string $escapestr )\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>$iId = $mysqli-&gt;real_escape_string(\"1 OR 1=1\");\n$mysqli-&gt;query(\"SELECT * FROM table WHERE id = $iId\");\n</code></pre>\n" }, { "answer_id": 12500462, "author": "Xeoncross", "author_id": 99923, "author_profile": "https://Stackoverflow.com/users/99923", "pm_score": 8, "selected": false, "text": "<p>For those unsure of how to use PDO (coming from the <code>mysql_</code> functions), I made a <a href=\"https://github.com/Xeoncross/DByte/blob/master/DByte/DB.php\" rel=\"noreferrer\">very, very simple PDO wrapper</a> that is a single file. It exists to show how easy it is to do all the common things applications need to be done. Works with PostgreSQL, MySQL, and SQLite.</p>\n<p>Basically, read it <a href=\"http://php.net/pdo\" rel=\"noreferrer\">while you read the manual</a> to see how to put the PDO functions to use in real life to make it simple to store and retrieve values in the format <strong>you</strong> want.</p>\n<blockquote>\n<p><strong>I want a single column</strong></p>\n<pre><code>$count = DB::column('SELECT COUNT(*) FROM `user`');\n</code></pre>\n<p><strong>I want an array(key =&gt; value) results (i.e. for making a selectbox)</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code>$pairs = DB::pairs('SELECT `id`, `username` FROM `user`');\n</code></pre>\n<p><strong>I want a single row result</strong></p>\n<pre><code>$user = DB::row('SELECT * FROM `user` WHERE `id` = ?', array($user_id));\n</code></pre>\n<p><strong>I want an array of results</strong></p>\n<pre><code>$banned_users = DB::fetch('SELECT * FROM `user` WHERE `banned` = ?', array('TRUE'));\n</code></pre>\n</blockquote>\n" }, { "answer_id": 12710285, "author": "Zaffy", "author_id": 823738, "author_profile": "https://Stackoverflow.com/users/823738", "pm_score": 9, "selected": false, "text": "<p>As you can see, people suggest you use prepared statements at the most. It's not wrong, but when your query is executed <strong>just once</strong> per process, there would be a slight performance penalty. </p>\n\n<p>I was facing this issue, but I think I solved it in <em>very</em> sophisticated way - the way hackers use to avoid using quotes. I used this in conjunction with emulated prepared statements. I use it to prevent <em>all</em> kinds of possible SQL injection attacks.</p>\n\n<h2>My approach:</h2>\n\n<ul>\n<li><p>If you expect input to be integer make sure it's <strong><em>really</em></strong> integer. In a variable-type language like PHP it is this <em>very</em> important. You can use for example this very simple but powerful solution: <code>sprintf(\"SELECT 1,2,3 FROM table WHERE 4 = %u\", $input);</code> </p></li>\n<li><p>If you expect anything else from integer <strong>hex it</strong>. If you hex it, you will perfectly escape all input. In C/C++ there's a function called <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-hex-string.html\" rel=\"noreferrer\"><code>mysql_hex_string()</code></a>, in PHP you can use <a href=\"http://www.php.net/manual/en/function.bin2hex.php\" rel=\"noreferrer\"><code>bin2hex()</code></a>.</p>\n\n<p>Don't worry about that the escaped string will have a 2x size of its original length because even if you use <code>mysql_real_escape_string</code>, PHP has to allocate same capacity <code>((2*input_length)+1)</code>, which is the same.</p></li>\n<li><p>This hex method is often used when you transfer binary data, but I see no reason why not use it on all data to prevent SQL injection attacks. Note that you have to prepend data with <code>0x</code> or use the MySQL function <code>UNHEX</code> instead.</p></li>\n</ul>\n\n<p>So, for example, the query:</p>\n\n<pre><code>SELECT password FROM users WHERE name = 'root';\n</code></pre>\n\n<p>Will become:</p>\n\n<pre><code>SELECT password FROM users WHERE name = 0x726f6f74;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT password FROM users WHERE name = UNHEX('726f6f74');\n</code></pre>\n\n<p>Hex is the perfect escape. No way to inject.</p>\n\n<h2>Difference between UNHEX function and 0x prefix</h2>\n\n<p>There was some discussion in comments, so I finally want to make it clear. These two approaches are very similar, but they are a little different in some ways:</p>\n\n<p>The <code>0x</code> prefix can only be used for data columns such as <code>char</code>, <code>varchar</code>, <code>text</code>, <code>block</code>, <code>binary</code>, etc.<br>\nAlso, its use is a little complicated if you are about to insert an empty string. You'll have to entirely replace it with <code>''</code>, or you'll get an error.</p>\n\n<p><code>UNHEX()</code> works on <strong>any</strong> column; you do not have to worry about the empty string.</p>\n\n<hr>\n\n<h2>Hex methods are often used as attacks</h2>\n\n<p>Note that this hex method is often used as an SQL injection attack where integers are just like strings and escaped just with <code>mysql_real_escape_string</code>. Then you can avoid the use of quotes.</p>\n\n<p>For example, if you just do something like this:</p>\n\n<pre><code>\"SELECT title FROM article WHERE id = \" . mysql_real_escape_string($_GET[\"id\"])\n</code></pre>\n\n<p>an attack can inject you very <em>easily</em>. Consider the following injected code returned from your script:</p>\n\n<pre><code>SELECT ... WHERE id = -1 UNION ALL SELECT table_name FROM information_schema.tables;\n</code></pre>\n\n<p>and now just extract table structure:</p>\n\n<pre><code>SELECT ... WHERE id = -1 UNION ALL SELECT column_name FROM information_schema.column WHERE table_name = __0x61727469636c65__;\n</code></pre>\n\n<p>And then just select whatever data ones want. Isn't it cool?</p>\n\n<p>But if the coder of an injectable site would hex it, no injection would be possible because the query would look like this:</p>\n\n<pre><code>SELECT ... WHERE id = UNHEX('2d312075...3635');\n</code></pre>\n" }, { "answer_id": 12822319, "author": "RDK", "author_id": 1032750, "author_profile": "https://Stackoverflow.com/users/1032750", "pm_score": 8, "selected": false, "text": "<p>I think if someone wants to use PHP and MySQL or some other dataBase server:</p>\n<ol>\n<li>Think about learning <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a> (PHP Data Objects) – it is a database access layer providing a uniform method of access to multiple databases.</li>\n<li>Think about learning <a href=\"http://en.wikipedia.org/wiki/MySQLi\" rel=\"nofollow noreferrer\">MySQLi</a></li>\n</ol>\n<hr />\n<p><strong>Libraries examples:</strong></p>\n<p>---- <strong>PDO</strong></p>\n<blockquote>\n<p>----- No placeholders - ripe for SQL injection! <strong>It's bad</strong></p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) values ($name, $addr, $city)&quot;);\n</code></pre>\n<blockquote>\n<p>----- Unnamed placeholders</p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) values (?, ?, ?);\n</code></pre>\n<blockquote>\n<p>----- Named placeholders</p>\n</blockquote>\n<pre><code>$request = $pdoConnection-&gt;(&quot;INSERT INTO parents (name, addr, city) value (:name, :addr, :city)&quot;);\n</code></pre>\n<p>--- <strong>MySQLi</strong></p>\n<pre><code>$request = $mysqliConnection-&gt;prepare('\n SELECT * FROM trainers\n WHERE name = ?\n AND email = ?\n AND last_login &gt; ?');\n\n $query-&gt;bind_param('first_param', 'second_param', $mail, time() - 3600);\n $query-&gt;execute();\n</code></pre>\n<hr />\n<p><strong>P.S</strong>:</p>\n<p>PDO wins this battle with ease. With support for twelve\ndifferent database drivers and named parameters, we can get used to its API. From a security standpoint, both of them are safe as long as the developer uses them the way they are supposed to be used</p>\n" }, { "answer_id": 13064261, "author": "Apurv Nerlekar", "author_id": 1266952, "author_profile": "https://Stackoverflow.com/users/1266952", "pm_score": 8, "selected": false, "text": "<p>The simple alternative to this problem could be solved by granting appropriate permissions in the database itself.\nFor example: if you are using a MySQL database then enter into the database through terminal or the UI provided and just follow this command:</p>\n\n<pre><code> GRANT SELECT, INSERT, DELETE ON database TO username@'localhost' IDENTIFIED BY 'password';\n</code></pre>\n\n<p>This will restrict the user to only get confined with the specified query's only. Remove the delete permission and so the data would never get deleted from the query fired from the PHP page.\nThe second thing to do is to flush the privileges so that the MySQL refreshes the permissions and updates.</p>\n\n<pre><code>FLUSH PRIVILEGES; \n</code></pre>\n\n<p>more information about <a href=\"https://dev.mysql.com/doc/refman/5.7/en/flush.html\" rel=\"noreferrer\">flush</a>.</p>\n\n<p>To see the current privileges for the user fire the following query.</p>\n\n<pre><code>select * from mysql.user where User='username';\n</code></pre>\n\n<p>Learn more about <a href=\"https://dev.mysql.com/doc/refman/5.7/en/grant.html\" rel=\"noreferrer\">GRANT</a>.</p>\n" }, { "answer_id": 14569797, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>Regarding many useful answers, I hope to add some value to this thread.</p>\n\n<p>SQL injection is an attack that can be done through user inputs (inputs that filled by a user and then used inside queries). The SQL injection patterns are correct query syntax while we can call it: bad queries for bad reasons, and we assume that there might be a bad person that try to get secret information (bypassing access control) that affect the three principles of security (confidentiality, integrity, and availability).</p>\n\n<p>Now, our point is to prevent security threats such as SQL injection attacks, the question asking (how to prevent an SQL injection attack using PHP), be more realistic, data filtering or clearing input data is the case when using user-input data inside such query, using PHP or any other programming language is not the case, or as recommended by more people to use modern technology such as prepared statement or any other tools that currently supporting SQL injection prevention, consider that these tools not available anymore? How do you secure your application?</p>\n\n<p>My approach against SQL injection is: clearing user-input data before sending it to the database (before using it inside any query).</p>\n\n<p><strong>Data filtering for (converting unsafe data to safe data)</strong></p>\n\n<p>Consider that <a href=\"http://en.wikipedia.org/wiki/PHP#History\" rel=\"noreferrer\">PDO</a> and <a href=\"http://en.wikipedia.org/wiki/MySQLi\" rel=\"noreferrer\">MySQLi</a> are not available. How can you secure your application? Do you force me to use them? What about other languages other than PHP? I prefer to provide general ideas as it can be used for wider border, not just for a specific language.</p>\n\n<ol>\n<li>SQL user (limiting user privilege): most common SQL operations are (SELECT, UPDATE, INSERT), then, why give the UPDATE privilege to a user that does not require it? For example, <strong>login, and search pages</strong> are only using SELECT, then, why use DB users in these pages with high privileges?</li>\n</ol>\n\n<p><strong>RULE: do not create one database user for all privileges. For all SQL operations, you can create your scheme like (deluser, selectuser, updateuser) as usernames for easy usage.</strong></p>\n\n<p>See <a href=\"http://en.wikipedia.org/wiki/Principle_of_least_privilege\" rel=\"noreferrer\">principle of least privilege</a>.</p>\n\n<ol start=\"2\">\n<li><p>Data filtering: before building any query user input, it should be validated and filtered. For programmers, it's important to define some properties for each user-input variables:\n<strong>data type, data pattern, and data length</strong>. A field that is a number between (x and y) must be exactly validated using the exact rule, and for a field that is a string (text): pattern is the case, for example, a username must contain only some characters, let’s say [a-zA-Z0-9_-.]. The length varies between (x and n) where x and n (integers, x &lt;=n).\n<strong>Rule: creating exact filters and validation rules are best practices for me.</strong></p></li>\n<li><p>Use other tools: Here, I will also agree with you that a prepared statement (parametrized query) and stored procedures. The disadvantages here is these ways require advanced skills which do not exist for most users. The basic idea here is to distinguish between the SQL query and the data that is used inside. Both approaches can be used even with unsafe data, because the user-input data here does not add anything to the original query, such as (any or x=x).</p></li>\n</ol>\n\n<p>For more information, please read <a href=\"https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet\" rel=\"noreferrer\">OWASP SQL Injection Prevention Cheat Sheet</a>.</p>\n\n<p>Now, if you are an advanced user, start using this defense as you like, but, for beginners, if they can't quickly implement a stored procedure and prepared the statement, it's better to filter input data as much they can.</p>\n\n<p>Finally, let's consider that a user sends this text below instead of entering his/her username:</p>\n\n<pre><code>[1] UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root'\n</code></pre>\n\n<p>This input can be checked early without any prepared statement and stored procedures, but to be on the safe side, using them starts after user-data filtering and validation.</p>\n\n<p>The last point is detecting unexpected behavior which requires more effort and complexity; it's not recommended for normal web applications.</p>\n\n<p>Unexpected behavior in the above user input is SELECT, UNION, IF, SUBSTRING, BENCHMARK, SHA, and root. Once these words detected, you can avoid the input.</p>\n\n<h2>UPDATE 1:</h2>\n\n<p>A user commented that this post is useless, OK! Here is what <a href=\"https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_3:_Escaping_All_User_Supplied_Input\" rel=\"noreferrer\">OWASP.ORG provided</a>:</p>\n\n<blockquote>\n <p>Primary defenses: <br/>\n <br/>\n Option #1: Use of Prepared Statements (Parameterized Queries) <br/>\n Option #2: Use of Stored Procedures <br/>\n Option #3: Escaping all User Supplied Input <br/>\n <br/>\n Additional defenses: <br/>\n <br/>\n Also Enforce: Least Privilege <br/>\n Also Perform: White List Input Validation <br/></p>\n</blockquote>\n\n<p>As you may know, claiming an article should be supported by a valid argument, at least by one reference! Otherwise, it's considered as an attack and a bad claim!</p>\n\n<h2>Update 2:</h2>\n\n<p>From the PHP manual, <a href=\"http://php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"noreferrer\">PHP: Prepared Statements - Manual</a>:</p>\n\n<blockquote>\n <p>Escaping and SQL injection <br/></p>\n \n <p>Bound variables will be escaped automatically by the server. The\n server inserts their escaped values at the appropriate places into the\n statement template before execution. A hint must be provided to the\n server for the type of bound variable, to create an appropriate\n conversion. See the mysqli_stmt_bind_param() function for more\n information. <br/></p>\n \n <p>The automatic escaping of values within the server is sometimes\n considered a security feature to prevent SQL injection. The same\n degree of security can be achieved with non-prepared statements if\n input values are escaped correctly. <br/></p>\n</blockquote>\n\n<h2>Update 3:</h2>\n\n<p>I created test cases for knowing how PDO and MySQLi send the query to the MySQL server when using a prepared statement:</p>\n\n<p><strong>PDO:</strong></p>\n\n<pre><code>$user = \"''1''\"; // Malicious keyword\n$sql = 'SELECT * FROM awa_user WHERE userame =:username';\n$sth = $dbh-&gt;prepare($sql, array(PDO::ATTR_CURSOR =&gt; PDO::CURSOR_FWDONLY));\n$sth-&gt;execute(array(':username' =&gt; $user));\n</code></pre>\n\n<p><strong>Query Log:</strong></p>\n\n<blockquote>\n<pre><code> 189 Query SELECT * FROM awa_user WHERE userame ='\\'\\'1\\'\\''\n 189 Quit\n</code></pre>\n</blockquote>\n\n<p><strong>MySQLi:</strong></p>\n\n<pre><code>$stmt = $mysqli-&gt;prepare(\"SELECT * FROM awa_user WHERE username =?\")) {\n$stmt-&gt;bind_param(\"s\", $user);\n$user = \"''1''\";\n$stmt-&gt;execute();\n</code></pre>\n\n<p><strong>Query Log:</strong></p>\n\n<blockquote>\n<pre><code> 188 Prepare SELECT * FROM awa_user WHERE username =?\n 188 Execute SELECT * FROM awa_user WHERE username ='\\'\\'1\\'\\''\n 188 Quit\n</code></pre>\n</blockquote>\n\n<h3>It's clear that a prepared statement is also escaping the data, nothing else.</h3>\n\n<p>As also mentioned in the above statement,</p>\n\n<blockquote>\n <p>The automatic escaping of values within the server is sometimes considered a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly</p>\n</blockquote>\n\n<p>Therefore, this proves that data validation such as <code>intval()</code> is a good idea for integer values before sending any query. In addition, preventing malicious user data before sending the query is <strong>a correct and valid approach</strong>.</p>\n\n<p>Please see this question for more detail: <em><a href=\"https://stackoverflow.com/questions/18026088/pdo-sends-raw-query-to-mysql-while-mysqli-sends-prepared-query-both-produce-the\">PDO sends raw query to MySQL while Mysqli sends prepared query, both produce the same result</a></em></p>\n\n<p>References:</p>\n\n<ol>\n<li><a href=\"http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/#UnionInjections\" rel=\"noreferrer\">SQL Injection Cheat Sheet</a></li>\n<li><a href=\"https://www.owasp.org/index.php/SQL_Injection\" rel=\"noreferrer\">SQL Injection</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Information_security\" rel=\"noreferrer\">Information security</a></li>\n<li><a href=\"http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/security-principles.html\" rel=\"noreferrer\">Security Principles</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Data_validation\" rel=\"noreferrer\">Data validation</a></li>\n</ol>\n" }, { "answer_id": 15805869, "author": "5ervant - techintel.github.io", "author_id": 2007055, "author_profile": "https://Stackoverflow.com/users/2007055", "pm_score": 7, "selected": false, "text": "<p><strong>Warning: the approach described in this answer only applies to very specific scenarios and isn't secure since SQL injection attacks do not only rely on being able to inject <code>X=Y</code>.</strong></p>\n\n<p>If the attackers are trying to hack into the form via PHP's <code>$_GET</code> variable or with the URL's query string, you would be able to catch them if they're not secure.</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ([0-9]+)=([0-9]+)\nRewriteRule ^(.*) ^/track.php\n</code></pre>\n\n<p>Because <code>1=1</code>, <code>2=2</code>, <code>1=2</code>, <code>2=1</code>, <code>1+1=2</code>, etc... are the common questions to an SQL database of an attacker. Maybe also it's used by many hacking applications.</p>\n\n<p>But you must be careful, that you must not rewrite a safe query from your site. The code above is giving you a tip, to rewrite or redirect <em>(it depends on you)</em> that hacking-specific dynamic query string into a page that will store the attacker's <a href=\"http://en.wikipedia.org/wiki/IP_address\" rel=\"noreferrer\">IP address</a>, or EVEN THEIR COOKIES, history, browser, or any other sensitive information, so you can deal with them later by banning their account or contacting authorities.</p>\n" }, { "answer_id": 16466714, "author": "Danijel", "author_id": 2352773, "author_profile": "https://Stackoverflow.com/users/2352773", "pm_score": 8, "selected": false, "text": "<blockquote>\n<p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"nofollow noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead.</p>\n</blockquote>\n<p>A few guidelines for escaping special characters in SQL statements.</p>\n<p>Don't use <a href=\"http://www.php.net/manual/en/intro.mysql.php\" rel=\"nofollow noreferrer\">MySQL</a>. This extension is deprecated. Use <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">MySQLi</a> or <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a> instead.</p>\n<p><strong>MySQLi</strong></p>\n<p>For manually escaping special characters in a string you can use the <a href=\"http://www.php.net/manual/en/mysqli.real-escape-string.php\" rel=\"nofollow noreferrer\">mysqli_real_escape_string</a> function. The function will not work properly unless the correct character set is set with <a href=\"http://www.php.net/manual/en/mysqli.set-charset.php\" rel=\"nofollow noreferrer\">mysqli_set_charset</a>.</p>\n<p>Example:</p>\n<pre><code>$mysqli = new mysqli('host', 'user', 'password', 'database');\n$mysqli-&gt;set_charset('charset');\n\n$string = $mysqli-&gt;real_escape_string($string);\n$mysqli-&gt;query(&quot;INSERT INTO table (column) VALUES ('$string')&quot;);\n</code></pre>\n<p>For automatic escaping of values with prepared statements, use <a href=\"http://www.php.net/manual/en/mysqli.prepare.php\" rel=\"nofollow noreferrer\">mysqli_prepare</a>, and <a href=\"http://www.php.net/manual/en/mysqli-stmt.bind-param.php\" rel=\"nofollow noreferrer\">mysqli_stmt_bind_param</a> where types for the corresponding bind variables must be provided for an appropriate conversion:</p>\n<p>Example:</p>\n<pre><code>$stmt = $mysqli-&gt;prepare(&quot;INSERT INTO table (column1, column2) VALUES (?,?)&quot;);\n\n$stmt-&gt;bind_param(&quot;is&quot;, $integer, $string);\n\n$stmt-&gt;execute();\n</code></pre>\n<p>No matter if you use prepared statements or <code>mysqli_real_escape_string</code>, you always have to know the type of input data you're working with.</p>\n<p>So if you use a prepared statement, you must specify the types of the variables for <code>mysqli_stmt_bind_param</code> function.</p>\n<p>And the use of <code>mysqli_real_escape_string</code> is for, as the name says, escaping special characters in a string, so it will not make integers safe. The purpose of this function is to prevent breaking the strings in SQL statements, and the damage to the database that it could cause. <code>mysqli_real_escape_string</code> is a useful function when used properly, especially when combined with <code>sprintf</code>.</p>\n<p>Example:</p>\n<pre><code>$string = &quot;x' OR name LIKE '%John%&quot;;\n$integer = '5 OR id != 0';\n\n$query = sprintf( &quot;SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d&quot;, $mysqli-&gt;real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email ='x\\' OR name LIKE \\'%John%' AND id = 5\n\n$integer = '99999999999999999999';\n$query = sprintf(&quot;SELECT id, email, pass, name FROM members WHERE email ='%s' AND id = %d&quot;, $mysqli-&gt;real_escape_string($string), $integer);\n\necho $query;\n// SELECT id, email, pass, name FROM members WHERE email ='x\\' OR name LIKE \\'%John%' AND id = 2147483647\n</code></pre>\n" }, { "answer_id": 17305423, "author": "Deepak Thomas", "author_id": 849829, "author_profile": "https://Stackoverflow.com/users/849829", "pm_score": 7, "selected": false, "text": "<p>A simple way would be to use a PHP framework like <a href=\"http://en.wikipedia.org/wiki/Codeigniter#CodeIgniter\" rel=\"noreferrer\">CodeIgniter</a> or <a href=\"https://laravel.com/\" rel=\"noreferrer\">Laravel</a> which have inbuilt features like filtering and active-record so that you don't have to worry about these nuances.</p>\n" }, { "answer_id": 21179234, "author": "Rakesh Sharma", "author_id": 878888, "author_profile": "https://Stackoverflow.com/users/878888", "pm_score": 7, "selected": false, "text": "<blockquote>\n <p><strong>Deprecated Warning:</strong>\n This answer's sample code (like the question's sample code) uses PHP's <code>MySQL</code> extension, which was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0.</p>\n \n <p><strong>Security Warning</strong>: This answer is not in line with security best practices. <a href=\"https://paragonie.com/blog/2015/05/preventing-sql-injection-in-php-applications-easy-and-definitive-guide\" rel=\"noreferrer\">Escaping is inadequate to prevent SQL injection</a>, use <em>prepared statements</em> instead. Use the strategy outlined below at your own risk. (Also, <code>mysql_real_escape_string()</code> was removed in PHP 7.)</p>\n</blockquote>\n\n<p>Using <a href=\"http://in3.php.net/pdo\" rel=\"noreferrer\">PDO</a> and <a href=\"http://in3.php.net/mysqli\" rel=\"noreferrer\">MYSQLi</a> is a good practice to prevent SQL injections, but if you really want to work with MySQL functions and queries, it would be better to use</p>\n\n<p><a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"noreferrer\">mysql_real_escape_string</a></p>\n\n<pre><code>$unsafe_variable = mysql_real_escape_string($_POST['user_input']);\n</code></pre>\n\n<p>There are more abilities to prevent this: like identify - if the input is a string, number, char or array, there are so many inbuilt functions to detect this. Also, it would be better to use these functions to check input data.</p>\n\n<p><a href=\"http://in3.php.net/is_string\" rel=\"noreferrer\">is_string</a></p>\n\n<pre><code>$unsafe_variable = (is_string($_POST['user_input']) ? $_POST['user_input'] : '');\n</code></pre>\n\n<p><a href=\"http://in3.php.net/manual/en/function.is-numeric.php\" rel=\"noreferrer\">is_numeric</a></p>\n\n<pre><code>$unsafe_variable = (is_numeric($_POST['user_input']) ? $_POST['user_input'] : '');\n</code></pre>\n\n<p>And it is so much better to use those functions to check input data with <code>mysql_real_escape_string</code>.</p>\n" }, { "answer_id": 21449836, "author": "Chintan Gor", "author_id": 2125924, "author_profile": "https://Stackoverflow.com/users/2125924", "pm_score": 7, "selected": false, "text": "<p>There are so many answers for <strong>PHP and MySQL</strong>, but here is code for <strong>PHP and Oracle</strong> for preventing SQL injection as well as regular use of oci8 drivers:</p>\n\n<pre><code>$conn = oci_connect($username, $password, $connection_string);\n$stmt = oci_parse($conn, 'UPDATE table SET field = :xx WHERE ID = 123');\noci_bind_by_name($stmt, ':xx', $fieldval);\noci_execute($stmt);\n</code></pre>\n" }, { "answer_id": 21864784, "author": "Calmarius", "author_id": 58805, "author_profile": "https://Stackoverflow.com/users/58805", "pm_score": 6, "selected": false, "text": "<p>I've written this little function several years ago:</p>\n\n<pre><code>function sqlvprintf($query, $args)\n{\n global $DB_LINK;\n $ctr = 0;\n ensureConnection(); // Connect to database if not connected already.\n $values = array();\n foreach ($args as $value)\n {\n if (is_string($value))\n {\n $value = \"'\" . mysqli_real_escape_string($DB_LINK, $value) . \"'\";\n }\n else if (is_null($value))\n {\n $value = 'NULL';\n }\n else if (!is_int($value) &amp;&amp; !is_float($value))\n {\n die('Only numeric, string, array and NULL arguments allowed in a query. Argument '.($ctr+1).' is not a basic type, it\\'s type is '. gettype($value). '.');\n }\n $values[] = $value;\n $ctr++;\n }\n $query = preg_replace_callback(\n '/{(\\\\d+)}/', \n function($match) use ($values)\n {\n if (isset($values[$match[1]]))\n {\n return $values[$match[1]];\n }\n else\n {\n return $match[0];\n }\n },\n $query\n );\n return $query;\n}\n\nfunction runEscapedQuery($preparedQuery /*, ...*/)\n{\n $params = array_slice(func_get_args(), 1);\n $results = runQuery(sqlvprintf($preparedQuery, $params)); // Run query and fetch results. \n return $results;\n}\n</code></pre>\n\n<p>This allows running statements in an one-liner C#-ish String.Format like:</p>\n\n<pre><code>runEscapedQuery(\"INSERT INTO Whatever (id, foo, bar) VALUES ({0}, {1}, {2})\", $numericVar, $stringVar1, $stringVar2);\n</code></pre>\n\n<p>It escapes considering the variable type. If you try to parameterize table, column names, it would fail as it puts every string in quotes which is an invalid syntax.</p>\n\n<p>SECURITY UPDATE: The previous <code>str_replace</code> version allowed injections by adding {#} tokens into user data. This <code>preg_replace_callback</code> version doesn't cause problems if the replacement contains these tokens.</p>\n" }, { "answer_id": 22520937, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 7, "selected": false, "text": "<p>A good idea is to use an <a href=\"https://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"noreferrer\">object-relational mapper</a> like <a href=\"http://j4mie.github.io/idiormandparis/\" rel=\"noreferrer\">Idiorm</a>:</p>\n\n<pre><code>$user = ORM::for_table('user')\n-&gt;where_equal('username', 'j4mie')\n-&gt;find_one();\n\n$user-&gt;first_name = 'Jamie';\n$user-&gt;save();\n\n$tweets = ORM::for_table('tweet')\n -&gt;select('tweet.*')\n -&gt;join('user', array(\n 'user.id', '=', 'tweet.user_id'\n ))\n -&gt;where_equal('user.username', 'j4mie')\n -&gt;find_many();\n\nforeach ($tweets as $tweet) {\n echo $tweet-&gt;text;\n}\n</code></pre>\n\n<p>It not only saves you from SQL injections, but from syntax errors too! It also supports collections of models with method chaining to filter or apply actions to multiple results at once and multiple connections.</p>\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/60174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to [SQL injection](https://stackoverflow.com/a/332367/), like in the following example: ```php $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); ``` That's because the user can input something like `value'); DROP TABLE table;--`, and the query becomes: ``` INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') ``` What can be done to prevent this from happening?
The *correct* way to avoid SQL injection attacks, no matter which database you use, is to **separate the data from SQL**, so that data stays data and will **never be interpreted** as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't *fully* understand the details, you should always **use prepared statements and parameterized queries.** These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL. You basically have two options to achieve this: 1. Using [**PDO**](http://php.net/manual/en/book.pdo.php) (for any supported database driver): ```php $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) { // Do something with $row } ``` 2. Using [**MySQLi**](http://php.net/manual/en/book.mysqli.php) (for MySQL): ```php $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Do something with $row } ``` If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, `pg_prepare()` and `pg_execute()` for PostgreSQL). PDO is the universal option. --- Correctly setting up the connection ----------------------------------- #### PDO Note that when using **PDO** to access a MySQL database *real* prepared statements are **not used by default**. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using **PDO** is: ```php $dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ``` In the above example, the error mode isn't strictly necessary, **but it is advised to add it**. This way PDO will inform you of all MySQL errors by means of throwing the `PDOException`. What is **mandatory**, however, is the first `setAttribute()` line, which tells PDO to disable emulated prepared statements and use *real* prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL). Although you can set the `charset` in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) [silently ignored the charset parameter](http://php.net/manual/en/ref.pdo-mysql.connection.php) in the DSN. #### Mysqli For mysqli we have to follow the same routine: ```php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting $dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test'); $dbConnection->set_charset('utf8mb4'); // charset ``` --- Explanation ----------- The SQL statement you pass to `prepare` is parsed and compiled by the database server. By specifying parameters (either a `?` or a named parameter like `:name` in the example above) you tell the database engine where you want to filter on. Then when you call `execute`, the prepared statement is combined with the parameter values you specify. The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the `$name` variable contains `'Sarah'; DELETE FROM employees` the result would simply be a search for the string `"'Sarah'; DELETE FROM employees"`, and you will not end up with [an empty table](http://xkcd.com/327/). Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains. Oh, and since you asked about how to do it for an insert, here's an example (using PDO): ```php $preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]); ``` --- Can prepared statements be used for dynamic queries? ---------------------------------------------------- While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized. For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values. ``` // Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC') { $dir = 'ASC'; } ```
60,204
<p>I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:</p> <p><a href="/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types">What is the best way to handle multiple permission types?</a></p> <p>It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer</p> <p>I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.</p> <p>Here is the original answer in the off chance the other question gets deleted:</p> <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> <pre><code>[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 } </code></pre> <p>Then, you can combine several permissions using the AND bitwise operator. </p> <p>For example, if a user can view &amp; 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).</p> <p>Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."</p>
[ { "answer_id": 60206, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 2, "selected": false, "text": "<p>Actually, this is how we determine authority within a fairly large web application that I'm the DBA for. </p>\n\n<p>If you are going to do something like this, you'll really benefit from having a <a href=\"http://snippets.dzone.com/posts/show/1184\" rel=\"nofollow noreferrer\">numbers table</a>. It will make your calculations much faster.</p>\n\n<p>The basic setup includes the following tables:</p>\n\n<ol>\n<li>Groups - for doing many to many of users and security points</li>\n<li>Security points - which contain a value for anonymous authorization and one for authenticated users who are not part of a separate group</li>\n<li>Group security point join table </li>\n<li>A special BitMask numbers table that contains entries for the ^2 values. Thus there is one entry for 2 (2) and two entries for three (2 and 1). This keeps us from having to calculate values each time.</li>\n</ol>\n\n<p>First we determine if the user is logged in. If they aren't we return the anonymous authorization for the security point.</p>\n\n<p>Next we determine if the user is a member of any groups associated with the security point through a simple <code>EXISTS</code> using a <code>JOIN</code>. If they aren't we return the value associated with authenticated user. Most of the anonymous and authenticated defaults are set to 1 on our system because we require you to belong to specific groups.</p>\n\n<blockquote>\n <p><strong>Note:</strong> If an anonymous user gets a no access, the interface throws them over to a log in box to allow them to log in and try again.</p>\n</blockquote>\n\n<p>If the user <em>is</em> a member of one or more groups, then we select distinct values from the BitMask table for each of the values defined for the groups. For example, if you belonged to three groups and had one authorization level of 8, one with 12 and the last with 36, our select against the Bit Mask table would return 8, 8 and 4, and 4 and 32 respectively. By doing a distinct we get the number 4, 8 and 32 which correctly bit masks to 101100.</p>\n\n<p>That value is returned as the users authorization level and processed by the web site.</p>\n\n<p>Make sense?</p>\n" }, { "answer_id": 60228, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 4, "selected": true, "text": "<p>You use bitwise operations. The pseudo-code would be something like:</p>\n\n<pre><code>bool HasPermission(User user, Permission permission) {\n return (user.Permission &amp; permission) != 0;\n}\n\nvoid SetPermission(User user, Permission permission) {\n user.Permission |= permission;\n}\n\nvoid ClearPermission(User user, Permission permission) {\n user.Permission &amp;= ~permission;\n}\n</code></pre>\n\n<p>Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type. The same applies to the User.Permission field.</p>\n\n<p>If those operators (&amp;, |=, and &amp;=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR).</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question: [What is the best way to handle multiple permission types?](/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types) It sounds like an innovative approach, so instead of a many-to-many relationship users\_to\_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well. Here is the original answer in the off chance the other question gets deleted: "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."
You use bitwise operations. The pseudo-code would be something like: ``` bool HasPermission(User user, Permission permission) { return (user.Permission & permission) != 0; } void SetPermission(User user, Permission permission) { user.Permission |= permission; } void ClearPermission(User user, Permission permission) { user.Permission &= ~permission; } ``` Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type. The same applies to the User.Permission field. If those operators (&, |=, and &=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR).
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?</p>
[ { "answer_id": 60211, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 12, "selected": true, "text": "<p>The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the <a href=\"https://www.python.org/dev/peps/pep-0634/\" rel=\"noreferrer\"><code>match</code>-<code>case</code></a> statement which provides a first-class implementation of a &quot;switch&quot; for Python. For example:</p>\n<pre><code>def f(x):\n match x:\n case 'a':\n return 1\n case 'b':\n return 2\n case _:\n return 0 # 0 is the default case if x is not found\n</code></pre>\n<p>The <code>match</code>-<code>case</code> statement is considerably more powerful than this simple example.</p>\n<hr />\n<p>You could use a dictionary:</p>\n<pre><code>def f(x):\n return {\n 'a': 1,\n 'b': 2,\n }[x]\n</code></pre>\n" }, { "answer_id": 60215, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 9, "selected": false, "text": "<p>I've always liked doing it this way</p>\n\n<pre><code>result = {\n 'a': lambda x: x * 5,\n 'b': lambda x: x + 7,\n 'c': lambda x: x - 2\n}[value](x)\n</code></pre>\n\n<p><a href=\"http://blog.simonwillison.net/post/57956755106/switch\" rel=\"noreferrer\">From here</a></p>\n" }, { "answer_id": 60216, "author": "Eugene", "author_id": 1155, "author_profile": "https://Stackoverflow.com/users/1155", "pm_score": 2, "selected": false, "text": "<p>If you are really just returning a predetermined, fixed value, you could create a dictionary with all possible input indexes as the keys, along with their corresponding values. Also, you might not really want a function to do this - unless you're computing the return value somehow.</p>\n\n<p>Oh, and if you feel like doing something switch-like, see <a href=\"https://web.archive.org/web/20120216013404/http://www.mustap.com/pythonzone_post_224_python-switch-statement?\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 60236, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 9, "selected": false, "text": "<p>In addition to the dictionary methods (which I really like, BTW), you can also use <code>if</code>-<code>elif</code>-<code>else</code> to obtain the <code>switch</code>/<code>case</code>/<code>default</code> functionality:</p>\n\n<pre><code>if x == 'a':\n # Do the thing\nelif x == 'b':\n # Do the other thing\nif x in 'bc':\n # Fall-through by not using elif, but now the default case includes case 'a'!\nelif x in 'xyz':\n # Do yet another thing\nelse:\n # Do the default\n</code></pre>\n\n<p>This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the <code>break</code> statement, but you can have a more complicated test. Its formatting is nicer than a series of nested <code>if</code>s, even though functionally that's what it is closer to.</p>\n" }, { "answer_id": 60243, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>There's a pattern that I learned from Twisted Python code.</p>\n\n<pre><code>class SMTP:\n def lookupMethod(self, command):\n return getattr(self, 'do_' + command.upper(), None)\n def do_HELO(self, rest):\n return 'Howdy ' + rest\n def do_QUIT(self, rest):\n return 'Bye'\n\nSMTP().lookupMethod('HELO')('foo.bar.com') # =&gt; 'Howdy foo.bar.com'\nSMTP().lookupMethod('QUIT')('') # =&gt; 'Bye'\n</code></pre>\n\n<p>You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have <code>state_</code> methods, and dispatch on <code>self.state</code>. This switch can be cleanly extended by inheriting from base class and defining your own <code>do_</code> methods. Often times you won't even have <code>do_</code> methods in the base class.</p>\n\n<p><em>Edit: how exactly is that used</em></p>\n\n<p>In case of SMTP you will receive <code>HELO</code> from the wire. The relevant code (from <code>twisted/mail/smtp.py</code>, modified for our case) looks like this</p>\n\n<pre><code>class SMTP:\n # ...\n\n def do_UNKNOWN(self, rest):\n raise NotImplementedError, 'received unknown command'\n\n def state_COMMAND(self, line):\n line = line.strip()\n parts = line.split(None, 1)\n if parts:\n method = self.lookupMethod(parts[0]) or self.do_UNKNOWN\n if len(parts) == 2:\n return method(parts[1])\n else:\n return method('')\n else:\n raise SyntaxError, 'bad syntax'\n\nSMTP().state_COMMAND(' HELO foo.bar.com ') # =&gt; Howdy foo.bar.com\n</code></pre>\n\n<p>You'll receive <code>' HELO foo.bar.com '</code> (or you might get <code>'QUIT'</code> or <code>'RCPT TO: foo'</code>). This is tokenized into <code>parts</code> as <code>['HELO', 'foo.bar.com']</code>. The actual method lookup name is taken from <code>parts[0]</code>.</p>\n\n<p>(The original method is also called <code>state_COMMAND</code>, because it uses the same pattern to implement a state machine, i.e. <code>getattr(self, 'state_' + self.mode)</code>)</p>\n" }, { "answer_id": 102990, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 4, "selected": false, "text": "<p>Expanding on the &quot;dict as switch&quot; idea. If you want to use a default value for your switch:</p>\n<pre><code>def f(x):\n try:\n return {\n 'a': 1,\n 'b': 2,\n }[x]\n except KeyError:\n return 'default'\n</code></pre>\n" }, { "answer_id": 103081, "author": "Nick", "author_id": 3233, "author_profile": "https://Stackoverflow.com/users/3233", "pm_score": 11, "selected": false, "text": "<p>If you'd like defaults, you could use the dictionary <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"noreferrer\"><code>get(key[, default])</code></a> function:</p>\n<pre><code>def f(x):\n return {\n 'a': 1,\n 'b': 2\n }.get(x, 9) # 9 will be returned default if x is not found\n</code></pre>\n" }, { "answer_id": 3129619, "author": "thomasf1", "author_id": 377671, "author_profile": "https://Stackoverflow.com/users/377671", "pm_score": 4, "selected": false, "text": "<p>The solutions I use: </p>\n\n<p>A combination of 2 of the solutions posted here, which is relatively easy to read and supports defaults.</p>\n\n<pre><code>result = {\n 'a': lambda x: x * 5,\n 'b': lambda x: x + 7,\n 'c': lambda x: x - 2\n}.get(whatToUse, lambda x: x - 22)(value)\n</code></pre>\n\n<p>where</p>\n\n<pre><code>.get('c', lambda x: x - 22)(23)\n</code></pre>\n\n<p>looks up <code>\"lambda x: x - 2\"</code> in the dict and uses it with <code>x=23</code> </p>\n\n<pre><code>.get('xxx', lambda x: x - 22)(44)\n</code></pre>\n\n<p>doesn't find it in the dict and uses the default <code>\"lambda x: x - 22\"</code> with <code>x=44</code>.</p>\n" }, { "answer_id": 3828986, "author": "GeeF", "author_id": 190001, "author_profile": "https://Stackoverflow.com/users/190001", "pm_score": 5, "selected": false, "text": "<p>Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:</p>\n<pre><code>result = {\n 'a': obj.increment(x),\n 'b': obj.decrement(x)\n}.get(value, obj.default(x))\n</code></pre>\n<p>Here Python evaluates all methods in the dictionary.</p>\n<p>So even if your value is 'a', the object will get incremented <strong>and</strong> decremented by x.</p>\n<p>Solution:</p>\n<pre><code>func, args = {\n 'a' : (obj.increment, (x,)),\n 'b' : (obj.decrement, (x,)),\n}.get(value, (obj.default, (x,)))\n\nresult = func(*args)\n</code></pre>\n<p>So you get a list containing a function and its arguments. This way, only the function pointer and the argument list get returned, <em>not</em> evaluated. 'result' then evaluates the returned function call.</p>\n" }, { "answer_id": 4367749, "author": "elp", "author_id": 532453, "author_profile": "https://Stackoverflow.com/users/532453", "pm_score": 4, "selected": false, "text": "<p>If you're searching extra-statement, as &quot;switch&quot;, I built a Python module that extends Python. It's called <a href=\"https://web.archive.org/web/20111103124355/http://elp.chronocv.fr/articles.php?lng=en&amp;pg=19\" rel=\"nofollow noreferrer\">ESPY</a> as &quot;Enhanced Structure for Python&quot; and it's available for both Python 2.x and Python 3.x.</p>\n<p>For example, in this case, a switch statement could be performed by the following code:</p>\n<pre><code>macro switch(arg1):\n while True:\n cont=False\n val=%arg1%\n socket case(arg2):\n if val==%arg2% or cont:\n cont=True\n socket\n socket else:\n socket\n break\n</code></pre>\n<p>That can be used like this:</p>\n<pre><code>a=3\nswitch(a):\n case(0):\n print(&quot;Zero&quot;)\n case(1):\n print(&quot;Smaller than 2&quot;):\n break\n else:\n print (&quot;greater than 1&quot;)\n</code></pre>\n<p>So espy translate it in Python as:</p>\n<pre><code>a=3\nwhile True:\n cont=False\n if a==0 or cont:\n cont=True\n print (&quot;Zero&quot;)\n if a==1 or cont:\n cont=True\n print (&quot;Smaller than 2&quot;)\n break\n print (&quot;greater than 1&quot;)\n break\n</code></pre>\n" }, { "answer_id": 6606504, "author": "adamh", "author_id": 832936, "author_profile": "https://Stackoverflow.com/users/832936", "pm_score": 7, "selected": false, "text": "<pre><code>class switch(object):\n value = None\n def __new__(class_, value):\n class_.value = value\n return True\n\ndef case(*args):\n return any((arg == switch.value for arg in args))\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>while switch(n):\n if case(0):\n print \"You typed zero.\"\n break\n if case(1, 4, 9):\n print \"n is a perfect square.\"\n break\n if case(2):\n print \"n is an even number.\"\n if case(2, 3, 5, 7):\n print \"n is a prime number.\"\n break\n if case(6, 8):\n print \"n is an even number.\"\n break\n print \"Only single-digit numbers are allowed.\"\n break\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>n = 2\n#Result:\n#n is an even number.\n#n is a prime number.\nn = 11\n#Result:\n#Only single-digit numbers are allowed.\n</code></pre>\n" }, { "answer_id": 6606540, "author": "John Doe", "author_id": 832391, "author_profile": "https://Stackoverflow.com/users/832391", "pm_score": 6, "selected": false, "text": "<p>My favorite one is a really nice <a href=\"http://code.activestate.com/recipes/410692/\" rel=\"noreferrer\">recipe</a>. It's the closest one I've seen to actual switch case statements, especially in features.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class switch(object):\n def __init__(self, value):\n self.value = value\n self.fall = False\n\n def __iter__(self):\n &quot;&quot;&quot;Return the match method once, then stop&quot;&quot;&quot;\n yield self.match\n raise StopIteration\n \n def match(self, *args):\n &quot;&quot;&quot;Indicate whether or not to enter a case suite&quot;&quot;&quot;\n if self.fall or not args:\n return True\n elif self.value in args: # changed for v1.5, see below\n self.fall = True\n return True\n else:\n return False\n</code></pre>\n<p>Here's an example:</p>\n<pre class=\"lang-py prettyprint-override\"><code># The following example is pretty much the exact use-case of a dictionary,\n# but is included for its simplicity. Note that you can include statements\n# in each suite.\nv = 'ten'\nfor case in switch(v):\n if case('one'):\n print 1\n break\n if case('two'):\n print 2\n break\n if case('ten'):\n print 10\n break\n if case('eleven'):\n print 11\n break\n if case(): # default, could also just omit condition or 'if True'\n print &quot;something else!&quot;\n # No need to break here, it'll stop anyway\n\n# break is used here to look as much like the real thing as possible, but\n# elif is generally just as good and more concise.\n\n# Empty suites are considered syntax errors, so intentional fall-throughs\n# should contain 'pass'\nc = 'z'\nfor case in switch(c):\n if case('a'): pass # only necessary if the rest of the suite is empty\n if case('b'): pass\n # ...\n if case('y'): pass\n if case('z'):\n print &quot;c is lowercase!&quot;\n break\n if case('A'): pass\n # ...\n if case('Z'):\n print &quot;c is uppercase!&quot;\n break\n if case(): # default\n print &quot;I dunno what c was!&quot;\n\n# As suggested by Pierre Quentel, you can even expand upon the\n# functionality of the classic 'case' statement by matching multiple\n# cases in a single shot. This greatly benefits operations such as the\n# uppercase/lowercase example above:\nimport string\nc = 'A'\nfor case in switch(c):\n if case(*string.lowercase): # note the * for unpacking as arguments\n print &quot;c is lowercase!&quot;\n break\n if case(*string.uppercase):\n print &quot;c is uppercase!&quot;\n break\n if case('!', '?', '.'): # normal argument passing style also applies\n print &quot;c is a sentence terminator!&quot;\n break\n if case(): # default\n print &quot;I dunno what c was!&quot;\n</code></pre>\n<p>Some of the comments indicated that a context manager solution using <code>with foo as case</code> rather than <code>for case in foo</code> might be cleaner, and for large switch statements the linear rather than quadratic behavior might be a nice touch. Part of the value in this answer with a for loop is the ability to have breaks and fallthrough, and if we're willing to play with our choice of keywords a little bit we can get that in a context manager too:</p>\n<pre><code>class Switch:\n def __init__(self, value):\n self.value = value\n self._entered = False\n self._broken = False\n self._prev = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n return False # Allows a traceback to occur\n\n def __call__(self, *values):\n if self._broken:\n return False\n \n if not self._entered:\n if values and self.value not in values:\n return False\n self._entered, self._prev = True, values\n return True\n \n if self._prev is None:\n self._prev = values\n return True\n \n if self._prev != values:\n self._broken = True\n return False\n \n if self._prev == values:\n self._prev = None\n return False\n \n @property\n def default(self):\n return self()\n</code></pre>\n<p>Here's an example:</p>\n<pre><code># Prints 'bar' then 'baz'.\nwith Switch(2) as case:\n while case(0):\n print('foo')\n while case(1, 2, 3):\n print('bar')\n while case(4, 5):\n print('baz')\n break\n while case.default:\n print('default')\n break\n</code></pre>\n" }, { "answer_id": 10272369, "author": "Asher", "author_id": 1164146, "author_profile": "https://Stackoverflow.com/users/1164146", "pm_score": 5, "selected": false, "text": "<p>If you have a complicated case block you can consider using a function dictionary lookup table...</p>\n<p>If you haven't done this before it's a good idea to step into your debugger and view exactly how the dictionary looks up each function.</p>\n<p>NOTE: Do <em>not</em> use &quot;()&quot; inside the case/dictionary lookup or it will call each of your functions as the dictionary / case block is created. Remember this because you only want to call each function once using a hash style lookup.</p>\n<pre><code>def first_case():\n print &quot;first&quot;\n\ndef second_case():\n print &quot;second&quot;\n\ndef third_case():\n print &quot;third&quot;\n\nmycase = {\n'first': first_case, #do not use ()\n'second': second_case, #do not use ()\n'third': third_case #do not use ()\n}\nmyfunc = mycase['first']\nmyfunc()\n</code></pre>\n" }, { "answer_id": 13239503, "author": "emu", "author_id": 797845, "author_profile": "https://Stackoverflow.com/users/797845", "pm_score": 3, "selected": false, "text": "<pre><code>def f(x):\n return 1 if x == 'a' else\\\n 2 if x in 'bcd' else\\\n 0 #default\n</code></pre>\n\n<p>Short and easy to read, has a default value and supports expressions in both conditions and return values.</p>\n\n<p>However, it is less efficient than the solution with a dictionary. For example, Python has to scan through all the conditions before returning the default value.</p>\n" }, { "answer_id": 14688688, "author": "Alden", "author_id": 585278, "author_profile": "https://Stackoverflow.com/users/585278", "pm_score": 2, "selected": false, "text": "<p>Just mapping some a key to some code is not really an issue as most people have shown using the dict. The real trick is trying to emulate the whole drop through and break thing. I don't think I've ever written a case statement where I used that &quot;feature&quot;. Here's a go at drop through.</p>\n<pre><code>def case(list): reduce(lambda b, f: (b | f[0], {False:(lambda:None),True:f[1]}[b | f[0]]())[0], list, False)\n\ncase([\n (False, lambda:print(5)),\n (True, lambda:print(4))\n])\n</code></pre>\n<p>I was really imagining it as a single statement. I hope you'll pardon the silly formatting.</p>\n<pre><code>reduce(\n initializer=False,\n function=(lambda b, f:\n ( b | f[0]\n , { False: (lambda:None)\n , True : f[1]\n }[b | f[0]]()\n )[0]\n ),\n iterable=[\n (False, lambda:print(5)),\n (True, lambda:print(4))\n ]\n)\n</code></pre>\n<p>I hope that's valid Python code. It should give you drop through. Of course the Boolean checks could be expressions and if you wanted them to be evaluated lazily you could wrap them all in a lambda. It wouldn't be to hard to make it accept after executing some of the items in the list either. Just make the tuple (bool, bool, function) where the second bool indicates whether or not to break or drop through.</p>\n" }, { "answer_id": 16964129, "author": "Harry247", "author_id": 2392636, "author_profile": "https://Stackoverflow.com/users/2392636", "pm_score": 1, "selected": false, "text": "<p>Also use the <em>list</em> for storing the cases, and call corresponding the function by select -</p>\n<pre><code>cases = ['zero()', 'one()', 'two()', 'three()']\n\ndef zero():\n print &quot;method for 0 called...&quot;\ndef one():\n print &quot;method for 1 called...&quot;\ndef two():\n print &quot;method for 2 called...&quot;\ndef three():\n print &quot;method for 3 called...&quot;\n\ni = int(raw_input(&quot;Enter choice between 0-3 &quot;))\n\nif(i&lt;=len(cases)):\n exec(cases[i])\nelse:\n print &quot;wrong choice&quot;\n</code></pre>\n<p>Also explained at <a href=\"http://screwdesk.com/python-switch-case-alternative/\" rel=\"nofollow noreferrer\">screwdesk</a>.</p>\n" }, { "answer_id": 17865871, "author": "William H. Hooper", "author_id": 2619926, "author_profile": "https://Stackoverflow.com/users/2619926", "pm_score": 3, "selected": false, "text": "<p>Defining:</p>\n\n<pre><code>def switch1(value, options):\n if value in options:\n options[value]()\n</code></pre>\n\n<p>allows you to use a fairly straightforward syntax, with the cases bundled into a map:</p>\n\n<pre><code>def sample1(x):\n local = 'betty'\n switch1(x, {\n 'a': lambda: print(\"hello\"),\n 'b': lambda: (\n print(\"goodbye,\" + local),\n print(\"!\")),\n })\n</code></pre>\n\n<p>I kept trying to redefine switch in a way that would let me get rid of the \"lambda:\", but gave up. Tweaking the definition:</p>\n\n<pre><code>def switch(value, *maps):\n options = {}\n for m in maps:\n options.update(m)\n if value in options:\n options[value]()\n elif None in options:\n options[None]()\n</code></pre>\n\n<p>Allowed me to map multiple cases to the same code, and to supply a default option:</p>\n\n<pre><code>def sample(x):\n switch(x, {\n _: lambda: print(\"other\") \n for _ in 'cdef'\n }, {\n 'a': lambda: print(\"hello\"),\n 'b': lambda: (\n print(\"goodbye,\"),\n print(\"!\")),\n None: lambda: print(\"I dunno\")\n })\n</code></pre>\n\n<p>Each replicated case has to be in its own dictionary; switch() consolidates the dictionaries before looking up the value. It's still uglier than I'd like, but it has the basic efficiency of using a hashed lookup on the expression, rather than a loop through all the keys.</p>\n" }, { "answer_id": 19335626, "author": "JD Graham", "author_id": 2874221, "author_profile": "https://Stackoverflow.com/users/2874221", "pm_score": 4, "selected": false, "text": "<p>I didn't find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It's really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else's head. The key is simply \"in\" and tuples. Here is the switch statement behavior with fall-through, including RANDOM fall-through.</p>\n\n<pre><code>l = ['Dog', 'Cat', 'Bird', 'Bigfoot',\n 'Dragonfly', 'Snake', 'Bat', 'Loch Ness Monster']\n\nfor x in l:\n if x in ('Dog', 'Cat'):\n x += \" has four legs\"\n elif x in ('Bat', 'Bird', 'Dragonfly'):\n x += \" has wings.\"\n elif x in ('Snake',):\n x += \" has a forked tongue.\"\n else:\n x += \" is a big mystery by default.\"\n print(x)\n\nprint()\n\nfor x in range(10):\n if x in (0, 1):\n x = \"Values 0 and 1 caught here.\"\n elif x in (2,):\n x = \"Value 2 caught here.\"\n elif x in (3, 7, 8):\n x = \"Values 3, 7, 8 caught here.\"\n elif x in (4, 6):\n x = \"Values 4 and 6 caught here\"\n else:\n x = \"Values 5 and 9 caught in default.\"\n print(x)\n</code></pre>\n\n<p>Provides:</p>\n\n<pre><code>Dog has four legs\nCat has four legs\nBird has wings.\nBigfoot is a big mystery by default.\nDragonfly has wings.\nSnake has a forked tongue.\nBat has wings.\nLoch Ness Monster is a big mystery by default.\n\nValues 0 and 1 caught here.\nValues 0 and 1 caught here.\nValue 2 caught here.\nValues 3, 7, 8 caught here.\nValues 4 and 6 caught here\nValues 5 and 9 caught in default.\nValues 4 and 6 caught here\nValues 3, 7, 8 caught here.\nValues 3, 7, 8 caught here.\nValues 5 and 9 caught in default.\n</code></pre>\n" }, { "answer_id": 27212138, "author": "guneysus", "author_id": 1766716, "author_profile": "https://Stackoverflow.com/users/1766716", "pm_score": 3, "selected": false, "text": "<p>I liked <a href=\"https://stackoverflow.com/a/60215/1766716\">Mark Bies's answer</a></p>\n\n<p>Since the <code>x</code> variable must used twice, I modified the lambda functions to parameterless.</p>\n\n<p>I have to run with <code>results[value](value)</code></p>\n\n<pre><code>In [2]: result = {\n ...: 'a': lambda x: 'A',\n ...: 'b': lambda x: 'B',\n ...: 'c': lambda x: 'C'\n ...: }\n ...: result['a']('a')\n ...: \nOut[2]: 'A'\n\nIn [3]: result = {\n ...: 'a': lambda : 'A',\n ...: 'b': lambda : 'B',\n ...: 'c': lambda : 'C',\n ...: None: lambda : 'Nothing else matters'\n\n ...: }\n ...: result['a']()\n ...: \nOut[3]: 'A'\n</code></pre>\n\n<p><strong>Edit:</strong> I noticed that I can use <code>None</code> type with with dictionaries. So this would emulate <code>switch ; case else</code></p>\n" }, { "answer_id": 27746465, "author": "leo", "author_id": 652066, "author_profile": "https://Stackoverflow.com/users/652066", "pm_score": 4, "selected": false, "text": "<p>I found that a common switch structure:</p>\n<pre><code>switch ...parameter...\ncase p1: v1; break;\ncase p2: v2; break;\ndefault: v3;\n</code></pre>\n<p>can be expressed in Python as follows:</p>\n<pre><code>(lambda x: v1 if p1(x) else v2 if p2(x) else v3)\n</code></pre>\n<p>or formatted in a clearer way:</p>\n<pre><code>(lambda x:\n v1 if p1(x) else\n v2 if p2(x) else\n v3)\n</code></pre>\n<p>Instead of being a statement, the Python version is an expression, which evaluates to a value.</p>\n" }, { "answer_id": 30012053, "author": "Ian Bell", "author_id": 4858820, "author_profile": "https://Stackoverflow.com/users/4858820", "pm_score": 6, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>class Switch:\n def __init__(self, value):\n self.value = value\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n return False # Allows a traceback to occur\n\n def __call__(self, *values):\n return self.value in values\n\n\nfrom datetime import datetime\n\nwith Switch(datetime.today().weekday()) as case:\n if case(0):\n # Basic usage of switch\n print(\"I hate mondays so much.\")\n # Note there is no break needed here\n elif case(1,2):\n # This switch also supports multiple conditions (in one line)\n print(\"When is the weekend going to be here?\")\n elif case(3,4):\n print(\"The weekend is near.\")\n else:\n # Default would occur here\n print(\"Let's go have fun!\") # Didn't use case for example purposes\n</code></pre>\n" }, { "answer_id": 30881320, "author": "ChaimG", "author_id": 2529619, "author_profile": "https://Stackoverflow.com/users/2529619", "pm_score": 8, "selected": false, "text": "<p><strong>Python &gt;= 3.10</strong></p>\n<p>Wow, Python 3.10+ now has a <a href=\"https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching\" rel=\"noreferrer\"><code>match</code>/<code>case</code></a> syntax which is like <code>switch/case</code> and more!</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0634/\" rel=\"noreferrer\">PEP 634 -- Structural Pattern Matching</a></p>\n<p><strong>Selected features of <code>match/case</code></strong></p>\n<p>1 - Match values:</p>\n<p>Matching values is similar to a simple <code>switch/case</code> in another language:</p>\n<pre><code>match something:\n case 1 | 2 | 3:\n # Match 1-3.\n case _:\n # Anything else.\n # \n # Match will throw an error if this is omitted \n # and it doesn't match any of the other patterns.\n</code></pre>\n<p>2 - Match structural patterns:</p>\n<pre><code>match something:\n case str() | bytes(): \n # Match a string like object.\n case [str(), int()]:\n # Match a `str` and an `int` sequence \n # (`list` or a `tuple` but not a `set` or an iterator). \n case [_, _]:\n # Match a sequence of 2 variables.\n # To prevent a common mistake, sequence patterns don’t match strings.\n case {&quot;bandwidth&quot;: 100, &quot;latency&quot;: 300}:\n # Match this dict. Extra keys are ignored.\n</code></pre>\n<p>3 - Capture variables</p>\n<p>Parse an object; saving it as variables:</p>\n<pre><code>match something:\n case [name, count]\n # Match a sequence of any two objects and parse them into the two variables.\n case [x, y, *rest]:\n # Match a sequence of two or more objects, \n # binding object #3 and on into the rest variable.\n case bytes() | str() as text:\n # Match any string like object and save it to the text variable.\n</code></pre>\n<p>Capture variables can be useful when parsing data (such as JSON or HTML) that may come in one of a number of different patterns.</p>\n<p>Capture variables is a feature. But it also means that you need to use dotted constants (ex: <code>COLOR.RED</code>) only. Otherwise, the constant will be treated as a capture variable and overwritten.</p>\n<p><a href=\"https://docs.python.org/3.10/tutorial/controlflow.html#match-statements\" rel=\"noreferrer\">More sample usage</a>:</p>\n<pre><code>match something:\n case 0 | 1 | 2:\n # Matches 0, 1 or 2 (value).\n print(&quot;Small number&quot;)\n case [] | [_]:\n # Matches an empty or single value sequence (structure).\n # Matches lists and tuples but not sets.\n print(&quot;A short sequence&quot;)\n case str() | bytes():\n # Something of `str` or `bytes` type (data type).\n print(&quot;Something string-like&quot;)\n case _:\n # Anything not matched by the above.\n print(&quot;Something else&quot;)\n</code></pre>\n<hr />\n<p><strong>Python &lt;= 3.9</strong></p>\n<p>My favorite Python recipe for switch/case was:</p>\n<pre><code>choices = {'a': 1, 'b': 2}\nresult = choices.get(key, 'default')\n</code></pre>\n<p>Short and simple for simple scenarios.</p>\n<p>Compare to 11+ lines of C code:</p>\n<pre><code>// C Language version of a simple 'switch/case'.\nswitch( key ) \n{\n case 'a' :\n result = 1;\n break;\n case 'b' :\n result = 2;\n break;\n default :\n result = -1;\n}\n</code></pre>\n<p>You can even assign multiple variables by using tuples:</p>\n<pre><code>choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}\n(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))\n</code></pre>\n" }, { "answer_id": 31995013, "author": "user5224656", "author_id": 5224656, "author_profile": "https://Stackoverflow.com/users/5224656", "pm_score": 4, "selected": false, "text": "<pre><code># simple case alternative\n\nsome_value = 5.0\n\n# this while loop block simulates a case block\n\n# case\nwhile True:\n\n # case 1\n if some_value &gt; 5:\n print ('Greater than five')\n break\n\n # case 2\n if some_value == 5:\n print ('Equal to five')\n break\n\n # else case 3\n print ( 'Must be less than 5')\n break\n</code></pre>\n" }, { "answer_id": 36079070, "author": "J_Zar", "author_id": 1351609, "author_profile": "https://Stackoverflow.com/users/1351609", "pm_score": 3, "selected": false, "text": "<p>I think the best way is to <strong>use the Python language idioms to keep your code testable</strong>. As showed in previous answers, I use dictionaries to <strong>take advantage of python structures and language</strong> and keep the &quot;case&quot; code isolated in different methods. Below there is a class, but you can use directly a module, globals and functions. The class has methods that <strong>can be tested with isolation</strong>.</p>\n<p>Depending to your needs, you can play with static methods and attributes too.</p>\n<pre><code>class ChoiceManager:\n\n def __init__(self):\n self.__choice_table = \\\n {\n &quot;CHOICE1&quot; : self.my_func1,\n &quot;CHOICE2&quot; : self.my_func2,\n }\n\n def my_func1(self, data):\n pass\n\n def my_func2(self, data):\n pass\n\n def process(self, case, data):\n return self.__choice_table[case](data)\n\nChoiceManager().process(&quot;CHOICE1&quot;, my_data)\n</code></pre>\n<p>It is possible to <strong>take advantage of this method using also classes as keys</strong> of &quot;__choice_table&quot;. In this way you can avoid <em>isinstance abuse</em> and keep all clean and testable.</p>\n<p>Supposing you have to process a lot of messages or packets from the net or your MQ. Every packet has its own structure and its management code (in a generic way).</p>\n<p>With the above code it is possible to do something like this:</p>\n<pre><code>class PacketManager:\n\n def __init__(self):\n self.__choice_table = \\\n {\n ControlMessage : self.my_func1,\n DiagnosticMessage : self.my_func2,\n }\n\n def my_func1(self, data):\n # process the control message here\n pass\n\n def my_func2(self, data):\n # process the diagnostic message here\n pass\n\n def process(self, pkt):\n return self.__choice_table[pkt.__class__](pkt)\n\npkt = GetMyPacketFromNet()\nPacketManager().process(pkt)\n\n\n# isolated test or isolated usage example\ndef test_control_packet():\n p = ControlMessage()\n PacketManager().my_func1(p)\n</code></pre>\n<p>So <strong>complexity is not spread in the code flow, but it is rendered in the code structure</strong>.</p>\n" }, { "answer_id": 37448954, "author": "dccsillag", "author_id": 4803382, "author_profile": "https://Stackoverflow.com/users/4803382", "pm_score": 2, "selected": false, "text": "<p>If you don't worry losing syntax highlight inside the case suites, you can do the following:</p>\n\n<pre><code>exec {\n 1: \"\"\"\nprint ('one')\n\"\"\", \n 2: \"\"\"\nprint ('two')\n\"\"\", \n 3: \"\"\"\nprint ('three')\n\"\"\",\n}.get(value, \"\"\"\nprint ('None')\n\"\"\")\n</code></pre>\n\n<p>Where <code>value</code> is the value. In C, this would be:</p>\n\n<pre><code>switch (value) {\n case 1:\n printf(\"one\");\n break;\n case 2:\n printf(\"two\");\n break;\n case 3:\n printf(\"three\");\n break;\n default:\n printf(\"None\");\n break;\n}\n</code></pre>\n\n<p>We can also create a helper function to do this:</p>\n\n<pre><code>def switch(value, cases, default):\n exec cases.get(value, default)\n</code></pre>\n\n<p>So we can use it like this for the example with one, two and three:</p>\n\n<pre><code>switch(value, {\n 1: \"\"\"\nprint ('one')\n \"\"\", \n 2: \"\"\"\nprint ('two')\n \"\"\", \n 3: \"\"\"\nprint ('three')\n \"\"\",\n}, \"\"\"\nprint ('None')\n\"\"\")\n</code></pre>\n" }, { "answer_id": 43536282, "author": "Tom", "author_id": 3106539, "author_profile": "https://Stackoverflow.com/users/3106539", "pm_score": 3, "selected": false, "text": "<p>Expanding on <a href=\"https://stackoverflow.com/a/60211/3106539\">Greg Hewgill's answer</a> - We can encapsulate the dictionary-solution using a decorator:</p>\n\n<pre><code>def case(callable):\n \"\"\"switch-case decorator\"\"\"\n class case_class(object):\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def do_call(self):\n return callable(*self.args, **self.kwargs)\n\nreturn case_class\n\ndef switch(key, cases, default=None):\n \"\"\"switch-statement\"\"\"\n ret = None\n try:\n ret = case[key].do_call()\n except KeyError:\n if default:\n ret = default.do_call()\n finally:\n return ret\n</code></pre>\n\n<p>This can then be used with the <code>@case</code>-decorator</p>\n\n<pre><code>@case\ndef case_1(arg1):\n print 'case_1: ', arg1\n\n@case\ndef case_2(arg1, arg2):\n print 'case_2'\n return arg1, arg2\n\n@case\ndef default_case(arg1, arg2, arg3):\n print 'default_case: ', arg1, arg2, arg3\n\nret = switch(somearg, {\n 1: case_1('somestring'),\n 2: case_2(13, 42)\n}, default_case(123, 'astring', 3.14))\n\nprint ret\n</code></pre>\n\n<p>The good news are that this has already been done in <a href=\"https://pypi.python.org/pypi/NeoPySwitch/0.2.0\" rel=\"nofollow noreferrer\">NeoPySwitch</a>-module. Simply install using pip:</p>\n\n<pre><code>pip install NeoPySwitch\n</code></pre>\n" }, { "answer_id": 44545063, "author": "Yster", "author_id": 1317559, "author_profile": "https://Stackoverflow.com/users/1317559", "pm_score": 4, "selected": false, "text": "<p>I was quite confused after reading the accepted answer, but this cleared it all up:</p>\n<pre><code>def numbers_to_strings(argument):\n switcher = {\n 0: &quot;zero&quot;,\n 1: &quot;one&quot;,\n 2: &quot;two&quot;,\n }\n return switcher.get(argument, &quot;nothing&quot;)\n</code></pre>\n<p>This code is analogous to:</p>\n<pre><code>function(argument){\n switch(argument) {\n case 0:\n return &quot;zero&quot;;\n case 1:\n return &quot;one&quot;;\n case 2:\n return &quot;two&quot;;\n default:\n return &quot;nothing&quot;;\n }\n}\n</code></pre>\n<p>Check the <a href=\"https://www.pydanny.com/why-doesnt-python-have-switch-case.html\" rel=\"noreferrer\">Source</a> for more about dictionary mapping to functions.</p>\n" }, { "answer_id": 45530307, "author": "damirlj", "author_id": 6424465, "author_profile": "https://Stackoverflow.com/users/6424465", "pm_score": 0, "selected": false, "text": "<p>A switch statement is just syntactic sugar for if/elif/else.\nWhat any control statement is doing is delegating the job based on certain condition is being fulfilled - decision path. For wrapping that into a module and being able to call a job based on its unique id, one can use inheritance and the fact that any method in Python is virtual, to provide the derived class specific job implementation, as a specific &quot;case&quot; handler:</p>\n<pre><code>#!/usr/bin/python\n\nimport sys\n\nclass Case(object):\n &quot;&quot;&quot;\n Base class which specifies the interface for the &quot;case&quot; handler.\n The all required arbitrary arguments inside &quot;execute&quot; method will be\n provided through the derived class\n specific constructor\n\n @note in Python, all class methods are virtual\n &quot;&quot;&quot;\n def __init__(self, id):\n self.id = id\n\n def pair(self):\n &quot;&quot;&quot;\n Pairs the given id of the &quot;case&quot; with\n the instance on which &quot;execute&quot; will be called\n &quot;&quot;&quot;\n return (self.id, self)\n\n def execute(self): # Base class virtual method that needs to be overridden\n pass\n\nclass Case1(Case):\n def __init__(self, id, msg):\n self.id = id\n self.msg = msg\n def execute(self): # Override the base class method\n print(&quot;&lt;Case1&gt; id={}, message: \\&quot;{}\\&quot;&quot;.format(str(self.id), self.msg))\n\nclass Case2(Case):\n def __init__(self, id, n):\n self.id = id\n self.n = n\n def execute(self): # Override the base class method\n print(&quot;&lt;Case2&gt; id={}, n={}.&quot;.format(str(self.id), str(self.n)))\n print(&quot;\\n&quot;.join(map(str, range(self.n))))\n\n\nclass Switch(object):\n &quot;&quot;&quot;\n The class which delegates the jobs\n based on the given job id\n &quot;&quot;&quot;\n def __init__(self, cases):\n self.cases = cases # dictionary: time complexity for the access operation is 1\n def resolve(self, id):\n\n try:\n cases[id].execute()\n except KeyError as e:\n print(&quot;Given id: {} is wrong!&quot;.format(str(id)))\n\n\n\nif __name__ == '__main__':\n\n # Cases\n cases=dict([Case1(0, &quot;switch&quot;).pair(), Case2(1, 5).pair()])\n\n switch = Switch(cases)\n\n # id will be dynamically specified\n switch.resolve(0)\n switch.resolve(1)\n switch.resolve(2)\n</code></pre>\n" }, { "answer_id": 45683860, "author": "user2233949", "author_id": 2233949, "author_profile": "https://Stackoverflow.com/users/2233949", "pm_score": 5, "selected": false, "text": "<p>I'm just going to drop my two cents in here. The reason there isn't a case/switch statement in Python is because Python follows the principle of &quot;there's only one right way to do something&quot;. So obviously you could come up with various ways of recreating switch/case functionality, but the Pythonic way of accomplishing this is the if/elif construct. I.e.,</p>\n<pre><code>if something:\n return &quot;first thing&quot;\nelif somethingelse:\n return &quot;second thing&quot;\nelif yetanotherthing:\n return &quot;third thing&quot;\nelse:\n return &quot;default thing&quot;\n</code></pre>\n<p>I just felt <a href=\"https://pep8.org/\" rel=\"noreferrer\">PEP 8</a> deserved a nod here. One of the beautiful things about Python is its simplicity and elegance. That is largely derived from principles laid out in PEP 8, including &quot;There's only one right way to do something.&quot;</p>\n" }, { "answer_id": 45981619, "author": "The Nomadic Coder", "author_id": 1933672, "author_profile": "https://Stackoverflow.com/users/1933672", "pm_score": 2, "selected": false, "text": "<p>I've made a <em>switch case</em> implementation that doesn't quite use <em>ifs</em> externally (it still uses an <em>if</em> in the class).</p>\n<pre><code>class SwitchCase(object):\n def __init__(self):\n self._cases = dict()\n\n def add_case(self,value, fn):\n self._cases[value] = fn\n\n def add_default_case(self,fn):\n self._cases['default'] = fn\n\n def switch_case(self,value):\n if value in self._cases.keys():\n return self._cases[value](value)\n else:\n return self._cases['default'](0)\n</code></pre>\n<p>Use it like this:</p>\n<pre><code>from switch_case import SwitchCase\nswitcher = SwitchCase()\nswitcher.add_case(1, lambda x:x+1)\nswitcher.add_case(2, lambda x:x+3)\nswitcher.add_default_case(lambda _:[1,2,3,4,5])\n\nprint switcher.switch_case(1) #2\nprint switcher.switch_case(2) #5\nprint switcher.switch_case(123) #[1, 2, 3, 4, 5]\n</code></pre>\n" }, { "answer_id": 47335084, "author": "nrp", "author_id": 3426366, "author_profile": "https://Stackoverflow.com/users/3426366", "pm_score": 1, "selected": false, "text": "<p>The following works for my situation when I need a simple switch-case to call a bunch of methods and not to just print some text. After playing with lambda and globals it hit me as the simplest option for me so far. Maybe it will help someone also:</p>\n\n<pre><code>def start():\n print(\"Start\")\n\ndef stop():\n print(\"Stop\")\n\ndef print_help():\n print(\"Help\")\n\ndef choose_action(arg):\n return {\n \"start\": start,\n \"stop\": stop,\n \"help\": print_help,\n }.get(arg, print_help)\n\nargument = sys.argv[1].strip()\nchoose_action(argument)() # calling a method from the given string\n</code></pre>\n" }, { "answer_id": 48013880, "author": "M T Head", "author_id": 6710305, "author_profile": "https://Stackoverflow.com/users/6710305", "pm_score": 1, "selected": false, "text": "<p>And another option: </p>\n\n<pre><code>def fnc_MonthSwitch(int_Month): #### Define a function take in the month variable \n str_Return =\"Not Found\" #### Set Default Value \n if int_Month==1: str_Return = \"Jan\" \n if int_Month==2: str_Return = \"Feb\" \n if int_Month==3: str_Return = \"Mar\" \n return str_Return; #### Return the month found \nprint (\"Month Test 3: \" + fnc_MonthSwitch( 3) )\nprint (\"Month Test 14: \" + fnc_MonthSwitch(14) )\n</code></pre>\n" }, { "answer_id": 48047214, "author": "ramazan polat", "author_id": 234775, "author_profile": "https://Stackoverflow.com/users/234775", "pm_score": 2, "selected": false, "text": "<p>Although there are already enough answers, I want to point a simpler and more powerful solution:</p>\n<pre><code>class Switch:\n def __init__(self, switches):\n self.switches = switches\n self.between = len(switches[0]) == 3\n\n def __call__(self, x):\n for line in self.switches:\n if self.between:\n if line[0] &lt;= x &lt; line[1]:\n return line[2]\n else:\n if line[0] == x:\n return line[1]\n return None\n\n\nif __name__ == '__main__':\n between_table = [\n (1, 4, 'between 1 and 4'),\n (4, 8, 'between 4 and 8')\n ]\n\n switch_between = Switch(between_table)\n\n print('Switch Between:')\n for i in range(0, 10):\n if switch_between(i):\n print('{} is {}'.format(i, switch_between(i)))\n else:\n print('No match for {}'.format(i))\n\n\n equals_table = [\n (1, 'One'),\n (2, 'Two'),\n (4, 'Four'),\n (5, 'Five'),\n (7, 'Seven'),\n (8, 'Eight')\n ]\n print('Switch Equals:')\n switch_equals = Switch(equals_table)\n for i in range(0, 10):\n if switch_equals(i):\n print('{} is {}'.format(i, switch_equals(i)))\n else:\n print('No match for {}'.format(i))\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Switch Between:\nNo match for 0\n1 is between 1 and 4\n2 is between 1 and 4\n3 is between 1 and 4\n4 is between 4 and 8\n5 is between 4 and 8\n6 is between 4 and 8\n7 is between 4 and 8\nNo match for 8\nNo match for 9\n\nSwitch Equals:\nNo match for 0\n1 is One\n2 is Two\nNo match for 3\n4 is Four\n5 is Five\nNo match for 6\n7 is Seven\n8 is Eight\nNo match for 9\n</code></pre>\n" }, { "answer_id": 48614894, "author": "Solomon Ucko", "author_id": 5445670, "author_profile": "https://Stackoverflow.com/users/5445670", "pm_score": 3, "selected": false, "text": "<p>Simple, not tested; each condition is evaluated independently: there is no fall-through, but all cases are evaluated (although the expression to switch on is only evaluated once), unless there is a break statement. For example,</p>\n\n<pre><code>for case in [expression]:\n if case == 1:\n print(end='Was 1. ')\n\n if case == 2:\n print(end='Was 2. ')\n break\n\n if case in (1, 2):\n print(end='Was 1 or 2. ')\n\n print(end='Was something. ')\n</code></pre>\n\n<p>prints <code>Was 1. Was 1 or 2. Was something.</code> <sup>(Dammit! Why can't I have trailing whitespace in inline code blocks?)</sup> if <code>expression</code> evaluates to <code>1</code>, <code>Was 2.</code> if <code>expression</code> evaluates to <code>2</code>, or <code>Was something.</code> if <code>expression</code> evaluates to something else.</p>\n" }, { "answer_id": 48846312, "author": "Alejandro Quintanar", "author_id": 1242902, "author_profile": "https://Stackoverflow.com/users/1242902", "pm_score": 5, "selected": false, "text": "<p>Solution to run functions:</p>\n<pre><code>result = {\n 'case1': foo1, \n 'case2': foo2,\n 'case3': foo3,\n}.get(option)(parameters_optional)\n</code></pre>\n<p>where foo1(), foo2() and foo3() are functions</p>\n<p><strong>Example 1</strong> (with parameters):</p>\n<pre><code>option = number['type']\nresult = {\n 'number': value_of_int, # result = value_of_int(number['value'])\n 'text': value_of_text, # result = value_of_text(number['value'])\n 'binary': value_of_bin, # result = value_of_bin(number['value'])\n}.get(option)(value['value'])\n</code></pre>\n<p><strong>Example 2</strong> (no parameters):</p>\n<pre><code>option = number['type']\nresult = {\n 'number': func_for_number, # result = func_for_number()\n 'text': func_for_text, # result = func_for_text()\n 'binary': func_for_bin, # result = func_for_bin()\n}.get(option)()\n</code></pre>\n<p><strong>Example 4</strong> (only values):</p>\n<pre><code>option = number['type']\nresult = {\n 'number': lambda: 10, # result = 10\n 'text': lambda: 'ten', # result = 'ten'\n 'binary': lambda: 0b101111, # result = 47\n}.get(option)()\n</code></pre>\n" }, { "answer_id": 49367931, "author": "True", "author_id": 4696698, "author_profile": "https://Stackoverflow.com/users/4696698", "pm_score": 2, "selected": false, "text": "<p><em>I've found the following answer from <a href=\"https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python\" rel=\"nofollow noreferrer\">Python documentation</a> most helpful:</em></p>\n<p>You can do this easily enough with a sequence of <code>if... elif... elif... else</code>. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.</p>\n<p>For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:</p>\n<pre><code>def function_1(...):\n ...\n\nfunctions = {'a': function_1,\n 'b': function_2,\n 'c': self.method_1, ...}\n\nfunc = functions[value]\nfunc()\n</code></pre>\n<p>For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:</p>\n<pre><code>def visit_a(self, ...):\n ...\n...\n\ndef dispatch(self, value):\n method_name = 'visit_' + str(value)\n method = getattr(self, method_name)\n method()\n</code></pre>\n<p>It’s suggested that you use a prefix for the method names, such as <code>visit_</code> in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.</p>\n" }, { "answer_id": 49746559, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 4, "selected": false, "text": "<p>Most of the answers here are pretty old, and especially the accepted ones, so it seems worth updating.</p>\n\n<p>First, the official <a href=\"https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python\" rel=\"noreferrer\">Python FAQ</a> covers this, and recommends the <code>elif</code> chain for simple cases and the <code>dict</code> for larger or more complex cases. It also suggests a set of <code>visit_</code> methods (a style used by many server frameworks) for some cases:</p>\n\n<pre><code>def dispatch(self, value):\n method_name = 'visit_' + str(value)\n method = getattr(self, method_name)\n method()\n</code></pre>\n\n<p>The FAQ also mentions <a href=\"https://www.python.org/dev/peps/pep-0275/\" rel=\"noreferrer\">PEP 275</a>, which was written to get an official once-and-for-all decision on adding C-style switch statements. But that PEP was actually deferred to Python 3, and it was only officially rejected as a separate proposal, <a href=\"https://www.python.org/dev/peps/pep-3103/\" rel=\"noreferrer\">PEP 3103</a>. The answer was, of course, no—but the two PEPs have links to additional information if you're interested in the reasons or the history.</p>\n\n<hr>\n\n<p>One thing that came up multiple times (and can be seen in PEP 275, even though it was cut out as an actual recommendation) is that if you're really bothered by having 8 lines of code to handle 4 cases, vs. the 6 lines you'd have in C or Bash, you can always write this:</p>\n\n<pre><code>if x == 1: print('first')\nelif x == 2: print('second')\nelif x == 3: print('third')\nelse: print('did not place')\n</code></pre>\n\n<p>This isn't exactly encouraged by PEP 8, but it's readable and not too unidiomatic.</p>\n\n<hr>\n\n<p>Over the more than a decade since PEP 3103 was rejected, the issue of C-style case statements, or even the slightly more powerful version in Go, has been considered dead; whenever anyone brings it up on python-ideas or -dev, they're referred to the old decision.</p>\n\n<p>However, the idea of full ML-style pattern matching arises every few years, especially since languages like Swift and Rust have adopted it. The problem is that it's hard to get much use out of pattern matching without algebraic data types. While Guido has been sympathetic to the idea, nobody's come up with a proposal that fits into Python very well. (You can read <a href=\"http://stupidpythonideas.blogspot.com/2014/08/a-pattern-matching-case-statement-for.html\" rel=\"noreferrer\">my 2014 strawman</a> for an example.) This could change with <code>dataclass</code> in 3.7 and some sporadic proposals for a more powerful <code>enum</code> to handle sum types, or with various proposals for different kinds of statement-local bindings (like <a href=\"https://www.python.org/dev/peps/pep-3150/\" rel=\"noreferrer\">PEP 3150</a>, or the set of proposals currently being discussed on -ideas). But so far, it hasn't.</p>\n\n<p>There are also occasionally proposals for Perl 6-style matching, which is basically a mishmash of everything from <code>elif</code> to regex to single-dispatch type-switching.</p>\n" }, { "answer_id": 50686874, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 2, "selected": false, "text": "<p>As a minor variation on <a href=\"https://stackoverflow.com/a/60215/908494\">Mark Biek's answer</a>, for uncommon cases like <a href=\"https://stackoverflow.com/questions/50686700/\">this duplicate</a> where the user has a bunch of function calls to delay with arguments to pack in (and it isn't worth building a bunch of functions out-of-line), instead of this:</p>\n\n<pre><code>d = {\n \"a1\": lambda: a(1),\n \"a2\": lambda: a(2),\n \"b\": lambda: b(\"foo\"),\n \"c\": lambda: c(),\n \"z\": lambda: z(\"bar\", 25),\n }\nreturn d[string]()\n</code></pre>\n\n<p>… you can do this:</p>\n\n<pre><code>d = {\n \"a1\": (a, 1),\n \"a2\": (a, 2),\n \"b\": (b, \"foo\"),\n \"c\": (c,)\n \"z\": (z, \"bar\", 25),\n }\nfunc, *args = d[string]\nreturn func(*args)\n</code></pre>\n\n<p>This is certainly shorter, but whether it's <em>more readable</em> is an open question…</p>\n\n<hr>\n\n<p>I think it might be more readable (although not briefer) to switch from <code>lambda</code> to <code>partial</code> for this particular use:</p>\n\n<pre><code>d = {\n \"a1\": partial(a, 1),\n \"a2\": partial(a, 2),\n \"b\": partial(b, \"foo\"),\n \"c\": c,\n \"z\": partial(z, \"bar\", 25),\n }\nreturn d[string]()\n</code></pre>\n\n<p>… which has the advantage of working nicely with keyword arguments as well:</p>\n\n<pre><code>d = {\n \"a1\": partial(a, 1),\n \"a2\": partial(a, 2),\n \"b\": partial(b, \"foo\"),\n \"c\": c,\n \"k\": partial(k, key=int),\n \"z\": partial(z, \"bar\", 25),\n }\nreturn d[string]()\n</code></pre>\n" }, { "answer_id": 50688208, "author": "Alex Hall", "author_id": 2482744, "author_profile": "https://Stackoverflow.com/users/2482744", "pm_score": 2, "selected": false, "text": "<p>Similar to <a href=\"https://stackoverflow.com/a/50686874/2482744\">this answer by abarnert</a>, here is a solution specifically for the use case of calling a single function for each 'case' in the switch, while avoiding the <code>lambda</code> or <code>partial</code> for ultra-conciseness while still being able to handle keyword arguments:</p>\n\n<pre><code>class switch(object):\n NO_DEFAULT = object()\n\n def __init__(self, value, default=NO_DEFAULT):\n self._value = value\n self._result = default\n\n def __call__(self, option, func, *args, **kwargs):\n if self._value == option:\n self._result = func(*args, **kwargs)\n return self\n\n def pick(self):\n if self._result is switch.NO_DEFAULT:\n raise ValueError(self._value)\n\n return self._result\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>def add(a, b):\n return a + b\n\ndef double(x):\n return 2 * x\n\ndef foo(**kwargs):\n return kwargs\n\nresult = (\n switch(3)\n (1, add, 7, 9)\n (2, double, 5)\n (3, foo, bar=0, spam=8)\n (4, lambda: double(1 / 0)) # if evaluating arguments is not safe\n).pick()\n\nprint(result)\n</code></pre>\n\n<p>Note that this is chaining calls, i.e. <code>switch(3)(...)(...)(...)</code>. Don't put commas in between. It's also important to put it all in one expression, which is why I've used extra parentheses around the main call for implicit line continuation.</p>\n\n<p>The above example will raise an error if you switch on a value that is not handled, e.g. <code>switch(5)(1, ...)(2, ...)(3, ...)</code>. You can provide a default value instead, e.g. <code>switch(5, default=-1)...</code> returns <code>-1</code>.</p>\n" }, { "answer_id": 50725576, "author": "Tony Suffolk 66", "author_id": 3426606, "author_profile": "https://Stackoverflow.com/users/3426606", "pm_score": 3, "selected": false, "text": "<p>A solution I tend to use which also makes use of dictionaries is:</p>\n<pre><code>def decision_time( key, *args, **kwargs):\n def action1()\n &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n pass\n def action2()\n &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n pass\n def action3()\n &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n pass\n\n return {1:action1, 2:action2, 3:action3}.get(key,default)()\n</code></pre>\n<p>This has the advantage that it doesn't try to evaluate the functions every time, and you just have to ensure that the outer function gets all the information that the inner functions need.</p>\n" }, { "answer_id": 51811745, "author": "sudhir tataraju", "author_id": 8520303, "author_profile": "https://Stackoverflow.com/users/8520303", "pm_score": 1, "selected": false, "text": "<p><strong>Easy to remember:</strong></p>\n\n<pre><code>while True:\n try:\n x = int(input(\"Enter a numerical input: \"))\n except:\n print(\"Invalid input - please enter a Integer!\");\n if x==1:\n print(\"good\");\n elif x==2:\n print(\"bad\");\n elif x==3:\n break\n else:\n print (\"terrible\");\n</code></pre>\n" }, { "answer_id": 52106213, "author": "Woody1193", "author_id": 3121975, "author_profile": "https://Stackoverflow.com/users/3121975", "pm_score": 3, "selected": false, "text": "<p>There have been a lot of answers so far that have said, \"we don't have a switch in Python, do it this way\". However, I would like to point out that the switch statement itself is an easily-abused construct that can and should be avoided in most cases because they promote lazy programming. Case in point:</p>\n\n<pre><code>def ToUpper(lcChar):\n if (lcChar == 'a' or lcChar == 'A'):\n return 'A'\n elif (lcChar == 'b' or lcChar == 'B'):\n return 'B'\n ...\n elif (lcChar == 'z' or lcChar == 'Z'):\n return 'Z'\n else:\n return None # or something\n</code></pre>\n\n<p>Now, you <em>could</em> do this with a switch-statement (if Python offered one) but you'd be wasting your time because there are methods that do this just fine. Or maybe, you have something less obvious:</p>\n\n<pre><code>def ConvertToReason(code):\n if (code == 200):\n return 'Okay'\n elif (code == 400):\n return 'Bad Request'\n elif (code == 404):\n return 'Not Found'\n else:\n return None\n</code></pre>\n\n<p>However, this sort of operation can and should be handled with a dictionary because it will be faster, less complex, less prone to error and more compact.</p>\n\n<p>And the vast majority of \"use cases\" for switch statements will fall into one of these two cases; there's just very little reason to use one if you've thought about your problem thoroughly.</p>\n\n<p>So, rather than asking \"how do I switch in Python?\", perhaps we should ask, \"why do I want to switch in Python?\" because that's often the more interesting question and will often expose flaws in the design of whatever you're building.</p>\n\n<p>Now, that isn't to say that switches should never be used either. State machines, lexers, parsers and automata all use them to some degree and, in general, when you start from a symmetrical input and go to an asymmetrical output they can be useful; you just need to make sure that you don't use the switch as a hammer because you see a bunch of nails in your code.</p>\n" }, { "answer_id": 52559968, "author": "Vikhyat Agarwal", "author_id": 8663663, "author_profile": "https://Stackoverflow.com/users/8663663", "pm_score": 4, "selected": false, "text": "<pre><code>def f(x):\n dictionary = {'a':1, 'b':2, 'c':3}\n return dictionary.get(x,'Not Found') \n##Returns the value for the letter x;returns 'Not Found' if x isn't a key in the dictionary\n</code></pre>\n" }, { "answer_id": 54549654, "author": "Felix Martinez", "author_id": 10967582, "author_profile": "https://Stackoverflow.com/users/10967582", "pm_score": 4, "selected": false, "text": "<p>You can use a dispatched dict:</p>\n<pre><code>#!/usr/bin/env python\n\n\ndef case1():\n print(&quot;This is case 1&quot;)\n\ndef case2():\n print(&quot;This is case 2&quot;)\n\ndef case3():\n print(&quot;This is case 3&quot;)\n\n\ntoken_dict = {\n &quot;case1&quot; : case1,\n &quot;case2&quot; : case2,\n &quot;case3&quot; : case3,\n}\n\n\ndef main():\n cases = (&quot;case1&quot;, &quot;case3&quot;, &quot;case2&quot;, &quot;case1&quot;)\n for case in cases:\n token_dict[case]()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>This is case 1\nThis is case 3\nThis is case 2\nThis is case 1\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907/" ]
I want to write a function in Python that returns different fixed values based on the value of an input index. In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario?
The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the [`match`-`case`](https://www.python.org/dev/peps/pep-0634/) statement which provides a first-class implementation of a "switch" for Python. For example: ``` def f(x): match x: case 'a': return 1 case 'b': return 2 case _: return 0 # 0 is the default case if x is not found ``` The `match`-`case` statement is considerably more powerful than this simple example. --- You could use a dictionary: ``` def f(x): return { 'a': 1, 'b': 2, }[x] ```
60,221
<p>I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:</p> <blockquote> <p>[======>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;] 37%</p> </blockquote> <p>and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?</p>
[ { "answer_id": 60226, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 7, "selected": true, "text": "<p>There are two ways I know of to do this:</p>\n\n<ul>\n<li>Use the backspace escape character ('\\b') to erase your line</li>\n<li>Use the <code>curses</code> package, if your programming language of choice has bindings for it.</li>\n</ul>\n\n<p>And a Google revealed <a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"noreferrer\">ANSI Escape Codes</a>, which appear to be a good way. For reference, here is a function in C++ to do this:</p>\n\n<pre><code>void DrawProgressBar(int len, double percent) {\n cout &lt;&lt; \"\\x1B[2K\"; // Erase the entire current line.\n cout &lt;&lt; \"\\x1B[0E\"; // Move to the beginning of the current line.\n string progress;\n for (int i = 0; i &lt; len; ++i) {\n if (i &lt; static_cast&lt;int&gt;(len * percent)) {\n progress += \"=\";\n } else {\n progress += \" \";\n }\n }\n cout &lt;&lt; \"[\" &lt;&lt; progress &lt;&lt; \"] \" &lt;&lt; (static_cast&lt;int&gt;(100 * percent)) &lt;&lt; \"%\";\n flush(cout); // Required.\n}\n</code></pre>\n" }, { "answer_id": 60227, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "<p>One way to do this is to repeatedly update the line of text with the current progress. For example:</p>\n\n<pre><code>def status(percent):\n sys.stdout.write(\"%3d%%\\r\" % percent)\n sys.stdout.flush()\n</code></pre>\n\n<p>Note that I used <code>sys.stdout.write</code> instead of <code>print</code> (this is Python) because <code>print</code> automatically prints \"\\r\\n\" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the <code>flush()</code> is necessary because by default, <code>sys.stdout</code> only flushes its output after a newline (or after its buffer gets full).</p>\n" }, { "answer_id": 60235, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.</p>\n" }, { "answer_id": 1618758, "author": "Justin", "author_id": 195960, "author_profile": "https://Stackoverflow.com/users/195960", "pm_score": 0, "selected": false, "text": "<p>If your using a scripting language you could use the \"tput cup\" command to get this done...\nP.S. This is a Linux/Unix thing only as far as I know...</p>\n" }, { "answer_id": 11173569, "author": "Blaker", "author_id": 1048120, "author_profile": "https://Stackoverflow.com/users/1048120", "pm_score": 2, "selected": false, "text": "<p>As a follow up to <a href=\"https://stackoverflow.com/a/60227/1048120\">Greg's answer</a>, here is an extended version of his function that allows you to display multi-line messages; just pass in a list or tuple of the strings you want to display/refresh.</p>\n\n<pre><code>def status(msgs):\n assert isinstance(msgs, (list, tuple))\n\n sys.stdout.write(''.join(msg + '\\n' for msg in msgs[:-1]) + msgs[-1] + ('\\x1b[A' * (len(msgs) - 1)) + '\\r')\n sys.stdout.flush()\n</code></pre>\n\n<p>Note: I have only tested this using a linux terminal, so your mileage may vary on Windows-based systems.</p>\n" }, { "answer_id": 11325990, "author": "naren", "author_id": 1193863, "author_profile": "https://Stackoverflow.com/users/1193863", "pm_score": 2, "selected": false, "text": "<p>Here is the answer for your question... (python)</p>\n\n<pre><code>def disp_status(timelapse, timeout):\n if timelapse and timeout:\n percent = 100 * (float(timelapse)/float(timeout))\n sys.stdout.write(\"progress : [\"+\"*\"*int(percent)+\" \"*(100-int(percent-1))+\"]\"+str(percent)+\" %\")\n sys.stdout.flush()\n stdout.write(\"\\r \\r\")\n</code></pre>\n" }, { "answer_id": 13738348, "author": "hustljian", "author_id": 1048072, "author_profile": "https://Stackoverflow.com/users/1048072", "pm_score": 2, "selected": false, "text": "<p>below is my answer,use the windows API<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682055%28v=vs.85%29.aspx\" rel=\"nofollow\">Consoles(Windows)</a>, coding of C.</p>\n\n<pre><code>/*\n* file: ProgressBarConsole.cpp\n* description: a console progress bar Demo\n* author: lijian &lt;[email protected]&gt;\n* version: 1.0\n* date: 2012-12-06\n*/\n#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n\nHANDLE hOut;\nCONSOLE_SCREEN_BUFFER_INFO bInfo;\nchar charProgress[80] = \n {\"================================================================\"};\nchar spaceProgress = ' ';\n\n/*\n* show a progress in the [row] line\n* row start from 0 to the end\n*/\nint ProgressBar(char *task, int row, int progress)\n{\n char str[100];\n int len, barLen,progressLen;\n COORD crStart, crCurr;\n GetConsoleScreenBufferInfo(hOut, &amp;bInfo);\n crCurr = bInfo.dwCursorPosition; //the old position\n len = bInfo.dwMaximumWindowSize.X;\n barLen = len - 17;//minus the extra char\n progressLen = (int)((progress/100.0)*barLen);\n crStart.X = 0;\n crStart.Y = row;\n\n sprintf(str,\"%-10s[%-.*s&gt;%*c]%3d%%\", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);\n#if 0 //use stdand libary\n SetConsoleCursorPosition(hOut, crStart);\n printf(\"%s\\n\", str);\n#else\n WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);\n#endif\n SetConsoleCursorPosition(hOut, crCurr);\n return 0;\n}\nint main(int argc, char* argv[])\n{\n int i;\n hOut = GetStdHandle(STD_OUTPUT_HANDLE);\n GetConsoleScreenBufferInfo(hOut, &amp;bInfo);\n\n for (i=0;i&lt;100;i++)\n {\n ProgressBar(\"test\", 0, i);\n Sleep(50);\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 26219138, "author": "icenac", "author_id": 3910576, "author_profile": "https://Stackoverflow.com/users/3910576", "pm_score": 5, "selected": false, "text": "<p>The secret is to print only \\r instead of \\n or \\r\\n at the and of the line.</p>\n\n<p>\\r is called carriage return and it moves the cursor at the start of the line</p>\n\n<p>\\n is called line feed and it moves the cursor on the next line\nIn the console. If you only use \\r you overwrite the previously written line. \nSo first write a line like the following:</p>\n\n<pre><code>[ ]\n</code></pre>\n\n<p>then add a sign for each tick</p>\n\n<pre><code>\\r[= ]\n\n\\r[== ]\n\n...\n\n\\r[==========]\n</code></pre>\n\n<p>and so on.\nYou can use 10 chars, each representing a 10%. \nAlso, if you want to display a message when finished, don't forget to also add enough white chars so that you overwrite the previously written equal signs like so:</p>\n\n<pre><code>\\r[done ]\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this: > > [======>                    ] 37% > > > and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?
There are two ways I know of to do this: * Use the backspace escape character ('\b') to erase your line * Use the `curses` package, if your programming language of choice has bindings for it. And a Google revealed [ANSI Escape Codes](http://en.wikipedia.org/wiki/ANSI_escape_code), which appear to be a good way. For reference, here is a function in C++ to do this: ``` void DrawProgressBar(int len, double percent) { cout << "\x1B[2K"; // Erase the entire current line. cout << "\x1B[0E"; // Move to the beginning of the current line. string progress; for (int i = 0; i < len; ++i) { if (i < static_cast<int>(len * percent)) { progress += "="; } else { progress += " "; } } cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%"; flush(cout); // Required. } ```
60,244
<p>I need to join two binary files with a <code>*.bat</code> script on Windows.</p> <p>How can I achieve that?</p>
[ { "answer_id": 60248, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "<p>You can use <code>copy /b</code> like this:</p>\n\n<pre><code>copy /b file1+file2 destfile\n</code></pre>\n" }, { "answer_id": 60249, "author": "simon", "author_id": 6040, "author_profile": "https://Stackoverflow.com/users/6040", "pm_score": 3, "selected": false, "text": "<p>Just use the dos copy command with multiple source files and one destination file.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>copy file1+file2 appendedfile\n</code></pre>\n\n<p>You might need the /B option for binary files</p>\n" }, { "answer_id": 60254, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 10, "selected": true, "text": "<p>Windows <code>type</code> command works similarly to UNIX <code>cat</code>.</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>type file1 file2 &gt; file3\n</code></pre>\n\n<p>is equivalent of:</p>\n\n<pre><code>cat file1 file2 &gt; file3\n</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><code>type *.vcf &gt; all_in_one.vcf \n</code></pre>\n\n<p>This command will merge all the vcards into one.</p>\n" }, { "answer_id": 60257, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 4, "selected": false, "text": "<p>Shameless PowerShell plug (because I think the learning curve is a pain, so teaching something at any opportunity can help)</p>\n\n<pre><code>Get-Content file1,file2\n</code></pre>\n\n<p>Note that <code>type</code> is an alias for Get-Content, so if you like it better, you can write:</p>\n\n<pre><code>type file1,file2\n</code></pre>\n" }, { "answer_id": 60313, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 5, "selected": false, "text": "<p>If you have control over the machine where you're doing your work, I highly recommend installing <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"noreferrer\">GnuWin32</a>. Just \"Download All\" and let the wget program retrieve all the packages. You will then have access to cat, grep, find, gzip, tar, less, and hundreds of others.</p>\n\n<p>GnuWin32 is one of the first things I install on a new Windows box.</p>\n" }, { "answer_id": 23946721, "author": "Jahmic", "author_id": 573927, "author_profile": "https://Stackoverflow.com/users/573927", "pm_score": 1, "selected": false, "text": "<p>If you simply want to append text to the end of existing file, you can use the >> pipe. ex:</p>\n\n<pre><code>echo new text &gt;&gt;existingFile.txt\n</code></pre>\n" }, { "answer_id": 26384080, "author": "Noelkd", "author_id": 1663352, "author_profile": "https://Stackoverflow.com/users/1663352", "pm_score": 0, "selected": false, "text": "<p>If you have to use a batch script and have python installed here is a <a href=\"http://en.wikipedia.org/wiki/Polyglot_%28computing%29\" rel=\"nofollow noreferrer\">polyglot</a> answer in batch and python:</p>\n<pre><code>1&gt;2# : ^\n'''\n@echo off\npython &quot;%~nx0&quot; &quot; %~nx1&quot; &quot;%~nx2&quot; &quot;%~nx3&quot;\nexit /b\nrem ^\n'''\nimport sys\nimport os\n\nsys.argv = [argv.strip() for argv in sys.argv]\nif len(sys.argv) != 4:\n sys.exit(1)\n\n_, file_one, file_two, out_file = sys.argv\n\nfor file_name in [file_one, file_two]:\n if not os.path.isfile(file_name):\n print &quot;Can't find: {0}&quot;.format(file_name)\n sys.exit(1)\n\nif os.path.isfile(out_file):\n print &quot;Output file exists and will be overwritten&quot;\n\nwith open(out_file, &quot;wb&quot;) as out:\n with open(file_one, &quot;rb&quot;) as f1:\n out.write(f1.read())\n\n with open(file_two, &quot;rb&quot;) as f2:\n out.write(f2.read())\n</code></pre>\n<p>If saved as join.bat usage would be:</p>\n<pre><code>join.bat file_one.bin file_two.bin out_file.bin\n</code></pre>\n<p>Thanks too <a href=\"https://stackoverflow.com/a/17468811/1663352\">this answer</a> for the inspiration.</p>\n" }, { "answer_id": 37285468, "author": "sam msft", "author_id": 640259, "author_profile": "https://Stackoverflow.com/users/640259", "pm_score": 2, "selected": false, "text": "<p>In Windows 10's Redstone 1 release, the Windows added a real Linux subsystem for the NTOS kernel. I think originally it was intended to support Android apps, and maybe docker type scenarios. Microsoft partnered with Canonical and added an actual native bash shell. Also, you can use the apt package manager to get many Ubuntu packages. For example, you can do apt-get gcc to install the GCC tool chain as you would on a Linux box.</p>\n\n<p>If such a thing existed while I was in university, I think I could have done most of my Unix programming assignments in the native Windows bash shell.</p>\n" }, { "answer_id": 53236194, "author": "Aaron Xu", "author_id": 10631886, "author_profile": "https://Stackoverflow.com/users/10631886", "pm_score": 0, "selected": false, "text": "<p>I try to rejoin tar archive which has been splitted in a Linux server.</p>\n\n<p>And I found if I use <code>type</code> in Windows's <code>cmd.exe</code>, it will causes the file being joined in wrong order.(i.e. <code>type</code> sometimes will puts XXXX.ad at first and then XXXX.ac , XXXX.aa etc ...)</p>\n\n<p>So, I found a tool named <code>bat</code> in GitHub <a href=\"https://github.com/sharkdp/bat\" rel=\"nofollow noreferrer\">https://github.com/sharkdp/bat</a> which has a Windows build, and has better code highlight and the important thing is, it works fine on Windows to rejoin tar archive!</p>\n" }, { "answer_id": 54167784, "author": "Ricky Divjakovski", "author_id": 2884140, "author_profile": "https://Stackoverflow.com/users/2884140", "pm_score": 1, "selected": false, "text": "<p>So i was looking for a similar solution with the abillity to preserve EOL chars and found out there was no way, so i do what i do best and made my own utillity\nThis is a native cat executable for windows - <a href=\"https://mega.nz/#!6AVgwQhL!qJ1sxx-tLtpBkPIUx__iQDGKAIfmb21GHLFerhNoaWk\" rel=\"nofollow noreferrer\">https://mega.nz/#!6AVgwQhL!qJ1sxx-tLtpBkPIUx__iQDGKAIfmb21GHLFerhNoaWk</a></p>\n\n<pre><code>Usage: cat file1 file2 file3 file4 -o output.txt\n-o | Specifies the next arg is the output, we must use this rather than \"&gt;&gt;\" to preserve the line endings\n</code></pre>\n\n<p>I call it sharp-cat as its built with C#, feel free to scan with an antivirus and source code will be made available at request</p>\n" }, { "answer_id": 61777615, "author": "user42391", "author_id": 13534511, "author_profile": "https://Stackoverflow.com/users/13534511", "pm_score": 0, "selected": false, "text": "<p>Windows type command has problems, for example with Unicode characters on 512 bytes boundary. Try Cygwin's cat.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ]
I need to join two binary files with a `*.bat` script on Windows. How can I achieve that?
Windows `type` command works similarly to UNIX `cat`. **Example 1:** ``` type file1 file2 > file3 ``` is equivalent of: ``` cat file1 file2 > file3 ``` **Example 2:** ``` type *.vcf > all_in_one.vcf ``` This command will merge all the vcards into one.
60,259
<p>Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding. Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.</p> <p>Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source? </p> <p>Code snippets would be great.</p> <p>Update: To make it more clear, Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls. </p>
[ { "answer_id": 60398, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 1, "selected": false, "text": "<p>using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider to the XMLDocument you got from the service.</p>\n\n<p>I'm not at a pc with visual studio to test it but it should be possible for you to do this.</p>\n\n<p>The steps are as you mentioned in your question:</p>\n\n<pre>\n1. Get XML from webservice\n2. Convert XML String to XML Document\n3. Set the XMLDataProvider.Document value to your XML Document\n4. Bind that to your controls\n</pre>\n" }, { "answer_id": 395358, "author": "Paul Osterhout", "author_id": 30976, "author_profile": "https://Stackoverflow.com/users/30976", "pm_score": 3, "selected": true, "text": "<p>Here is some code I used to load a XML file from disk and bind it to a TreeView. I removed some of the normal tests for conciseness. The XML in the example is an OPML file.</p>\n\n<pre><code>XmlDataProvider provider = new XmlDataProvider();\n\nif (provider != null)\n{\n System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n doc.Load(fileName);\n provider.Document = doc;\n provider.XPath = \"/opml/body/outline\";\n FeedListTreeView.DataContext = provider;\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding. Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI. Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source? Code snippets would be great. Update: To make it more clear, Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls.
Here is some code I used to load a XML file from disk and bind it to a TreeView. I removed some of the normal tests for conciseness. The XML in the example is an OPML file. ``` XmlDataProvider provider = new XmlDataProvider(); if (provider != null) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(fileName); provider.Document = doc; provider.XPath = "/opml/body/outline"; FeedListTreeView.DataContext = provider; } ```
60,260
<p>I've been working through <a href="http://gigamonkeys.com/book" rel="nofollow noreferrer">Practical Common Lisp</a> and as an exercise decided to write a macro to determine if a number is a multiple of another number:</p> <p><code>(defmacro multp (value factor)<br> `(= (rem ,value ,factor) 0))</code></p> <p>so that : <code>(multp 40 10)</code> evaluates to true whilst <code>(multp 40 13)</code> does not </p> <p>The question is does this macro <a href="http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks" rel="nofollow noreferrer">leak</a> in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?</p>
[ { "answer_id": 60267, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both <code>value</code> and <code>factor</code> are evaluated only once and in order, and <code>rem</code> doesn't have any side effects.</p>\n\n<p>This is not good Lisp though, because there's no reason to use a macro in this case. A function</p>\n\n<pre><code>(defun multp (value factor)\n (zerop (rem value factor)))\n</code></pre>\n\n<p>is identical for all practical purposes. (Note the use of <code>zerop</code>. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, <code>(= ... 0)</code> might be better)</p>\n" }, { "answer_id": 60268, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "<p>Your macro looks fine to me. I don't know what a leaky macro is, but yours is pretty straightforward and doesn't require any gensyms. As far as if this is \"good\" Lisp, my rule of thumb is to use a macro only when a function won't do, and in this case a function can be used in place of your macro. However, if this solution works for you there's no reason not to use it.</p>\n" }, { "answer_id": 81824, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "<p>Well, in principle, a user could do this:</p>\n\n<pre><code>(flet ((= (&amp;rest args) nil))\n (multp 40 10))\n</code></pre>\n\n<p>which would evaluate to NIL... except that ANSI CL makes it illegal to rebind most standard symbols, including CL:=, so you're on the safe side in this particular case.</p>\n\n<p>In generial, of course, you should be aware of both referential untransparency (capturing identifiers from the context the macro is expanded in) and macro unhygiene (leaking identifiers to expanded code).</p>\n" }, { "answer_id": 268416, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 0, "selected": false, "text": "<p>No, no symbol introduced in the macro's \"lexical closure\" is released to the outside.</p>\n\n<p>Note that leaking isn't NECESSARILY a bad thing, even if accidental leaking almost always is. For one project I worked on, I found that a macro similar to this was useful:</p>\n\n<pre><code>(defmacro ana-and (&amp;rest forms)\n (loop for form in (reverse forms)\n for completion = form then `(let ((it ,form))\n (when it\n ,completion))\n finally (return completion)))\n</code></pre>\n\n<p>This allowed me to get \"short-circuiting\" of things needed to be done in sequence, with arguments carried over from previous calls in the sequence (and a failure signalled by returning NIL). The specific context this code is from is for a hand-written parser for a configuration file that has a cobbled-together-enough syntax that writing a proper parser using a parser generator was more work than hand-rolling.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303/" ]
I've been working through [Practical Common Lisp](http://gigamonkeys.com/book) and as an exercise decided to write a macro to determine if a number is a multiple of another number: `(defmacro multp (value factor) `(= (rem ,value ,factor) 0))` so that : `(multp 40 10)` evaluates to true whilst `(multp 40 13)` does not The question is does this macro [leak](http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks) in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?
Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both `value` and `factor` are evaluated only once and in order, and `rem` doesn't have any side effects. This is not good Lisp though, because there's no reason to use a macro in this case. A function ``` (defun multp (value factor) (zerop (rem value factor))) ``` is identical for all practical purposes. (Note the use of `zerop`. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, `(= ... 0)` might be better)
60,269
<p>How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.</p> <p><strong>EDIT</strong>: <a href="http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html" rel="noreferrer">The Java Tutorials - Drag and Drop and Data Transfer</a>.</p>
[ { "answer_id": 60279, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 3, "selected": false, "text": "<p>Found this code out there on the <a href=\"http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html\" rel=\"noreferrer\">tubes</a>:</p>\n\n<pre><code>class DnDTabbedPane extends JTabbedPane {\n private static final int LINEWIDTH = 3;\n private static final String NAME = \"test\";\n private final GhostGlassPane glassPane = new GhostGlassPane();\n private final Rectangle2D lineRect = new Rectangle2D.Double();\n private final Color lineColor = new Color(0, 100, 255);\n //private final DragSource dragSource = new DragSource();\n //private final DropTarget dropTarget;\n private int dragTabIndex = -1;\n\n public DnDTabbedPane() {\n super();\n final DragSourceListener dsl = new DragSourceListener() {\n public void dragEnter(DragSourceDragEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }\n public void dragExit(DragSourceEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n lineRect.setRect(0,0,0,0);\n glassPane.setPoint(new Point(-1000,-1000));\n glassPane.repaint();\n }\n public void dragOver(DragSourceDragEvent e) {\n //e.getLocation()\n //This method returns a Point indicating the cursor location in screen coordinates at the moment\n Point tabPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n Point glassPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(glassPt, glassPane);\n int targetIdx = getTargetTabIndex(glassPt);\n if(getTabAreaBound().contains(tabPt) &amp;&amp; targetIdx&gt;=0 &amp;&amp;\n targetIdx!=dragTabIndex &amp;&amp; targetIdx!=dragTabIndex+1) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }else{\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n }\n }\n public void dragDropEnd(DragSourceDropEvent e) {\n lineRect.setRect(0,0,0,0);\n dragTabIndex = -1;\n if(hasGhost()) {\n glassPane.setVisible(false);\n glassPane.setImage(null);\n }\n }\n public void dropActionChanged(DragSourceDragEvent e) {}\n };\n final Transferable t = new Transferable() {\n private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);\n public Object getTransferData(DataFlavor flavor) {\n return DnDTabbedPane.this;\n }\n public DataFlavor[] getTransferDataFlavors() {\n DataFlavor[] f = new DataFlavor[1];\n f[0] = this.FLAVOR;\n return f;\n }\n public boolean isDataFlavorSupported(DataFlavor flavor) {\n return flavor.getHumanPresentableName().equals(NAME);\n }\n };\n final DragGestureListener dgl = new DragGestureListener() {\n public void dragGestureRecognized(DragGestureEvent e) {\n Point tabPt = e.getDragOrigin();\n dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n if(dragTabIndex&lt;0) return;\n initGlassPane(e.getComponent(), e.getDragOrigin());\n try{\n e.startDrag(DragSource.DefaultMoveDrop, t, dsl);\n }catch(InvalidDnDOperationException idoe) {\n idoe.printStackTrace();\n }\n }\n };\n //dropTarget =\n new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);\n new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n }\n\n class CDropTargetListener implements DropTargetListener{\n public void dragEnter(DropTargetDragEvent e) {\n if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());\n else e.rejectDrag();\n }\n public void dragExit(DropTargetEvent e) {}\n public void dropActionChanged(DropTargetDragEvent e) {}\n public void dragOver(final DropTargetDragEvent e) {\n if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {\n initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));\n }else{\n initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));\n }\n repaint();\n if(hasGhost()) {\n glassPane.setPoint(e.getLocation());\n glassPane.repaint();\n }\n }\n\n public void drop(DropTargetDropEvent e) {\n if(isDropAcceptable(e)) {\n convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));\n e.dropComplete(true);\n }else{\n e.dropComplete(false);\n }\n repaint();\n }\n public boolean isDragAcceptable(DropTargetDragEvent e) {\n Transferable t = e.getTransferable();\n if(t==null) return false;\n DataFlavor[] f = e.getCurrentDataFlavors();\n if(t.isDataFlavorSupported(f[0]) &amp;&amp; dragTabIndex&gt;=0) {\n return true;\n }\n return false;\n }\n public boolean isDropAcceptable(DropTargetDropEvent e) {\n Transferable t = e.getTransferable();\n if(t==null) return false;\n DataFlavor[] f = t.getTransferDataFlavors();\n if(t.isDataFlavorSupported(f[0]) &amp;&amp; dragTabIndex&gt;=0) {\n return true;\n }\n return false;\n }\n }\n\n private boolean hasGhost = true;\n public void setPaintGhost(boolean flag) {\n hasGhost = flag;\n }\n public boolean hasGhost() {\n return hasGhost;\n }\n private int getTargetTabIndex(Point glassPt) {\n Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);\n boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;\n for(int i=0;i&lt;getTabCount();i++) {\n Rectangle r = getBoundsAt(i);\n if(isTB) r.setRect(r.x-r.width/2, r.y, r.width, r.height);\n else r.setRect(r.x, r.y-r.height/2, r.width, r.height);\n if(r.contains(tabPt)) return i;\n }\n Rectangle r = getBoundsAt(getTabCount()-1);\n if(isTB) r.setRect(r.x+r.width/2, r.y, r.width, r.height);\n else r.setRect(r.x, r.y+r.height/2, r.width, r.height);\n return r.contains(tabPt)?getTabCount():-1;\n }\n private void convertTab(int prev, int next) {\n if(next&lt;0 || prev==next) {\n //System.out.println(\"press=\"+prev+\" next=\"+next);\n return;\n }\n Component cmp = getComponentAt(prev);\n String str = getTitleAt(prev);\n if(next==getTabCount()) {\n //System.out.println(\"last: press=\"+prev+\" next=\"+next);\n remove(prev);\n addTab(str, cmp);\n setSelectedIndex(getTabCount()-1);\n }else if(prev&gt;next) {\n //System.out.println(\" &gt;: press=\"+prev+\" next=\"+next);\n remove(prev);\n insertTab(str, null, cmp, null, next);\n setSelectedIndex(next);\n }else{\n //System.out.println(\" &lt;: press=\"+prev+\" next=\"+next);\n remove(prev);\n insertTab(str, null, cmp, null, next-1);\n setSelectedIndex(next-1);\n }\n }\n\n private void initTargetLeftRightLine(int next) {\n if(next&lt;0 || dragTabIndex==next || next-dragTabIndex==1) {\n lineRect.setRect(0,0,0,0);\n }else if(next==getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount()-1);\n lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }else if(next==0) {\n Rectangle rect = getBoundsAt(0);\n lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }else{\n Rectangle rect = getBoundsAt(next-1);\n lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n }\n }\n private void initTargetTopBottomLine(int next) {\n if(next&lt;0 || dragTabIndex==next || next-dragTabIndex==1) {\n lineRect.setRect(0,0,0,0);\n }else if(next==getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount()-1);\n lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n }else if(next==0) {\n Rectangle rect = getBoundsAt(0);\n lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);\n }else{\n Rectangle rect = getBoundsAt(next-1);\n lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n }\n }\n\n private void initGlassPane(Component c, Point tabPt) {\n //Point p = (Point) pt.clone();\n getRootPane().setGlassPane(glassPane);\n if(hasGhost()) {\n Rectangle rect = getBoundsAt(dragTabIndex);\n BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics g = image.getGraphics();\n c.paint(g);\n image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);\n glassPane.setImage(image);\n }\n Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);\n glassPane.setPoint(glassPt);\n glassPane.setVisible(true);\n }\n\n private Rectangle getTabAreaBound() {\n Rectangle lastTab = getUI().getTabBounds(this, getTabCount()-1);\n return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n if(dragTabIndex&gt;=0) {\n Graphics2D g2 = (Graphics2D)g;\n g2.setPaint(lineColor);\n g2.fill(lineRect);\n }\n }\n}\n\nclass GhostGlassPane extends JPanel {\n private final AlphaComposite composite;\n private Point location = new Point(0, 0);\n private BufferedImage draggingGhost = null;\n public GhostGlassPane() {\n setOpaque(false);\n composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);\n }\n public void setImage(BufferedImage draggingGhost) {\n this.draggingGhost = draggingGhost;\n }\n public void setPoint(Point location) {\n this.location = location;\n }\n public void paintComponent(Graphics g) {\n if(draggingGhost == null) return;\n Graphics2D g2 = (Graphics2D) g;\n g2.setComposite(composite);\n double xx = location.getX() - (draggingGhost.getWidth(this) /2d);\n double yy = location.getY() - (draggingGhost.getHeight(this)/2d);\n g2.drawImage(draggingGhost, (int)xx, (int)yy , null);\n }\n}\n</code></pre>\n" }, { "answer_id": 60306, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 5, "selected": false, "text": "<p>Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are:</p>\n\n<ol>\n<li>Detect that a drag has occurred</li>\n<li>Draw the dragged tab to an offscreen buffer</li>\n<li>Track the mouse position whilst dragging occurs</li>\n<li>Draw the tab in the buffer on top of the component.</li>\n</ol>\n\n<p>The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.</p>\n\n<p>Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.awt.Component;\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseMotionAdapter;\nimport java.awt.image.BufferedImage;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JTabbedPane;\n\n\npublic class DraggableTabbedPane extends JTabbedPane {\n\n private boolean dragging = false;\n private Image tabImage = null;\n private Point currentMouseLocation = null;\n private int draggedTabIndex = 0;\n\n public DraggableTabbedPane() {\n super();\n addMouseMotionListener(new MouseMotionAdapter() {\n public void mouseDragged(MouseEvent e) {\n\n if(!dragging) {\n // Gets the tab index based on the mouse position\n int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());\n\n if(tabNumber &gt;= 0) {\n draggedTabIndex = tabNumber;\n Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);\n\n\n // Paint the tabbed pane to a buffer\n Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics totalGraphics = totalImage.getGraphics();\n totalGraphics.setClip(bounds);\n // Don't be double buffered when painting to a static image.\n setDoubleBuffered(false);\n paintComponent(totalGraphics);\n\n // Paint just the dragged tab to the buffer\n tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);\n Graphics graphics = tabImage.getGraphics();\n graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);\n\n dragging = true;\n repaint();\n }\n } else {\n currentMouseLocation = e.getPoint();\n\n // Need to repaint\n repaint();\n }\n\n super.mouseDragged(e);\n }\n });\n\n addMouseListener(new MouseAdapter() {\n public void mouseReleased(MouseEvent e) {\n\n if(dragging) {\n int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);\n\n if(tabNumber &gt;= 0) {\n Component comp = getComponentAt(draggedTabIndex);\n String title = getTitleAt(draggedTabIndex);\n removeTabAt(draggedTabIndex);\n insertTab(title, null, comp, null, tabNumber);\n }\n }\n\n dragging = false;\n tabImage = null;\n }\n });\n }\n\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n // Are we dragging?\n if(dragging &amp;&amp; currentMouseLocation != null &amp;&amp; tabImage != null) {\n // Draw the dragged tab\n g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);\n }\n }\n\n public static void main(String[] args) {\n JFrame test = new JFrame(\"Tab test\");\n test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n test.setSize(400, 400);\n\n DraggableTabbedPane tabs = new DraggableTabbedPane();\n tabs.addTab(\"One\", new JButton(\"One\"));\n tabs.addTab(\"Two\", new JButton(\"Two\"));\n tabs.addTab(\"Three\", new JButton(\"Three\"));\n tabs.addTab(\"Four\", new JButton(\"Four\"));\n\n test.add(tabs);\n test.setVisible(true);\n }\n}\n</code></pre>\n" }, { "answer_id": 61982, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 5, "selected": true, "text": "<p>I liked <a href=\"http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html\" rel=\"nofollow noreferrer\">Terai Atsuhiro san's DnDTabbedPane</a>, but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.</p>\n\n<p>Inspired by @<a href=\"https://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing#60306\">Tom</a>'s effort, I decided to modify the code myself.\nThere are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.</p>\n\n<p><code>setAcceptor(TabAcceptor a_acceptor)</code> should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns <code>true</code>.</p>\n\n<pre><code>/** Modified DnDTabbedPane.java\n * http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html\n * originally written by Terai Atsuhiro.\n * so that tabs can be transfered from one pane to another.\n * eed3si9n.\n */\n\nimport java.awt.*;\nimport java.awt.datatransfer.*;\nimport java.awt.dnd.*;\nimport java.awt.geom.*;\nimport java.awt.image.*;\nimport javax.swing.*;\n\npublic class DnDTabbedPane extends JTabbedPane {\n public static final long serialVersionUID = 1L;\n private static final int LINEWIDTH = 3;\n private static final String NAME = \"TabTransferData\";\n private final DataFlavor FLAVOR = new DataFlavor(\n DataFlavor.javaJVMLocalObjectMimeType, NAME);\n private static GhostGlassPane s_glassPane = new GhostGlassPane();\n\n private boolean m_isDrawRect = false;\n private final Rectangle2D m_lineRect = new Rectangle2D.Double();\n\n private final Color m_lineColor = new Color(0, 100, 255);\n private TabAcceptor m_acceptor = null;\n\n public DnDTabbedPane() {\n super();\n final DragSourceListener dsl = new DragSourceListener() {\n public void dragEnter(DragSourceDragEvent e) {\n e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n }\n\n public void dragExit(DragSourceEvent e) {\n e.getDragSourceContext()\n .setCursor(DragSource.DefaultMoveNoDrop);\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n s_glassPane.setPoint(new Point(-1000, -1000));\n s_glassPane.repaint();\n }\n\n public void dragOver(DragSourceDragEvent e) {\n //e.getLocation()\n //This method returns a Point indicating the cursor location in screen coordinates at the moment\n\n TabTransferData data = getTabTransferData(e);\n if (data == null) {\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveNoDrop);\n return;\n } // if\n\n /*\n Point tabPt = e.getLocation();\n SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n if (DnDTabbedPane.this.contains(tabPt)) {\n int targetIdx = getTargetTabIndex(tabPt);\n int sourceIndex = data.getTabIndex();\n if (getTabAreaBound().contains(tabPt)\n &amp;&amp; (targetIdx &gt;= 0)\n &amp;&amp; (targetIdx != sourceIndex)\n &amp;&amp; (targetIdx != sourceIndex + 1)) {\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveDrop);\n\n return;\n } // if\n\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveNoDrop);\n return;\n } // if\n */\n\n e.getDragSourceContext().setCursor(\n DragSource.DefaultMoveDrop);\n }\n\n public void dragDropEnd(DragSourceDropEvent e) {\n m_isDrawRect = false;\n m_lineRect.setRect(0, 0, 0, 0);\n // m_dragTabIndex = -1;\n\n if (hasGhost()) {\n s_glassPane.setVisible(false);\n s_glassPane.setImage(null);\n }\n }\n\n public void dropActionChanged(DragSourceDragEvent e) {\n }\n };\n\n final DragGestureListener dgl = new DragGestureListener() {\n public void dragGestureRecognized(DragGestureEvent e) {\n // System.out.println(\"dragGestureRecognized\");\n\n Point tabPt = e.getDragOrigin();\n int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n if (dragTabIndex &lt; 0) {\n return;\n } // if\n\n initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);\n try {\n e.startDrag(DragSource.DefaultMoveDrop, \n new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);\n } catch (InvalidDnDOperationException idoe) {\n idoe.printStackTrace();\n }\n }\n };\n\n //dropTarget =\n new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,\n new CDropTargetListener(), true);\n new DragSource().createDefaultDragGestureRecognizer(this,\n DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n m_acceptor = new TabAcceptor() {\n public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {\n return true;\n }\n };\n }\n\n public TabAcceptor getAcceptor() {\n return m_acceptor;\n }\n\n public void setAcceptor(TabAcceptor a_value) {\n m_acceptor = a_value;\n }\n\n private TabTransferData getTabTransferData(DropTargetDropEvent a_event) { \n try {\n TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {\n try {\n TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {\n try {\n TabTransferData data = (TabTransferData) a_event.getDragSourceContext()\n .getTransferable().getTransferData(FLAVOR); \n return data;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null; \n }\n\n class TabTransferable implements Transferable {\n private TabTransferData m_data = null;\n\n public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);\n }\n\n public Object getTransferData(DataFlavor flavor) {\n return m_data;\n // return DnDTabbedPane.this;\n }\n\n public DataFlavor[] getTransferDataFlavors() {\n DataFlavor[] f = new DataFlavor[1];\n f[0] = FLAVOR;\n return f;\n }\n\n public boolean isDataFlavorSupported(DataFlavor flavor) {\n return flavor.getHumanPresentableName().equals(NAME);\n } \n }\n\n class TabTransferData {\n private DnDTabbedPane m_tabbedPane = null;\n private int m_tabIndex = -1;\n\n public TabTransferData() {\n }\n\n public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n m_tabbedPane = a_tabbedPane;\n m_tabIndex = a_tabIndex;\n }\n\n public DnDTabbedPane getTabbedPane() {\n return m_tabbedPane;\n }\n\n public void setTabbedPane(DnDTabbedPane pane) {\n m_tabbedPane = pane;\n }\n\n public int getTabIndex() {\n return m_tabIndex;\n }\n\n public void setTabIndex(int index) {\n m_tabIndex = index;\n }\n }\n\n private Point buildGhostLocation(Point a_location) {\n Point retval = new Point(a_location);\n\n switch (getTabPlacement()) {\n case JTabbedPane.TOP: {\n retval.y = 1;\n retval.x -= s_glassPane.getGhostWidth() / 2;\n } break;\n\n case JTabbedPane.BOTTOM: {\n retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();\n retval.x -= s_glassPane.getGhostWidth() / 2;\n } break;\n\n case JTabbedPane.LEFT: {\n retval.x = 1;\n retval.y -= s_glassPane.getGhostHeight() / 2;\n } break;\n\n case JTabbedPane.RIGHT: {\n retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();\n retval.y -= s_glassPane.getGhostHeight() / 2;\n } break;\n } // switch\n\n retval = SwingUtilities.convertPoint(DnDTabbedPane.this,\n retval, s_glassPane);\n return retval;\n }\n\n class CDropTargetListener implements DropTargetListener {\n public void dragEnter(DropTargetDragEvent e) {\n // System.out.println(\"DropTarget.dragEnter: \" + DnDTabbedPane.this);\n\n if (isDragAcceptable(e)) {\n e.acceptDrag(e.getDropAction());\n } else {\n e.rejectDrag();\n } // if\n }\n\n public void dragExit(DropTargetEvent e) {\n // System.out.println(\"DropTarget.dragExit: \" + DnDTabbedPane.this);\n m_isDrawRect = false;\n }\n\n public void dropActionChanged(DropTargetDragEvent e) {\n }\n\n public void dragOver(final DropTargetDragEvent e) {\n TabTransferData data = getTabTransferData(e);\n\n if (getTabPlacement() == JTabbedPane.TOP\n || getTabPlacement() == JTabbedPane.BOTTOM) {\n initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);\n } else {\n initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);\n } // if-else\n\n repaint();\n if (hasGhost()) {\n s_glassPane.setPoint(buildGhostLocation(e.getLocation()));\n s_glassPane.repaint();\n }\n }\n\n public void drop(DropTargetDropEvent a_event) {\n // System.out.println(\"DropTarget.drop: \" + DnDTabbedPane.this);\n\n if (isDropAcceptable(a_event)) {\n convertTab(getTabTransferData(a_event),\n getTargetTabIndex(a_event.getLocation()));\n a_event.dropComplete(true);\n } else {\n a_event.dropComplete(false);\n } // if-else\n\n m_isDrawRect = false;\n repaint();\n }\n\n public boolean isDragAcceptable(DropTargetDragEvent e) {\n Transferable t = e.getTransferable();\n if (t == null) {\n return false;\n } // if\n\n DataFlavor[] flavor = e.getCurrentDataFlavors();\n if (!t.isDataFlavorSupported(flavor[0])) {\n return false;\n } // if\n\n TabTransferData data = getTabTransferData(e);\n\n if (DnDTabbedPane.this == data.getTabbedPane()\n &amp;&amp; data.getTabIndex() &gt;= 0) {\n return true;\n } // if\n\n if (DnDTabbedPane.this != data.getTabbedPane()) {\n if (m_acceptor != null) {\n return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n } // if\n } // if\n\n return false;\n }\n\n public boolean isDropAcceptable(DropTargetDropEvent e) {\n Transferable t = e.getTransferable();\n if (t == null) {\n return false;\n } // if\n\n DataFlavor[] flavor = e.getCurrentDataFlavors();\n if (!t.isDataFlavorSupported(flavor[0])) {\n return false;\n } // if\n\n TabTransferData data = getTabTransferData(e);\n\n if (DnDTabbedPane.this == data.getTabbedPane()\n &amp;&amp; data.getTabIndex() &gt;= 0) {\n return true;\n } // if\n\n if (DnDTabbedPane.this != data.getTabbedPane()) {\n if (m_acceptor != null) {\n return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n } // if\n } // if\n\n return false;\n }\n }\n\n private boolean m_hasGhost = true;\n\n public void setPaintGhost(boolean flag) {\n m_hasGhost = flag;\n }\n\n public boolean hasGhost() {\n return m_hasGhost;\n }\n\n /**\n * returns potential index for drop.\n * @param a_point point given in the drop site component's coordinate\n * @return returns potential index for drop.\n */\n private int getTargetTabIndex(Point a_point) {\n boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP\n || getTabPlacement() == JTabbedPane.BOTTOM;\n\n // if the pane is empty, the target index is always zero.\n if (getTabCount() == 0) {\n return 0;\n } // if\n\n for (int i = 0; i &lt; getTabCount(); i++) {\n Rectangle r = getBoundsAt(i);\n if (isTopOrBottom) {\n r.setRect(r.x - r.width / 2, r.y, r.width, r.height);\n } else {\n r.setRect(r.x, r.y - r.height / 2, r.width, r.height);\n } // if-else\n\n if (r.contains(a_point)) {\n return i;\n } // if\n } // for\n\n Rectangle r = getBoundsAt(getTabCount() - 1);\n if (isTopOrBottom) {\n int x = r.x + r.width / 2;\n r.setRect(x, r.y, getWidth() - x, r.height);\n } else {\n int y = r.y + r.height / 2;\n r.setRect(r.x, y, r.width, getHeight() - y);\n } // if-else\n\n return r.contains(a_point) ? getTabCount() : -1;\n }\n\n private void convertTab(TabTransferData a_data, int a_targetIndex) {\n DnDTabbedPane source = a_data.getTabbedPane();\n int sourceIndex = a_data.getTabIndex();\n if (sourceIndex &lt; 0) {\n return;\n } // if\n\n Component cmp = source.getComponentAt(sourceIndex);\n String str = source.getTitleAt(sourceIndex);\n if (this != source) {\n source.remove(sourceIndex);\n\n if (a_targetIndex == getTabCount()) {\n addTab(str, cmp);\n } else {\n if (a_targetIndex &lt; 0) {\n a_targetIndex = 0;\n } // if\n\n insertTab(str, null, cmp, null, a_targetIndex);\n\n } // if\n\n setSelectedComponent(cmp);\n // System.out.println(\"press=\"+sourceIndex+\" next=\"+a_targetIndex);\n return;\n } // if\n\n if (a_targetIndex &lt; 0 || sourceIndex == a_targetIndex) {\n //System.out.println(\"press=\"+prev+\" next=\"+next);\n return;\n } // if\n\n if (a_targetIndex == getTabCount()) {\n //System.out.println(\"last: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n addTab(str, cmp);\n setSelectedIndex(getTabCount() - 1);\n } else if (sourceIndex &gt; a_targetIndex) {\n //System.out.println(\" &gt;: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex);\n setSelectedIndex(a_targetIndex);\n } else {\n //System.out.println(\" &lt;: press=\"+prev+\" next=\"+next);\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex - 1);\n setSelectedIndex(a_targetIndex - 1);\n }\n }\n\n private void initTargetLeftRightLine(int next, TabTransferData a_data) { \n if (next &lt; 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } // if\n\n if ((a_data.getTabbedPane() == this)\n &amp;&amp; (a_data.getTabIndex() == next\n || next - a_data.getTabIndex() == 1)) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n } else if (getTabCount() == 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } else if (next == 0) {\n Rectangle rect = getBoundsAt(0);\n m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);\n m_isDrawRect = true;\n } else if (next == getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount() - 1);\n m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n LINEWIDTH, rect.height);\n m_isDrawRect = true;\n } else {\n Rectangle rect = getBoundsAt(next - 1);\n m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n LINEWIDTH, rect.height);\n m_isDrawRect = true;\n }\n }\n\n private void initTargetTopBottomLine(int next, TabTransferData a_data) {\n if (next &lt; 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } // if\n\n if ((a_data.getTabbedPane() == this)\n &amp;&amp; (a_data.getTabIndex() == next\n || next - a_data.getTabIndex() == 1)) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n } else if (getTabCount() == 0) {\n m_lineRect.setRect(0, 0, 0, 0);\n m_isDrawRect = false;\n return;\n } else if (next == getTabCount()) {\n Rectangle rect = getBoundsAt(getTabCount() - 1);\n m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n rect.width, LINEWIDTH);\n m_isDrawRect = true;\n } else if (next == 0) {\n Rectangle rect = getBoundsAt(0);\n m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);\n m_isDrawRect = true;\n } else {\n Rectangle rect = getBoundsAt(next - 1);\n m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n rect.width, LINEWIDTH);\n m_isDrawRect = true;\n }\n }\n\n private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {\n //Point p = (Point) pt.clone();\n getRootPane().setGlassPane(s_glassPane);\n if (hasGhost()) {\n Rectangle rect = getBoundsAt(a_tabIndex);\n BufferedImage image = new BufferedImage(c.getWidth(),\n c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics g = image.getGraphics();\n c.paint(g);\n image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);\n s_glassPane.setImage(image); \n } // if\n\n s_glassPane.setPoint(buildGhostLocation(tabPt));\n s_glassPane.setVisible(true);\n }\n\n private Rectangle getTabAreaBound() {\n Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);\n return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n if (m_isDrawRect) {\n Graphics2D g2 = (Graphics2D) g;\n g2.setPaint(m_lineColor);\n g2.fill(m_lineRect);\n } // if\n }\n\n public interface TabAcceptor {\n boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);\n }\n}\n\nclass GhostGlassPane extends JPanel {\n public static final long serialVersionUID = 1L;\n private final AlphaComposite m_composite;\n\n private Point m_location = new Point(0, 0);\n\n private BufferedImage m_draggingGhost = null;\n\n public GhostGlassPane() {\n setOpaque(false);\n m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);\n }\n\n public void setImage(BufferedImage draggingGhost) {\n m_draggingGhost = draggingGhost;\n }\n\n public void setPoint(Point a_location) {\n m_location.x = a_location.x;\n m_location.y = a_location.y;\n }\n\n public int getGhostWidth() {\n if (m_draggingGhost == null) {\n return 0;\n } // if\n\n return m_draggingGhost.getWidth(this);\n }\n\n public int getGhostHeight() {\n if (m_draggingGhost == null) {\n return 0;\n } // if\n\n return m_draggingGhost.getHeight(this);\n }\n\n public void paintComponent(Graphics g) {\n if (m_draggingGhost == null) {\n return;\n } // if \n\n Graphics2D g2 = (Graphics2D) g;\n g2.setComposite(m_composite);\n\n g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);\n }\n}\n</code></pre>\n" }, { "answer_id": 8610017, "author": "Jay Warrick", "author_id": 1112480, "author_profile": "https://Stackoverflow.com/users/1112480", "pm_score": 3, "selected": false, "text": "<p>@Tony: It looks like <a href=\"https://stackoverflow.com/a/61982/1112480\">Euguenes solution</a> just overlooks preserving TabComponents during a swap.</p>\n\n<p>The convertTab method just needs to remember the TabComponent and set it to the new tabs it makes.</p>\n\n<p>Try using this:</p>\n\n<pre><code> private void convertTab(TabTransferData a_data, int a_targetIndex) {\n\n DnDTabbedPane source = a_data.getTabbedPane();\n System.out.println(\"this=source? \" + (this == source));\n int sourceIndex = a_data.getTabIndex();\n if (sourceIndex &lt; 0) {\n return;\n } // if\n //Save the tab's component, title, and TabComponent.\n Component cmp = source.getComponentAt(sourceIndex);\n String str = source.getTitleAt(sourceIndex);\n Component tcmp = source.getTabComponentAt(sourceIndex);\n\n if (this != source) {\n source.remove(sourceIndex);\n\n if (a_targetIndex == getTabCount()) {\n addTab(str, cmp);\n setTabComponentAt(getTabCount()-1, tcmp);\n } else {\n if (a_targetIndex &lt; 0) {\n a_targetIndex = 0;\n } // if\n\n insertTab(str, null, cmp, null, a_targetIndex);\n setTabComponentAt(a_targetIndex, tcmp);\n } // if\n\n setSelectedComponent(cmp);\n return;\n } // if\n if (a_targetIndex &lt; 0 || sourceIndex == a_targetIndex) {\n return;\n } // if\n if (a_targetIndex == getTabCount()) { \n source.remove(sourceIndex);\n addTab(str, cmp);\n setTabComponentAt(getTabCount() - 1, tcmp);\n setSelectedIndex(getTabCount() - 1);\n } else if (sourceIndex &gt; a_targetIndex) {\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex);\n setTabComponentAt(a_targetIndex, tcmp);\n setSelectedIndex(a_targetIndex);\n } else {\n source.remove(sourceIndex);\n insertTab(str, null, cmp, null, a_targetIndex - 1);\n setTabComponentAt(a_targetIndex - 1, tcmp);\n setSelectedIndex(a_targetIndex - 1);\n }\n\n }\n</code></pre>\n" }, { "answer_id": 20433634, "author": "Pascal", "author_id": 3076046, "author_profile": "https://Stackoverflow.com/users/3076046", "pm_score": 2, "selected": false, "text": "<p>Add this to isDragAcceptable to avoid Exceptions:</p>\n\n<pre><code>boolean transferDataFlavorFound = false;\nfor (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {\n if (FLAVOR.equals(transferDataFlavor)) {\n transferDataFlavorFound = true;\n break;\n }\n}\nif (transferDataFlavorFound == false) {\n return false;\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827/" ]
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs. **EDIT**: [The Java Tutorials - Drag and Drop and Data Transfer](http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html).
I liked [Terai Atsuhiro san's DnDTabbedPane](http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html), but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another. Inspired by @[Tom](https://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing#60306)'s effort, I decided to modify the code myself. There are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse. `setAcceptor(TabAcceptor a_acceptor)` should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns `true`. ``` /** Modified DnDTabbedPane.java * http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html * originally written by Terai Atsuhiro. * so that tabs can be transfered from one pane to another. * eed3si9n. */ import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.geom.*; import java.awt.image.*; import javax.swing.*; public class DnDTabbedPane extends JTabbedPane { public static final long serialVersionUID = 1L; private static final int LINEWIDTH = 3; private static final String NAME = "TabTransferData"; private final DataFlavor FLAVOR = new DataFlavor( DataFlavor.javaJVMLocalObjectMimeType, NAME); private static GhostGlassPane s_glassPane = new GhostGlassPane(); private boolean m_isDrawRect = false; private final Rectangle2D m_lineRect = new Rectangle2D.Double(); private final Color m_lineColor = new Color(0, 100, 255); private TabAcceptor m_acceptor = null; public DnDTabbedPane() { super(); final DragSourceListener dsl = new DragSourceListener() { public void dragEnter(DragSourceDragEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); } public void dragExit(DragSourceEvent e) { e.getDragSourceContext() .setCursor(DragSource.DefaultMoveNoDrop); m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; s_glassPane.setPoint(new Point(-1000, -1000)); s_glassPane.repaint(); } public void dragOver(DragSourceDragEvent e) { //e.getLocation() //This method returns a Point indicating the cursor location in screen coordinates at the moment TabTransferData data = getTabTransferData(e); if (data == null) { e.getDragSourceContext().setCursor( DragSource.DefaultMoveNoDrop); return; } // if /* Point tabPt = e.getLocation(); SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this); if (DnDTabbedPane.this.contains(tabPt)) { int targetIdx = getTargetTabIndex(tabPt); int sourceIndex = data.getTabIndex(); if (getTabAreaBound().contains(tabPt) && (targetIdx >= 0) && (targetIdx != sourceIndex) && (targetIdx != sourceIndex + 1)) { e.getDragSourceContext().setCursor( DragSource.DefaultMoveDrop); return; } // if e.getDragSourceContext().setCursor( DragSource.DefaultMoveNoDrop); return; } // if */ e.getDragSourceContext().setCursor( DragSource.DefaultMoveDrop); } public void dragDropEnd(DragSourceDropEvent e) { m_isDrawRect = false; m_lineRect.setRect(0, 0, 0, 0); // m_dragTabIndex = -1; if (hasGhost()) { s_glassPane.setVisible(false); s_glassPane.setImage(null); } } public void dropActionChanged(DragSourceDragEvent e) { } }; final DragGestureListener dgl = new DragGestureListener() { public void dragGestureRecognized(DragGestureEvent e) { // System.out.println("dragGestureRecognized"); Point tabPt = e.getDragOrigin(); int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y); if (dragTabIndex < 0) { return; } // if initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex); try { e.startDrag(DragSource.DefaultMoveDrop, new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl); } catch (InvalidDnDOperationException idoe) { idoe.printStackTrace(); } } }; //dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true); new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl); m_acceptor = new TabAcceptor() { public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) { return true; } }; } public TabAcceptor getAcceptor() { return m_acceptor; } public void setAcceptor(TabAcceptor a_value) { m_acceptor = a_value; } private TabTransferData getTabTransferData(DropTargetDropEvent a_event) { try { TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); return data; } catch (Exception e) { e.printStackTrace(); } return null; } private TabTransferData getTabTransferData(DropTargetDragEvent a_event) { try { TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR); return data; } catch (Exception e) { e.printStackTrace(); } return null; } private TabTransferData getTabTransferData(DragSourceDragEvent a_event) { try { TabTransferData data = (TabTransferData) a_event.getDragSourceContext() .getTransferable().getTransferData(FLAVOR); return data; } catch (Exception e) { e.printStackTrace(); } return null; } class TabTransferable implements Transferable { private TabTransferData m_data = null; public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) { m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex); } public Object getTransferData(DataFlavor flavor) { return m_data; // return DnDTabbedPane.this; } public DataFlavor[] getTransferDataFlavors() { DataFlavor[] f = new DataFlavor[1]; f[0] = FLAVOR; return f; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getHumanPresentableName().equals(NAME); } } class TabTransferData { private DnDTabbedPane m_tabbedPane = null; private int m_tabIndex = -1; public TabTransferData() { } public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) { m_tabbedPane = a_tabbedPane; m_tabIndex = a_tabIndex; } public DnDTabbedPane getTabbedPane() { return m_tabbedPane; } public void setTabbedPane(DnDTabbedPane pane) { m_tabbedPane = pane; } public int getTabIndex() { return m_tabIndex; } public void setTabIndex(int index) { m_tabIndex = index; } } private Point buildGhostLocation(Point a_location) { Point retval = new Point(a_location); switch (getTabPlacement()) { case JTabbedPane.TOP: { retval.y = 1; retval.x -= s_glassPane.getGhostWidth() / 2; } break; case JTabbedPane.BOTTOM: { retval.y = getHeight() - 1 - s_glassPane.getGhostHeight(); retval.x -= s_glassPane.getGhostWidth() / 2; } break; case JTabbedPane.LEFT: { retval.x = 1; retval.y -= s_glassPane.getGhostHeight() / 2; } break; case JTabbedPane.RIGHT: { retval.x = getWidth() - 1 - s_glassPane.getGhostWidth(); retval.y -= s_glassPane.getGhostHeight() / 2; } break; } // switch retval = SwingUtilities.convertPoint(DnDTabbedPane.this, retval, s_glassPane); return retval; } class CDropTargetListener implements DropTargetListener { public void dragEnter(DropTargetDragEvent e) { // System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this); if (isDragAcceptable(e)) { e.acceptDrag(e.getDropAction()); } else { e.rejectDrag(); } // if } public void dragExit(DropTargetEvent e) { // System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this); m_isDrawRect = false; } public void dropActionChanged(DropTargetDragEvent e) { } public void dragOver(final DropTargetDragEvent e) { TabTransferData data = getTabTransferData(e); if (getTabPlacement() == JTabbedPane.TOP || getTabPlacement() == JTabbedPane.BOTTOM) { initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data); } else { initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data); } // if-else repaint(); if (hasGhost()) { s_glassPane.setPoint(buildGhostLocation(e.getLocation())); s_glassPane.repaint(); } } public void drop(DropTargetDropEvent a_event) { // System.out.println("DropTarget.drop: " + DnDTabbedPane.this); if (isDropAcceptable(a_event)) { convertTab(getTabTransferData(a_event), getTargetTabIndex(a_event.getLocation())); a_event.dropComplete(true); } else { a_event.dropComplete(false); } // if-else m_isDrawRect = false; repaint(); } public boolean isDragAcceptable(DropTargetDragEvent e) { Transferable t = e.getTransferable(); if (t == null) { return false; } // if DataFlavor[] flavor = e.getCurrentDataFlavors(); if (!t.isDataFlavorSupported(flavor[0])) { return false; } // if TabTransferData data = getTabTransferData(e); if (DnDTabbedPane.this == data.getTabbedPane() && data.getTabIndex() >= 0) { return true; } // if if (DnDTabbedPane.this != data.getTabbedPane()) { if (m_acceptor != null) { return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex()); } // if } // if return false; } public boolean isDropAcceptable(DropTargetDropEvent e) { Transferable t = e.getTransferable(); if (t == null) { return false; } // if DataFlavor[] flavor = e.getCurrentDataFlavors(); if (!t.isDataFlavorSupported(flavor[0])) { return false; } // if TabTransferData data = getTabTransferData(e); if (DnDTabbedPane.this == data.getTabbedPane() && data.getTabIndex() >= 0) { return true; } // if if (DnDTabbedPane.this != data.getTabbedPane()) { if (m_acceptor != null) { return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex()); } // if } // if return false; } } private boolean m_hasGhost = true; public void setPaintGhost(boolean flag) { m_hasGhost = flag; } public boolean hasGhost() { return m_hasGhost; } /** * returns potential index for drop. * @param a_point point given in the drop site component's coordinate * @return returns potential index for drop. */ private int getTargetTabIndex(Point a_point) { boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP || getTabPlacement() == JTabbedPane.BOTTOM; // if the pane is empty, the target index is always zero. if (getTabCount() == 0) { return 0; } // if for (int i = 0; i < getTabCount(); i++) { Rectangle r = getBoundsAt(i); if (isTopOrBottom) { r.setRect(r.x - r.width / 2, r.y, r.width, r.height); } else { r.setRect(r.x, r.y - r.height / 2, r.width, r.height); } // if-else if (r.contains(a_point)) { return i; } // if } // for Rectangle r = getBoundsAt(getTabCount() - 1); if (isTopOrBottom) { int x = r.x + r.width / 2; r.setRect(x, r.y, getWidth() - x, r.height); } else { int y = r.y + r.height / 2; r.setRect(r.x, y, r.width, getHeight() - y); } // if-else return r.contains(a_point) ? getTabCount() : -1; } private void convertTab(TabTransferData a_data, int a_targetIndex) { DnDTabbedPane source = a_data.getTabbedPane(); int sourceIndex = a_data.getTabIndex(); if (sourceIndex < 0) { return; } // if Component cmp = source.getComponentAt(sourceIndex); String str = source.getTitleAt(sourceIndex); if (this != source) { source.remove(sourceIndex); if (a_targetIndex == getTabCount()) { addTab(str, cmp); } else { if (a_targetIndex < 0) { a_targetIndex = 0; } // if insertTab(str, null, cmp, null, a_targetIndex); } // if setSelectedComponent(cmp); // System.out.println("press="+sourceIndex+" next="+a_targetIndex); return; } // if if (a_targetIndex < 0 || sourceIndex == a_targetIndex) { //System.out.println("press="+prev+" next="+next); return; } // if if (a_targetIndex == getTabCount()) { //System.out.println("last: press="+prev+" next="+next); source.remove(sourceIndex); addTab(str, cmp); setSelectedIndex(getTabCount() - 1); } else if (sourceIndex > a_targetIndex) { //System.out.println(" >: press="+prev+" next="+next); source.remove(sourceIndex); insertTab(str, null, cmp, null, a_targetIndex); setSelectedIndex(a_targetIndex); } else { //System.out.println(" <: press="+prev+" next="+next); source.remove(sourceIndex); insertTab(str, null, cmp, null, a_targetIndex - 1); setSelectedIndex(a_targetIndex - 1); } } private void initTargetLeftRightLine(int next, TabTransferData a_data) { if (next < 0) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; return; } // if if ((a_data.getTabbedPane() == this) && (a_data.getTabIndex() == next || next - a_data.getTabIndex() == 1)) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; } else if (getTabCount() == 0) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; return; } else if (next == 0) { Rectangle rect = getBoundsAt(0); m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height); m_isDrawRect = true; } else if (next == getTabCount()) { Rectangle rect = getBoundsAt(getTabCount() - 1); m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height); m_isDrawRect = true; } else { Rectangle rect = getBoundsAt(next - 1); m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height); m_isDrawRect = true; } } private void initTargetTopBottomLine(int next, TabTransferData a_data) { if (next < 0) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; return; } // if if ((a_data.getTabbedPane() == this) && (a_data.getTabIndex() == next || next - a_data.getTabIndex() == 1)) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; } else if (getTabCount() == 0) { m_lineRect.setRect(0, 0, 0, 0); m_isDrawRect = false; return; } else if (next == getTabCount()) { Rectangle rect = getBoundsAt(getTabCount() - 1); m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2, rect.width, LINEWIDTH); m_isDrawRect = true; } else if (next == 0) { Rectangle rect = getBoundsAt(0); m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH); m_isDrawRect = true; } else { Rectangle rect = getBoundsAt(next - 1); m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2, rect.width, LINEWIDTH); m_isDrawRect = true; } } private void initGlassPane(Component c, Point tabPt, int a_tabIndex) { //Point p = (Point) pt.clone(); getRootPane().setGlassPane(s_glassPane); if (hasGhost()) { Rectangle rect = getBoundsAt(a_tabIndex); BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); c.paint(g); image = image.getSubimage(rect.x, rect.y, rect.width, rect.height); s_glassPane.setImage(image); } // if s_glassPane.setPoint(buildGhostLocation(tabPt)); s_glassPane.setVisible(true); } private Rectangle getTabAreaBound() { Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1); return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height); } public void paintComponent(Graphics g) { super.paintComponent(g); if (m_isDrawRect) { Graphics2D g2 = (Graphics2D) g; g2.setPaint(m_lineColor); g2.fill(m_lineRect); } // if } public interface TabAcceptor { boolean isDropAcceptable(DnDTabbedPane a_component, int a_index); } } class GhostGlassPane extends JPanel { public static final long serialVersionUID = 1L; private final AlphaComposite m_composite; private Point m_location = new Point(0, 0); private BufferedImage m_draggingGhost = null; public GhostGlassPane() { setOpaque(false); m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f); } public void setImage(BufferedImage draggingGhost) { m_draggingGhost = draggingGhost; } public void setPoint(Point a_location) { m_location.x = a_location.x; m_location.y = a_location.y; } public int getGhostWidth() { if (m_draggingGhost == null) { return 0; } // if return m_draggingGhost.getWidth(this); } public int getGhostHeight() { if (m_draggingGhost == null) { return 0; } // if return m_draggingGhost.getHeight(this); } public void paintComponent(Graphics g) { if (m_draggingGhost == null) { return; } // if Graphics2D g2 = (Graphics2D) g; g2.setComposite(m_composite); g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null); } } ```
60,278
<p>In all the Git tutorials I've read they say that you can do:</p> <pre><code>git init git add . git commit </code></pre> <p>When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.</p>
[ { "answer_id": 60283, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 3, "selected": false, "text": "<p>The <code>git commit</code> command will open up the editor specified in the <code>EDITOR</code> environment variable so you can enter a commit comment. On a Linux or BSD system, this should be vi by default, although any editor should work.</p>\n\n<p>Just enter your comments and save the file.</p>\n" }, { "answer_id": 60284, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>The <code>-m</code> option to commit lets you enter a commit message on the command line:</p>\n\n<pre><code>git commit -m \"my first commit\"\n</code></pre>\n" }, { "answer_id": 60286, "author": "Lou", "author_id": 4341, "author_profile": "https://Stackoverflow.com/users/4341", "pm_score": 5, "selected": false, "text": "<p>The text file that is being opened is a summary of the current commit operation. The git commit drops you into this file so the you can add a commit message at the top of the file. Once you've added your message just save and exit from this file.</p>\n\n<p>There is also a \"-m msg\" switch on this command that allows you to add the commit message on the command line.</p>\n" }, { "answer_id": 60292, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 1, "selected": false, "text": "<p>When doing revision control, you should always explain what the changed you made are. Usually the first time you're have a comment such as \"Initial Commit.\"</p>\n\n<p>However in the long run you want to make a good comment for each commit. You will want something of the form:</p>\n\n<blockquote>\n <p>Added experimental feature x.</p>\n \n <p>X will increase the performance of\n feature Y in condition Z. Should you\n need X activate it with the -x or\n --feature-eks switches. This addresses feature request #1138.</p>\n</blockquote>\n" }, { "answer_id": 60311, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 6, "selected": false, "text": "<p>As mentioned by <a href=\"https://stackoverflow.com/questions/60278/git-commit-text-file#60283\">Ben Collins</a>, without the <code>-m \"...\"</code> argument to type the commit inline (which is generally a bad idea as it encourages you to be brief), this \"big text file\" that is opened up is a window in which to type the commit message.</p>\n\n<p>Usually it's recommended to write a summary in the first line, skip a line, and then write more detailed notes beneath; this helps programs that do things like email the commit messages with an appropriate subject line and the full list of changes made in the body.</p>\n\n<p>Instead of changing the <code>EDITOR</code> shell variable, you can also change the editor used by adding the additional lines in your <code>~/.gitconfig</code> file:</p>\n\n<pre><code>[core]\n editor = emacs\n excludesfile = /Users/will/.gitignore\n</code></pre>\n\n<p>That second line actually has nothing to do with your problem, but I find it really useful so I can populate my <code>~/.gitignore</code> file with all those filetypes I <em>know</em> I'll never, ever, want to commit to a repository.</p>\n" }, { "answer_id": 60320, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 1, "selected": false, "text": "<p>Yeah, make sure you have a sensible editor set. Not sure what your default editor will be but if, like me, it is <code>nano</code> (it will say so somewhere near the top after you type commit) you just need to type in a comment and then hit <kbd>Ctrl</kbd>-<kbd>X</kbd> to finish. Then hit <kbd>y</kbd>, followed by <kbd>enter</kbd> to affirm the commit.</p>\n<p>Also, if you want to see a simple list of the files you'll be committing rather than a huge diff listing beforehand try</p>\n<pre class=\"lang-sh prettyprint-override\"><code>git diff --name-only\n</code></pre>\n" }, { "answer_id": 466803, "author": "Stephen Bailey", "author_id": 15385, "author_profile": "https://Stackoverflow.com/users/15385", "pm_score": 4, "selected": false, "text": "<p>As all have said this is just where you add your commit comment - but for some it may still be confusing esp if you have not configured your editor settings, and you are not aware of what <a href=\"http://en.wikipedia.org/wiki/Vi\" rel=\"noreferrer\">VI</a> is : then you could be in for a shock, because you will think you are still in the GIT-Bash</p>\n\n<p>In that case you are in fact in a text editor with some interesting ways of dealing with things and <a href=\"http://www.tuxfiles.org/linuxhelp/vimcheat.html\" rel=\"noreferrer\">this set of commands</a> may help you out so that you can get past your first commit and then configure an editor you are familiar with or use it as an opportunity to learn how to use it.</p>\n" }, { "answer_id": 532094, "author": "vikhyat", "author_id": 257349, "author_profile": "https://Stackoverflow.com/users/257349", "pm_score": 7, "selected": false, "text": "<p>You're meant to put the commit message in this text file, then save and quit.</p>\n\n<p>You can change the default text editor that git uses with this command:</p>\n\n<pre><code>git config --global core.editor \"nano\"\n</code></pre>\n\n<p>You have to change nano to whatever command would normally open your text editor.</p>\n" }, { "answer_id": 1077672, "author": "PHLAK", "author_id": 27025, "author_profile": "https://Stackoverflow.com/users/27025", "pm_score": 0, "selected": false, "text": "<p>The following is probably the easiest way to commit all changes:</p>\n\n<pre><code>git commit -a -m \"Type your commit message here...\"\n</code></pre>\n\n<p>Of course there are much more detailed ways of committing, but that should get you started.</p>\n" }, { "answer_id": 1385246, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If you’re on Mac OS X and using BBEdit, you can set this up as the editor of choice for commit messages:</p>\n\n<pre><code>git config --global core.editor \"bbedit -w\"\n</code></pre>\n\n<p>Once finished edit, save and close the file and git will use it for the comments.</p>\n" }, { "answer_id": 1464333, "author": "TheGeoff", "author_id": 18095, "author_profile": "https://Stackoverflow.com/users/18095", "pm_score": 3, "selected": false, "text": "<p>Try Escape then ZZ, after you're done typing your message.\nAs others have said when you run that commit command it actually runs a text editor to enter the message into.\nIn my case (OS X) it was VI, which I figured out after some digging around.\nIn that case, hit Escape to go into \"command\" mode (as opposed to INSERT mode) the enter ZZ. I'm sure there are other ways of accomplishing the task but that did it for me.\nHaving never used VI or emacs it wasn't readily apparent to me and wasn't mentioned in any of the beginner guides I was using.\nHopefully this helps.</p>\n" }, { "answer_id": 2988154, "author": "user360221", "author_id": 360221, "author_profile": "https://Stackoverflow.com/users/360221", "pm_score": 2, "selected": false, "text": "<p>I was confused because I kept trying to enter a filename after the :w in VIM. That doesn't trigger the commit. Instead I kept getting a message \"Aborting commit due to empty commit message.\" Don't put a filename after the :w. :w saves the file to .git/COMMIT_EDITMSG by default. Then :q to exit to complete the commit. You can see the results with git log.</p>\n" }, { "answer_id": 3983599, "author": "Yarito", "author_id": 482433, "author_profile": "https://Stackoverflow.com/users/482433", "pm_score": 1, "selected": false, "text": "<p>Being new to Terminal as well, \"Escape and then ZZ\" worked for me, I've been having this issue for months and also couldn't find a way around it. </p>\n\n<p>Thanks TheGeoff for your simple advice!</p>\n" }, { "answer_id": 4658092, "author": "Peter", "author_id": 571309, "author_profile": "https://Stackoverflow.com/users/571309", "pm_score": 2, "selected": false, "text": "<p>Now that I've changed my editor to emacs, everything work fine.</p>\n\n<p>But before I set this, \"git commit -a\" did open gedit, but also immediately ended with a \"Aborting commit due to empty commit message.\". Saving the file from gedit had no effect. Explicitly setting the editor with \"git config --global core.editor \"gedit\"\" had the same result.</p>\n\n<p>There's nothing wrong with emacs, but out of curiosity why doesn't this work with gedit, and is there any way to get it to work?</p>\n\n<p>Thanks.</p>\n" }, { "answer_id": 5747603, "author": "MatthiasS", "author_id": 163725, "author_profile": "https://Stackoverflow.com/users/163725", "pm_score": 4, "selected": false, "text": "<p>Assuming that your editor defaults to vi/vim, you can exit the commit message editor by typing:</p>\n\n<pre><code>:x\n</code></pre>\n\n<p>which will save and exit the commit message file. Then you'll go back to the normal git command section.</p>\n\n<p><em>More vi commands:<br>\n<a href=\"http://www.lagmonster.org/docs/vi.html\" rel=\"nofollow noreferrer\">http://www.lagmonster.org/docs/vi.html</a></em></p>\n" }, { "answer_id": 10051167, "author": "JiuJitsuCoder", "author_id": 1318525, "author_profile": "https://Stackoverflow.com/users/1318525", "pm_score": 2, "selected": false, "text": "<p>For those of you using OS X I found this command to work well:<br>\n<code>git config --global core.editor \"open -t -W\"</code></p>\n\n<p>which will force git to open the default text editor (textedit in my case) and then wait for you to exit the application. Keep in mind that you need to \"Save\" and then \"Quit\" textedit before the commit will go through. There are a few other commands you can play around with as detailed on this page:</p>\n\n<p><a href=\"http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/open.1.html\" rel=\"nofollow noreferrer\" title=\"Apple Developer Library - Open Command\">Apple Developer Library - Open Command</a></p>\n\n<p>You can also try <code>git config --global core.editor \"open -e -W\"</code> if you want git to always open textedit regardless of what the default editor is.</p>\n" }, { "answer_id": 15530614, "author": "nothankyou", "author_id": 1388224, "author_profile": "https://Stackoverflow.com/users/1388224", "pm_score": 3, "selected": false, "text": "<p>When you create a new commit, git fires up a text editor and writes some stuff into it.</p>\n\n<p><strong>Using this text editor, the intention is for you to write the commit message that will be associated with your feshly created commit.</strong></p>\n\n<p><strong>After you have finished doing so, save and exit the text editor. Git will use what you've written as the commit message.</strong></p>\n\n<p>The commit message has a particular structure, described as follows: </p>\n\n<p>The first line of the commit message is used as the message header (or title). The preffered length of the commit header is less than 40 characters, as this is the number of characters that github displays on the Commits tab of a given repository before truncating it, which some people find irritating.</p>\n\n<p>When composing the header, using a capitalized, present tense verb for the first word is common practice, though not at all required. </p>\n\n<p>One newline delineates the header and body of the message.</p>\n\n<p>The body can consist whatever you like. An overview of the changes introduced by your commit is reasonable. Some third party applications use info included the body of commit messages to set off various kinds of hooks (I'm thinking Gerrit and Pivotal Tracker, to name two). </p>\n\n<p>Here's a short and sweet example. A leading <code>#</code> denotes a comment.</p>\n\n<pre><code>Gitignore index.pyc\n\nIgnore gunicorn generated binary file\n# Please enter the commit message for your changes. Lines starting\n# with '#' will be ignored, and an empty message aborts the commit.\n# On branch dev\n# Your branch is ahead of 'origin/dev' by 10 commits.\n# (use \"git push\" to publish your local commits)\n#\n# Changes to be committed:\n# (use \"git reset HEAD &lt;file&gt;...\" to unstage)\n#\n# modified: .gitignore\n#\n</code></pre>\n\n<p><a href=\"https://gist.github.com/matthewhudson/1475276\">Here</a> one Mr. Torvalds opines on what makes a good commit.</p>\n\n<p>And <a href=\"http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html\">here</a> Tpope does likewise.</p>\n\n<p>As stated in several other answers, changing the default editor is a one-liner on the command line. </p>\n\n<p>For my preference: </p>\n\n<pre><code>git config --global core.editor \"vim\"\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In all the Git tutorials I've read they say that you can do: ``` git init git add . git commit ``` When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.
You're meant to put the commit message in this text file, then save and quit. You can change the default text editor that git uses with this command: ``` git config --global core.editor "nano" ``` You have to change nano to whatever command would normally open your text editor.
60,290
<p>Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>
[ { "answer_id": 60294, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 1, "selected": false, "text": "<p>The way I usually see things done with smaller images such as buttons it that only a certain portion of the image is shown. Then many states of the picture will make up a larger picture which gets shifted around behind the visible port. I'll delete this when someone has code.</p>\n" }, { "answer_id": 60295, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://www.w3schools.com/css/css_image_transparency.asp\" rel=\"nofollow noreferrer\">Here's some good information about image opacity and transparency with CSS</a>.</p>\n\n<p>So to make an image with opacity 50%, you'd do this:</p>\n\n<pre><code>&lt;img src=\"image.png\" style=\"opacity: 0.5; filter: alpha(opacity=50)\" /&gt;\n</code></pre>\n\n<p>The <strong>opacity:</strong> part is how Firefox does it, and it's a value between 0.0 and 1.0. <strong>filter:</strong> is how IE does it, and it's a value from 0 to 100.</p>\n" }, { "answer_id": 60316, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 3, "selected": false, "text": "<p>You don't use an img tag, but an element with a background-image css attribute and set the background-position on hover. IE requires an 'a' tag as a parent element for the :hover selector. They are called css sprites.</p>\n\n<p><a href=\"http://www.alistapart.com/articles/sprites/\" rel=\"nofollow noreferrer\">A great article explaining how to use CSS sprites</a>.</p>\n" }, { "answer_id": 60322, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here's some code to play with. Basic idea: put all possible states of the picture into one big image, set a \"window size\", that's smaller than the image; move the window around using <code>background-position</code>.</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>#test {\r\n display: block;\r\n width: 250px; /* window */\r\n height: 337px; /* size */\r\n background: url(http://vi.sualize.us/thumbs/08/09/01/fashion,indie,inspiration,portrait-f825c152cc04c3dbbb6a38174a32a00f_h.jpg) no-repeat; /* put the image */\r\n border: 1px solid red; /* for debugging */\r\n text-indent: -1000px; /* hide the text */\r\n}\r\n\r\n#test:hover {\r\n background-position: -250px 0; /* on mouse over move the window to a different part of the image */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a href=\"#\" id=\"test\"&gt;a button&lt;/a&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?
[Here's some good information about image opacity and transparency with CSS](http://www.w3schools.com/css/css_image_transparency.asp). So to make an image with opacity 50%, you'd do this: ``` <img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" /> ``` The **opacity:** part is how Firefox does it, and it's a value between 0.0 and 1.0. **filter:** is how IE does it, and it's a value from 0 to 100.
60,293
<p>I have a little problem with a Listview.</p> <p>I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header. </p> <p>If you have a thought on what can be done to make the background draw I'd love to hear it. </p> <p>Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]</p> <p><strong>Edit:</strong></p> <p>Here is a sample that exhibits the problem.</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); ListView lv = new ListView(); lv.Dock = System.Windows.Forms.DockStyle.Fill; lv.FullRowSelect = true; lv.GridLines = true; lv.HideSelection = false; lv.Location = new System.Drawing.Point(0, 0); lv.TabIndex = 0; lv.View = System.Windows.Forms.View.Details; lv.AllowColumnReorder = true; this.Controls.Add(lv); lv.MultiSelect = true; ColumnHeader ch = new ColumnHeader(); ch.Name = "Foo"; ch.Text = "Foo"; ch.Width = 40; ch.TextAlign = HorizontalAlignment.Left; lv.Columns.Add(ch); ColumnHeader ch2 = new ColumnHeader(); ch.Name = "Bar"; ch.Text = "Bar"; ch.Width = 40; ch.TextAlign = HorizontalAlignment.Left; lv.Columns.Add(ch2); lv.BeginUpdate(); for (int i = 0; i &lt; 3; i++) { ListViewItem lvi = new ListViewItem("1", "2"); lvi.BackColor = Color.Black; lvi.ForeColor = Color.White; lv.Items.Add(lvi); } lv.EndUpdate(); } } </code></pre>
[ { "answer_id": 60300, "author": "moobaa", "author_id": 3569, "author_profile": "https://Stackoverflow.com/users/3569", "pm_score": 1, "selected": false, "text": "<p>(Prior to the Edit...)</p>\n\n<p>I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is applied across the control just fine (with and without images).</p>\n\n<p>Are you doing any Custom Painting at all?</p>\n" }, { "answer_id": 60339, "author": "moobaa", "author_id": 3569, "author_profile": "https://Stackoverflow.com/users/3569", "pm_score": 4, "selected": true, "text": "<p>Ah! I see now :}</p>\n\n<p>You want hacky? I present unto you the following:</p>\n\n<pre><code> ...\n lv.OwnerDraw = true;\n lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );\n ...\n\nvoid lv_DrawItem( object sender, DrawListViewItemEventArgs e )\n{\n Rectangle foo = e.Bounds;\n foo.Offset( -10, 0 );\n e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo );\n e.DrawDefault = true;\n}\n</code></pre>\n\n<p>For a more inventive - and no less hacky - approach, you could try utilising the background image of the ListView ;)</p>\n" }, { "answer_id": 80045, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 0, "selected": false, "text": "<p>Ok I'm adding some additional solution notes. If you use the solution above you also need to insert a draw handler for the column headers, otherwise they won't paint. The selected item rectangle also looks funny so you'll want to check for that in the lv_DrawItem function and implement a similar solution. Remeber that highlighting is chosen at the system level and not in you application. </p>\n" }, { "answer_id": 23231928, "author": "Libor", "author_id": 148156, "author_profile": "https://Stackoverflow.com/users/148156", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.componentowl.com/better-listview\" rel=\"nofollow noreferrer\">Better ListView</a> (and free <a href=\"http://www.componentowl.com/better-listview-express\" rel=\"nofollow noreferrer\">Better ListView Express</a>) allows setting background image with various alignment settings (centered, tiled, stretched, fit, snap to border/corner). Alpha transparency is also supported:</p>\n\n<p><img src=\"https://i.stack.imgur.com/OZicy.png\" alt=\"enter image description here\"></p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327/" ]
I have a little problem with a Listview. I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header. If you have a thought on what can be done to make the background draw I'd love to hear it. Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.] **Edit:** Here is a sample that exhibits the problem. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); ListView lv = new ListView(); lv.Dock = System.Windows.Forms.DockStyle.Fill; lv.FullRowSelect = true; lv.GridLines = true; lv.HideSelection = false; lv.Location = new System.Drawing.Point(0, 0); lv.TabIndex = 0; lv.View = System.Windows.Forms.View.Details; lv.AllowColumnReorder = true; this.Controls.Add(lv); lv.MultiSelect = true; ColumnHeader ch = new ColumnHeader(); ch.Name = "Foo"; ch.Text = "Foo"; ch.Width = 40; ch.TextAlign = HorizontalAlignment.Left; lv.Columns.Add(ch); ColumnHeader ch2 = new ColumnHeader(); ch.Name = "Bar"; ch.Text = "Bar"; ch.Width = 40; ch.TextAlign = HorizontalAlignment.Left; lv.Columns.Add(ch2); lv.BeginUpdate(); for (int i = 0; i < 3; i++) { ListViewItem lvi = new ListViewItem("1", "2"); lvi.BackColor = Color.Black; lvi.ForeColor = Color.White; lv.Items.Add(lvi); } lv.EndUpdate(); } } ```
Ah! I see now :} You want hacky? I present unto you the following: ``` ... lv.OwnerDraw = true; lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem ); ... void lv_DrawItem( object sender, DrawListViewItemEventArgs e ) { Rectangle foo = e.Bounds; foo.Offset( -10, 0 ); e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo ); e.DrawDefault = true; } ``` For a more inventive - and no less hacky - approach, you could try utilising the background image of the ListView ;)
60,302
<p>If I start a process via Java's <a href="http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html" rel="noreferrer">ProcessBuilder</a> class, I have full access to that process's standard in, standard out, and standard error streams as Java <code>InputStreams</code> and <code>OutputStreams</code>. However, I can't find a way to seamlessly connect those streams to <code>System.in</code>, <code>System.out</code>, and <code>System.err</code>.</p> <p>It's possible to use <code>redirectErrorStream()</code> to get a single <code>InputStream</code> that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C <code>system()</code> call.</p> <p>This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of <a href="http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html" rel="noreferrer"><code>isatty()</code></a> in the child process carries through the redirection.</p>
[ { "answer_id": 60578, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 5, "selected": true, "text": "<p>You will need to copy the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Process.html\" rel=\"noreferrer\">Process</a> out, err, and input streams to the System versions. The easiest way to do that is using the <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html\" rel=\"noreferrer\">IOUtils</a> class from the Commons IO package. The <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29\" rel=\"noreferrer\">copy method</a> looks to be what you need. The copy method invocations will need to be in separate threads. </p>\n\n<p>Here is the basic code:</p>\n\n<pre><code>// Assume you already have a processBuilder all configured and ready to go\nfinal Process process = processBuilder.start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(process.getOutputStream(), System.out);\n} } ).start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(process.getErrorStream(), System.err);\n} } ).start();\nnew Thread(new Runnable() {public void run() {\n IOUtils.copy(System.in, process.getInputStream());\n} } ).start();\n</code></pre>\n" }, { "answer_id": 1570269, "author": "Eelco", "author_id": 445367, "author_profile": "https://Stackoverflow.com/users/445367", "pm_score": 4, "selected": false, "text": "<p>A variation on John's answer that compiles and doesn't require you to use Commons IO:</p>\n\n<pre><code>private static void pipeOutput(Process process) {\n pipe(process.getErrorStream(), System.err);\n pipe(process.getInputStream(), System.out);\n}\n\nprivate static void pipe(final InputStream src, final PrintStream dest) {\n new Thread(new Runnable() {\n public void run() {\n try {\n byte[] buffer = new byte[1024];\n for (int n = 0; n != -1; n = src.read(buffer)) {\n dest.write(buffer, 0, n);\n }\n } catch (IOException e) { // just exit\n }\n }\n }).start();\n}\n</code></pre>\n" }, { "answer_id": 6303744, "author": "claude", "author_id": 792382, "author_profile": "https://Stackoverflow.com/users/792382", "pm_score": 2, "selected": false, "text": "<p>For <code>System.in</code> use the following <code>pipein()</code> instead of <code>pipe()</code></p>\n\n<pre><code>pipein(System.in, p.getOutputStream());\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>private static void pipein(final InputStream src, final OutputStream dest) {\n\n new Thread(new Runnable() {\n public void run() {\n try {\n int ret = -1;\n while ((ret = System.in.read()) != -1) {\n dest.write(ret);\n dest.flush();\n }\n } catch (IOException e) { // just exit\n }\n }\n }).start();\n\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5696/" ]
If I start a process via Java's [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html) class, I have full access to that process's standard in, standard out, and standard error streams as Java `InputStreams` and `OutputStreams`. However, I can't find a way to seamlessly connect those streams to `System.in`, `System.out`, and `System.err`. It's possible to use `redirectErrorStream()` to get a single `InputStream` that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C `system()` call. This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of [`isatty()`](http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html) in the child process carries through the redirection.
You will need to copy the [Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) out, err, and input streams to the System versions. The easiest way to do that is using the [IOUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html) class from the Commons IO package. The [copy method](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29) looks to be what you need. The copy method invocations will need to be in separate threads. Here is the basic code: ``` // Assume you already have a processBuilder all configured and ready to go final Process process = processBuilder.start(); new Thread(new Runnable() {public void run() { IOUtils.copy(process.getOutputStream(), System.out); } } ).start(); new Thread(new Runnable() {public void run() { IOUtils.copy(process.getErrorStream(), System.err); } } ).start(); new Thread(new Runnable() {public void run() { IOUtils.copy(System.in, process.getInputStream()); } } ).start(); ```
60,352
<p>If all of my <code>__init__.py</code> files are empty, do I have to store them into version control, or is there a way to make <code>distutils</code> create empty <code>__init__.py</code> files during installation?</p>
[ { "answer_id": 60431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>In Python, <code>__init__.py</code> files actually have a meaning! They mean that the folder they are in is a Python module. As such, they have a real role in your code and should most probably be stored in Version Control.</p>\n\n<p>You could well imagine a folder in your source tree that is NOT a Python module, for example a folder containing only resources (e.g. images) and no code. That folder would not need to have a <code>__init__.py</code> file in it. Now how do you make the difference between folders where distutils should create those files and folders where it should not ?</p>\n" }, { "answer_id": 60506, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": true, "text": "<p>Is there a reason you want to <em>avoid</em> putting empty <code>__init__.py</code> files in version control? If you do this you won't be able to <code>import</code> your packages from the source directory wihout first running distutils.</p>\n\n<p>If you really want to, I suppose you can create <code>__init__.py</code> in <code>setup.py</code>. It has to be <em>before</em> running <code>distutils.setup</code>, so <code>setup</code> itself is able to find your packages:</p>\n\n<pre><code>from distutils import setup\nimport os\n\nfor path in [my_package_directories]:\n filename = os.path.join(pagh, '__init__.py')\n if not os.path.exists(filename):\n init = open(filename, 'w')\n init.close()\n\nsetup(\n...\n)\n</code></pre>\n\n<p>but... what would you gain from this, compared to having the empty <code>__init__.py</code> files there in the first place? </p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679/" ]
If all of my `__init__.py` files are empty, do I have to store them into version control, or is there a way to make `distutils` create empty `__init__.py` files during installation?
Is there a reason you want to *avoid* putting empty `__init__.py` files in version control? If you do this you won't be able to `import` your packages from the source directory wihout first running distutils. If you really want to, I suppose you can create `__init__.py` in `setup.py`. It has to be *before* running `distutils.setup`, so `setup` itself is able to find your packages: ``` from distutils import setup import os for path in [my_package_directories]: filename = os.path.join(pagh, '__init__.py') if not os.path.exists(filename): init = open(filename, 'w') init.close() setup( ... ) ``` but... what would you gain from this, compared to having the empty `__init__.py` files there in the first place?
60,369
<p>I'm currently playing around with <a href="http://pear.php.net/package/HTML_QuickForm" rel="noreferrer">HTML_QuickForm</a> for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.</p> <p>Are there any alternatives to QuickForm that might provide more flexibility?</p>
[ { "answer_id": 60372, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a> or <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. There, you can centralize the task of injecting event handling into form controls.</p>\n\n<p>By that, I mean that you won't need to insert event handlers into the HTML form code. Instead, you register those events from somewhere else. For example, in Prototype you would be able to write something like this:</p>\n\n<pre><code>$('myFormControl').observe('click', myClickFunction)\n</code></pre>\n\n<p>Also have a look at the answers to <a href=\"https://stackoverflow.com/questions/34126/whats-the-best-way-to-add-event-in-javascript\">another question</a>.</p>\n\n<p>/EDIT: of course, you can also insert custom attributes and thus event handlers into the form elements using HTML_QuickForm. However, the above way is superior.</p>\n" }, { "answer_id": 60384, "author": "Kieran Hall", "author_id": 6085, "author_profile": "https://Stackoverflow.com/users/6085", "pm_score": 3, "selected": false, "text": "<p>I've found the <a href=\"http://framework.zend.com/manual/en/zend.form.html\" rel=\"nofollow noreferrer\">Zend_Form</a> package of the <a href=\"http://framework.zend.com\" rel=\"nofollow noreferrer\">Zend Framework</a> to be particulary flexible. This component can also be used with <a href=\"http://framework.zend.com/manual/en/zend.dojo.html\" rel=\"nofollow noreferrer\">Zend_Dojo</a> to rapidly implement common javascript form helpers. However, the component is agnostic when it comes to the library that you use, but supports Dojo naitively. The component also allows for grouping, multi-page forms, custom decorators, validators and other features making it very flexible.</p>\n" }, { "answer_id": 62035, "author": "Andrew Taylor", "author_id": 1776, "author_profile": "https://Stackoverflow.com/users/1776", "pm_score": 1, "selected": false, "text": "<p>I'll second Zend_Form; it has an excellent ini style implementation that allows you to define a form extremely quickly:</p>\n\n<pre><code>[main]\nvessel.form.method = \"post\"\n\nvessel.form.elements.name.type = \"text\"\nvessel.form.elements.name.name = \"name\"\nvessel.form.elements.name.options.label = \"Name: \"\nvessel.form.elements.name.options.required = true\n\nvessel.form.elements.identifier_type.type = \"select\"\nvessel.form.elements.identifier_type.name = \"identifier_type\"\nvessel.form.elements.identifier_type.options.label = \"Identifier type: \"\nvessel.form.elements.identifier_type.options.required = true\nvessel.form.elements.identifier_type.options.multioptions.IMO Number = \"IMO Number\";\nvessel.form.elements.identifier_type.options.multioptions.Registry organisation and Number = \"Registry organisation and Number\";\nvessel.form.elements.identifier_type.options.multioptions.SSR Number = \"SSR Number\";\n\nvessel.form.elements.identifier.type = \"text\"\nvessel.form.elements.identifier.name = \"identifier\"\nvessel.form.elements.identifier.options.label = \"Identifier: \"\nvessel.form.elements.identifier.options.required = true\nvessel.form.elements.identifier.options.filters.lower.filter = \"StringToUpper\"\n\nvessel.form.elements.email.type = \"text\"\nvessel.form.elements.email.name = \"email\"\nvessel.form.elements.email.options.label = \"Email: \"\nvessel.form.elements.email.options.required = true\n\nvessel.form.elements.owner_id.type = \"hidden\"\nvessel.form.elements.owner_id.name = \"owner_id\"\nvessel.form.elements.owner_id.options.required = true\n\n; submit button\nvessel.form.elements.submit.type = \"submit\"\nvessel.form.elements.submit.name = \"Update\"\nvessel.form.elements.submit.option.value = \"Update\"\n</code></pre>\n" }, { "answer_id": 473995, "author": "gavinandresen", "author_id": 58359, "author_profile": "https://Stackoverflow.com/users/58359", "pm_score": 2, "selected": false, "text": "<p>I wrote an article about this for OnLamp: <a href=\"http://www.onlamp.com/pub/a/php/2006/03/16/autofill-forms.html\" rel=\"nofollow noreferrer\">Autofilled PHP Forms</a></p>\n\n<p>My beef with HTML_QuickForm and Zend_Form and all the other form-handling frameworks I could find is that they seem to assume that you'll be writing code to generate the form. But that didn't match my development process, where I'd start with the LOOK of the page (specified via HTML templates) and add functionality to it.</p>\n\n<p>In my view of the world, form handling boils down to:</p>\n\n<ol>\n<li>Fetching the data that should go in the form to start (usually from a database).</li>\n<li>Fetching the HTML code for the form (usually a template).</li>\n<li>Mushing 1 and 2 together, and outputting the result.</li>\n<li>Getting the submitted form data and validating it.</li>\n<li>Re-displaying the form with error messages and the invalid data, OR</li>\n<li>Displaying the congratulations-your-data-was-ok page.</li>\n</ol>\n\n<p>fillInFormValues() makes 2, 3, and 5 really easy.</p>\n" }, { "answer_id": 663432, "author": "blockhead", "author_id": 60223, "author_profile": "https://Stackoverflow.com/users/60223", "pm_score": 1, "selected": false, "text": "<p>With Zend_Form it is entirely possible to start with your form visually, and then work backwords.</p>\n\n<p>This is done by removing all decorators and replacing them with a ViewScript decorator</p>\n\n<pre><code>$this-&gt;form-&gt;setDecorators( array(array('ViewScript', array('viewScript' =&gt; 'forms/aform.phtml'))));\n</code></pre>\n\n<p>And in that viewscript you would do something like this:</p>\n\n<pre><code>&lt;?=$this-&gt;element-&gt;title-&gt;renderViewHelper()?&gt;\n</code></pre>\n\n<p>Going with this approach, you can basically do anything you want with the form.</p>\n\n<p>Another great thing about Zend_Form is that you can create custom elements which can encapsulate other stuff in them. For example, you can have an element which outputs a textarea and then some Javascript to turn it into a WYSIWYG area.</p>\n" }, { "answer_id": 663571, "author": "Sean McSomething", "author_id": 39413, "author_profile": "https://Stackoverflow.com/users/39413", "pm_score": 0, "selected": false, "text": "<p>I can't really say anything about it but, the other day, I ran across the <a href=\"http://www.phpformclass.com/page/index\" rel=\"nofollow noreferrer\">clonefish</a> form library. It looked promising enough to end up in my bookmarks list as a \"look at this later\".</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
I'm currently playing around with [HTML\_QuickForm](http://pear.php.net/package/HTML_QuickForm) for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements. Are there any alternatives to QuickForm that might provide more flexibility?
If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as [Prototype](http://www.prototypejs.org/) or [jQuery](http://jquery.com/). There, you can centralize the task of injecting event handling into form controls. By that, I mean that you won't need to insert event handlers into the HTML form code. Instead, you register those events from somewhere else. For example, in Prototype you would be able to write something like this: ``` $('myFormControl').observe('click', myClickFunction) ``` Also have a look at the answers to [another question](https://stackoverflow.com/questions/34126/whats-the-best-way-to-add-event-in-javascript). /EDIT: of course, you can also insert custom attributes and thus event handlers into the form elements using HTML\_QuickForm. However, the above way is superior.
60,409
<p>I know in php you can embed variables inside variables, like:</p> <pre><code>&lt;? $var1 = "I\'m including {$var2} in this variable.."; ?&gt; </code></pre> <p>But I was wondering how, and if it was possible to include a function inside a variable. I know I could just write:</p> <pre><code>&lt;?php $var1 = "I\'m including "; $var1 .= somefunc(); $var1 = " in this variable.."; ?&gt; </code></pre> <p>But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:</p> <pre><code>&lt;?php $var1 = &lt;&lt;&lt;EOF &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;AAAHHHHH&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt; &lt;/head&gt; &lt;body&gt; There is &lt;b&gt;alot&lt;/b&gt; of text and html here... but I want some &lt;i&gt;functions&lt;/i&gt;! -somefunc() doesn't work -{somefunc()} doesn't work -$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string -more non-working: ${somefunc()} &lt;/body&gt; &lt;/html&gt; EOF; ?&gt; </code></pre> <p>Or I want dynamic changes in that load of code:</p> <pre><code>&lt;? function somefunc($stuff) { $output = "my bold text &lt;b&gt;{$stuff}&lt;/b&gt;."; return $output; } $var1 = &lt;&lt;&lt;EOF &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;AAAHHHHH&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt; &lt;/head&gt; &lt;body&gt; somefunc("is awesome!") somefunc("is actually not so awesome..") because somefunc("won\'t work due to my problem.") &lt;/body&gt; &lt;/html&gt; EOF; ?&gt; </code></pre> <p>Well?</p>
[ { "answer_id": 60420, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 6, "selected": true, "text": "<p>Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:</p>\n\n<pre><code>&lt;?\nfunction somefunc($stuff)\n{\n $output = \"&lt;b&gt;{$stuff}&lt;/b&gt;\";\n return $output;\n}\n$somefunc='somefunc';\necho \"foo {$somefunc(\"bar\")} baz\";\n?&gt;\n</code></pre>\n\n<p>will output \"<code>foo &lt;b&gt;bar&lt;/b&gt; baz</code>\".</p>\n\n<p>I find it easier however (and this works in PHP4) to either just call the function outside of the string:</p>\n\n<pre><code>&lt;?\necho \"foo \" . somefunc(\"bar\") . \" baz\";\n?&gt;\n</code></pre>\n\n<p>or assign to a temporary variable:</p>\n\n<pre><code>&lt;?\n$bar = somefunc(\"bar\");\necho \"foo {$bar} baz\";\n?&gt;\n</code></pre>\n" }, { "answer_id": 60421, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "<p><code>\"bla bla bla\".function(\"blub\").\" and on it goes\"</code></p>\n" }, { "answer_id": 61270, "author": "Tim Kennedy", "author_id": 5699, "author_profile": "https://Stackoverflow.com/users/5699", "pm_score": -1, "selected": false, "text": "<p>Expanding a bit on what Jason W said:</p>\n\n<pre>\nI find it easier however (and this works in PHP4) to either just call the \nfunction outside of the string:\n\n&lt;?\necho \"foo \" . somefunc(\"bar\") . \" baz\";\n?&gt;\n</pre>\n\n<p>You can also just embed this function call directly in your html, like:</p>\n\n<pre>&lt;?\n\nfunction get_date() {\n $date = `date`;\n return $date;\n}\n\nfunction page_title() {\n $title = \"Today's date is: \". get_date() .\"!\";\n echo \"$title\";\n}\n\nfunction page_body() {\n $body = \"Hello\";\n $body = \", World!\";\n $body = \"\\n<br/>\\n\";\n $body = \"Today is: \" . get_date() . \"\\n\";\n}\n\n?&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;? page_title(); ?&gt;&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;? page_body(); ?&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n\n</pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4867/" ]
I know in php you can embed variables inside variables, like: ``` <? $var1 = "I\'m including {$var2} in this variable.."; ?> ``` But I was wondering how, and if it was possible to include a function inside a variable. I know I could just write: ``` <?php $var1 = "I\'m including "; $var1 .= somefunc(); $var1 = " in this variable.."; ?> ``` But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions: ``` <?php $var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> There is <b>alot</b> of text and html here... but I want some <i>functions</i>! -somefunc() doesn't work -{somefunc()} doesn't work -$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string -more non-working: ${somefunc()} </body> </html> EOF; ?> ``` Or I want dynamic changes in that load of code: ``` <? function somefunc($stuff) { $output = "my bold text <b>{$stuff}</b>."; return $output; } $var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> somefunc("is awesome!") somefunc("is actually not so awesome..") because somefunc("won\'t work due to my problem.") </body> </html> EOF; ?> ``` Well?
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call: ``` <? function somefunc($stuff) { $output = "<b>{$stuff}</b>"; return $output; } $somefunc='somefunc'; echo "foo {$somefunc("bar")} baz"; ?> ``` will output "`foo <b>bar</b> baz`". I find it easier however (and this works in PHP4) to either just call the function outside of the string: ``` <? echo "foo " . somefunc("bar") . " baz"; ?> ``` or assign to a temporary variable: ``` <? $bar = somefunc("bar"); echo "foo {$bar} baz"; ?> ```
60,422
<p>As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: <a href="http://damianblog.com/2008/09/09/tracejs-v2-rip/" rel="nofollow noreferrer">http://damianblog.com/2008/09/09/tracejs-v2-rip/</a>).</p> <p>The call to GetProviderProcessData is failing on Vista. Anyone have any suggestions?</p> <p>Thanks, Damian</p> <pre><code>// Create the MsProgramProvider IDebugProgramProvider2* pIDebugProgramProvider2 = 0; HRESULT st = CoCreateInstance(CLSID_MsProgramProvider, 0, CLSCTX_ALL, IID_IDebugProgramProvider2, (void**)&amp;pIDebugProgramProvider2); if(st != S_OK) { return st; } // Get the IDebugProgramNode2 instances running in this process AD_PROCESS_ID processID; processID.ProcessId.dwProcessId = GetCurrentProcessId(); processID.ProcessIdType = AD_PROCESS_ID_SYSTEM; CONST_GUID_ARRAY engineFilter; engineFilter.dwCount = 0; PROVIDER_PROCESS_DATA processData; st = pIDebugProgramProvider2-&gt;GetProviderProcessData(PFLAG_GET_PROGRAM_NODES|PFLAG_DEBUGGEE, 0, processID, engineFilter, &amp;processData); if(st != S_OK) { ShowError(L"GPPD Failed", st); pIDebugProgramProvider2-&gt;Release(); return st; } </code></pre>
[ { "answer_id": 60468, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with these interfaces, but unexpected failures in Vista may require being past a UAC prompt. Have you tried starting the debugger with admin privileges?</p>\n" }, { "answer_id": 930781, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 2, "selected": true, "text": "<p>It would help to know what the error result was.</p>\n\n<p>Possible problems I can think of:</p>\n\n<p>If your getting permission denied, your most likely missing some requried <a href=\"http://msdn.microsoft.com/en-us/library/aa375728(VS.85).aspx\" rel=\"nofollow noreferrer\">Privilege</a> in your ACL. New ones are sometimes not doceumented well, check the latest Platform SDK headers to see if any new ones that still out. It may be that under vista the Privilege is not assigned my default to your ACL any longer.</p>\n\n<p>If your getting some sort of Not Found type error, then it may be 32bit / 64bit problem. Your debbugging API may only be available under 64bit COM on vista 64. The 32bit/64bit interoperation can be very confusing.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390/" ]
As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: <http://damianblog.com/2008/09/09/tracejs-v2-rip/>). The call to GetProviderProcessData is failing on Vista. Anyone have any suggestions? Thanks, Damian ``` // Create the MsProgramProvider IDebugProgramProvider2* pIDebugProgramProvider2 = 0; HRESULT st = CoCreateInstance(CLSID_MsProgramProvider, 0, CLSCTX_ALL, IID_IDebugProgramProvider2, (void**)&pIDebugProgramProvider2); if(st != S_OK) { return st; } // Get the IDebugProgramNode2 instances running in this process AD_PROCESS_ID processID; processID.ProcessId.dwProcessId = GetCurrentProcessId(); processID.ProcessIdType = AD_PROCESS_ID_SYSTEM; CONST_GUID_ARRAY engineFilter; engineFilter.dwCount = 0; PROVIDER_PROCESS_DATA processData; st = pIDebugProgramProvider2->GetProviderProcessData(PFLAG_GET_PROGRAM_NODES|PFLAG_DEBUGGEE, 0, processID, engineFilter, &processData); if(st != S_OK) { ShowError(L"GPPD Failed", st); pIDebugProgramProvider2->Release(); return st; } ```
It would help to know what the error result was. Possible problems I can think of: If your getting permission denied, your most likely missing some requried [Privilege](http://msdn.microsoft.com/en-us/library/aa375728(VS.85).aspx) in your ACL. New ones are sometimes not doceumented well, check the latest Platform SDK headers to see if any new ones that still out. It may be that under vista the Privilege is not assigned my default to your ACL any longer. If your getting some sort of Not Found type error, then it may be 32bit / 64bit problem. Your debbugging API may only be available under 64bit COM on vista 64. The 32bit/64bit interoperation can be very confusing.
60,438
<p>I am using jQuery. I call a JavaScript function with next html:</p> <pre><code>&lt;li&gt;&lt;span&gt;&lt;a href="javascript:uncheckEl('tagVO-$id')"&gt;$tagname&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; </code></pre> <p>I would like to remove the <code>li</code> element and I thought this would be easy with the <code>$(this)</code> object. This is my JavaScript function:</p> <pre><code>function uncheckEl(id) { $("#"+id+"").attr("checked",""); $("#"+id+"").parent("li").css("color","black"); $(this).parent("li").remove(); // This is not working retrieveItems(); } </code></pre> <p>But <code>$(this)</code> is undefined. Any ideas?</p>
[ { "answer_id": 60449, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<p>Try something like this (e.g. to hide the <code>&lt;li&gt;</code>):</p>\n\n<pre><code>function unCheckEl(id, ref) {\n (...)\n $(ref).parent().parent().hide(); // this should be your &lt;li&gt;\n}\n</code></pre>\n\n<p>And your link:</p>\n\n<pre><code>&lt;a href=\"javascript:uncheckEl('tagVO-$id', \\$(this))\"&gt;\n</code></pre>\n\n<p><code>$(this)</code> is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so <code>$(this)</code> could refer to everything but the <code>&lt;a&gt;</code>.</p>\n" }, { "answer_id": 74712, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 1, "selected": false, "text": "<p>Why not something like:</p>\n\n<pre><code>&lt;li id=\"uncheck_tagVO-$id\"&gt;$tagname&lt;/li&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$('li').click( function() {\n var id = this.id.split(\"_\")[1];\n $('#'+id).attr(\"checked\",\"\").parent(\"li\").css(\"color\",\"black\"); \n $(this).remove();\n retrieveItems();\n});\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I am using jQuery. I call a JavaScript function with next html: ``` <li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li> ``` I would like to remove the `li` element and I thought this would be easy with the `$(this)` object. This is my JavaScript function: ``` function uncheckEl(id) { $("#"+id+"").attr("checked",""); $("#"+id+"").parent("li").css("color","black"); $(this).parent("li").remove(); // This is not working retrieveItems(); } ``` But `$(this)` is undefined. Any ideas?
Try something like this (e.g. to hide the `<li>`): ``` function unCheckEl(id, ref) { (...) $(ref).parent().parent().hide(); // this should be your <li> } ``` And your link: ``` <a href="javascript:uncheckEl('tagVO-$id', \$(this))"> ``` `$(this)` is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so `$(this)` could refer to everything but the `<a>`.
60,455
<p>Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?</p> <p>I'm not so concerned with browser security issues. etc. as the implementation would be for <a href="http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx" rel="noreferrer">HTA</a>. But is it possible?</p>
[ { "answer_id": 60471, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>You can achieve that using HTA and <a href=\"http://en.wikipedia.org/wiki/VBScript\" rel=\"nofollow noreferrer\">VBScript</a>. Just call an external tool to do the screenshotting. I forgot what the name is, but on Windows&nbsp;Vista there is a tool to do screenshots. You don't even need an extra install for it.</p>\n\n<p>As for as automatic - it totally depends on the tool you use. If it has an API, I am sure you can trigger the screenshot and saving process through a couple of Visual Basic calls without the user knowing that you did what you did.</p>\n\n<p>Since you mentioned HTA, I am assuming you are on Windows and (probably) know your environment (e.g. OS and version) very well. </p>\n" }, { "answer_id": 60614, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>We had a similar requirement for reporting bugs. Since it was for an intranet scenario, we were able to use browser addons (like <a href=\"https://addons.mozilla.org/en-US/firefox/addon/5648\" rel=\"nofollow noreferrer\">Fireshot</a> for Firefox and <a href=\"http://www.softpedia.com/get/Tweak/Browser-Tweak/IE-Screenshot-Pro.shtml\" rel=\"nofollow noreferrer\">IE Screenshot</a> for Internet&nbsp;Explorer).</p>\n" }, { "answer_id": 63506, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 6, "selected": true, "text": "<p>I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd_event API call because SendKeys can't do PrintScreen. Here's the code for that:</p>\n\n<pre><code>Declare Sub keybd_event Lib \"user32\" _\n(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)\n\nPublic Const CaptWindow = 2\n\nPublic Sub ScreenGrab()\n keybd_event &amp;H12, 0, 0, 0\n keybd_event &amp;H2C, CaptWindow, 0, 0\n keybd_event &amp;H2C, CaptWindow, &amp;H2, 0\n keybd_event &amp;H12, 0, &amp;H2, 0\nEnd Sub\n</code></pre>\n\n<p>That only gets you as far as getting the window to the clipboard.</p>\n\n<p>Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side.</p>\n" }, { "answer_id": 63657, "author": "nikhil", "author_id": 7926, "author_profile": "https://Stackoverflow.com/users/7926", "pm_score": 3, "selected": false, "text": "<p>This might not be the ideal solution for you, but it might still be worth mentioning. </p>\n\n<p><em><a href=\"http://snapsie.sourceforge.net/\" rel=\"nofollow noreferrer\">Snapsie</a> is an open source, <a href=\"http://en.wikipedia.org/wiki/ActiveX\" rel=\"nofollow noreferrer\">ActiveX</a> object that enables Internet Explorer screenshots to be captured and saved.</em> Once the DLL file is registered on the client, you should be able to capture the screenshot and upload the file to the server withing JavaScript. Drawbacks: it needs to register the DLL file at the client and works only with Internet&nbsp;Explorer.</p>\n" }, { "answer_id": 3936602, "author": "xmedeko", "author_id": 254109, "author_profile": "https://Stackoverflow.com/users/254109", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.snapengage.com/\" rel=\"nofollow noreferrer\">SnapEngage</a> uses a <a href=\"http://en.wikipedia.org/wiki/Java_applet\" rel=\"nofollow noreferrer\">Java applet</a> (1.5+) to make a browser screenshot. AFAIK, <code>java.awt.Robot</code> should do the job - the user has just to permit the applet to do it (once).</p>\n\n<p>And I have just found a post about it: </p>\n\n<ul>\n<li>Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/2046812\">JavaScript code to take a screenshot of a website without using ActiveX</a></em></li>\n<li>Blog post <em><a href=\"http://www.barklund.org/blog/2009/10/14/how-snapabug-works/\" rel=\"nofollow noreferrer\">How SnapABug works – and what they should do</a></em></li>\n</ul>\n" }, { "answer_id": 4012915, "author": "RobertPitt", "author_id": 353790, "author_profile": "https://Stackoverflow.com/users/353790", "pm_score": 4, "selected": false, "text": "<p>Pounder's if this is possible to do by setting the whole body elements into a canvase then using canvas2image ?</p>\n\n<p><a href=\"http://www.nihilogic.dk/labs/canvas2image/\" rel=\"noreferrer\">http://www.nihilogic.dk/labs/canvas2image/</a></p>\n" }, { "answer_id": 4340297, "author": "RobertPitt", "author_id": 353790, "author_profile": "https://Stackoverflow.com/users/353790", "pm_score": 3, "selected": false, "text": "<p>A possible way to do this, if running on windows and have .NET installed you can do:</p>\n\n<pre><code>public Bitmap GenerateScreenshot(string url)\n{\n // This method gets a screenshot of the webpage\n // rendered at its full size (height and width)\n return GenerateScreenshot(url, -1, -1);\n}\n\npublic Bitmap GenerateScreenshot(string url, int width, int height)\n{\n // Load the webpage into a WebBrowser control\n WebBrowser wb = new WebBrowser();\n wb.ScrollBarsEnabled = false;\n wb.ScriptErrorsSuppressed = true;\n wb.Navigate(url);\n while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }\n\n\n // Set the size of the WebBrowser control\n wb.Width = width;\n wb.Height = height;\n\n if (width == -1)\n {\n // Take Screenshot of the web pages full width\n wb.Width = wb.Document.Body.ScrollRectangle.Width;\n }\n\n if (height == -1)\n {\n // Take Screenshot of the web pages full height\n wb.Height = wb.Document.Body.ScrollRectangle.Height;\n }\n\n // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control\n Bitmap bitmap = new Bitmap(wb.Width, wb.Height);\n wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));\n wb.Dispose();\n\n return bitmap;\n}\n</code></pre>\n\n<p>And then via PHP you can do:</p>\n\n<p><code>exec(\"CreateScreenShot.exe -url http://.... -save C:/shots domain_page.png\");</code></p>\n\n<p>Then you have the screenshot in the server side.</p>\n" }, { "answer_id": 6919676, "author": "JAAulde", "author_id": 239567, "author_profile": "https://Stackoverflow.com/users/239567", "pm_score": 7, "selected": false, "text": "<p>Google is doing this in Google+ and a talented developer reverse engineered it and produced <a href=\"http://html2canvas.hertzen.com/\" rel=\"noreferrer\">http://html2canvas.hertzen.com/</a> . To work in IE you'll need a canvas support library such as <a href=\"http://excanvas.sourceforge.net/\" rel=\"noreferrer\">http://excanvas.sourceforge.net/</a></p>\n" }, { "answer_id": 9269601, "author": "Scott Bennett-McLeish", "author_id": 1915, "author_profile": "https://Stackoverflow.com/users/1915", "pm_score": 4, "selected": false, "text": "<p>Another possible solution that I've discovered is <a href=\"http://www.phantomjs.org/\" rel=\"noreferrer\">http://www.phantomjs.org/</a> which allows one to very easily take screenshots of pages and a whole lot more. Whilst my original requirements for this question aren't valid any more (different job), I will likely integrate PhantomJS into future projects.</p>\n" }, { "answer_id": 44859895, "author": "Johnny", "author_id": 2811258, "author_profile": "https://Stackoverflow.com/users/2811258", "pm_score": 0, "selected": false, "text": "<p>A great solution for screenshot taking in Javascript is the one by <a href=\"https://grabz.it\" rel=\"nofollow noreferrer\">https://grabz.it</a>. </p>\n\n<p>They have a flexible and simple-to-use screenshot API which can be used by any type of JS application.</p>\n\n<p>If you want to try it, at first you should get the authorization <a href=\"https://grabz.it/api/#Key\" rel=\"nofollow noreferrer\">app key + secret</a> and the <a href=\"https://grabz.it/api/javascript/download.ashx\" rel=\"nofollow noreferrer\">free SDK</a></p>\n\n<p>Then, in your app, the implementation steps would be:</p>\n\n<pre><code>// include the grabzit.min.js library in the web page you want the capture to appear\n&lt;script src=\"grabzit.min.js\"&gt;&lt;/script&gt;\n\n//use the key and the secret to login, capture the url\n&lt;script&gt;\nGrabzIt(\"KEY\", \"SECRET\").ConvertURL(\"http://www.google.com\").Create();\n&lt;/script&gt;\n</code></pre>\n\n<p>Screenshot could be customized with different <a href=\"https://grabz.it/api/javascript/parameters.aspx\" rel=\"nofollow noreferrer\">parameters</a>. For example:</p>\n\n<pre><code>GrabzIt(\"KEY\", \"SECRET\").ConvertURL(\"http://www.google.com\", \n{\"width\": 400, \"height\": 400, \"format\": \"png\", \"delay\", 10000}).Create();\n&lt;/script&gt;\n</code></pre>\n\n<p>That's all. \nThen simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.</p>\n\n<p>There are other functionalities to the screenshot mechanism which you can explore <a href=\"https://grabz.it/api/javascript/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>It's also possible to save the screenshot locally. For that you will need to utilize GrabzIt server side API. For more info check the detailed guide <a href=\"https://grabz.it/support/?uniqueId=SaveJavaScriptScreenshot\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 49495374, "author": "maltem-za", "author_id": 207981, "author_profile": "https://Stackoverflow.com/users/207981", "pm_score": 2, "selected": false, "text": "<p>I found that <strong>dom-to-image</strong> did a good job (much better than html2canvas). See the following question &amp; answer: <a href=\"https://stackoverflow.com/a/32776834/207981\">https://stackoverflow.com/a/32776834/207981</a></p>\n\n<p>This question asks about submitting this back to the server, which should be possible, but if you're looking to download the image(s) you'll want to combine it with <a href=\"https://github.com/eligrey/FileSaver.js/\" rel=\"nofollow noreferrer\">FileSaver.js</a>, and if you want to download a zip with multiple image files all generated client-side take a look at <a href=\"http://stuk.github.io/jszip/\" rel=\"nofollow noreferrer\">jszip</a>.</p>\n" }, { "answer_id": 53336136, "author": "Ekin Koc", "author_id": 257925, "author_profile": "https://Stackoverflow.com/users/257925", "pm_score": 1, "selected": false, "text": "<p>If you are willing to do it on the server side, there are options like <a href=\"https://github.com/ariya/phantomjs\" rel=\"nofollow noreferrer\">PhantomJS</a>, which is now deprecated. The best way to go would be Headless Chrome with something like <a href=\"https://github.com/GoogleChrome/puppeteer\" rel=\"nofollow noreferrer\">Puppeteer</a> on Node.JS. Capturing a web page using Puppeteer would be as simple as follows:</p>\n\n<pre><code>const puppeteer = require('puppeteer');\n\n(async () =&gt; {\n const browser = await puppeteer.launch();\n const page = await browser.newPage();\n await page.goto('https://example.com');\n await page.screenshot({path: 'example.png'});\n\n await browser.close();\n})();\n</code></pre>\n\n<p>However it requires headless chrome to be able to run on your servers, which has some dependencies and might not be suitable on restricted environments. (Also, if you are not using Node.JS, you might need to handle installation / launching of browsers yourself.)</p>\n\n<p>If you are willing to use a SaaS service, there are many options such as</p>\n\n<ul>\n<li><a href=\"https://restpack.io\" rel=\"nofollow noreferrer\">Restpack</a></li>\n<li><a href=\"https://urlbox.io\" rel=\"nofollow noreferrer\">UrlBox</a></li>\n<li><a href=\"https://screenshotlayer.com\" rel=\"nofollow noreferrer\">Screenshot Layer</a></li>\n</ul>\n" }, { "answer_id": 59056978, "author": "shaedrich", "author_id": 7451109, "author_profile": "https://Stackoverflow.com/users/7451109", "pm_score": 2, "selected": false, "text": "<p>This question is old but maybe there's still someone interested in a state-of-the-art answer:</p>\n\n<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia\" rel=\"nofollow noreferrer\"><code>getDisplayMedia</code></a>:</p>\n\n<p><a href=\"https://github.com/ondras/browsershot\" rel=\"nofollow noreferrer\">https://github.com/ondras/browsershot</a></p>\n" }, { "answer_id": 61255772, "author": "zennni", "author_id": 2369164, "author_profile": "https://Stackoverflow.com/users/2369164", "pm_score": 0, "selected": false, "text": "<p>As of today Apr 2020 GitHub library html2Canvas \n<a href=\"https://github.com/niklasvh/html2canvas\" rel=\"nofollow noreferrer\">https://github.com/niklasvh/html2canvas</a></p>\n\n<p><strong>GitHub 20K stars</strong> | Azure pipeles : Succeeded | Downloads 1.3M/mo |</p>\n\n<p>quote : \" <em>JavaScript HTML renderer The script allows you to <strong>take \"screenshots\" of webpages or parts of it, directly on the users browser</strong>. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.</em></p>\n" }, { "answer_id": 62433612, "author": "Diego Favero", "author_id": 688689, "author_profile": "https://Stackoverflow.com/users/688689", "pm_score": 0, "selected": false, "text": "<p>I made a simple function that uses rasterizeHTML to build a svg and/or an image with page contents. </p>\n\n<p>Check it out :</p>\n\n<p><a href=\"https://github.com/orisha/tdg-screen-shooter-pure-js\" rel=\"nofollow noreferrer\">https://github.com/orisha/tdg-screen-shooter-pure-js</a></p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915/" ]
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server? I'm not so concerned with browser security issues. etc. as the implementation would be for [HTA](http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx). But is it possible?
I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd\_event API call because SendKeys can't do PrintScreen. Here's the code for that: ``` Declare Sub keybd_event Lib "user32" _ (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) Public Const CaptWindow = 2 Public Sub ScreenGrab() keybd_event &H12, 0, 0, 0 keybd_event &H2C, CaptWindow, 0, 0 keybd_event &H2C, CaptWindow, &H2, 0 keybd_event &H12, 0, &H2, 0 End Sub ``` That only gets you as far as getting the window to the clipboard. Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side.
60,456
<p>I have this in a page :</p> <pre><code>&lt;textarea id="taEditableContent" runat="server" rows="5"&gt;&lt;/textarea&gt; &lt;ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent" ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx" ServiceMethod="EditContent" ContextKey='&lt;%=ContextKey %&gt;' /&gt; </code></pre> <p>Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.</p> <p>If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;string xmlns="http://rprealm.com/"&gt;First line Third line Fourth line&lt;/string&gt; </code></pre> <p>But what I get in the text area is :</p> <pre><code>First line Third line Fourth line </code></pre>
[ { "answer_id": 60490, "author": "Ricky Supit", "author_id": 4191, "author_profile": "https://Stackoverflow.com/users/4191", "pm_score": 0, "selected": false, "text": "<p>Try to add the following style on textarea: <strong>style=\"white-space: pre\"</strong></p>\n" }, { "answer_id": 321353, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 1, "selected": false, "text": "<p>The problem is that the white space is ignored by default when the XML is processed. Try to add the <code>xml:space=\"preserve\"</code> attribute to the string element. You'll also need to define the xml prefix as <code>xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"</code>.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
I have this in a page : ``` <textarea id="taEditableContent" runat="server" rows="5"></textarea> <ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent" ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx" ServiceMethod="EditContent" ContextKey='<%=ContextKey %>' /> ``` Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds. If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly: ``` <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://rprealm.com/">First line Third line Fourth line</string> ``` But what I get in the text area is : ``` First line Third line Fourth line ```
The problem is that the white space is ignored by default when the XML is processed. Try to add the `xml:space="preserve"` attribute to the string element. You'll also need to define the xml prefix as `xmlns:xml="http://www.w3.org/XML/1998/namespace"`.
60,470
<p>If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them?</p> <p>I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.</p> <p>Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?</p>
[ { "answer_id": 60574, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 0, "selected": false, "text": "<p>Sounds like it should be possible (but I've never done it). Have you already had a look at Remote Method Invocation (<a href=\"http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp\" rel=\"nofollow noreferrer\">RMI</a>)?</p>\n" }, { "answer_id": 60615, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 4, "selected": true, "text": "<p>I think classes are lazy loaded in applets. being loaded on demand.</p>\n\n<p>Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex:</p>\n\n<pre><code>ClassLoader loader = this.getClass().getClassLoader();\nClass clazz = loader.loadClass(\"acme.AppletAddon\");\n</code></pre>\n\n<p>If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s).</p>\n\n<pre><code>URL[] urls = new URL[]{new URL(\"http://localhost:8080/addon.jar\")};\nURLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader());\nClass clazz = loader.loadClass(\"acme.AppletAddon\");\n</code></pre>\n\n<p>By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.</p>\n" }, { "answer_id": 61203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Yes, you can open URL connections to the host you ran your applet from. You can either create a classloader with HTTP urls, or download the classes (as jars) to the user's machine and create a classloader with those jars in the classpath. The applet won't stop and you don't need to load another page.</p>\n\n<p>Regarding the second part of your question about confidence, once the user has granted access to your applet it can download anything, yes anything, it wants to the local machine. You can probably inform the user as to what it's doing, if your UI design permits this.</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them? I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once. Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?
I think classes are lazy loaded in applets. being loaded on demand. Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex: ``` ClassLoader loader = this.getClass().getClassLoader(); Class clazz = loader.loadClass("acme.AppletAddon"); ``` If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s). ``` URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")}; URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader()); Class clazz = loader.loadClass("acme.AppletAddon"); ``` By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.
60,507
<p>Say I have:</p> <pre><code>void Render(void(*Call)()) { D3dDevice-&gt;BeginScene(); Call(); D3dDevice-&gt;EndScene(); D3dDevice-&gt;Present(0,0,0,0); } </code></pre> <p>This is fine as long as the function I want to use to render is a function or a <code>static</code> member function:</p> <pre><code>Render(MainMenuRender); Render(MainMenu::Render); </code></pre> <p>However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.</p> <pre><code>Render(MainMenu-&gt;Render); </code></pre> <p>However I really have no idea how to do this, and still allow functions and <code>static</code> member functions to be used.</p>
[ { "answer_id": 60512, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 2, "selected": false, "text": "<p>You can make a wrapper function <code>void Wrap(T *t)</code> that just calls <code>t-&gt;Call()</code> and have <code>Render</code> take such a function together with an object. That is:</p>\n\n<pre><code>void Wrap(T *t)\n{\n t-&gt;Call();\n}\n\nvoid Render(void (*f)(T *), T *t)\n{\n ...\n f(t);\n ...\n}\n</code></pre>\n" }, { "answer_id": 60513, "author": "David Joyner", "author_id": 1146, "author_profile": "https://Stackoverflow.com/users/1146", "pm_score": 5, "selected": true, "text": "<p>There are a lot of ways to skin this cat, including templates. My favorite is <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function.html\" rel=\"nofollow noreferrer\">Boost.function</a> as I've found it to be the most flexible in the long run. Also read up on <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html\" rel=\"nofollow noreferrer\">Boost.bind</a> for binding to member functions as well as many other tricks.</p>\n\n<p>It would look like this:</p>\n\n<pre><code>#include &lt;boost/bind.hpp&gt;\n#include &lt;boost/function.hpp&gt;\n\nvoid Render(boost::function0&lt;void&gt; Call)\n{\n // as before...\n}\n\nRender(boost::bind(&amp;MainMenu::Render, myMainMenuInstance));\n</code></pre>\n" }, { "answer_id": 60515, "author": "cjanssen", "author_id": 2950, "author_profile": "https://Stackoverflow.com/users/2950", "pm_score": 1, "selected": false, "text": "<p>I did so once by defining a global function \"Call\" which accepts a pointer to your intance as member</p>\n\n<pre><code>void CallRender(myclass *Instance)\n{\n Instance-&gt;Render();\n}\n</code></pre>\n\n<p>So render becomes:</p>\n\n<pre><code>void Render(void (*Call)(myclass*), myclass* Instance)\n{\n ...\n Call(Instance);\n ...\n}\n</code></pre>\n\n<p>And your call to render is:</p>\n\n<pre><code>Render(CallRender, &amp;MainMenu);\n</code></pre>\n\n<p>I know it's ugly, but worked for me (I was using pthreads)</p>\n" }, { "answer_id": 60527, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 1, "selected": false, "text": "<p>You can't call a member function from a pointer unless you have a reference to the object as well. For example:\n<pre><code>((object).*(ptrToMember))</pre></code></p>\n\n<p>So you won't be able to acheive this without changing the signature of your render method. <a href=\"http://www.parashift.com/c++-faq-lite/pointers-to-members.html\" rel=\"nofollow noreferrer\">This</a> article explains why this is generally a bad idea.</p>\n\n<p>A better way might be to define a \"Renderer\" interface which your classes that have render methods can implement and have that be the parameter type of your main Render method. You could then write a \"StaticCaller\" implementation to support the calling of your static methods by reference.</p>\n\n<p>eg (My C++ is really rusty, I haven't compiled this either).</p>\n\n<pre><code>\n\nvoid Render(IRenderer *Renderer)\n{\n D3dDevice->BeginScene();\n Renderer->Render();\n D3dDevice->EndScene();\n D3dDevice->Present(0,0,0,0);\n}\n\n// The \"interface\"\npublic class IRenderer \n{\npublic:\n virtual void Render();\n};\n\npublic class StaticCaller: public IRenderer\n{\n void (*Call)();\npublic:\n\n StaticCaller((*Call)())\n {\n this->Call = Call;\n }\n\n void Render()\n {\n Call();\n }\n};\n\n</code></pre>\n\n<p>All this is pretty boilerplate but it should make for more readability.</p>\n" }, { "answer_id": 60549, "author": "Marcin Gil", "author_id": 5731, "author_profile": "https://Stackoverflow.com/users/5731", "pm_score": 2, "selected": false, "text": "<p>What about what <a href=\"http://www.parashift.com/c++-faq-lite/pointers-to-members.html\" rel=\"nofollow noreferrer\">C++ FAQ: Pointers to members</a> says?</p>\n" }, { "answer_id": 354514, "author": "Nick Gebbie", "author_id": 44761, "author_profile": "https://Stackoverflow.com/users/44761", "pm_score": 0, "selected": false, "text": "<p>You can declare a function pointer to a member function of class T using:</p>\n\n<pre><code>typedef void (T::*FUNCTIONPOINTERTYPE)(args..)\nFUNCTIONPOINTERTYPE function;\n</code></pre>\n\n<p>And invoke it as:</p>\n\n<pre><code>T* t;\nFUNCTIONPOINTERTYPE function;\n(t-&gt;*function)(args..);\n</code></pre>\n\n<p>Extrapolating this into useful currying system with variable arguments, types, return values, etc, is monotonous and annoying. I've heard good things about the aforementioned boost library, so I'd recommend looking into that before doing anything drastic.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
Say I have: ``` void Render(void(*Call)()) { D3dDevice->BeginScene(); Call(); D3dDevice->EndScene(); D3dDevice->Present(0,0,0,0); } ``` This is fine as long as the function I want to use to render is a function or a `static` member function: ``` Render(MainMenuRender); Render(MainMenu::Render); ``` However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g. ``` Render(MainMenu->Render); ``` However I really have no idea how to do this, and still allow functions and `static` member functions to be used.
There are a lot of ways to skin this cat, including templates. My favorite is [Boost.function](http://www.boost.org/doc/libs/1_36_0/doc/html/function.html) as I've found it to be the most flexible in the long run. Also read up on [Boost.bind](http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html) for binding to member functions as well as many other tricks. It would look like this: ``` #include <boost/bind.hpp> #include <boost/function.hpp> void Render(boost::function0<void> Call) { // as before... } Render(boost::bind(&MainMenu::Render, myMainMenuInstance)); ```
60,558
<p>I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.</p> <p><img src="https://i.stack.imgur.com/qFtvP.png" alt="alt text"></p> <p>The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.</p> <p>I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?</p>
[ { "answer_id": 60564, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>The font is fixed width and height, so making a background bitmap dynamically isn't difficult, and is probably the quickest and easiest solution. In fact, if you size it correctly there will only be one stretched pixel per character.</p>\n\n<p>Color the pixel (or pixels) according to the background of the character.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 60595, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html\" rel=\"nofollow noreferrer\"><code>TextField.getCharBoundaries</code></a> to get a rectangle of the first and last characters in the areas where you want a background. From these rectangles you can construct a rectangle that spans the whole area. Use this to draw the background in a <code>Shape</code> placed behind the text field, or in the parent of the text field.</p>\n\n<p><em>Update</em> you asked for an example, here is how to get a rectangle from a range of characters:</p>\n\n<pre><code>var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex);\nvar lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex);\n\nvar rangeBounds : Rectangle = new Rectangle();\n\nrangeBounds.topLeft = firstCharBounds.topLeft;\nrangeBounds.bottomRight = lastCharBounds.bottomRight;\n</code></pre>\n\n<p>If you want to find a rectangle for a whole line you can do this instead:</p>\n\n<pre><code>var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber));\n\nvar lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height);\n</code></pre>\n\n<p>When you have the bounds of the text range you want to paint a background for, you can do this in the <code>updateDisplayList</code> method of the parent of the text field (assuming the text field is positioned at [0, 0] and has white text, and that <code>textRangesWithYellowBackground</code> is an array of rectangles that represent the text ranges that should have yellow backgrounds):</p>\n\n<pre><code>graphics.clear();\n\n// this draws the black background\ngraphics.beginFill(0x000000);\ngraphics.drawRect(0, 0, textField.width, textField.height);\ngraphics.endFill();\n\n// this draws yellow text backgrounds\nfor each ( var r : Rectangle in textRangesWithYellowBackground )\n graphics.beginFill(0xFFFF00);\n graphics.drawRect(r.x, r.y, r.width, r.height);\n graphics.endFill();\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6277/" ]
I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example. ![alt text](https://i.stack.imgur.com/qFtvP.png) The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text. I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?
Use [`TextField.getCharBoundaries`](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html) to get a rectangle of the first and last characters in the areas where you want a background. From these rectangles you can construct a rectangle that spans the whole area. Use this to draw the background in a `Shape` placed behind the text field, or in the parent of the text field. *Update* you asked for an example, here is how to get a rectangle from a range of characters: ``` var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex); var lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex); var rangeBounds : Rectangle = new Rectangle(); rangeBounds.topLeft = firstCharBounds.topLeft; rangeBounds.bottomRight = lastCharBounds.bottomRight; ``` If you want to find a rectangle for a whole line you can do this instead: ``` var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber)); var lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height); ``` When you have the bounds of the text range you want to paint a background for, you can do this in the `updateDisplayList` method of the parent of the text field (assuming the text field is positioned at [0, 0] and has white text, and that `textRangesWithYellowBackground` is an array of rectangles that represent the text ranges that should have yellow backgrounds): ``` graphics.clear(); // this draws the black background graphics.beginFill(0x000000); graphics.drawRect(0, 0, textField.width, textField.height); graphics.endFill(); // this draws yellow text backgrounds for each ( var r : Rectangle in textRangesWithYellowBackground ) graphics.beginFill(0xFFFF00); graphics.drawRect(r.x, r.y, r.width, r.height); graphics.endFill(); } ```
60,570
<p>Backgrounder:</p> <p>The <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">PIMPL Idiom</a> (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.</p> <p>This hides internal implementation details and data from the user of the library.</p> <p>When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?</p> <p>To illustrate, this code puts the <code>Purr()</code> implementation on the impl class and wraps it as well.</p> <p><strong>Why not implement Purr directly on the public class?</strong></p> <pre class="lang-c++ prettyprint-override"><code>// header file: class Cat { private: class CatImpl; // Not defined here CatImpl *cat_; // Handle public: Cat(); // Constructor ~Cat(); // Destructor // Other operations... Purr(); }; // CPP file: #include "cat.h" class Cat::CatImpl { Purr(); ... // The actual implementation can be anything }; Cat::Cat() { cat_ = new CatImpl; } Cat::~Cat() { delete cat_; } Cat::Purr(){ cat_-&gt;Purr(); } CatImpl::Purr(){ printf("purrrrrr"); } </code></pre>
[ { "answer_id": 60575, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 2, "selected": false, "text": "<p>Placing the call to the impl-&gt;Purr inside the .cpp file means that in the future you could do something completely different without having to change the header file.</p>\n<p>Maybe next year they discover a helper method they could have called instead and so they can change the code to call that directly and not use impl-&gt;Purr at all. (Yes, they could achieve the same thing by updating the actual impl::Purr method as well, but in that case you are stuck with an extra function call that achieves nothing but calling the next function in turn.)</p>\n<p>It also means the header only has definitions and does not have any implementation which makes for a cleaner separation, which is the whole point of the idiom.</p>\n" }, { "answer_id": 60579, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 6, "selected": false, "text": "<p>I think most people refer to this as the <em>Handle Body</em> idiom. See James Coplien's book <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201548550\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Advanced C++ Programming Styles and Idioms</a></em>. It's also known as the <a href=\"http://en.wikipedia.org/wiki/Cheshire_Cat\" rel=\"noreferrer\">Cheshire Cat</a> because of <a href=\"https://en.wikipedia.org/wiki/Lewis_Carroll\" rel=\"noreferrer\">Lewis Caroll's</a> character that fades away until only the grin remains.</p>\n<p>The example code should be distributed across two sets of source files. Then only <em>Cat.h</em> is the file that is shipped with the product.</p>\n<p><em>CatImpl.h</em> is included by <em>Cat.cpp</em> and <em>CatImpl.cpp</em> contains the implementation for <em>CatImpl::Purr()</em>. This won't be visible to the public using your product.</p>\n<p>Basically the idea is to hide as much as possible of the implementation from prying eyes.</p>\n<p>This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.</p>\n<p>We did this with the rewrite of <a href=\"https://en.wikipedia.org/wiki/IONA_Technologies\" rel=\"noreferrer\">IONA's</a> <a href=\"https://en.wikipedia.org/wiki/Orbix_(software)\" rel=\"noreferrer\">Orbix</a> 3.3 product in 2000.</p>\n<p>As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses <em>Cat</em> if you just want to change the implementation of <em>Purr()</em>.</p>\n<p>This technique is used in a methodology called <a href=\"http://en.wikipedia.org/wiki/Design_by_contract\" rel=\"noreferrer\">design by contract</a>.</p>\n" }, { "answer_id": 60582, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 3, "selected": false, "text": "<p>Typically, the only reference to a PIMPL class in the header for the <em>owner</em> class (<em>Cat</em> in this case) would be a forward declaration, as you have done here, because that can greatly reduce the dependencies.</p>\n<p>For example, if your PIMPL class has <em>ComplicatedClass</em> as a member (and not just a pointer or reference to it) then you would need to have <em>ComplicatedClass</em> fully defined before its use. In practice, this means including file &quot;ComplicatedClass.h&quot; (which will also indirectly include anything <em>ComplicatedClass</em> depends on). This can lead to a single header fill pulling in lots and lots of stuff, which is bad for managing your dependencies (and your compile times).</p>\n<p>When you use the PIMPL idiom, you only need to #include the stuff used in the public interface of your <em>owner</em> type (which would be <em>Cat</em> here). Which makes things better for people using your library, and means you don't need to worry about people depending on some internal part of your library - either by mistake, or because they want to do something you don't allow, so they #define private public before including your files.</p>\n<p>If it's a simple class, there's usually isn't any reason to use a PIMPL, but for times when the types are quite big, it can be a big help (especially in avoiding long build times).</p>\n" }, { "answer_id": 60605, "author": "Xavier Nodet", "author_id": 4177, "author_profile": "https://Stackoverflow.com/users/4177", "pm_score": 6, "selected": true, "text": "<ul>\n<li>Because you want <code>Purr()</code> to be able to use private members of <code>CatImpl</code>. <code>Cat::Purr()</code> would not be allowed such an access without a <code>friend</code> declaration.</li>\n<li>Because you then don't mix responsibilities: one class implements, one class forwards. </li>\n</ul>\n" }, { "answer_id": 60616, "author": "Nick", "author_id": 4949, "author_profile": "https://Stackoverflow.com/users/4949", "pm_score": 4, "selected": false, "text": "<p>If your class uses the PIMPL idiom, you can avoid changing the header file on the public class.</p>\n<p>This allows you to add/remove methods to the PIMPL class, without modifying the external class's header file. You can also add/remove #includes to the PIMPL too.</p>\n<p>When you change the external class's header file, you have to recompile everything that #includes it (and if any of those are header files, you have to recompile everything that #includes them, and so on).</p>\n" }, { "answer_id": 60618, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is a difference worth mentioning but...</p>\n\n<p>Would it be possible to have the implementation in its own namespace and have a public wrapper / library namespace for the code the user sees:</p>\n\n<pre><code>catlib::Cat::Purr(){ cat_-&gt;Purr(); }\ncat::Cat::Purr(){\n printf(\"purrrrrr\");\n}\n</code></pre>\n\n<p>This way all library code can make use of the cat namespace and as the need to expose a class to the user arises a wrapper could be created in the catlib namespace.</p>\n" }, { "answer_id": 62059, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<p>I find it telling that, in spite of how well-known the PIMPL idiom is, I don't see it crop up very often in real life (e.g., in open source projects).</p>\n<p>I often wonder if the &quot;benefits&quot; are overblown; yes, you can make some of your implementation details even more hidden, and yes, you can change your implementation without changing the header, but it's not obvious that these are big advantages in reality.</p>\n<p>That is to say, it's not clear that there's any need for your implementation to be <em>that</em> well hidden, and perhaps it's quite rare that people really do change only the implementation; as soon as you need to add new methods, say, you need to change the header anyway.</p>\n" }, { "answer_id": 678205, "author": "markh44", "author_id": 79047, "author_profile": "https://Stackoverflow.com/users/79047", "pm_score": 1, "selected": false, "text": "<p>I just implemented my first PIMPL class over the last couple of days. I used it to eliminate problems I was having, including file *winsock2.*h in Borland Builder. It seemed to be screwing up struct alignment and since I had socket things in the class private data, those problems were spreading to any .cpp file that included the header.</p>\n<p>By using PIMPL, <em>winsock2.h</em> was included in only one .cpp file where I could put a lid on the problem and not worry that it would come back to bite me.</p>\n<p>To answer the original question, the advantage I found in forwarding the calls to the PIMPL class was that the PIMPL class is the same as what your original class would have been before you pimpl'd it, plus your implementations aren't spread over two classes in some weird fashion. It's much clearer to implement the public members to simply forward to the PIMPL class.</p>\n<p>Like <a href=\"https://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used/60605#60605\">Mr Nodet said</a>, one class, one responsibility.</p>\n" }, { "answer_id": 6426059, "author": "Esben Nielsen", "author_id": 808531, "author_profile": "https://Stackoverflow.com/users/808531", "pm_score": 2, "selected": false, "text": "<p>Well, I wouldn't use it. I have a better alternative:</p>\n<h3>File <em>foo.h</em></h3>\n<pre><code>class Foo {\npublic:\n virtual ~Foo() { }\n virtual void someMethod() = 0;\n\n // This &quot;replaces&quot; the constructor\n static Foo *create();\n}\n</code></pre>\n<h3>File <em>foo.cpp</em></h3>\n<pre><code>namespace {\n class FooImpl: virtual public Foo {\n\n public:\n void someMethod() {\n //....\n }\n };\n}\n\nFoo *Foo::create() {\n return new FooImpl;\n}\n</code></pre>\n<p>Does this pattern have a name?</p>\n<p>As someone who is also a Python and Java programmer, I like this a lot more than the PIMPL idiom.</p>\n" }, { "answer_id": 25993728, "author": "the swine", "author_id": 1140976, "author_profile": "https://Stackoverflow.com/users/1140976", "pm_score": 5, "selected": false, "text": "<p>For what is worth, it separates the implementation from the interface. This is usually not very important in small size projects. But, in large projects and libraries, it can be used to reduce the build times significantly.</p>\n<p>Consider that the implementation of <code>Cat</code> may include many headers, may involve template meta-programming which takes time to compile on its own. Why should a user, who just wants to use the <code>Cat</code> have to include all that? Hence, all the necessary files are hidden using the pimpl idiom (hence the forward declaration of <code>CatImpl</code>), and using the interface does not force the user to include them.</p>\n<p>I'm developing a library for nonlinear optimization (read &quot;lots of nasty math&quot;), which is implemented in templates, so most of the code is in headers. It takes about five minutes to compile (on a decent multi-core CPU), and just parsing the headers in an otherwise empty <code>.cpp</code> takes about a minute. So anyone using the library has to wait a couple of minutes every time they compile their code, which makes the development quite <a href=\"http://xkcd.com/303/\" rel=\"nofollow noreferrer\">tedious</a>. However, by hiding the implementation and the headers, one just includes a simple interface file, which compiles instantly.</p>\n<p>It does not necessarily have anything to do with protecting the implementation from being copied by other companies - which wouldn't probably happen anyway, unless the inner workings of your algorithm can be guessed from the definitions of the member variables (if so, it is probably not very complicated and not worth protecting in the first place).</p>\n" }, { "answer_id": 26871719, "author": "nurettin", "author_id": 227755, "author_profile": "https://Stackoverflow.com/users/227755", "pm_score": 2, "selected": false, "text": "<p>We use the PIMPL idiom in order to emulate <a href=\"https://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow noreferrer\">aspect-oriented programming</a> where pre, post and error aspects are called before and after the execution of a member function.</p>\n<pre><code>struct Omg{\n void purr(){ cout&lt;&lt; &quot;purr\\n&quot;; }\n};\n\nstruct Lol{\n Omg* omg;\n /*...*/\n void purr(){ try{ pre(); omg-&gt; purr(); post(); }catch(...){ error(); } }\n};\n</code></pre>\n<p>We also use a pointer-to-base class to share different aspects between many classes.</p>\n<p>The drawback of this approach is that the library user has to take into account all the aspects that are going to be executed, but only sees his/her class. It requires browsing the documentation for any side effects.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
Backgrounder: The [PIMPL Idiom](http://en.wikipedia.org/wiki/Opaque_pointer) (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of. This hides internal implementation details and data from the user of the library. When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file? To illustrate, this code puts the `Purr()` implementation on the impl class and wraps it as well. **Why not implement Purr directly on the public class?** ```c++ // header file: class Cat { private: class CatImpl; // Not defined here CatImpl *cat_; // Handle public: Cat(); // Constructor ~Cat(); // Destructor // Other operations... Purr(); }; // CPP file: #include "cat.h" class Cat::CatImpl { Purr(); ... // The actual implementation can be anything }; Cat::Cat() { cat_ = new CatImpl; } Cat::~Cat() { delete cat_; } Cat::Purr(){ cat_->Purr(); } CatImpl::Purr(){ printf("purrrrrr"); } ```
* Because you want `Purr()` to be able to use private members of `CatImpl`. `Cat::Purr()` would not be allowed such an access without a `friend` declaration. * Because you then don't mix responsibilities: one class implements, one class forwards.
60,573
<p>Using C# .NET 2.0, I have a composite data class that does have the <code>[Serializable]</code> attribute on it. I am creating an <code>XMLSerializer</code> class and passing that into the constructor:</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(DataClass)); </code></pre> <p>I am getting an exception saying: </p> <blockquote> <p>There was an error reflecting type.</p> </blockquote> <p>Inside the data class there is another composite object. Does this also need to have the <code>[Serializable]</code> attribute, or by having it on the top object, does it recursively apply it to all objects inside?</p>
[ { "answer_id": 60581, "author": "Lamar", "author_id": 3566, "author_profile": "https://Stackoverflow.com/users/3566", "pm_score": 10, "selected": true, "text": "<p>Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing. </p>\n\n<p>You can exclude fields/properties from xml serialization by decorating them with the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute\" rel=\"noreferrer\"><code>[XmlIgnore]</code></a> attribute. </p>\n\n<p><code>XmlSerializer</code> does not use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute\" rel=\"noreferrer\"><code>[Serializable]</code></a> attribute, so I doubt that is the problem.</p>\n" }, { "answer_id": 60583, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 0, "selected": false, "text": "<p>Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.</p>\n" }, { "answer_id": 60596, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>All the objects in the serialization graph have to be serializable.</p>\n\n<p>Since <code>XMLSerializer</code> is a blackbox, check these links if you want to debug further into the serialization process..</p>\n\n<p><a href=\"http://www.hanselman.com/blog/CategoryView.aspx?category=XmlSerializer\" rel=\"nofollow noreferrer\">Changing where XmlSerializer Outputs Temporary Assemblies</a> </p>\n\n<p><a href=\"http://www.hanselman.com/blog/HOWTODebugIntoANETXmlSerializerGeneratedAssembly.aspx\" rel=\"nofollow noreferrer\">HOW TO: Debug into a .NET XmlSerializer Generated Assembly</a> </p>\n" }, { "answer_id": 60610, "author": "Darren", "author_id": 6065, "author_profile": "https://Stackoverflow.com/users/6065", "pm_score": 2, "selected": false, "text": "<p>I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the <a href=\"http://www.sliver.com/dotnet/SnippetCompiler/\" rel=\"nofollow noreferrer\">SnippetCompiler</a>:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Xml;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\n\npublic class Inner\n{\n private string _AnotherStringProperty;\n public string AnotherStringProperty \n { \n get { return _AnotherStringProperty; } \n set { _AnotherStringProperty = value; } \n }\n}\n\npublic class DataClass\n{\n private string _StringProperty;\n public string StringProperty \n { \n get { return _StringProperty; } \n set{ _StringProperty = value; } \n }\n\n private Inner _InnerObject;\n public Inner InnerObject \n { \n get { return _InnerObject; } \n set { _InnerObject = value; } \n }\n}\n\npublic class MyClass\n{\n\n public static void Main()\n {\n try\n {\n XmlSerializer serializer = new XmlSerializer(typeof(DataClass));\n TextWriter writer = new StreamWriter(@\"c:\\tmp\\dataClass.xml\");\n DataClass clazz = new DataClass();\n Inner inner = new Inner();\n inner.AnotherStringProperty = \"Foo2\";\n clazz.InnerObject = inner;\n clazz.StringProperty = \"foo\";\n serializer.Serialize(writer, clazz);\n }\n finally\n {\n Console.Write(\"Press any key to continue...\");\n Console.ReadKey();\n }\n }\n\n}\n</code></pre>\n\n<p>I would imagine that the XmlSerializer is using reflection over the public properties.</p>\n" }, { "answer_id": 60665, "author": "Jeremy McGee", "author_id": 3546, "author_profile": "https://Stackoverflow.com/users/3546", "pm_score": 7, "selected": false, "text": "<p>Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.</p>\n" }, { "answer_id": 60714, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": false, "text": "<p>Also be aware that <code>XmlSerializer</code> cannot serialize abstract properties.. See my question <a href=\"https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types\">here</a> (which I have added the solution code to)..</p>\n\n<p><a href=\"https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types\">XML Serialization and Inherited Types</a></p>\n" }, { "answer_id": 72043, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have been using the <code>NetDataSerialiser</code> class to serialise \nmy domain classes. <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx\" rel=\"nofollow noreferrer\">NetDataContractSerializer Class</a>.</p>\n\n<p>The domain classes are shared between client and server.</p>\n" }, { "answer_id": 1076259, "author": "Charlie Salts", "author_id": 37971, "author_profile": "https://Stackoverflow.com/users/37971", "pm_score": 2, "selected": false, "text": "<p>I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used. </p>\n\n<p>I found a work around <a href=\"http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx\" rel=\"nofollow noreferrer\">here</a>. </p>\n" }, { "answer_id": 2715915, "author": "Luca", "author_id": 161554, "author_profile": "https://Stackoverflow.com/users/161554", "pm_score": 3, "selected": false, "text": "<p>If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the <a href=\"http://msdn.microsoft.com/it-it/library/system.xml.serialization.ixmlserializable%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">IXmlSerialiable</a> interface, which will allow you more freedom <em>at the cost of more verbose coding</em>.</p>\n\n<pre><code>public class NetService : IXmlSerializable\n{\n #region Data\n\n public string Identifier = String.Empty;\n\n public string Name = String.Empty;\n\n public IPAddress Address = IPAddress.None;\n public int Port = 7777;\n\n #endregion\n\n #region IXmlSerializable Implementation\n\n public XmlSchema GetSchema() { return (null); }\n\n public void ReadXml(XmlReader reader)\n {\n // Attributes\n Identifier = reader[XML_IDENTIFIER];\n if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)\n throw new XmlException(\"unable to parse the element \" + typeof(NetService).Name + \" (badly formatted parameter \" + XML_NETWORK_PORT);\n if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)\n throw new XmlException(\"unable to parse the element \" + typeof(NetService).Name + \" (badly formatted parameter \" + XML_NETWORK_ADDR);\n }\n\n public void WriteXml(XmlWriter writer)\n {\n // Attributes\n writer.WriteAttributeString(XML_IDENTIFIER, Identifier);\n writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());\n writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());\n }\n\n private const string XML_IDENTIFIER = \"Id\";\n\n private const string XML_NETWORK_ADDR = \"Address\";\n\n private const string XML_NETWORK_PORT = \"Port\";\n\n #endregion\n}\n</code></pre>\n\n<p>There is an interesting <a href=\"http://msdn.microsoft.com/en-us/magazine/cc164135.aspx\" rel=\"nofollow noreferrer\">article</a>, which show an elegant way to implements a sophisticated way to \"extend\" the XmlSerializer.</p>\n\n<hr>\n\n<p>The article say:</p>\n\n<blockquote>\n <p>IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.</p>\n</blockquote>\n\n<p>Because this, I suggest to implement you're own <code>IXmlSerializable</code> classes, in order to avoid too much complicated implementations.</p>\n\n<p>...it could be straightforward to implements our custom <code>XmlSerializer</code> class using reflection.</p>\n" }, { "answer_id": 4471269, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 2, "selected": false, "text": "<p>I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.</p>\n\n<pre><code> [System.Xml.Serialization.XmlElementAttribute(Order = XX)]\n</code></pre>\n\n<p>I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.</p>\n" }, { "answer_id": 7450751, "author": "Dennis Calla", "author_id": 510199, "author_profile": "https://Stackoverflow.com/users/510199", "pm_score": 5, "selected": false, "text": "<p>I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this: </p>\n\n<p>'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type. </p>\n\n<p>Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1. </p>\n\n<p>What I needed to do was add an attribute to one of the classes (I added to the base class):</p>\n\n<pre><code>[XmlType(\"BaseNamespace.Class1\")]\n</code></pre>\n\n<p>Note: If you have more layers of classes you need to add an attribute to them as well.</p>\n" }, { "answer_id": 8835456, "author": "jkokorian", "author_id": 1068959, "author_profile": "https://Stackoverflow.com/users/1068959", "pm_score": 3, "selected": false, "text": "<p>I just got the same error and discovered that a property of type <code>IEnumerable&lt;SomeClass&gt;</code> was the problem. It appears that <code>IEnumerable</code> cannot be serialized directly.</p>\n\n<p>Instead, one could use <code>List&lt;SomeClass&gt;</code>.</p>\n" }, { "answer_id": 13923224, "author": "Jeremy Brown", "author_id": 1911312, "author_profile": "https://Stackoverflow.com/users/1911312", "pm_score": 1, "selected": false, "text": "<p>I had a situation where the Order was the same for two elements in a row</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = \"SeriousInjuryFlag\")]\n</code></pre>\n\n<p>.... some code ...</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = \"AccidentFlag\")]\n</code></pre>\n\n<p>When I changed the code to increment the order by one for each new Property in the class, the error went away.</p>\n" }, { "answer_id": 21954336, "author": "Stefan Michev", "author_id": 754571, "author_profile": "https://Stackoverflow.com/users/754571", "pm_score": 3, "selected": false, "text": "<p>Most common reasons by me:</p>\n\n<pre><code> - the object being serialized has no parameterless constructor\n - the object contains Dictionary\n - the object has some public Interface members\n</code></pre>\n" }, { "answer_id": 42273101, "author": "Kiran.Bakwad", "author_id": 2940450, "author_profile": "https://Stackoverflow.com/users/2940450", "pm_score": 0, "selected": false, "text": "<pre><code>[System.Xml.Serialization.XmlElementAttribute(\"strFieldName\", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>[XmlIgnore]\nstring [] strFielsName {get;set;}\n</code></pre>\n" }, { "answer_id": 44192135, "author": "Curious Dev", "author_id": 3952153, "author_profile": "https://Stackoverflow.com/users/3952153", "pm_score": 0, "selected": false, "text": "<p>I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable. </p>\n" }, { "answer_id": 59372719, "author": "chxzy", "author_id": 4871263, "author_profile": "https://Stackoverflow.com/users/4871263", "pm_score": 0, "selected": false, "text": "<p>I have a slightly different solution to all described here so far, so for any future civilisation here's mine!</p>\n\n<p>I had declared a datatype of \"time\" as the original type was a <code>TimeSpan</code> and subsequently changed to a <code>String</code>:</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(DataType=\"time\", Order=3)]\n</code></pre>\n\n<p>however the actual type was a string</p>\n\n<pre><code>public string TimeProperty {\n get {\n return this.timePropertyField;\n }\n set {\n this.timePropertyField = value;\n this.RaisePropertyChanged(\"TimeProperty\");\n }\n}\n</code></pre>\n\n<p>by removing the <code>DateType</code> property the <code>Xml</code> can be serialized</p>\n\n<pre><code>[System.Xml.Serialization.XmlElementAttribute(Order=3)]\npublic string TimeProperty {\n get {\n return this.timePropertyField;\n }\n set {\n this.timePropertyField = value;\n this.RaisePropertyChanged(\"TimeProperty\");\n }\n}\n</code></pre>\n" }, { "answer_id": 59372769, "author": "Iqra.", "author_id": 7596696, "author_profile": "https://Stackoverflow.com/users/7596696", "pm_score": 1, "selected": false, "text": "<p>I was getting the same error when I created a property having a datatype - <code>Type</code>. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was <code>Type</code>) in my case. The solution is as follows: </p>\n\n<pre><code> [XmlIgnore]\n public Type Type { get; set; }\n</code></pre>\n" }, { "answer_id": 66289667, "author": "Esperento57", "author_id": 3735690, "author_profile": "https://Stackoverflow.com/users/3735690", "pm_score": 2, "selected": false, "text": "<p>Sometime, this type of error is because you dont have constructur of class without argument</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Using C# .NET 2.0, I have a composite data class that does have the `[Serializable]` attribute on it. I am creating an `XMLSerializer` class and passing that into the constructor: ``` XmlSerializer serializer = new XmlSerializer(typeof(DataClass)); ``` I am getting an exception saying: > > There was an error reflecting type. > > > Inside the data class there is another composite object. Does this also need to have the `[Serializable]` attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing. You can exclude fields/properties from xml serialization by decorating them with the [`[XmlIgnore]`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute) attribute. `XmlSerializer` does not use the [`[Serializable]`](https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute) attribute, so I doubt that is the problem.
60,585
<p>I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).</p> <p>I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?</p>
[ { "answer_id": 61062, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 0, "selected": false, "text": "<p>Good Question!</p>\n\n<p>I've given this some thought... and I can't think of a good solution. What I can think of is a horrible horrible hack that just might work. After seeing that no one has posted an answer to this question for nearly a day, I figured a bad, but working answer would be ok. </p>\n\n<p>The SAM file is off limits while the system is running. There are some DLL Injection tricks which you may be able to get working but in the end you'll just end up with password hashes and you'd have to hash the user provided passwords to match against them anyway.</p>\n\n<p>What you really want is something that tries to authenticate the user against the SAM file. I think you can do this by doing something like the following. </p>\n\n<ol>\n<li>Create a File Share on the server and make it so that only accounts that you want to be able to log in as are granted access to it.</li>\n<li>In PHP use the system command to invoke a wsh script that: mounts the share using the username and password that the website user provides. records if it works, and then unmounts the drive if it does. </li>\n<li>Collect the result somehow. The result can be returned to php either on the stdout of the script, or hopefully using the return code for the script.</li>\n</ol>\n\n<p>I know it's not pretty, but it should work.</p>\n\n<p>I feel dirty :|</p>\n\n<p>Edit: reason for invoking the external wsh script is that PHP doesn't allow you to use UNC paths (as far as I can remember).</p>\n" }, { "answer_id": 61220, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 3, "selected": true, "text": "<p>I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into <a href=\"http://support.microsoft.com/kb/218497\" rel=\"nofollow noreferrer\">\nUser authentication issues with the Active Directory Service Interfaces WinNT provider</a>. I'm not 100% sure but I <i>guess</i> the WSH/network connect approach has the same problem.<br />\nAccording to <a href=\"http://support.microsoft.com/kb/180548/\" rel=\"nofollow noreferrer\">How to validate user credentials on Microsoft operating systems</a> you should use LogonUser or SSPI.\n<br />\nIt also says<blockquote><pre>LogonUser Win32 API does not require TCB privilege in Microsoft Windows Server 2003, however, for downlevel compatibility, this is still the best approach.</p>\n\n<p>On Windows XP, it is no longer required that a process have the SE_TCB_NAME privilege in order to call LogonUser. Therefore, the simplest method to validate a user's credentials on Windows XP, is to call the LogonUser API.</pre></blockquote>Therefore, if I were certain Win9x/2000 support isn't needed, I would write an extension that exposes LogonUser to php.<br />\nYou might also be interested in <a href=\"http://www.codewalkers.com/c/a/User-Management-Code/User-Authentication-from-NT-Accounts/\" rel=\"nofollow noreferrer\">User Authentication from NT Accounts</a>. It uses the w32api extension, and needs a support dll ...I'd rather write that small LogonUser-extension ;-)<br />\nIf that's not feasible I'd probably look into the fastcgi module for IIS and how stable it is and let the IIS handle the authentication.</p>\n\n<p>edit:<br />\nI've also tried to utilize <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx\" rel=\"nofollow noreferrer\">System.Security.Principal.WindowsIdentity</a> and php's <a href=\"http://uk.php.net/manual/en/book.com.php\" rel=\"nofollow noreferrer\">com/.net extension</a>. But the dotnet constructor doesn't seem to allow passing parameters to the objects constructor and my \"experiment\" to get the assembly (and with it CreateInstance()) from GetType() has failed with an \"unknown zval\" error.</p>\n" }, { "answer_id": 66417, "author": "Martin", "author_id": 2581, "author_profile": "https://Stackoverflow.com/users/2581", "pm_score": 0, "selected": false, "text": "<p>Building a PHP extension requires a pretty large investment in terms of hard disk space. Since I already have the GCC (MinGW) environment installed, I have decided to take the performance hit of launching a process from the PHP script. The source code is below.</p>\n\n<pre><code>// Usage: logonuser.exe /user username /password password [/domain domain]\n// Exit code is 0 on logon success and 1 on failure.\n\n#include &lt;windows.h&gt;\n\nint main(int argc, char *argv[]) {\n HANDLE r = 0;\n char *user = 0;\n char *password = 0;\n char *domain = 0;\n int i;\n\n for(i = 1; i &lt; argc; i++) {\n if(!strcmp(argv[i], \"/user\")) {\n if(i + 1 &lt; argc) {\n user = argv[i + 1];\n i++;\n }\n } else if(!strcmp(argv[i], \"/domain\")) {\n if(i + 1 &lt; argc) {\n domain = argv[i + 1];\n i++;\n }\n } else if(!strcmp(argv[i], \"/password\")) {\n if(i + 1 &lt; argc) {\n password = argv[i + 1];\n i++;\n }\n }\n }\n\n if(user &amp;&amp; password) {\n LogonUser(user, domain, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &amp;r);\n }\n return r ? 0 : 1;\n}\n</code></pre>\n\n<p>Next is the PHP source demonstrating its use.\n \n\n<pre><code>if($_SERVER['REQUEST_METHOD'] == 'POST') {\n if(isset($_REQUEST['user'], $_REQUEST['password'], $_REQUEST['domain'])) {\n $failure = 1;\n $user = $_REQUEST['user'];\n $password = $_REQUEST['password'];\n $domain = $_REQUEST['domain'];\n\n if($user &amp;&amp; $password) {\n $cmd = \"logonuser.exe /user \" . escapeshellarg($user) . \" /password \" . escapeshellarg($password);\n if($domain) $cmd .= \" /domain \" . escapeshellarg($domain);\n system($cmd, $failure);\n }\n\n if($failure) {\n echo(\"Incorrect credentials.\");\n } else {\n echo(\"Correct credentials!\");\n }\n }\n}\n?&gt;\n&lt;form action=\"&lt;?php echo(htmlentities($_SERVER['PHP_SELF'])); ?&gt;\" method=\"post\"&gt;\n Username: &lt;input type=\"text\" name=\"user\" value=\"&lt;?php echo(htmlentities($user)); ?&gt;\" /&gt;&lt;br /&gt;\n Password: &lt;input type=\"password\" name=\"password\" value=\"\" /&gt;&lt;br /&gt;\n Domain: &lt;input type=\"text\" name=\"domain\" value=\"&lt;?php echo(htmlentities($domain)); ?&gt;\" /&gt;&lt;br /&gt;\n &lt;input type=\"submit\" value=\"logon\" /&gt;\n&lt;/form&gt;\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM). I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?
I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into [User authentication issues with the Active Directory Service Interfaces WinNT provider](http://support.microsoft.com/kb/218497). I'm not 100% sure but I *guess* the WSH/network connect approach has the same problem. According to [How to validate user credentials on Microsoft operating systems](http://support.microsoft.com/kb/180548/) you should use LogonUser or SSPI. It also says > > ``` > LogonUser Win32 API does not require TCB privilege in Microsoft Windows Server 2003, however, for downlevel compatibility, this is still the best approach. > ``` > On Windows XP, it is no longer required that a process have the SE\_TCB\_NAME privilege in order to call LogonUser. Therefore, the simplest method to validate a user's credentials on Windows XP, is to call the LogonUser API.Therefore, if I were certain Win9x/2000 support isn't needed, I would write an extension that exposes LogonUser to php. You might also be interested in [User Authentication from NT Accounts](http://www.codewalkers.com/c/a/User-Management-Code/User-Authentication-from-NT-Accounts/). It uses the w32api extension, and needs a support dll ...I'd rather write that small LogonUser-extension ;-) If that's not feasible I'd probably look into the fastcgi module for IIS and how stable it is and let the IIS handle the authentication. edit: I've also tried to utilize [System.Security.Principal.WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) and php's [com/.net extension](http://uk.php.net/manual/en/book.com.php). But the dotnet constructor doesn't seem to allow passing parameters to the objects constructor and my "experiment" to get the assembly (and with it CreateInstance()) from GetType() has failed with an "unknown zval" error.
60,590
<p>On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."</p> <p>A couple of <strong>possible approaches</strong> I know about, and browser compatibility (based on a quick test):</p> <p><strong>1) Do a <code>window.open</code> pointing to the new file.</strong> </p> <pre><code>- FireFox 3 blocks this. - IE6 blocks this. - IE7 blocks this. </code></pre> <p><strong>2) Create an iframe pointing to the new file.</strong> </p> <pre><code>- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?) - IE6 blocks this. - IE7 blocks this. How can I do this so that at least these three browsers will not object? </code></pre> <p>Bonus: is there a method that doesn't require browser-conditional statements? </p> <p>(I believe that download.com employs both methods conditionally, but I can't get either one to work.)</p> <p><strong>Responses and Clarifications:</strong></p> <pre><code>Q: "Why not point the current window to the file?" A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?" </code></pre> <p><strong>UPDATE: I have abandoned this approach. See my answer below for reasons.</strong></p>
[ { "answer_id": 60598, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "<p>How about changing the location to point to the new file? (e.g. by changing window.location)</p>\n" }, { "answer_id": 60603, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>I usually just have a PHP script that outputs the file directly to the browser with the appropriate Content-Type</p>\n\n<pre><code>if(file_exists($filename)) {\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, pre-check=0\");\n header(\"Cache-Control: private\", false);\n header(\"Content-Type: \" . $content-type);\n header(\"Content-Disposition: attachment; filename=\\\"\" . basename($filename) . \"\\\";\" );\n header(\"Content-Transfer-Encoding: binary\");\n header(\"Content-Length: \" . filesize($filename));\n\n readfile(\"$filename\");\n}else{\n print \"ERROR: the file \" . basename($filename) . \" could not be downloaded because it did not exist.\";\n}\n</code></pre>\n\n<p>The only disadvantage is that, since this sets the HTTP header, it has be called before you have any other output.</p>\n\n<p>But you can have a link to the PHP download page and it will cause the browser to pop up a download box without messing up the content of the current page.</p>\n" }, { "answer_id": 60606, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 5, "selected": true, "text": "<p>You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag.</p>\n\n<pre><code>&lt;meta http-equiv=\"refresh\" content=\"5;url=/download.php?doc=123.zip\"/&gt;\n</code></pre>\n" }, { "answer_id": 60619, "author": "Dan Walker", "author_id": 752, "author_profile": "https://Stackoverflow.com/users/752", "pm_score": 0, "selected": false, "text": "<p>I've always just made an iframe which points to the file.</p>\n\n<pre><code>&lt;iframe src=\"/download.exe\" frameborder=\"0\" height=\"0\" width=\"0\"&gt;&lt;a href=\"/download.exe\"&gt;Click here to download.&lt;/a&gt;&lt;/iframe&gt;\n</code></pre>\n" }, { "answer_id": 62248, "author": "Effata", "author_id": 5740, "author_profile": "https://Stackoverflow.com/users/5740", "pm_score": 0, "selected": false, "text": "<p>Regarding not pointing the current window to the download.\nIn my experience you can still show your \"please donate\" page, since downloads (as long as they send the correct headers) don't actually update the browser window.\nI do this for csv exports on one of my sites, and as far as the user is concerned it just pops up a safe file window.\nSo i would recommend a simple meta-redirect as Soldarnal showed.</p>\n" }, { "answer_id": 62495, "author": "Vitaly Sharovatov", "author_id": 6647, "author_profile": "https://Stackoverflow.com/users/6647", "pm_score": 0, "selected": false, "text": "<p>Just to summarise, you have 2 goals: </p>\n\n<ol>\n<li>start download process</li>\n<li>show user a page with a donate options</li>\n</ol>\n\n<p>To achieve this I would do the following:</p>\n\n<p>When your user submits the form, he gets the resulting page with a donate options and a text saying that his download will start in 5 seconds. And in the head section of this page you put the META code as Soldarnal said:\n&lt;meta http-equiv=\"refresh\" content=\"5;url=/download.php?doc=123.zip&gt;</p>\n\n<p>And that's all.</p>\n" }, { "answer_id": 62899, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>One catch is that you may encounter issues with IE (version 6 in particular) if the headers are not set up \"correctly\".</p>\n\n<p>Ensure you set the right Content-Type, but also consider setting the Cache options for IE (at least) to <em>allow</em> caching. If the file is one the user can open rather than save (e.g. an MS Word document) early versions of IE need to cache the file, as they hand off the \"open\" request to the applicable app, pointing to the file that was downloaded in the cache.</p>\n\n<p>There's also a related issue, if the IE6 user's cache is full, it won't properly save the file (thus when the applicable app gets the hand off to open it, it will complain the file is corrupt.</p>\n\n<p>You may also want to turn of any gzip actions on the downloads too (for IE)</p>\n\n<p>IE6/IE7 both have issues with large downloads (e.g. 4.x Gigs...) not a likely scenario since IE doesn't even have a download manager, but something to be aware of.</p>\n\n<p>Finally, IE6 sometimes doesn't nicely handle a download \"push\" if it was initiated from within a nested iframe. I'm not exactly sure what triggers the issue, but I find it is easier with IE6 to avoid this scenario.</p>\n" }, { "answer_id": 73190, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 4, "selected": false, "text": "<p>Update: I have decided to abandon this approach, and instead just present the user with a link to the actual file. My reasoning is this:</p>\n\n<p>My initial attempts at a server-initiated download were blocked by the browser. That got me thinking: \"the browser is right. How does <strong>it</strong> know that this is a legitimate download? It <strong>should</strong> block a download that isn't obviously user-initiated.\"</p>\n\n<p>Any method that I can use for a server-initiated download could <strong>also</strong> be used by someone who wants to send malware. Therefore, downloads should only happen when the user specifically requests the file by clicking on a link for it.</p>\n\n<p>You're free to disagree, and if you still want to initiate a download, hopefully this thread will help you do it.</p>\n" }, { "answer_id": 114732, "author": "bastiandoeen", "author_id": 371953, "author_profile": "https://Stackoverflow.com/users/371953", "pm_score": 1, "selected": false, "text": "<p>Hoi!</p>\n\n<p>@Nathan:\nI decided to do exactly that: Have my \"getfile.php\" load all necessary stuff and then do a </p>\n\n<pre><code>header(\"Location: ./$path/$filename\");\n</code></pre>\n\n<p>to let the browser itself and directly do whatever it thinks is correct do with the file. This even works fine in Opera with me. </p>\n\n<p>But this will be a problem in environments, where no direct access to the files is allowed, in that case you will have to find a different way! (Thank Discordia my files are public PDFs!)</p>\n\n<p>Best regards, Basty</p>\n" }, { "answer_id": 728009, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;a href=\"normaldownload.zip\" onclick=\"use_dhtml_or_ajax_to_display_page()\"&gt;\n</code></pre>\n\n<p>Current page is unaffected if download is saved. Just ensure that download doesn't open in the same window (proper MIME type or <code>Content-Disposition</code>) and you'll be able to show anything.</p>\n\n<p><a href=\"https://stackoverflow.com/a/300517\">See more complete answer</a></p>\n" }, { "answer_id": 29692393, "author": "sagunms", "author_id": 1297184, "author_profile": "https://Stackoverflow.com/users/1297184", "pm_score": 0, "selected": false, "text": "<p>You can use Javascript/jQuery to initiate the download. Here's an example - you can get rid of the Ajax request and just use the setTimeout() block.</p>\n\n<pre><code>$(\"btnDownloadCSV\").on('click', function() {\n $.ajax({\n url: \"php_backend/get_download_url\",\n type: 'post',\n contentType: \"application/x-www-form-urlencoded\",\n data: {somedata: \"somedata\"},\n success: function(data) {\n // If iFrame already exists, remove it.\n if($(\"[id^='iframeTempCSV_\"]).length) { \n $(\"[id^='iframeTempCSV_\"]).remove();\n }\n setTimeout(function() {\n // If I'm creating an iframe with the same id, it will permit download only the first time.\n // So randHashId appended to ID to trick the browser.\n var randHashId = Math.random().toString(36).substr(2);\n // Create a fresh iFrame for auto-downloading CSV\n $('&lt;iframe id=\"iframeTempCSV_'+randHashId+'\" style=\"display:none;\" src=\"'+data.filepath+'\"&gt;&lt;/iframe&gt;').appendTo('body');\n }, 1000);\n },\n error: function(xhr, textStatus, errorThrown) {\n console.error(\"Error downloading...\");\n }\n });\n});\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment." A couple of **possible approaches** I know about, and browser compatibility (based on a quick test): **1) Do a `window.open` pointing to the new file.** ``` - FireFox 3 blocks this. - IE6 blocks this. - IE7 blocks this. ``` **2) Create an iframe pointing to the new file.** ``` - FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?) - IE6 blocks this. - IE7 blocks this. How can I do this so that at least these three browsers will not object? ``` Bonus: is there a method that doesn't require browser-conditional statements? (I believe that download.com employs both methods conditionally, but I can't get either one to work.) **Responses and Clarifications:** ``` Q: "Why not point the current window to the file?" A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?" ``` **UPDATE: I have abandoned this approach. See my answer below for reasons.**
You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag. ``` <meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip"/> ```
60,607
<p>What are the pros/cons of doing either way. Is there One Right Way(tm) ?</p>
[ { "answer_id": 60631, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 2, "selected": false, "text": "<p>It depends on the situation. I tend to use Exceptions when I am writing business logic/application internals, and trigger_error for Validator's and things of that sort.</p>\n\n<p>The pro's of using Exceptions at the logic level is to allow your application to do in case of such an error. You allow the application to chose instead of having the business logic know how to present the error.</p>\n\n<p>The pro's of using trigger_error for Validator's and things of that nature are, say,</p>\n\n<p>\n\n<pre><code>try {\n $user-&gt;login();\n} catch (AuthenticationFailureException $e) {\n set_error_handler(\"my_login_form_handler\");\n trigger_error(\"User could not be logged in. Please check username and password and try again!\");\n} catch (PersistenceException $pe) { // database unavailable\n set_error_handler(\"my_login_form_handler\"); \n trigger_error(\"Internal system error. Please contact the administrator.\");\n}\n</code></pre>\n\n<p>where my_login_form_handler pretties up the string and places the element in a visible area above the login form.</p>\n" }, { "answer_id": 60813, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 3, "selected": false, "text": "<p>I love the idea of using exceptions, but I often have third party libraries involved, and then if they don't use exceptions you end up with 3-4 different approaches to the problem! Zend uses exceptions. CakePHP uses a custom error handler, and most PEAR libraries use the PEAR::Error object. </p>\n\n<p>I which there WAS one true way in this regard. The custom error handlers route is probably the most flexible in this situation. Exceptions are a great idea though if you're either only using your own code, or using libraries that use them. </p>\n\n<p>Unfortunately in the PHP world we're still suffering from the refusal to die of PHP4, so things like exceptions, while they may represent best practise have been incredibly slow to catch on while everyone is still writing things to be able to work in both 4 and 5. Hopefully this debacle is now ending, though by the time it does, we'll have tensions between 6 and 5 instead... </p>\n\n<p>/me holds head in hands...</p>\n" }, { "answer_id": 76111, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 2, "selected": false, "text": "<p>The idea of exception is elegant and makes the error handling process so smooth. but this only applies when you have appropriate exception classes and in team development, one more important thing is \"standard\" exceptions. so if you plan to use exceptions, you'd better first standardize your exception types, or the better choice is to use exceptions from some popular framework. one other thing that applies to PHP (where you can write your code object orienter combined with structural code), is that if you are writing your whole application using classes. If you are writing object oriented, then exceptions are better for sure. after all I think your error handling process will be much smoother with exception than trigger_error and stuff.</p>\n" }, { "answer_id": 82207, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Obviously, there's no \"One Right Way\", but there's a multitude of opinions on this one. ;)</p>\n\n<p>Personally i use trigger_error for things the exceptions cannot do, namely notices and warnings (i.e. stuff you want to get logged, but not stop the flow of the application in the same way that errors/exceptions do (even if you catch them at some level)).</p>\n\n<p>I also mostly use exceptions for conditions that are assumed to be non-recoverable (to the caller of the method in which the exception occurs), i.e. serious errors. I don't use exceptions as an alternative to returning a value with the same meaning, if that's possible in a non-convoluted way. For example, if I create a lookup method, I usually return a null value if it didn't find whatever it was looking for instead of throwing an EntityNotFoundException (or equivalent).</p>\n\n<p>So my rule of thumb is this:</p>\n\n<ul>\n<li>As long as not finding something is a reasonable result, I find it much easier returning and checking for null-values (or some other default value) than handling it using a try-catch-clause.</li>\n<li>If, on the other hand, not finding it is a serious error that's not within the scope of the caller to recover from, I'd still throw an exception.</li>\n</ul>\n\n<p>The reason for throwing exceptions in the latter case (as opposed to triggering errors), is that exceptions are much more expressive, given that you use properly named Exception subclasses. I find that using PHP's Standard Library's exceptions is a good starting point when deciding what exceptions to use: <a href=\"http://www.php.net/~helly/php/ext/spl/classException.html\" rel=\"nofollow noreferrer\">http://www.php.net/~helly/php/ext/spl/classException.html</a></p>\n\n<p>You might want to extend them to get more semantically correct exceptions for your particular case, however.</p>\n" }, { "answer_id": 170546, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 1, "selected": false, "text": "<p>The Exceptions are the modern and robust way of signaling an error condition / an exceptional situation. Use them :)</p>\n" }, { "answer_id": 525113, "author": "Luke P M", "author_id": 53608, "author_profile": "https://Stackoverflow.com/users/53608", "pm_score": 3, "selected": false, "text": "<p>You should use exceptions in \"Exceptional circumstances\", that is when you call a method doFoo() you should expect it to perform, if for some reason doFoo is unable to do it's job then it should raise an exception.</p>\n\n<p>A lot of old php code would take the approach of returning false or null when a failure has occured, but this makes things hard to debug, exceptions make this debugging much easier. </p>\n\n<p>For example say you had a method called getDogFood() which returned an array of DogFood objects, if you called this method and it returns null when something goes wrong how will your calling code be able to tell whether null was returned because there was an error or there is just no dog food available?</p>\n\n<p>Regarding dealing with legacy code libraries that use php's inbuilt error logging, you can override the error logging with the set_error_handler() function, which you could use to then rethrow a generic Exception.</p>\n\n<p>Now that you have all of your code throwing detailed exceptions, you are free to decide what to do with them, in some parts of your code you may wish to catch them and try alternative methods or you can log them using your own logging functions which might log to a database, file, email - whichever you prefer. In short - Exceptions are more flexible .</p>\n" }, { "answer_id": 1129157, "author": "shadowhand", "author_id": 49146, "author_profile": "https://Stackoverflow.com/users/49146", "pm_score": 4, "selected": false, "text": "<p>If you want to use exceptions instead of errors for your entire application, you can do it with <a href=\"http://php.net/ErrorException\" rel=\"noreferrer\">ErrorException</a> and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an <code>E_NOTICE</code> will halt your entire application if your <a href=\"http://php.net/error_reporting\" rel=\"noreferrer\">error_reporting</a> settings do not suppress them.</p>\n\n<p>In my opinion, there are several benefits to using ErrorException:</p>\n\n<ol>\n<li>A custom exception handler will let you display nice messages, even for errors, using <a href=\"http://php.net/set_exception_handler\" rel=\"noreferrer\">set_exception_handler</a>.</li>\n<li>It does not disrupt existing code in any way... <a href=\"http://php.net/trigger_error\" rel=\"noreferrer\">trigger_error</a> and other error functions will still work normally.</li>\n<li>It makes it really hard to ignore stupid coding mistakes that trigger <code>E_NOTICE</code>s and <code>E_WARNING</code>s.</li>\n<li><p>You can use <code>try</code>/<code>catch</code> to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the <code>@</code> error suppression hack:</p>\n\n<pre><code>try {\n $foo = $_GET['foo'];\n} catch (ErrorException $e) {\n $foo = NULL;\n}\n</code></pre></li>\n<li><p>You can wrap your entire script in a single <code>try</code>/<code>catch</code> block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)</p></li>\n</ol>\n" }, { "answer_id": 13334532, "author": "unity100", "author_id": 1792090, "author_profile": "https://Stackoverflow.com/users/1792090", "pm_score": -1, "selected": false, "text": "<p><em><strong>Using exceptions are not a good idea in the era of 3rd party application integration</em></strong>. </p>\n\n<p>Because, the moment you try to integrate your app with something else, or someone else's app with yours, your entire application will come to a halt the moment a class in some 3rd party plugin throws an exception. Even if you have full fledged error handling, logging implemented in your own app, someone's random object in a 3rd party plugin will throw an exception, and your entire application will stop right there. </p>\n\n<p><em><strong>EVEN if you have the means in your application to make up for the error of that library you are using</em></strong>.... </p>\n\n<p>A case in example may be a 3rd party social login library which throws an exception because the social login provider returned an error, and kills your entire app unnecessarily - hybridauth, by the way. So, There you have an entire app, and there you have a library bringing in added functionality for you - in this case, social login - and even though you have a lot of fallback stuff in the case a provider does not authenticate (your own login system, plus like 20 or so other social login providers), your ENTIRE application will come to a grinding halt. And you will end up having to change the 3rd party library to work around these issues, and the point of using a 3rd party library to speed up development will be lost. </p>\n\n<p>This is a serious design flaw in regard to philosophy of handling errors in PHP. Lets face it - under the other end of most of applications developed today, there is a user. Be it an intranet user, be it a user over internet, be it a sysadmin, it does not matter - there is generally a user.</p>\n\n<p>And, having an application die on your face without there being anything you can do at that point other than to go back to a previous page and have a shot in the dark regarding what you are trying to do, as a user, is bad, bad practice from development side. Not to mention, an internal error which only the developers should know due to many reasons (from usability to security) being thrown on the face of a user. </p>\n\n<p>As a result, im going to have to just let go of a particular 3rd party library (hybridauth in this case) and not use it in my application, solely for that reason. Despite the fact that hybridauth is a very good library, and apparently a lot of good effort have been spent on it, with a phletora of capabilities. </p>\n\n<p>Therefore, you should refrain from using exceptions in your code. EVEN if the code you are doing right now, is the top level code that will run your application, and not a library, it is possible that you may want to include all or part of your code in other projects, or have to integrate parts or entirety of it with other code of yours or 3rd party code. And if you used exceptions, you will end up with the same situation - entire applications/integrations dying in your face even if you have proper means to handle whatever issue a piece of code provides.</p>\n" }, { "answer_id": 13655714, "author": "Tivie", "author_id": 295342, "author_profile": "https://Stackoverflow.com/users/295342", "pm_score": 2, "selected": false, "text": "<h2>Intro</h2>\n\n<p>In my personal experience, as a general rule, I prefer to use Exceptions in my code instead of trigger_error. This is mainly because using Exceptions is more flexible than triggering errors. And, IMHO, this is also beneficial not only for myself as for the 3rd party developer.</p>\n\n<ol>\n<li>I can extend the Exception class (or use exception codes) to explicitly differentiate the states of my library. This helps me and 3rd party developers in handling and debugging the code. <strong>This also exposes where and why it can fail</strong> without the need for source code browsing.</li>\n<li>I can effectively halt the execution of my Library without halting the execution of the script.</li>\n<li>The 3rd party developer can chain my Exceptions (in PHP > 5.3.*) Very useful for debugging and might be handy in handling situations where my library can fail due to disparate reasons.</li>\n</ol>\n\n<p>And I can do all this without imposing how he should handle my library failures. (ie: creating complex error handling functions). He can use a try catch block or just use an generic exception handler</p>\n\n<p><em><strong>Note:</em></strong></p>\n\n<p>Some of these points, in essence, are also valid for trigger_error, just a bit more complex to implement. Try catch blocks are really easy to use and very code friendly.</p>\n\n<hr>\n\n<h2>Example</h2>\n\n<p>I think this is an example might illustrate my point of view:</p>\n\n<pre><code>class HTMLParser {\n protected $doc;\n protected $source = null;\n public $parsedHtml;\n protected $parseErrors = array();\n public function __construct($doc) {\n if (!$doc instanceof DOMDocument) {\n // My Object is unusable without a valid DOMDOcument object\n // so I throw a CriticalException\n throw new CriticalException(\"Could not create Object Foo. You must pass a valid DOMDOcument object as parameter in the constructor\");\n }\n $this-&gt;doc = $doc;\n }\n\n public function setSource($source) {\n if (!is_string($source)) {\n // I expect $source to be a string but was passed something else so I throw an exception\n throw new InvalidArgumentException(\"I expected a string but got \" . gettype($source) . \" instead\");\n }\n $this-&gt;source = trim($source);\n return $this;\n }\n\n public function parse() {\n if (is_null($this-&gt;source) || $this-&gt;source == '') {\n throw new EmptyStringException(\"Source is empty\");\n }\n libxml_use_internal_errors(true);\n $this-&gt;doc-&gt;loadHTML($this-&gt;source);\n $this-&gt;parsedHtml = $this-&gt;doc-&gt;saveHTML();\n $errors = libxml_get_errors();\n if (count($errors) &gt; 0) {\n $this-&gt;parseErrors = $errors;\n throw new HtmlParsingException($errors[0]-&gt;message,$errors[0]-&gt;code,null,\n $errors[0]-&gt;level,$errors[0]-&gt;column,$errors[0]-&gt;file,$errors[0]-&gt;line);\n }\n return $this;\n }\n\n public function getParseErrors() {\n return $this-&gt;parseErrors;\n }\n\n public function getDOMObj() {\n return clone $this-&gt;doc;\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Explanation</h2>\n\n<p>In the <strong>constructor</strong> I throw a <em><code>CriticalException</code></em> if the param passed is not of type <em><code>DOMDocument</code></em> because without it my library will not work at all. </p>\n\n<p>(Note: I could simply write <code>__construct(DOMDocument $doc)</code> but this is just an example).</p>\n\n<p>In <strong><code>setsource()</code></strong> method I throw a <em><code>InvalidArgumentException</code></em> if the param passed is something other than a string. I prefer to halt the library execution here because <strong>source property</strong> is an essential property of my class and an invalid value will propagate the error throughout my library.</p>\n\n<p>The <strong><code>parse()</code></strong> method is usually the last method invoked in the cycle. Even though I throw a <em><code>XmlParsingException</code></em> if libXML finds a malformed document, the parsing is completed first and the results usable (to an extent).</p>\n\n<hr>\n\n<h2>Handling the example library</h2>\n\n<p>Here's an example how to handle this made up library:</p>\n\n<pre><code>$source = file_get_contents('http://www.somehost.com/some_page.html');\ntry {\n $parser = new HTMLParser(new DOMDocument());\n $parser-&gt;setSource($source)\n -&gt;parse();\n} catch (CriticalException $e) {\n // Library failed miserably, no recover is possible for it.\n // In this case, it's prorably my fault because I didn't pass\n // a DOMDocument object.\n print 'Sorry. I made a mistake. Please send me feedback!';\n} catch (InvalidArgumentException $e) {\n // the source passed is not a string, again probably my fault.\n // But I have a working parser object. \n // Maybe I can try again by typecasting the argument to string\n var_dump($parser);\n} catch (EmptyStringException $e) {\n // The source string was empty. Maybe there was an error\n // retrieving the HTML? Maybe the remote server is down?\n // Maybe the website does not exist anymore? In this case,\n // it isn't my fault it failed. Maybe I can use a cached\n // version?\n var_dump($parser);\n} catch (HtmlParsingException $e) {\n // The html suplied is malformed. I got it from the interwebs\n // so it's not my fault. I can use $e or getParseErrors() \n // to see if the html (and DOM Object) is usable\n // I also have a full functioning HTMLParser Object and can\n // retrieve a \"loaded\" functioning DOMDocument Object\n var_dump($parser-&gt;getParseErrors());\n var_dump($parser-&gt;getDOMObj());\n}\n$var = 'this will print wether an exception was previously thrown or not';\nprint $var;\n</code></pre>\n\n<p>You can take this further and nest try catch blocks, chain exceptions, run selective code following a determined exception chain path, selective logging, etc...</p>\n\n<p>As a side note, using Exceptions does not mean that the PROGRAM execution will halt, it just means that the code depending of my object will be bypassed. It's up to me or the 3rd party developer to do with it as he pleases.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What are the pros/cons of doing either way. Is there One Right Way(tm) ?
If you want to use exceptions instead of errors for your entire application, you can do it with [ErrorException](http://php.net/ErrorException) and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an `E_NOTICE` will halt your entire application if your [error\_reporting](http://php.net/error_reporting) settings do not suppress them. In my opinion, there are several benefits to using ErrorException: 1. A custom exception handler will let you display nice messages, even for errors, using [set\_exception\_handler](http://php.net/set_exception_handler). 2. It does not disrupt existing code in any way... [trigger\_error](http://php.net/trigger_error) and other error functions will still work normally. 3. It makes it really hard to ignore stupid coding mistakes that trigger `E_NOTICE`s and `E_WARNING`s. 4. You can use `try`/`catch` to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the `@` error suppression hack: ``` try { $foo = $_GET['foo']; } catch (ErrorException $e) { $foo = NULL; } ``` 5. You can wrap your entire script in a single `try`/`catch` block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)
60,645
<p>Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure. </p>
[ { "answer_id": 60681, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": false, "text": "<p>No. As explained <a href=\"http://msdn.microsoft.com/en-us/library/aa365141%28VS.85%29.aspx\" rel=\"noreferrer\">here</a>, anonymous pipes do not support asynchronous I/O. You need to use a named pipe. There's example code to do this on MSDN <a href=\"http://msdn.microsoft.com/en-us/library/aa365603%28VS.85%29.aspx\" rel=\"noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/aa365592%28VS.85%29.aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 419736, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>Here is an implementation for an anonymous pipe function with the possibility to specify FILE_FLAG_OVERLAPPED:</p>\n\n<pre><code>/******************************************************************************\\\n* This is a part of the Microsoft Source Code Samples. \n* Copyright 1995 - 1997 Microsoft Corporation.\n* All rights reserved. \n* This source code is only intended as a supplement to \n* Microsoft Development Tools and/or WinHelp documentation.\n* See these sources for detailed information regarding the \n* Microsoft samples programs.\n\\******************************************************************************/\n\n/*++\nCopyright (c) 1997 Microsoft Corporation\nModule Name:\n pipeex.c\nAbstract:\n CreatePipe-like function that lets one or both handles be overlapped\nAuthor:\n Dave Hart Summer 1997\nRevision History:\n--*/\n\n#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\nstatic volatile long PipeSerialNumber;\n\nBOOL\nAPIENTRY\nMyCreatePipeEx(\n OUT LPHANDLE lpReadPipe,\n OUT LPHANDLE lpWritePipe,\n IN LPSECURITY_ATTRIBUTES lpPipeAttributes,\n IN DWORD nSize,\n DWORD dwReadMode,\n DWORD dwWriteMode\n )\n\n/*++\nRoutine Description:\n The CreatePipeEx API is used to create an anonymous pipe I/O device.\n Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or\n both handles.\n Two handles to the device are created. One handle is opened for\n reading and the other is opened for writing. These handles may be\n used in subsequent calls to ReadFile and WriteFile to transmit data\n through the pipe.\nArguments:\n lpReadPipe - Returns a handle to the read side of the pipe. Data\n may be read from the pipe by specifying this handle value in a\n subsequent call to ReadFile.\n lpWritePipe - Returns a handle to the write side of the pipe. Data\n may be written to the pipe by specifying this handle value in a\n subsequent call to WriteFile.\n lpPipeAttributes - An optional parameter that may be used to specify\n the attributes of the new pipe. If the parameter is not\n specified, then the pipe is created without a security\n descriptor, and the resulting handles are not inherited on\n process creation. Otherwise, the optional security attributes\n are used on the pipe, and the inherit handles flag effects both\n pipe handles.\n nSize - Supplies the requested buffer size for the pipe. This is\n only a suggestion and is used by the operating system to\n calculate an appropriate buffering mechanism. A value of zero\n indicates that the system is to choose the default buffering\n scheme.\nReturn Value:\n TRUE - The operation was successful.\n FALSE/NULL - The operation failed. Extended error status is available\n using GetLastError.\n--*/\n\n{\n HANDLE ReadPipeHandle, WritePipeHandle;\n DWORD dwError;\n UCHAR PipeNameBuffer[ MAX_PATH ];\n\n //\n // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED\n //\n\n if ((dwReadMode | dwWriteMode) &amp; (~FILE_FLAG_OVERLAPPED)) {\n SetLastError(ERROR_INVALID_PARAMETER);\n return FALSE;\n }\n\n //\n // Set the default timeout to 120 seconds\n //\n\n if (nSize == 0) {\n nSize = 4096;\n }\n\n sprintf( PipeNameBuffer,\n \"\\\\\\\\.\\\\Pipe\\\\RemoteExeAnon.%08x.%08x\",\n GetCurrentProcessId(),\n InterlockedIncrement(&amp;PipeSerialNumber)\n );\n\n ReadPipeHandle = CreateNamedPipeA(\n PipeNameBuffer,\n PIPE_ACCESS_INBOUND | dwReadMode,\n PIPE_TYPE_BYTE | PIPE_WAIT,\n 1, // Number of pipes\n nSize, // Out buffer size\n nSize, // In buffer size\n 120 * 1000, // Timeout in ms\n lpPipeAttributes\n );\n\n if (! ReadPipeHandle) {\n return FALSE;\n }\n\n WritePipeHandle = CreateFileA(\n PipeNameBuffer,\n GENERIC_WRITE,\n 0, // No sharing\n lpPipeAttributes,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL | dwWriteMode,\n NULL // Template file\n );\n\n if (INVALID_HANDLE_VALUE == WritePipeHandle) {\n dwError = GetLastError();\n CloseHandle( ReadPipeHandle );\n SetLastError(dwError);\n return FALSE;\n }\n\n *lpReadPipe = ReadPipeHandle;\n *lpWritePipe = WritePipeHandle;\n return( TRUE );\n}\n</code></pre>\n" }, { "answer_id": 51448441, "author": "RbMm", "author_id": 6401656, "author_profile": "https://Stackoverflow.com/users/6401656", "pm_score": 4, "selected": false, "text": "<p>first of all need understand - what is <a href=\"https://learn.microsoft.com/en-us/windows/desktop/ipc/anonymous-pipes\" rel=\"noreferrer\"><em>Anonymous Pipes</em></a> and what, are exist difference between anonymous and <a href=\"https://learn.microsoft.com/en-us/windows/desktop/ipc/named-pipes\" rel=\"noreferrer\"><em>Named Pipes</em></a> at all. </p>\n\n<p>really exist only <strong>single pipe type</strong> (implemented by <em>npfs.sys</em>). no any difference, except name, between named and anonymous pipes at all. both is only pipes. </p>\n\n<p>so called anonymous pipes - this is special/random named pipes before win7 and true unnamed pipes begin from win7. </p>\n\n<p>when msdn write that <em>\"anonymous pipe is one-way pipe\"</em> - this is <strong>lie</strong>. as any pipe it can be one-way or duplex. when msdn write that <em>\"Asynchronous (overlapped) read and write operations are not supported by anonymous pipes.\"</em> - this is <strong>lie</strong>. of course pipes support asynchronous io. the name of pipe not affect this.</p>\n\n<p>before win7 really unnamed pipes even not exist at all. <a href=\"https://learn.microsoft.com/en-us/windows/desktop/ipc/anonymous-pipe-operations\" rel=\"noreferrer\"><code>CreatePipe</code></a> function use <code>Win32Pipes.%08x.%08x</code> format for create name of \"Anonymous Pipe\". </p>\n\n<pre><code> static LONG PipeSerialNumber;\n WCHAR name[64];\n swprintf(name, L\"\\\\Device\\\\NamedPipe\\\\Win32Pipes.%08x.%08x\", \n GetCurrentProcessId(), InterlockedIncrement(&amp;PipeSerialNumber));\n</code></pre>\n\n<p>begin from win7 <code>CreatePipe</code> use another technique (relative file open) for create pipe pair - now it really anonymous.</p>\n\n<p>for example code witch create pipe pair where one pipe is asynchronous and not inheritable. and another pipe is synchronous and inheritable. both pipes is duplex (support both read and write)</p>\n\n<pre><code>ULONG CreatePipeAnonymousPair7(PHANDLE phServerPipe, PHANDLE phClientPipe)\n{\n HANDLE hNamedPipe;\n\n IO_STATUS_BLOCK iosb;\n\n static UNICODE_STRING NamedPipe = RTL_CONSTANT_STRING(L\"\\\\Device\\\\NamedPipe\\\\\");\n\n OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, const_cast&lt;PUNICODE_STRING&gt;(&amp;NamedPipe), OBJ_CASE_INSENSITIVE };\n\n NTSTATUS status;\n\n if (0 &lt;= (status = NtOpenFile(&amp;hNamedPipe, SYNCHRONIZE, &amp;oa, &amp;iosb, FILE_SHARE_VALID_FLAGS, 0)))\n {\n oa.RootDirectory = hNamedPipe;\n\n static LARGE_INTEGER timeout = { 0, MINLONG };\n static UNICODE_STRING empty = {};\n\n oa.ObjectName = &amp;empty;\n\n if (0 &lt;= (status = ZwCreateNamedPipeFile(phServerPipe,\n FILE_READ_ATTRIBUTES|FILE_READ_DATA|\n FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA|\n FILE_CREATE_PIPE_INSTANCE, \n &amp;oa, &amp;iosb, FILE_SHARE_READ|FILE_SHARE_WRITE,\n FILE_CREATE, 0, FILE_PIPE_BYTE_STREAM_TYPE, FILE_PIPE_BYTE_STREAM_MODE,\n FILE_PIPE_QUEUE_OPERATION, 1, 0, 0, &amp;timeout)))\n {\n oa.RootDirectory = *phServerPipe;\n oa.Attributes = OBJ_CASE_INSENSITIVE|OBJ_INHERIT;\n\n if (0 &gt; (status = NtOpenFile(phClientPipe, SYNCHRONIZE|FILE_READ_ATTRIBUTES|FILE_READ_DATA|\n FILE_WRITE_ATTRIBUTES|FILE_WRITE_DATA, &amp;oa, &amp;iosb, \n FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT)))\n {\n NtClose(oa.RootDirectory);\n }\n }\n\n NtClose(hNamedPipe);\n }\n\n return RtlNtStatusToDosError(status);\n}\n\nULONG CreatePipeAnonymousPair(PHANDLE phServerPipe, PHANDLE phClientPipe)\n{\n static char flag_supported = -1;\n\n if (flag_supported &lt; 0)\n {\n ULONG dwMajorVersion, dwMinorVersion;\n RtlGetNtVersionNumbers(&amp;dwMajorVersion, &amp;dwMinorVersion, 0);\n flag_supported = _WIN32_WINNT_WIN7 &lt;= ((dwMajorVersion &lt;&lt; 8)| dwMinorVersion);\n }\n\n if (flag_supported)\n {\n return CreatePipeAnonymousPair7(phServerPipe, phClientPipe);\n }\n\n static LONG PipeSerialNumber;\n\n WCHAR name[64];\n\n swprintf(name, L\"\\\\\\\\?\\\\pipe\\\\Win32Pipes.%08x.%08x\", GetCurrentProcessId(), InterlockedIncrement(&amp;PipeSerialNumber));\n\n HANDLE hClient, hServer = CreateNamedPipeW(name, \n PIPE_ACCESS_DUPLEX|FILE_READ_DATA|FILE_WRITE_DATA|FILE_FLAG_OVERLAPPED, \n PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, 0, 0, 0, 0);\n\n if (hServer != INVALID_HANDLE_VALUE)\n {\n static SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };\n\n hClient = CreateFileW(name, FILE_GENERIC_READ|FILE_GENERIC_WRITE, \n FILE_SHARE_READ|FILE_SHARE_WRITE, &amp;sa, OPEN_EXISTING, 0, 0);\n\n if (hClient != INVALID_HANDLE_VALUE)\n {\n *phServerPipe = hServer, *phClientPipe = hClient;\n return NOERROR;\n }\n\n CloseHandle(hServer);\n }\n\n return GetLastError();\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3923/" ]
Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE\_FLAG\_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure.
Here is an implementation for an anonymous pipe function with the possibility to specify FILE\_FLAG\_OVERLAPPED: ``` /******************************************************************************\ * This is a part of the Microsoft Source Code Samples. * Copyright 1995 - 1997 Microsoft Corporation. * All rights reserved. * This source code is only intended as a supplement to * Microsoft Development Tools and/or WinHelp documentation. * See these sources for detailed information regarding the * Microsoft samples programs. \******************************************************************************/ /*++ Copyright (c) 1997 Microsoft Corporation Module Name: pipeex.c Abstract: CreatePipe-like function that lets one or both handles be overlapped Author: Dave Hart Summer 1997 Revision History: --*/ #include <windows.h> #include <stdio.h> static volatile long PipeSerialNumber; BOOL APIENTRY MyCreatePipeEx( OUT LPHANDLE lpReadPipe, OUT LPHANDLE lpWritePipe, IN LPSECURITY_ATTRIBUTES lpPipeAttributes, IN DWORD nSize, DWORD dwReadMode, DWORD dwWriteMode ) /*++ Routine Description: The CreatePipeEx API is used to create an anonymous pipe I/O device. Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or both handles. Two handles to the device are created. One handle is opened for reading and the other is opened for writing. These handles may be used in subsequent calls to ReadFile and WriteFile to transmit data through the pipe. Arguments: lpReadPipe - Returns a handle to the read side of the pipe. Data may be read from the pipe by specifying this handle value in a subsequent call to ReadFile. lpWritePipe - Returns a handle to the write side of the pipe. Data may be written to the pipe by specifying this handle value in a subsequent call to WriteFile. lpPipeAttributes - An optional parameter that may be used to specify the attributes of the new pipe. If the parameter is not specified, then the pipe is created without a security descriptor, and the resulting handles are not inherited on process creation. Otherwise, the optional security attributes are used on the pipe, and the inherit handles flag effects both pipe handles. nSize - Supplies the requested buffer size for the pipe. This is only a suggestion and is used by the operating system to calculate an appropriate buffering mechanism. A value of zero indicates that the system is to choose the default buffering scheme. Return Value: TRUE - The operation was successful. FALSE/NULL - The operation failed. Extended error status is available using GetLastError. --*/ { HANDLE ReadPipeHandle, WritePipeHandle; DWORD dwError; UCHAR PipeNameBuffer[ MAX_PATH ]; // // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED // if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } // // Set the default timeout to 120 seconds // if (nSize == 0) { nSize = 4096; } sprintf( PipeNameBuffer, "\\\\.\\Pipe\\RemoteExeAnon.%08x.%08x", GetCurrentProcessId(), InterlockedIncrement(&PipeSerialNumber) ); ReadPipeHandle = CreateNamedPipeA( PipeNameBuffer, PIPE_ACCESS_INBOUND | dwReadMode, PIPE_TYPE_BYTE | PIPE_WAIT, 1, // Number of pipes nSize, // Out buffer size nSize, // In buffer size 120 * 1000, // Timeout in ms lpPipeAttributes ); if (! ReadPipeHandle) { return FALSE; } WritePipeHandle = CreateFileA( PipeNameBuffer, GENERIC_WRITE, 0, // No sharing lpPipeAttributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | dwWriteMode, NULL // Template file ); if (INVALID_HANDLE_VALUE == WritePipeHandle) { dwError = GetLastError(); CloseHandle( ReadPipeHandle ); SetLastError(dwError); return FALSE; } *lpReadPipe = ReadPipeHandle; *lpWritePipe = WritePipeHandle; return( TRUE ); } ```
60,653
<p>Is global memory initialized in C++? And if so, how?</p> <p>(Second) clarification:</p> <p>When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.</p> <p>The situation is: can a singleton reference be set - via an <code>instance()</code> call, prior to its initialization:</p> <pre><code>MySingleton* MySingleton::_instance = NULL; </code></pre> <p>and get two singleton instances as a result?</p> <p>See my C++ quiz on on multiple instances of a singleton...</p>
[ { "answer_id": 60655, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": true, "text": "<p>Yes global primitives are initialized to NULL.</p>\n\n<p>Example:</p>\n\n<pre><code>int x;\n\nint main(int argc, char**argv)\n{\n assert(x == 0);\n int y;\n //assert(y == 0); &lt;-- wrong can't assume this.\n}\n</code></pre>\n\n<p>You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap...</p>\n\n<p>It's safest just to always initialize everything. </p>\n" }, { "answer_id": 60669, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 3, "selected": false, "text": "<p>Coming from the embedded world...</p>\n\n<p>Your code gets compiled into three types of memory:<br>\n 1. .data: initialized memory<br>\n 2. .text: constants and code<br>\n 3. .bss: uninitialized memory (initialized to 0 in C++ if not explicitly initialized)</p>\n\n<p>Globals go in .data if initialized. If not they are placed in .bss and zero'ed in premain code.</p>\n" }, { "answer_id": 60677, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>Variables declared with static/global scope are always initialized under VC++ at least.</p>\n\n<p>Under some circumstances there can actually be a difference in behaviour between:</p>\n\n<pre><code>int x = 0;\n\nint main() { ... }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>int x;\n\nint main() { ... }\n</code></pre>\n\n<p>If you are using shared data segments then VC++ at least uses the presence of an explicit initialization along with a <code>#pragma data_seg</code> to determine whether a particular variable should go in the shared data segment or the private data segment for a process.</p>\n\n<p>For added fun consider what happens if you have a static C++ object with constructor/destructor declared in a shared data segment. The constructor/destructor is called every time the exe/dll attaches to the data segment which is almost certainly not what you want.</p>\n\n<p>More details in this <a href=\"http://support.microsoft.com/kb/125677\" rel=\"nofollow noreferrer\">KB article</a></p>\n" }, { "answer_id": 60707, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "<p>From the standard:</p>\n\n<blockquote>\n <p>Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called <em>static initialization</em>; all other initialization is <em>dynamic initialization</em>. Objects of POD [plain old data] types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. [Note:8.5.1 describes the order in which aggregate members are initialized. The initial- \n ization of local static objects is described in 6.7.] </p>\n</blockquote>\n\n<p>So yes, globals which have static storage duration will be initialized. Globals allocated, e.g., on the heap will of course not be initialized automatically.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2167252/" ]
Is global memory initialized in C++? And if so, how? (Second) clarification: When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example. The situation is: can a singleton reference be set - via an `instance()` call, prior to its initialization: ``` MySingleton* MySingleton::_instance = NULL; ``` and get two singleton instances as a result? See my C++ quiz on on multiple instances of a singleton...
Yes global primitives are initialized to NULL. Example: ``` int x; int main(int argc, char**argv) { assert(x == 0); int y; //assert(y == 0); <-- wrong can't assume this. } ``` You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap... It's safest just to always initialize everything.
60,664
<p>is it possible to display &#8659; entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as: </p> <pre><code>&lt;span&gt;&amp;#8659;&lt;/span&gt; </code></pre>
[ { "answer_id": 60679, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "<p>According to <a href=\"https://web.archive.org/web/20080221144246/http://www.ackadia.com:80/web-design/character-code/character-code-symbols.php\" rel=\"nofollow noreferrer\">this page</a>, that symbol doesn't show in IE6 at all. </p>\n\n<pre><code>Symbol Character Numeric Description\n⇓ &amp;dArr; &amp;#8659; Down double arrow - - * Doesn't show with MS IE6\n</code></pre>\n\n<p>If you really need that particular symbol, you may just have to go for a small graphic of the arrow - not an ideal solution, but if you need it to display in IE6 then that may be your only option.</p>\n" }, { "answer_id": 60688, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<p>Yes, it is possible... But you'll need to explicitly tell IE which font to find it in. For instance:</p>\n\n<pre><code>&lt;span style=\"font-family:Arial Unicode MS\"&gt; &amp;#8659; &lt;/span&gt;\n</code></pre>\n\n<p>should produce &#8659; in most browsers.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as: ``` <span>&#8659;</span> ```
According to [this page](https://web.archive.org/web/20080221144246/http://www.ackadia.com:80/web-design/character-code/character-code-symbols.php), that symbol doesn't show in IE6 at all. ``` Symbol Character Numeric Description ⇓ &dArr; &#8659; Down double arrow - - * Doesn't show with MS IE6 ``` If you really need that particular symbol, you may just have to go for a small graphic of the arrow - not an ideal solution, but if you need it to display in IE6 then that may be your only option.
60,672
<p>I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.</p> <p>The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. <code>(for ex: HTTP\_EAUTH\_ID)</code></p> <p>And later in the page lifecycle of an ASPX page, i should be able to use that variable as</p> <pre><code>string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString(); </code></pre> <p>So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ?? </p>
[ { "answer_id": 60696, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 0, "selected": false, "text": "<p>I believe the server variables list only contains the headers sent from the browser to the server.</p>\n" }, { "answer_id": 60728, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx\" rel=\"nofollow noreferrer\">HttpRequest.ServerVariables</a> Property is a read-only collection. So, you cannot directly modify that. I would suggest storing your custom data in <a href=\"http://www.odetocode.com/Articles/111.aspx\" rel=\"nofollow noreferrer\">httpcontext</a> (or global application object or your database) from your httpmodule and then reading that shared value in the aspx page.</p>\n\n<p>If you still want to modify server variables, there is a hack technique mentioned in this <a href=\"http://forums.asp.net/t/1125149.aspx\" rel=\"nofollow noreferrer\">thread</a> using Reflection.</p>\n" }, { "answer_id": 61224, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 0, "selected": false, "text": "<p>You won't be able to modify either the <code>HttpRequest.Headers</code> or the <code>HttpRequest.ServerVariables</code> collection. You will however be able to tack on your information to any of: </p>\n\n<pre><code>HttpContext.Current.Items\nHttpContext.Current.Response.Headers\n</code></pre>\n\n<p>Unfortunately, <code>Request.Params, Request.QueryString, Request.Cookies, Request.Form</code> (and almost any other place you'd think of stuffing it is read only.</p>\n\n<p><strong>I'd strongly advise against using reflection if this is a HttpModule you're planning on installing into IIS 7</strong>. Given that this code will be called for (potentially) every request that goes through the web server it'll need to be really fast and reflection just isn't going to cut it (unless you have very few users).</p>\n\n<p>Good luck!</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647/" ]
I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode. The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. `(for ex: HTTP\_EAUTH\_ID)` And later in the page lifecycle of an ASPX page, i should be able to use that variable as ``` string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString(); ``` So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ??
[HttpRequest.ServerVariables](http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx) Property is a read-only collection. So, you cannot directly modify that. I would suggest storing your custom data in [httpcontext](http://www.odetocode.com/Articles/111.aspx) (or global application object or your database) from your httpmodule and then reading that shared value in the aspx page. If you still want to modify server variables, there is a hack technique mentioned in this [thread](http://forums.asp.net/t/1125149.aspx) using Reflection.
60,673
<p>What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people <em>insist</em> that every <code>if</code> statement is followed by a brace block (<code>{...}</code>).</p> <p>I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?</p> <p>To get the ball rolling, I'll mention a few to start with:</p> <ul> <li>Always use braces after every <code>if</code> / <code>else</code> statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:</li> </ul> <pre> // top of file: #define statement doSomething(); doSomethingElse // in implementation: if (somecondition) doSomething(); </pre> <p>but if you use braces then it will work as expected.</p> <ul> <li>Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!</li> </ul> <p>Now over to you.</p>
[ { "answer_id": 60682, "author": "DShook", "author_id": 370, "author_profile": "https://Stackoverflow.com/users/370", "pm_score": 0, "selected": false, "text": "<p>make sure you indent properly</p>\n" }, { "answer_id": 60687, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Use and enforce a common coding style and guidelines. <em>Rationale:</em> Every developer on the team or in the firm is able to read the code without distractions that may occur due to different brace styles or similar.</li>\n<li>Regularly do a full rebuild of your entire source base (i.e. do daily builds or builds after each checkin) and report any errors! <em>Rationale:</em> The source is almost always in a usable state, and problems are detected shortly after they are \"implemented\", where problem solving is cheap.</li>\n</ul>\n" }, { "answer_id": 60712, "author": "David Joyner", "author_id": 1146, "author_profile": "https://Stackoverflow.com/users/1146", "pm_score": 4, "selected": true, "text": "<p>A few of my personal favorites:</p>\n\n<p>Strive to write code that is <a href=\"http://www.parashift.com/c++-faq-lite/const-correctness.html\" rel=\"noreferrer\">const correct</a>. You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone.</p>\n\n<p>Get out of the memory management business. Learn to use smart pointers: <code>std::auto_ptr</code>, <code>std::tr1::shared_ptr</code> (or <code>boost::shared_ptr</code>) and <code>boost::scoped_ptr</code>. Learn the differences between them and when to use one vs. another.</p>\n\n<p>You're probably going to be using the Standard Template Library. Read the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201379260\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Josuttis book</a>. Don't just stop after the first few chapters on containers thinking that you know the STL. Push through to the good stuff: algorithms and function objects.</p>\n" }, { "answer_id": 60715, "author": "Brian Paden", "author_id": 3176, "author_profile": "https://Stackoverflow.com/users/3176", "pm_score": 2, "selected": false, "text": "<p>In if statements put the constant on the left i.e.</p>\n\n<pre><code>if( 12 == var )\n</code></pre>\n\n<p>not</p>\n\n<pre><code>if( var == 12 )\n</code></pre>\n\n<p>Beacause if you miss typing a '=' then it becomes assignment. In the top version the compiler says this isn't possible, in the latter it runs and the if is always true.</p>\n\n<p>I use braces for if's whenever they are not on the same line.</p>\n\n<pre><code>if( a == b ) something();\nif( b == d )\n{\n bigLongStringOfStuffThatWontFitOnASingleLineNeatly();\n}\n</code></pre>\n\n<p>Open and close braces always get their own lines. But that is of course personal convention.</p>\n" }, { "answer_id": 60721, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 1, "selected": false, "text": "<p>In a similar vein you might find some useful suggestions here: <a href=\"https://stackoverflow.com/questions/26086/how-do-you-make-wrong-code-look-wrong-what-patterns-do-you-use-to-avoid-semanti\">How do you make wrong code look wrong? What patterns do you use to avoid semantic errors?</a></p>\n" }, { "answer_id": 60733, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<ul>\n<li><p>Use tabs for indentations, but align data with spaces\nThis means people can decide how much to indent by changing the tab size, but also that things stay aligned (eg you might want all the '=' in a vertical line when assign values to a struct)</p></li>\n<li><p>Allways use constants or inline functions instead of macros where posible</p></li>\n<li><p>Never use 'using' in header files, because everything that includes that heafer will also be affected, even if the person includeing your header doesn't want all of std (for example) in their global namespace.</p></li>\n<li><p>If something is longer than about 80 columes, break it up into multiple lines eg</p>\n\n<pre><code>if(SomeVeryLongVaribleName != LongFunction(AnotherVarible, AString) &amp;&amp;\n BigVaribleIsValid(SomeVeryLongVaribleName))\n{\n DoSomething();\n}\n</code></pre></li>\n<li><p>Only overload operators to make them do what the user expects, eg overloading the + and - operators for a 2dVector is fine</p></li>\n<li><p>Always comment your code, even if its just to say what the next block is doing (eg \"delete all textures that are not needed for this level\"). Someone may need to work with it later, posibly after you have left and they don't want to find 1000's of lines of code with no comments to indicate whats doing what.</p></li>\n</ul>\n" }, { "answer_id": 60735, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Delete unnecessary code.</li>\n</ol>\n\n<p>That is all.</p>\n" }, { "answer_id": 60747, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Use consistent formatting.</li>\n<li>When working on legacy code employ the existing style of formatting, esp. brace style.</li>\n<li>Get a copy of Scott Meyer's book Effective C++</li>\n<li>Get a copy of Steve MConnell's book Code Complete.</li>\n</ol>\n" }, { "answer_id": 60749, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>Only comment when it's only necessary to explain what the code is doing, where reading the code couldn't tell you the same.</p>\n\n<p>Don't comment out code that you aren't using any more. If you want to recover old code, use your source control system. Commenting out code just makes things look messy, and makes your comments that actually are important fade into the background mess of commented code.</p>\n" }, { "answer_id": 60773, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 1, "selected": false, "text": "<ol>\n<li>setup coding convention and make everyone involved follow the convention (you wouldn't want reading code that require you to figure out where is the next statement/expression because it is not indented properly)</li>\n<li>constantly refactoring your code (get a copy of Refactoring, by Martin Fowler, pros and cons are detailed in the book)</li>\n<li>write loosely coupled code (avoid writing comment by writing self-explanatory code, loosely coupled code tends to be easier to manage/adapt to change)</li>\n<li>if possible, unit test your code (or if you are macho enough, TDD.)</li>\n<li>release early, release often</li>\n<li>avoid premature optimization (profiling helps in optimizing)</li>\n</ol>\n" }, { "answer_id": 60796, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Turn on all the warnings you can stand in your compiler (gcc: <code>-Wall</code> is a good start but doesn't include everything so check the docs), and make them errors so you have to fix them (gcc: <code>-Werror</code>).</p>\n" }, { "answer_id": 61182, "author": "Thomi", "author_id": 1304, "author_profile": "https://Stackoverflow.com/users/1304", "pm_score": 0, "selected": false, "text": "<p>Hmm - I probably should have been a bit more specific.</p>\n\n<p>I'm not so much looking for advice for myself - I'm writing a static code analysis tool (the current commercial offerings just aren't good enough for what I want), and I'm looking for ideas for plugins to highlight possible errors in the code.</p>\n\n<p>Several people have mentioned things like const correctness and using smart pointers - that's the kind of think I can check for. Checking for indentation and commenting is a bit harder to do (from a programming point of view anyway).</p>\n" }, { "answer_id": 61187, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 2, "selected": false, "text": "<p>There is also a nice <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\" rel=\"nofollow noreferrer\">C++ Style Guide</a> used internally by Google, which includes most of the rules mentioned here.</p>\n" }, { "answer_id": 61273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Google's style guide, mentioned in one of these answers, is pretty solid. There's some pointless stuff in it, but it's more good than bad.</p>\n\n<p>Sutter and Alexandrescu wrote a decent book on this subject, called <em>C++ Coding Standards</em>.</p>\n\n<p>Here's some general tips from lil' ole me:</p>\n\n<ol>\n<li><p>Your indentation and bracketing style are both wrong. So are everyone else's. So follow the project's standards for this. Swallow your pride and setup your editor so that everything is as consistent as possible with the rest of the codebase. It's really really annoying having to read code that's indented inconsistently. That said, bracketing and indenting have nothing whatsoever to do with \"improving your code.\" It's more about improving your ability to work with others.</p></li>\n<li><p>Comment well. This is extremely subjective, but in general it's always good to write comments about <em>why</em> code works the way it does, rather than explaining what it does. Of course for complex code it's also good for programmers who may not be familiar with the algorithm or code to have an idea of <em>what</em> it's doing as well. Links to descriptions of the algorithms employed are very welcome.</p></li>\n<li><p>Express logic in as straightforward a manner as possible. Ironically suggestions like \"put constants on the left side of comparisons\" have gone wrong here, I think. They're very popular, but for English speakers, they often break the logical flow of the program to those reading. If you can't trust yourself (or your compiler) to write equality compares correctly, then by all means use tricks like this. But you're sacrificing clarity when you do it. Also falling under this category are things like ... \"Does my logic have 3 levels of indentation? Could it be simpler?\" and rolling similar code into functions. Maybe even splitting up functions. It takes experience to write code that elegantly expresses the underlying logic, but it's worth working at it.</p></li>\n</ol>\n\n<p>Those were pretty general. For specific tips I can't do a much better job than Sutter and Alexandrescu.</p>\n" }, { "answer_id": 64902, "author": "Ian Hickman", "author_id": 8915, "author_profile": "https://Stackoverflow.com/users/8915", "pm_score": 1, "selected": false, "text": "<p>Where you can, use pre-increment instead of post-increment.</p>\n" }, { "answer_id": 64984, "author": "Dave", "author_id": 9056, "author_profile": "https://Stackoverflow.com/users/9056", "pm_score": 2, "selected": false, "text": "<p>Start to write a lot of comments -- but use that as an opportunity to refactor the code so that it's self explanatory. </p>\n\n<p>ie:</p>\n\n<pre><code>for(int i=0; i&lt;=arr.length; i++) {\n arr[i].conf() //confirm that every username doesn't contain invalid characters\n}\n</code></pre>\n\n<p>Should've been something more like</p>\n\n<pre><code>for(int i=0; i&lt;=activeusers.length; i++) {\n activeusers[i].UsernameStripInvalidChars()\n}\n</code></pre>\n" }, { "answer_id": 65279, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 1, "selected": false, "text": "<p>I use PC-Lint on my C++ projects and especially like how it references existing publications such as the MISRA guidelines or Scott Meyers' \"Effective C++\" and \"More Effective C++\". Even if you are planning on writing very detailed justifications for each rule your static analysis tool checks, it is a good idea to point to established publications that your user trusts.</p>\n" }, { "answer_id": 70111, "author": "Stacker", "author_id": 6574, "author_profile": "https://Stackoverflow.com/users/6574", "pm_score": 1, "selected": false, "text": "<p>Here is the most important piece of advice I was given by a C++ guru, and it helped me in a few critical occasions to find bugs in my code:</p>\n\n<ul>\n<li>Use const methods when a method is <strong>not supposed</strong> to modify the object.</li>\n<li>Use const references and pointers in parameters when the object is <strong>not supposed</strong> to modify the object.</li>\n</ul>\n\n<p>With these 2 rules, the compiler will tell you for free where in your code the logic is flawed!</p>\n" }, { "answer_id": 70220, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 0, "selected": false, "text": "<p>Smart pointers have a nice way of indicating ownership very clearly. If you're a class or a function:</p>\n\n<ul>\n<li>if you get a <strong>raw pointer</strong>, you don't own anything. You're allowed to use the pointee, courtesy of your caller, who guarantees that the pointee will stay alive longer than you.</li>\n<li>if you get a <strong>weak_ptr</strong>, you don't own the pointee, and on top of that the pointee can disappear at any time.</li>\n<li>if you get a <strong>shared_ptr</strong>, you own the object along with others, so you don't need to worry. Less stress, but also less control.</li>\n<li>if you get an <strong>auto_ptr</strong>, you are the sole owner of the object. It's yours, you're the king. You have the power to destroy that object, or give it to someone else (thereby losing ownership).</li>\n</ul>\n\n<p>I find the case for auto_ptr particularly strong: in a design, if I see an auto_ptr, I immediately know that that object is going to \"wander\" from one part of the system to the other.</p>\n\n<p>This is at least the logic I use on my pet project. I'm not sure how many variations there can be on the topic, but until now this ruleset has served me well.</p>\n" }, { "answer_id": 70260, "author": "Marcin Gil", "author_id": 5731, "author_profile": "https://Stackoverflow.com/users/5731", "pm_score": 1, "selected": false, "text": "<p>Also, for some good techniques you might follow <a href=\"http://googletesting.blogspot.com/2007/01/introducing-testing-on-toilet.html\" rel=\"nofollow noreferrer\">Google's blog \"Testing on the Toilet\"</a>.</p>\n" }, { "answer_id": 181235, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 1, "selected": false, "text": "<p>Look at it six months later</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ]
What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people *insist* that every `if` statement is followed by a brace block (`{...}`). I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few? To get the ball rolling, I'll mention a few to start with: * Always use braces after every `if` / `else` statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break: ``` // top of file: #define statement doSomething(); doSomethingElse // in implementation: if (somecondition) doSomething(); ``` but if you use braces then it will work as expected. * Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc! Now over to you.
A few of my personal favorites: Strive to write code that is [const correct](http://www.parashift.com/c++-faq-lite/const-correctness.html). You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone. Get out of the memory management business. Learn to use smart pointers: `std::auto_ptr`, `std::tr1::shared_ptr` (or `boost::shared_ptr`) and `boost::scoped_ptr`. Learn the differences between them and when to use one vs. another. You're probably going to be using the Standard Template Library. Read the [Josuttis book](https://rads.stackoverflow.com/amzn/click/com/0201379260). Don't just stop after the first few chapters on containers thinking that you know the STL. Push through to the good stuff: algorithms and function objects.
60,680
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() </code></pre>
[ { "answer_id": 60753, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 6, "selected": true, "text": "<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href=\"http://localhost:1111/\" rel=\"noreferrer\">http://localhost:1111/</a> and <a href=\"http://localhost:2222/\" rel=\"noreferrer\">http://localhost:2222/</a></p>\n\n<pre><code>from threading import Thread\nfrom SocketServer import ThreadingMixIn\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\n\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n self.wfile.write(\"Hello World!\")\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer):\n daemon_threads = True\n\ndef serve_on_port(port):\n server = ThreadingHTTPServer((\"localhost\",port), Handler)\n server.serve_forever()\n\nThread(target=serve_on_port, args=[1111]).start()\nserve_on_port(2222)\n</code></pre>\n\n<p><em>update:</em></p>\n\n<p>This also works with Python 3 but three lines need to be slightly changed:</p>\n\n<pre><code>from socketserver import ThreadingMixIn\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n</code></pre>\n\n<p>and</p>\n\n<pre><code>self.wfile.write(bytes(\"Hello World!\", \"utf-8\"))\n</code></pre>\n" }, { "answer_id": 60754, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 3, "selected": false, "text": "<p>Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).</p>\n\n<p>The existing function:</p>\n\n<pre><code>def serve_forever(self, poll_interval=0.5):\n \"\"\"Handle one request at a time until shutdown.\n\n Polls for shutdown every poll_interval seconds. Ignores\n self.timeout. If you need to do periodic tasks, do them in\n another thread.\n \"\"\"\n self.__serving = True\n self.__is_shut_down.clear()\n while self.__serving:\n # XXX: Consider using another file descriptor or\n # connecting to the socket to wake this up instead of\n # polling. Polling reduces our responsiveness to a\n # shutdown request and wastes cpu at all other times.\n r, w, e = select.select([self], [], [], poll_interval)\n if r:\n self._handle_request_noblock()\n self.__is_shut_down.set()\n</code></pre>\n\n<p>So our replacement would be something like:</p>\n\n<pre><code>def serve_forever(server1,server2):\n while True:\n r,w,e = select.select([server1,server2],[],[],0)\n if server1 in r:\n server1.handle_request()\n if server2 in r:\n server2.handle_request()\n</code></pre>\n" }, { "answer_id": 61322, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 3, "selected": false, "text": "<p>I would say that threading for something this simple is overkill. You're better off using some form of asynchronous programming.</p>\n\n<p>Here is an example using <a href=\"http://twistedmatrix.com/\" rel=\"noreferrer\">Twisted</a>:</p>\n\n<pre><code>from twisted.internet import reactor\nfrom twisted.web import resource, server\n\nclass MyResource(resource.Resource):\n isLeaf = True\n def render_GET(self, request):\n return 'gotten'\n\nsite = server.Site(MyResource())\n\nreactor.listenTCP(8000, site)\nreactor.listenTCP(8001, site)\nreactor.run()\n</code></pre>\n\n<p>I also thinks it looks a lot cleaner to have each port be handled in the same way, instead of having the main thread handle one port and an additional thread handle the other. Arguably that can be fixed in the thread example, but then you're using three threads.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4321/" ]
I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port? What I'm doing now: ``` class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() ```
Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <http://localhost:1111/> and <http://localhost:2222/> ``` from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = True def serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever() Thread(target=serve_on_port, args=[1111]).start() serve_on_port(2222) ``` *update:* This also works with Python 3 but three lines need to be slightly changed: ``` from socketserver import ThreadingMixIn from http.server import HTTPServer, BaseHTTPRequestHandler ``` and ``` self.wfile.write(bytes("Hello World!", "utf-8")) ```
60,683
<p>Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated.</p> <p>I am using visual studio 2005</p>
[ { "answer_id": 60695, "author": "Winter", "author_id": 6227, "author_profile": "https://Stackoverflow.com/users/6227", "pm_score": 4, "selected": true, "text": "<p>Allan Anderson created a custom control to let you do this.\nYou can find it here: <a href=\"http://www.codeproject.com/KB/list/aa_listview.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/list/aa_listview.aspx</a></p>\n\n<p>Here's some example code for that control:</p>\n\n<pre><code>\n GlacialList mylist = new GlacialList();\n\nmylist.Columns.Add( \"Column1\", 100 ); // this can also be added \n\n // through the design time support \n\nmylist.Columns.Add( \"Column2\", 100 ); \nmylist.Columns.Add( \"Column3\", 100 ); \nmylist.Columns.Add( \"Column4\", 100 ); \n\nGLItem item;\n\nitem = this.glacialList1.Items.Add( \"Atlanta Braves\" );\nitem.SubItems[1].Text = \"8v\";\nitem.SubItems[2].Text = \"Live\";\nitem.SubItems[2].BackColor = Color.Bisque;\nitem.SubItems[3].Text = \"MLB.TV\"; \n\nitem = this.glacialList1.Items.Add( \"Florida Marlins\" );\nitem.SubItems[1].Text = \"\";\nitem.SubItems[2].Text = \"Delayed\";\nitem.SubItems[2].BackColor = Color.LightCoral;\nitem.SubItems[3].Text = \"Audio\";\n\n\nitem.SubItems[1].BackColor = Color.Aqua; // set the background \n\n // of this particular subitem ONLY\n\nitem.UserObject = myownuserobjecttype; // set a private user object\n\nitem.Selected = true; // set this item to selected state\n\nitem.SubItems[1].Span = 2; // set this sub item to span 2 spaces\n\n\nArrayList selectedItems = mylist.SelectedItems; \n // get list of selected items\n</code></pre>\n" }, { "answer_id": 60698, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>Maybe <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.checkboxes(VS.80).aspx\" rel=\"nofollow noreferrer\">ListView.Checkboxes</a>.</p>\n" }, { "answer_id": 60708, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>You could use a grid view instead, as that gives you more fine control of column contents.</p>\n" }, { "answer_id": 60716, "author": "idursun", "author_id": 5984, "author_profile": "https://Stackoverflow.com/users/5984", "pm_score": 1, "selected": false, "text": "<p>You can try <a href=\"http://www.codeproject.com/KB/tree/treeviewadv.aspx\" rel=\"nofollow noreferrer\">TreeViewAdv</a>. It is open source and hosted on sourceforge.</p>\n" }, { "answer_id": 83882, "author": "Makis Arvanitis", "author_id": 66654, "author_profile": "https://Stackoverflow.com/users/66654", "pm_score": 5, "selected": false, "text": "<p>Better use grid view control, but if you want <strong>only</strong> one column with checkboxes and that column is the <strong>first</strong> one you can just write: </p>\n\n<pre><code>this.listView1.CheckBoxes = true;\n</code></pre>\n" }, { "answer_id": 5534056, "author": "CharithJ", "author_id": 591656, "author_profile": "https://Stackoverflow.com/users/591656", "pm_score": 3, "selected": false, "text": "<p><em>Add Checkbox column like below.</em></p>\n\n<pre><code>myListView.CheckBoxes = true;\nmyListView.Columns.Add(text, width, alignment);\n</code></pre>\n\n<p><em>Add ListViewItem s like below.</em></p>\n\n<pre><code>ListViewItem lstViewItem = new ListViewItem();\nlstViewItem.SubItems.Add(\"Testing..\");\nlstViewItem.SubItems.Add(\"Testing1..\");\n\nmyListView.Items.Add(lstViewItem);\n</code></pre>\n" }, { "answer_id": 5643318, "author": "chatcja", "author_id": 256522, "author_profile": "https://Stackoverflow.com/users/256522", "pm_score": 3, "selected": false, "text": "<p>Why dont you try for <a href=\"http://www.codeproject.com/KB/list/XPTable.aspx\" rel=\"noreferrer\">XPTable by Mathew Hall</a></p>\n" }, { "answer_id": 30975220, "author": "Sohaib Afzal", "author_id": 4228223, "author_profile": "https://Stackoverflow.com/users/4228223", "pm_score": 2, "selected": false, "text": "<p>You can set the the <code>CheckBoxes</code> property to <code>true</code>. In code this can be done like this:</p>\n\n<pre><code>listView1.CheckBoxes = true;\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated. I am using visual studio 2005
Allan Anderson created a custom control to let you do this. You can find it here: <http://www.codeproject.com/KB/list/aa_listview.aspx> Here's some example code for that control: ``` GlacialList mylist = new GlacialList(); mylist.Columns.Add( "Column1", 100 ); // this can also be added // through the design time support mylist.Columns.Add( "Column2", 100 ); mylist.Columns.Add( "Column3", 100 ); mylist.Columns.Add( "Column4", 100 ); GLItem item; item = this.glacialList1.Items.Add( "Atlanta Braves" ); item.SubItems[1].Text = "8v"; item.SubItems[2].Text = "Live"; item.SubItems[2].BackColor = Color.Bisque; item.SubItems[3].Text = "MLB.TV"; item = this.glacialList1.Items.Add( "Florida Marlins" ); item.SubItems[1].Text = ""; item.SubItems[2].Text = "Delayed"; item.SubItems[2].BackColor = Color.LightCoral; item.SubItems[3].Text = "Audio"; item.SubItems[1].BackColor = Color.Aqua; // set the background // of this particular subitem ONLY item.UserObject = myownuserobjecttype; // set a private user object item.Selected = true; // set this item to selected state item.SubItems[1].Span = 2; // set this sub item to span 2 spaces ArrayList selectedItems = mylist.SelectedItems; // get list of selected items ```
60,684
<p><strong><em>Edit:</em></strong> This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you.</p> <p>This question is about how you use text editors in general. I’m looking for the best way to <em>delete</em> a plurality of lines of code (no intent to patent it:) This extends to <em>transposing</em> lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once.</p> <p>Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets:</p> <pre> if (true) {\n \t int i = 1;\n \t &lt;i *= 2;&gt;\n \t i += 3;\n }\n </pre> <p>Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n. </p> <p>You end up with:</p> <pre> if (true) {\n \t int i = 1;\n \t i += 3;\n }\n </pre> <p>When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly).</p> <p>When using Visual Studio and other editors in general, here’s the solution that currently works best for me:</p> <p>Using the mouse, I select the characters that I put between angle brackets:</p> <pre> if (true) {\n \t int i = 1;&lt;\n \t i *= 2;&gt;\n \t i += 3;\n }\n </pre> <p>Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret:</p> <pre> if (true) {\n \t int i = 1;&lt;\n \t i *= 2;&gt;\n \t i += 3;^\n }\n </pre> <p>This leaves you with:</p> <pre> if (true) {\n \t int i = 1;\n \t i += 3;&lt;\n \t i *= 2;&gt;\n }\n </pre> <p>where lines 3 and 4 have switched place.</p> <p>There are variations on this theme. When you want to delete line 3, you could also select the following characters:</p> <pre> if (true) {\n \t int i = 1;\n &lt;\t i *= 2;\n &gt;\t i += 3;\n }\n </pre> <p>In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select.</p> <p>Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:)</p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <p>With respect to Visual Studio: Navigating well with the cursor keys.</p> <p>The solution that would best suit my style of going over and editing code is the <em>Eclipse</em> way:</p> <p>You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio!</p>
[ { "answer_id": 60697, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>In Emacs:</p>\n\n<ul>\n<li>kill-line C-k </li>\n<li>transpose-lines C-x C-t</li>\n</ul>\n\n<p>C-a C-k C-k -- kill whole line including newline (or <code>kill-whole-line</code> by C-S-backspace).</p>\n\n<p>C-u &lt;number> C-k -- kill &lt;number> of lines (including newlines).</p>\n\n<p>C-y -- yank back the most recently killed text (aka paste)</p>\n" }, { "answer_id": 60704, "author": "Pedro", "author_id": 5488, "author_profile": "https://Stackoverflow.com/users/5488", "pm_score": 2, "selected": false, "text": "<p>In Eclipse you can <kbd>ALT</kbd>-<kbd>&darr;</kbd> or <kbd>ALT</kbd>-<kbd>&uarr;</kbd> to move a line. I find this incredibly useful, as well as <kbd>ALT</kbd>-<kbd>SHIFT</kbd>-{<kbd>&darr;</kbd>, <kbd>&uarr;</kbd>} to copy a line. In addition, it doesn't wreck your clipboard. It even corrects indentation as the line is moving!</p>\n" }, { "answer_id": 60709, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "<p>In VIM:</p>\n<ul>\n<li>Delete the whole line including the newline: <code>dd</code></li>\n<li>Transpose lines: <code>dd p</code></li>\n</ul>\n<p>You can always prefix any command with a number to repeat it, so to delete 10 lines do:</p>\n<pre><code>10 dd\n</code></pre>\n<p>You can also specify a range of lines to delete. For instance, to delete lines 10-15:</p>\n<pre><code>:10,15d\n</code></pre>\n<p>Or you can move the lines, for instance move lines 10-15 below line 20:</p>\n<pre><code>:10,15m20\n</code></pre>\n<p>Or you can <em>copy</em> the lines:</p>\n<pre><code>:10,15t20\n</code></pre>\n" }, { "answer_id": 60717, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 1, "selected": false, "text": "<p>Learn to use your cursor keys.</p>\n\n<p>For moving lines I do the following:</p>\n\n<ol>\n<li>Use <kbd>&uarr;</kbd>/<kbd>&darr;</kbd>to move to the line you want to copy.</li>\n<li>Hit <kbd>Home</kbd> if not there already, and again if it places the cursor after whitespace.</li>\n<li>Then press <strong><kbd>Shift</kbd>+<kbd>&darr;</kbd></strong> to select the line (or lines) you want to move</li>\n<li><kbd>Ctrl</kbd>+<kbd>X</kbd> to cut the line.</li>\n<li>Move Up/Down to the line you want to insert</li>\n<li><kbd>Ctrl</kbd>+<kbd>V</kbd></li>\n</ol>\n\n<p>This should work in pretty much any text editor on Windows.</p>\n\n<p>When deleting lines I still tend to use <kbd>Ctrl</kbd>+<kbd>X</kbd> (although I guess I also use backspace) as the above is so ingrained in how I edit, and it's also more forgiving.</p>\n\n<p>(Although I find them disorienting on the occasions I use Macs, I think Apple might have been on to something with the way they've set up the Home/End, skip word shortcuts on Macs)</p>\n" }, { "answer_id": 60718, "author": "Andres", "author_id": 1815, "author_profile": "https://Stackoverflow.com/users/1815", "pm_score": 2, "selected": false, "text": "<p>What I do is, starting with the cursor at the start of the line (in some editors you have to press home twice to do this), hold shift and press down until all lines that I want to delete are selected. Then I press delete.</p>\n" }, { "answer_id": 89783, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": "<p>Using the <strong>Brief</strong> keyboard mapping this is done using the <strong><kbd>Alt</kbd>+<kbd>L</kbd></strong> to mark the line and the <strong><kbd>-</kbd></strong> key on the numeric keypad (or <strong><kbd>Alt</kbd>+<kbd>D</kbd></strong>) to cut the line to clipboard. The cut will remove the line entirely, including the newline character.</p>\n\n<p>Hitting the <strong><kbd>Ins</kbd></strong> key on the numeric keypad would put the line back into the document including the newline character. </p>\n\n<p>IMHO <strong>Brief</strong> is a really well designed keyboard mapping.</p>\n\n<p><strong>PS:</strong> I think MSVC has an option to emulate the Brief keyboard mapping.</p>\n" }, { "answer_id": 116861, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 0, "selected": false, "text": "<p>in Eclipse i use <kbd>CTRL</kbd>+ <kbd>D</kbd> to delete a single line (or a couple) \nfor many lines i'll select them with the mouse or with <kbd>SHIFT</kbd> + <kbd>ARROW</kbd> then press the <kbd>DEL</kbd> key.</p>\n" }, { "answer_id": 147676, "author": "Ted", "author_id": 9344, "author_profile": "https://Stackoverflow.com/users/9344", "pm_score": 0, "selected": false, "text": "<p>In addition to the above, use <a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">Resharper</a> for Visual Studio to do what you want. Best VS plugin you will find ever. It provides a bunch of different commands that help with moving/deleting/copying code here there and everywhere. Not to mention refactor/generate/etc code.</p>\n\n<p><kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>Alt</kbd> <kbd>&uarr;</kbd>or <kbd>&darr;</kbd> will move a method up or down, line up or down, etc.\n<kbd>Shift</kbd>-<kbd>Del</kbd> - deletes the current line, but puts it in the clipboard (unless you modify your settings to not do this - I'm trying to recall if this is a VS standard shortcut, not just Resharper - been too long).\n<kbd>Ctrl</kbd>-<kbd>C</kbd>, <kbd>Ctrl</kbd>-<kbd>X</kbd> without selecting copies/cuts the current line.\nAnd on and on...</p>\n\n<p>See <a href=\"http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap2.pdf\" rel=\"nofollow noreferrer\">http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap2.pdf</a> for a full list.</p>\n" }, { "answer_id": 147709, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<p>Adding to the existing vim answer, you can use d along with any cursor movement command to delete from the cursor's current position to the new position. For example, to delete...</p>\n\n<ul>\n<li>...to end-of-paragraph (usually meaning \"to the next blank line\"): d}</li>\n<li>...the line containing the cursor and the next 5 lines: d5j</li>\n<li>...a set of parentheses, braces, etc. and its contents: d% (with the cursor on the opening or closing paren/brace/etc.)</li>\n<li>...to the third appearance of the word \"foo\": d3/foo</li>\n</ul>\n\n<p>It's quite flexible.</p>\n" }, { "answer_id": 5565739, "author": "Vasyl Boroviak", "author_id": 188475, "author_profile": "https://Stackoverflow.com/users/188475", "pm_score": 0, "selected": false, "text": "<p><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>L</kbd> removes line without copying it to the buffer.</p>\n" }, { "answer_id": 20648989, "author": "Drew", "author_id": 729907, "author_profile": "https://Stackoverflow.com/users/729907", "pm_score": 0, "selected": false, "text": "<p>In Emacs, in addition to <code>C-k</code> (and <code>C-k</code> with a numeric prefix arg, to kill N lines), you can just use the mouse:</p>\n\n<ul>\n<li><p><em><strong>To kill one line:</em></strong> triple-click it, then right-click twice</p></li>\n<li><p><em><strong>To kill multiple lines:</em></strong> triple-click the first line, then right-click on the last line (\"first\" line can be after the \"last\" line -- \"first\" here means first one you click)</p></li>\n</ul>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6103/" ]
***Edit:*** This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you. This question is about how you use text editors in general. I’m looking for the best way to *delete* a plurality of lines of code (no intent to patent it:) This extends to *transposing* lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once. Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets: ``` if (true) {\n \t int i = 1;\n \t <i *= 2;>\n \t i += 3;\n }\n ``` Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n. You end up with: ``` if (true) {\n \t int i = 1;\n \t i += 3;\n }\n ``` When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly). When using Visual Studio and other editors in general, here’s the solution that currently works best for me: Using the mouse, I select the characters that I put between angle brackets: ``` if (true) {\n \t int i = 1;<\n \t i *= 2;>\n \t i += 3;\n }\n ``` Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret: ``` if (true) {\n \t int i = 1;<\n \t i *= 2;>\n \t i += 3;^\n }\n ``` This leaves you with: ``` if (true) {\n \t int i = 1;\n \t i += 3;<\n \t i *= 2;>\n }\n ``` where lines 3 and 4 have switched place. There are variations on this theme. When you want to delete line 3, you could also select the following characters: ``` if (true) {\n \t int i = 1;\n <\t i *= 2;\n >\t i += 3;\n }\n ``` In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select. Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:) --- ***Summary of Answers*** With respect to Visual Studio: Navigating well with the cursor keys. The solution that would best suit my style of going over and editing code is the *Eclipse* way: You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio!
In Emacs: * kill-line C-k * transpose-lines C-x C-t C-a C-k C-k -- kill whole line including newline (or `kill-whole-line` by C-S-backspace). C-u <number> C-k -- kill <number> of lines (including newlines). C-y -- yank back the most recently killed text (aka paste)
60,685
<p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p> <p>Here's the regex:</p> <pre><code>\s*#define(.*\\\n)+[\S]+(?!\\) </code></pre> <p>It should match all of this:</p> <pre><code>#define foo(x) if(x) \ doSomething(x) </code></pre> <p>But only some of this (shouldn't match the next line of code:</p> <pre><code>#define foo(x) if(x) \ doSomething(x) normalCode(); </code></pre> <p>And also shouldn't match single-line preprocessor macros.</p> <p>I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?</p>
[ { "answer_id": 60723, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 4, "selected": true, "text": "<p>This is a simple test program I knocked up:</p>\n\n<pre><code>#!/usr/bin/env python\n\nTEST1=\"\"\"\n#include \"Foo.h\"\n#define bar foo\\\\\n x\n#include \"Bar.h\"\n\"\"\"\n\nTEST2=\"\"\"\n#define bar foo\n#define x 1 \\\\\n 12 \\\\\n 2 \\\\\\\\ 3\nFoobar\n\"\"\"\n\nTEST3=\"\"\"\n#define foo(x) if(x) \\\\\ndoSomething(x)\n\"\"\"\n\nTEST4=\"\"\"\n#define foo(x) if(x) \\\\\ndoSomething(x)\nnormalCode();\n\"\"\"\n\nimport re\nmatcher = re.compile(r\"^[ \\t]*#define(.*\\\\\\n)+.*$\",re.MULTILINE)\n\ndef extractDefines(s):\n mo = matcher.search(s)\n if not mo:\n print mo\n return\n print mo.group(0)\n\nextractDefines(TEST1)\nextractDefines(TEST2)\nextractDefines(TEST3)\nextractDefines(TEST4)\n</code></pre>\n\n<p>The re I used:</p>\n\n<pre><code>r\"^[ \\t]*#define(.*\\\\\\n)+.*$\"\n</code></pre>\n\n<p>Is very similar to the one use used, the changes:</p>\n\n<ol>\n<li>[ \\t] To avoid newlines at the start\nof the define.</li>\n<li>I rely on + being\ngreedy, so I can use a simple .*$ at\nthe end to get the first line of the\ndefine that doesn't end with \\</li>\n</ol>\n" }, { "answer_id": 60729, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<pre><code>start = r\"^\\s*#define\\s+\"\ncontinuation = r\"(?:.*\\\\\\n)+\"\nlastline = r\".*$\"\n\nre_multiline_macros = re.compile(start + continuation + lastline, \n re.MULTILINE)\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ]
What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better. Here's the regex: ``` \s*#define(.*\\\n)+[\S]+(?!\\) ``` It should match all of this: ``` #define foo(x) if(x) \ doSomething(x) ``` But only some of this (shouldn't match the next line of code: ``` #define foo(x) if(x) \ doSomething(x) normalCode(); ``` And also shouldn't match single-line preprocessor macros. I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?
This is a simple test program I knocked up: ``` #!/usr/bin/env python TEST1=""" #include "Foo.h" #define bar foo\\ x #include "Bar.h" """ TEST2=""" #define bar foo #define x 1 \\ 12 \\ 2 \\\\ 3 Foobar """ TEST3=""" #define foo(x) if(x) \\ doSomething(x) """ TEST4=""" #define foo(x) if(x) \\ doSomething(x) normalCode(); """ import re matcher = re.compile(r"^[ \t]*#define(.*\\\n)+.*$",re.MULTILINE) def extractDefines(s): mo = matcher.search(s) if not mo: print mo return print mo.group(0) extractDefines(TEST1) extractDefines(TEST2) extractDefines(TEST3) extractDefines(TEST4) ``` The re I used: ``` r"^[ \t]*#define(.*\\\n)+.*$" ``` Is very similar to the one use used, the changes: 1. [ \t] To avoid newlines at the start of the define. 2. I rely on + being greedy, so I can use a simple .\*$ at the end to get the first line of the define that doesn't end with \
60,736
<p>I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to:</p> <ul> <li>Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific)</li> <li>Configure a secure way of accessing the server (SSH/HTTPS)</li> <li>Configure a set of authorised users (as in, they must authorised to commit, but are free to browse)</li> <li>Validate the setup with an initial commit (a "Hello world" of sorts)</li> </ul> <p>These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, <a href="https://en.wikipedia.org/wiki/GNU_nano" rel="noreferrer">nano</a> instead of <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>).</p>
[ { "answer_id": 60741, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<p>For Apache:</p>\n\n<pre><code>sudo apt-get -yq install apache2\n</code></pre>\n\n<p>For SSH:</p>\n\n<pre><code>sudo apt-get -yq install openssh-server\n</code></pre>\n\n<p>For Subversion:</p>\n\n<pre><code>sudo apt-get -yq install subversion subversion-tools\n</code></pre>\n\n<p>If you'd like you can combine these into one command like:</p>\n\n<pre><code>sudo apt-get -yq install apache2 openssh-server subversion subversion-tools\n</code></pre>\n\n<p>I can't help with the rest...</p>\n" }, { "answer_id": 60792, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 8, "selected": true, "text": "<p>Steps I've taken to make my laptop a Subversion server. Credit must go to <a href=\"http://alephzarro.com/blog/\" rel=\"noreferrer\">AlephZarro</a> for his directions <a href=\"http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth/\" rel=\"noreferrer\">here</a>. I now have a working SVN server (which has currently only been tested locally).</p>\n\n<p>Specific setup:\n Kubuntu 8.04 Hardy Heron</p>\n\n<p>Requirements to follow this guide:</p>\n\n<ul>\n<li>apt-get package manager program</li>\n<li>text editor (I use kate)</li>\n<li>sudo access rights</li>\n</ul>\n\n<p>1: Install Apache HTTP server and required modules:</p>\n\n<pre><code>sudo apt-get install libapache2-svn apache2\n</code></pre>\n\n<p>The following extra packages will be installed:</p>\n\n<pre><code>apache2-mpm-worker apache2-utils apache2.2-common\n</code></pre>\n\n<p>2: Enable SSL</p>\n\n<pre><code>sudo a2enmod ssl\nsudo kate /etc/apache2/ports.conf\n</code></pre>\n\n<p>Add or check that the following is in the file:</p>\n\n<pre><code>&lt;IfModule mod_ssl.c&gt;\n Listen 443\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>3: Generate an SSL certificate:</p>\n\n<pre><code>sudo apt-get install ssl-cert\nsudo mkdir /etc/apache2/ssl\nsudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem\n</code></pre>\n\n<p>4: Create virtual host</p>\n\n<pre><code>sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserver\nsudo kate /etc/apache2/sites-available/svnserver\n</code></pre>\n\n<p>Change (in ports.conf):</p>\n\n<pre><code>\"NameVirtualHost *\" to \"NameVirtualHost *:443\"\n</code></pre>\n\n<p>and (in svnserver)</p>\n\n<pre><code>&lt;VirtualHost *&gt; to &lt;VirtualHost *:443&gt;\n</code></pre>\n\n<p>Add, under ServerAdmin (also in file svnserver):</p>\n\n<pre><code>SSLEngine on\nSSLCertificateFile /etc/apache2/ssl/apache.pem\nSSLProtocol all\nSSLCipherSuite HIGH:MEDIUM\n</code></pre>\n\n<p>5: Enable the site:</p>\n\n<pre><code>sudo a2ensite svnserver\nsudo /etc/init.d/apache2 restart\n</code></pre>\n\n<p>To overcome warnings:</p>\n\n<pre><code>sudo kate /etc/apache2/apache2.conf\n</code></pre>\n\n<p>Add:</p>\n\n<pre><code>\"ServerName $your_server_name\"\n</code></pre>\n\n<p>6: Adding repository(ies):\nThe following setup assumes we want to host multiple repositories.\nRun this for creating the first repository:</p>\n\n<pre><code>sudo mkdir /var/svn\n\nREPOS=myFirstRepo\nsudo svnadmin create /var/svn/$REPOS\nsudo chown -R www-data:www-data /var/svn/$REPOS\nsudo chmod -R g+ws /var/svn/$REPOS\n</code></pre>\n\n<p>6.a. For more repositories: do step 6 again (changing the value of REPOS), skipping the step <code>mkdir /var/svn</code></p>\n\n<p>7: Add an authenticated user</p>\n\n<pre><code>sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name\n</code></pre>\n\n<p>8: Enable and configure WebDAV and SVN:</p>\n\n<pre><code>sudo kate /etc/apache2/mods-available/dav_svn.conf\n</code></pre>\n\n<p>Add or uncomment:</p>\n\n<pre><code>&lt;Location /svn&gt;\nDAV svn\n\n# for multiple repositories - see comments in file\nSVNParentPath /var/svn\n\nAuthType Basic\nAuthName \"Subversion Repository\"\nAuthUserFile /etc/apache2/dav_svn.passwd\nRequire valid-user\nSSLRequireSSL\n&lt;/Location&gt;\n</code></pre>\n\n<p>9: Restart apache server:</p>\n\n<pre><code>sudo /etc/init.d/apache2 restart\n</code></pre>\n\n<p>10: Validation:</p>\n\n<p>Fired up a browser:</p>\n\n<pre><code>http://localhost/svn/$REPOS\nhttps://localhost/svn/$REPOS\n</code></pre>\n\n<p>Both required a username and password. I think uncommenting:</p>\n\n<pre><code>&lt;LimitExcept GET PROPFIND OPTIONS REPORT&gt;\n\n&lt;/LimitExcept&gt;\n</code></pre>\n\n<p>in <code>/etc/apache2/mods-available/dav_svn.conf</code>, would allow anonymous browsing. </p>\n\n<p>The browser shows \"Revision 0: /\"</p>\n\n<p>Commit something:</p>\n\n<pre><code>svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing”\n</code></pre>\n\n<p>Accept the certificate and enter password.\nCheck out what you've just committed:</p>\n\n<pre><code>svn co --username $user_name https://localhost/svn/$REPOS\n</code></pre>\n\n<p>Following these steps (assuming I haven't made any error copy/pasting), I had a working SVN repository on my laptop.</p>\n" }, { "answer_id": 3329059, "author": "PuO2", "author_id": 399977, "author_profile": "https://Stackoverflow.com/users/399977", "pm_score": 1, "selected": false, "text": "<p>If you get 403 forbidden when you hit the webserver it may be because you used a hostname that is not what you specified in your config file (ie localhost or 127.0.0.1). Try hitting <a href=\"https://whateveryousetasyourhostname\" rel=\"nofollow noreferrer\">https://whateveryousetasyourhostname</a> instead...</p>\n" }, { "answer_id": 5193555, "author": "Thierry M.S.", "author_id": 282073, "author_profile": "https://Stackoverflow.com/users/282073", "pm_score": 2, "selected": false, "text": "<p>Afterwards, I needed to execute (within the context of the example quoted above)</p>\n\n<p>$ sudo chmod g+w /var/svn/$REPOS/db/rep-cache.db</p>\n\n<p>$ sudo chown www-data:www-data /var/svn/$REPOS/db/rep-cache.db</p>\n\n<p>Otherwise I kept receiving a 409 error when committing local modifications \n(though the commitments were server side effective, I needed to follow up with local updates)</p>\n" }, { "answer_id": 26987985, "author": "Ashish Saini", "author_id": 834799, "author_profile": "https://Stackoverflow.com/users/834799", "pm_score": -1, "selected": false, "text": "<p>Please write a single command on the terminal.</p>\n\n<p>To open the terminal please press <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>T</kbd>, and then type this command:</p>\n\n<pre><code>$sudo apt-get install subversion\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to: * Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific) * Configure a secure way of accessing the server (SSH/HTTPS) * Configure a set of authorised users (as in, they must authorised to commit, but are free to browse) * Validate the setup with an initial commit (a "Hello world" of sorts) These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, [nano](https://en.wikipedia.org/wiki/GNU_nano) instead of [vi](http://en.wikipedia.org/wiki/Vi)).
Steps I've taken to make my laptop a Subversion server. Credit must go to [AlephZarro](http://alephzarro.com/blog/) for his directions [here](http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth/). I now have a working SVN server (which has currently only been tested locally). Specific setup: Kubuntu 8.04 Hardy Heron Requirements to follow this guide: * apt-get package manager program * text editor (I use kate) * sudo access rights 1: Install Apache HTTP server and required modules: ``` sudo apt-get install libapache2-svn apache2 ``` The following extra packages will be installed: ``` apache2-mpm-worker apache2-utils apache2.2-common ``` 2: Enable SSL ``` sudo a2enmod ssl sudo kate /etc/apache2/ports.conf ``` Add or check that the following is in the file: ``` <IfModule mod_ssl.c> Listen 443 </IfModule> ``` 3: Generate an SSL certificate: ``` sudo apt-get install ssl-cert sudo mkdir /etc/apache2/ssl sudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem ``` 4: Create virtual host ``` sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserver sudo kate /etc/apache2/sites-available/svnserver ``` Change (in ports.conf): ``` "NameVirtualHost *" to "NameVirtualHost *:443" ``` and (in svnserver) ``` <VirtualHost *> to <VirtualHost *:443> ``` Add, under ServerAdmin (also in file svnserver): ``` SSLEngine on SSLCertificateFile /etc/apache2/ssl/apache.pem SSLProtocol all SSLCipherSuite HIGH:MEDIUM ``` 5: Enable the site: ``` sudo a2ensite svnserver sudo /etc/init.d/apache2 restart ``` To overcome warnings: ``` sudo kate /etc/apache2/apache2.conf ``` Add: ``` "ServerName $your_server_name" ``` 6: Adding repository(ies): The following setup assumes we want to host multiple repositories. Run this for creating the first repository: ``` sudo mkdir /var/svn REPOS=myFirstRepo sudo svnadmin create /var/svn/$REPOS sudo chown -R www-data:www-data /var/svn/$REPOS sudo chmod -R g+ws /var/svn/$REPOS ``` 6.a. For more repositories: do step 6 again (changing the value of REPOS), skipping the step `mkdir /var/svn` 7: Add an authenticated user ``` sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name ``` 8: Enable and configure WebDAV and SVN: ``` sudo kate /etc/apache2/mods-available/dav_svn.conf ``` Add or uncomment: ``` <Location /svn> DAV svn # for multiple repositories - see comments in file SVNParentPath /var/svn AuthType Basic AuthName "Subversion Repository" AuthUserFile /etc/apache2/dav_svn.passwd Require valid-user SSLRequireSSL </Location> ``` 9: Restart apache server: ``` sudo /etc/init.d/apache2 restart ``` 10: Validation: Fired up a browser: ``` http://localhost/svn/$REPOS https://localhost/svn/$REPOS ``` Both required a username and password. I think uncommenting: ``` <LimitExcept GET PROPFIND OPTIONS REPORT> </LimitExcept> ``` in `/etc/apache2/mods-available/dav_svn.conf`, would allow anonymous browsing. The browser shows "Revision 0: /" Commit something: ``` svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing” ``` Accept the certificate and enter password. Check out what you've just committed: ``` svn co --username $user_name https://localhost/svn/$REPOS ``` Following these steps (assuming I haven't made any error copy/pasting), I had a working SVN repository on my laptop.
60,751
<p>Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?</p> <p>At present there are various Render methods in my code</p> <pre><code>void Render(boost::function&lt;void()&gt; &amp;Call) { D3dDevice-&gt;BeginScene(); Call(); D3dDevice-&gt;EndScene(); D3dDevice-&gt;Present(0,0,0,0); } </code></pre> <p>The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects.</p> <pre><code>void RenderGame() { for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it) (*it)-&gt;Render(); UI-&gt;Render(); } </code></pre> <p>And a sample class derived from entity::Base</p> <pre><code>class Sprite: public Base { IDirect3DTexture9 *Tex; Point2 Pos; Size2 Size; public: Sprite(IDirect3DTexture9 *Tex, const Point2 &amp;Pos, const Size2 &amp;Size); virtual void Render(); }; </code></pre> <p>Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not).</p> <p>The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes...</p>
[ { "answer_id": 60790, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 4, "selected": true, "text": "<p>Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every renderer you want to support.</p>\n\n<pre><code>class IRenderer {\n public:\n virtual ~IRenderer() {}\n virtual void RenderModel(CModel* model) = 0;\n virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) = 0;\n // ...etc...\n};\n\nclass COpenGLRenderer : public IRenderer {\n public:\n virtual void RenderModel(CModel* model) {\n // render model using OpenGL\n }\n virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) {\n // draw screen aligned quad using OpenGL\n }\n};\n\nclass CDirect3DRenderer : public IRenderer {\n // similar, but render using Direct3D\n};\n</code></pre>\n\n<p>Properly designing and maintaining these interfaces can be very challenging though.</p>\n\n<p>In case you also operate with render driver dependent objects like textures, you can use a factory pattern to have the separate renderers each create their own implementation of e.g. ITexture using a factory method in IRenderer:</p>\n\n<pre><code>class IRenderer {\n //...\n virtual ITexture* CreateTexture(const char* filename) = 0;\n //...\n};\n\nclass COpenGLRenderer : public IRenderer {\n //...\n virtual ITexture* CreateTexture(const char* filename) {\n // COpenGLTexture is the OpenGL specific ITexture implementation\n return new COpenGLTexture(filename);\n }\n //...\n};\n</code></pre>\n\n<p>Isn't it an idea to look at existing (3d) engines though? In my experience designing this kind of interfaces really distracts from what you actually want to make :)</p>\n" }, { "answer_id": 69100, "author": "Baxissimo", "author_id": 9631, "author_profile": "https://Stackoverflow.com/users/9631", "pm_score": 1, "selected": false, "text": "<p>I'd say if you want a really complete the answer, go look at the source code for <code>Ogre3D</code>. They have both <code>D3D</code> and <code>OpenGL</code> back ends. Look at : <a href=\"http://www.ogre3d.org\" rel=\"nofollow noreferrer\">http://www.ogre3d.org</a>\nBasically their API kind of forces you into working in a D3D-ish way, creating buffer objects and stuffing them with data, then issuing draw calls on those buffers. That's the way the hardware likes it anyway, so it's not a bad way to go. </p>\n\n<p>And then once you see how they do things, you might as well just just go ahead and use it and save yourself the trouble of having to re-implement all that it already provides. :-)</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way? At present there are various Render methods in my code ``` void Render(boost::function<void()> &Call) { D3dDevice->BeginScene(); Call(); D3dDevice->EndScene(); D3dDevice->Present(0,0,0,0); } ``` The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects. ``` void RenderGame() { for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it) (*it)->Render(); UI->Render(); } ``` And a sample class derived from entity::Base ``` class Sprite: public Base { IDirect3DTexture9 *Tex; Point2 Pos; Size2 Size; public: Sprite(IDirect3DTexture9 *Tex, const Point2 &Pos, const Size2 &Size); virtual void Render(); }; ``` Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not). The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes...
Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every renderer you want to support. ``` class IRenderer { public: virtual ~IRenderer() {} virtual void RenderModel(CModel* model) = 0; virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) = 0; // ...etc... }; class COpenGLRenderer : public IRenderer { public: virtual void RenderModel(CModel* model) { // render model using OpenGL } virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) { // draw screen aligned quad using OpenGL } }; class CDirect3DRenderer : public IRenderer { // similar, but render using Direct3D }; ``` Properly designing and maintaining these interfaces can be very challenging though. In case you also operate with render driver dependent objects like textures, you can use a factory pattern to have the separate renderers each create their own implementation of e.g. ITexture using a factory method in IRenderer: ``` class IRenderer { //... virtual ITexture* CreateTexture(const char* filename) = 0; //... }; class COpenGLRenderer : public IRenderer { //... virtual ITexture* CreateTexture(const char* filename) { // COpenGLTexture is the OpenGL specific ITexture implementation return new COpenGLTexture(filename); } //... }; ``` Isn't it an idea to look at existing (3d) engines though? In my experience designing this kind of interfaces really distracts from what you actually want to make :)
60,764
<p>Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own <code>ClassLoader</code>, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.</p> <p>Any suggestions for simple code that does this?</p>
[ { "answer_id": 60766, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "<p>The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:</p>\n\n<pre><code>File file = ...\nURL url = file.toURI().toURL();\n\nURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\nMethod method = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\nmethod.setAccessible(true);\nmethod.invoke(classLoader, url);\n</code></pre>\n" }, { "answer_id": 60770, "author": "Martin Klinke", "author_id": 1793, "author_profile": "https://Stackoverflow.com/users/1793", "pm_score": 6, "selected": false, "text": "<p>You should take a look at <a href=\"http://www.osgi.org\" rel=\"noreferrer\">OSGi</a>, e.g. implemented in the <a href=\"http://www.eclipse.org\" rel=\"noreferrer\">Eclipse Platform</a>. It does exactly that. You can install, uninstall, start and stop so called bundles, which are effectively JAR files. But it does a little more, as it offers e.g. services that can be dynamically discovered in JAR files at runtime.</p>\n\n<p>Or see the specification for the <a href=\"http://jcp.org/en/jsr/detail?id=277\" rel=\"noreferrer\">Java Module System</a>.</p>\n" }, { "answer_id": 60775, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 9, "selected": true, "text": "<p>The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader:</p>\n\n<pre><code>URLClassLoader child = new URLClassLoader(\n new URL[] {myJar.toURI().toURL()},\n this.getClass().getClassLoader()\n);\nClass classToLoad = Class.forName(\"com.MyClass\", true, child);\nMethod method = classToLoad.getDeclaredMethod(\"myMethod\");\nObject instance = classToLoad.newInstance();\nObject result = method.invoke(instance);\n</code></pre>\n\n<p>Painful, but there it is.</p>\n" }, { "answer_id": 63892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The best I've found is <a href=\"http://svn.apache.org/viewvc/geronimo/xbean/trunk/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarFileClassLoader.java?view=markup\" rel=\"noreferrer\">org.apache.xbean.classloader.JarFileClassLoader</a> which is part of the <a href=\"http://geronimo.apache.org/xbean\" rel=\"noreferrer\">XBean</a> project.</p>\n\n<p>Here's a short method I've used in the past, to create a class loader from all the lib files in a specific directory</p>\n\n<pre><code>public void initialize(String libDir) throws Exception {\n File dependencyDirectory = new File(libDir);\n File[] files = dependencyDirectory.listFiles();\n ArrayList&lt;URL&gt; urls = new ArrayList&lt;URL&gt;();\n for (int i = 0; i &lt; files.length; i++) {\n if (files[i].getName().endsWith(\".jar\")) {\n urls.add(files[i].toURL());\n //urls.add(files[i].toURI().toURL());\n }\n }\n classLoader = new JarFileClassLoader(\"Scheduler CL\" + System.currentTimeMillis(), \n urls.toArray(new URL[urls.size()]), \n GFClassLoader.class.getClassLoader());\n}\n</code></pre>\n\n<p>Then to use the classloader, just do: </p>\n\n<pre><code>classLoader.loadClass(name);\n</code></pre>\n" }, { "answer_id": 1450837, "author": "Chris", "author_id": 92813, "author_profile": "https://Stackoverflow.com/users/92813", "pm_score": 5, "selected": false, "text": "<p>How about the <a href=\"https://github.com/kamranzafar/JCL\" rel=\"noreferrer\">JCL class loader framework</a>? I have to admit, I haven't used it, but it looks promising.</p>\n\n<p>Usage example:</p>\n\n<pre><code>JarClassLoader jcl = new JarClassLoader();\njcl.add(\"myjar.jar\"); // Load jar file \njcl.add(new URL(\"http://myserver.com/myjar.jar\")); // Load jar from a URL\njcl.add(new FileInputStream(\"myotherjar.jar\")); // Load jar file from stream\njcl.add(\"myclassfolder/\"); // Load class folder \njcl.add(\"myjarlib/\"); // Recursively load all jar files in the folder/sub-folder(s)\n\nJclObjectFactory factory = JclObjectFactory.getInstance();\n// Create object of loaded class \nObject obj = factory.create(jcl, \"mypackage.MyClass\");\n</code></pre>\n" }, { "answer_id": 2593771, "author": "Jonathan Nadeau", "author_id": 311140, "author_profile": "https://Stackoverflow.com/users/311140", "pm_score": 4, "selected": false, "text": "<p>Here is a version that is not deprecated. I modified the original to remove the deprecated functionality.</p>\n\n<pre><code>/**************************************************************************************************\n * Copyright (c) 2004, Federal University of So Carlos *\n * *\n * All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, with or without modification, are permitted *\n * provided that the following conditions are met: *\n * *\n * * Redistributions of source code must retain the above copyright notice, this list of *\n * conditions and the following disclaimer. *\n * * Redistributions in binary form must reproduce the above copyright notice, this list of *\n * * conditions and the following disclaimer in the documentation and/or other materials *\n * * provided with the distribution. *\n * * Neither the name of the Federal University of So Carlos nor the names of its *\n * * contributors may be used to endorse or promote products derived from this software *\n * * without specific prior written permission. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR *\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\n **************************************************************************************************/\n/*\n * Created on Oct 6, 2004\n */\npackage tools;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.net.URLClassLoader;\n\n/**\n * Useful class for dynamically changing the classpath, adding classes during runtime. \n */\npublic class ClasspathHacker {\n /**\n * Parameters of the method to add an URL to the System classes. \n */\n private static final Class&lt;?&gt;[] parameters = new Class[]{URL.class};\n\n /**\n * Adds a file to the classpath.\n * @param s a String pointing to the file\n * @throws IOException\n */\n public static void addFile(String s) throws IOException {\n File f = new File(s);\n addFile(f);\n }\n\n /**\n * Adds a file to the classpath\n * @param f the file to be added\n * @throws IOException\n */\n public static void addFile(File f) throws IOException {\n addURL(f.toURI().toURL());\n }\n\n /**\n * Adds the content pointed by the URL to the classpath.\n * @param u the URL pointing to the content to be added\n * @throws IOException\n */\n public static void addURL(URL u) throws IOException {\n URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n Class&lt;?&gt; sysclass = URLClassLoader.class;\n try {\n Method method = sysclass.getDeclaredMethod(\"addURL\",parameters);\n method.setAccessible(true);\n method.invoke(sysloader,new Object[]{ u }); \n } catch (Throwable t) {\n t.printStackTrace();\n throw new IOException(\"Error, could not add URL to system classloader\");\n } \n }\n\n public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{\n addFile(\"C:\\\\dynamicloading.jar\");\n Constructor&lt;?&gt; cs = ClassLoader.getSystemClassLoader().loadClass(\"test.DymamicLoadingTest\").getConstructor(String.class);\n DymamicLoadingTest instance = (DymamicLoadingTest)cs.newInstance();\n instance.test();\n }\n}\n</code></pre>\n" }, { "answer_id": 7523747, "author": "tanyehzheng", "author_id": 284126, "author_profile": "https://Stackoverflow.com/users/284126", "pm_score": -1, "selected": false, "text": "<p>I personally find that <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html\" rel=\"nofollow\">java.util.ServiceLoader</a> does the job pretty well. You can get an example <a href=\"http://java.sun.com/developer/technicalArticles/javase/extensible/\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 18253109, "author": "Caner", "author_id": 448625, "author_profile": "https://Stackoverflow.com/users/448625", "pm_score": 3, "selected": false, "text": "<p>If you are working on Android, the following code works:</p>\n\n<pre><code>String jarFile = \"path/to/jarfile.jar\";\nDexClassLoader classLoader = new DexClassLoader(jarFile, \"/data/data/\" + context.getPackageName() + \"/\", null, getClass().getClassLoader());\nClass&lt;?&gt; myClass = classLoader.loadClass(\"MyClass\");\n</code></pre>\n" }, { "answer_id": 31624177, "author": "venergiac", "author_id": 1645339, "author_profile": "https://Stackoverflow.com/users/1645339", "pm_score": 2, "selected": false, "text": "<p>The solution proposed by jodonnell is good but should be a little bit enhanced. I used this post to develop my application with success. </p>\n\n<h2>Assign the current thread</h2>\n\n<p>Firstly we have to add</p>\n\n<pre><code>Thread.currentThread().setContextClassLoader(classLoader);\n</code></pre>\n\n<p>or you will not able to load resource (such as spring/context.xml) stored into the jar.</p>\n\n<h2>Do not include</h2>\n\n<p>your jars into the parent class loader or you will not able to understand who is loading what.</p>\n\n<p>see also <a href=\"https://stackoverflow.com/questions/3216780/problem-reloading-a-jar-using-urlclassloader/31624123#31624123\">Problem reloading a jar using URLClassLoader</a></p>\n\n<p>However, OSGi framework remain the best way.</p>\n" }, { "answer_id": 46457506, "author": "fgb", "author_id": 298029, "author_profile": "https://Stackoverflow.com/users/298029", "pm_score": 4, "selected": false, "text": "<p>With <strong>Java 9</strong>, the answers with <code>URLClassLoader</code> now give an error like:</p>\n\n<pre><code>java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClassLoader\n</code></pre>\n\n<p>This is because the class loaders used have changed. Instead, to add to the system class loader, you can use the <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/instrument/Instrumentation.html\" rel=\"noreferrer\">Instrumentation</a> API through an agent.</p>\n\n<p><strong>Create an agent class:</strong></p>\n\n<pre><code>package ClassPathAgent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class ClassPathAgent {\n public static void agentmain(String args, Instrumentation instrumentation) throws IOException {\n instrumentation.appendToSystemClassLoaderSearch(new JarFile(args));\n }\n}\n</code></pre>\n\n<p><strong>Add META-INF/MANIFEST.MF and put it in a JAR file with the agent class:</strong></p>\n\n<pre><code>Manifest-Version: 1.0\nAgent-Class: ClassPathAgent.ClassPathAgent\n</code></pre>\n\n<p><strong>Run the agent:</strong></p>\n\n<p>This uses the <a href=\"https://github.com/raphw/byte-buddy\" rel=\"noreferrer\">byte-buddy-agent</a> library to add the agent to the running JVM:</p>\n\n<pre><code>import java.io.File;\n\nimport net.bytebuddy.agent.ByteBuddyAgent;\n\npublic class ClassPathUtil {\n private static File AGENT_JAR = new File(\"/path/to/agent.jar\");\n\n public static void addJarToClassPath(File jarFile) {\n ByteBuddyAgent.attach(AGENT_JAR, String.valueOf(ProcessHandle.current().pid()), jarFile.getPath());\n }\n}\n</code></pre>\n" }, { "answer_id": 50521611, "author": "Aleksey", "author_id": 1433446, "author_profile": "https://Stackoverflow.com/users/1433446", "pm_score": 2, "selected": false, "text": "<p>please take a look at this project that i started: <a href=\"https://github.com/avinokurov/proxy-object\" rel=\"nofollow noreferrer\">proxy-object lib</a></p>\n\n<p>This lib will load jar from file system or any other location. It will dedicate a class loader for the jar to make sure there are no library conflicts. Users will be able to create any object from the loaded jar and call any method on it. \nThis lib was designed to load jars compiled in Java 8 from the code base that supports Java 7.</p>\n\n<p>To create an object:</p>\n\n<pre><code> File libDir = new File(\"path/to/jar\");\n\n ProxyCallerInterface caller = ObjectBuilder.builder()\n .setClassName(\"net.proxy.lib.test.LibClass\")\n .setArtifact(DirArtifact.builder()\n .withClazz(ObjectBuilderTest.class)\n .withVersionInfo(newVersionInfo(libDir))\n .build())\n .build();\n String version = caller.call(\"getLibVersion\").asString();\n</code></pre>\n\n<p>ObjectBuilder supports factory methods, calling static functions, and call back interface implementations.\ni will be posting more examples on the readme page.</p>\n" }, { "answer_id": 52616924, "author": "czdepski", "author_id": 10448469, "author_profile": "https://Stackoverflow.com/users/10448469", "pm_score": 2, "selected": false, "text": "<p>Another version of the hackish solution from Allain, that also works on JDK 11:</p>\n\n<pre><code>File file = ...\nURL url = file.toURI().toURL();\nURLClassLoader sysLoader = new URLClassLoader(new URL[0]);\n\nMethod sysMethod = URLClassLoader.class.getDeclaredMethod(\"addURL\", new Class[]{URL.class});\nsysMethod.setAccessible(true);\nsysMethod.invoke(sysLoader, new Object[]{url});\n</code></pre>\n\n<p>On JDK 11 it gives some deprecation warnings but serves as a temporary solution those who use Allain solution on JDK 11.</p>\n" }, { "answer_id": 52741647, "author": "czdepski", "author_id": 10448469, "author_profile": "https://Stackoverflow.com/users/10448469", "pm_score": 3, "selected": false, "text": "<p>Another working solution using Instrumentation that works for me. It has the advantage of modifying the class loader search, avoiding problems on class visibility for dependent classes:</p>\n\n<p><strong>Create an Agent Class</strong></p>\n\n<p>For this example, it has to be on the same jar invoked by the command line:</p>\n\n<pre><code>package agent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class Agent {\n public static Instrumentation instrumentation;\n\n public static void premain(String args, Instrumentation instrumentation) {\n Agent.instrumentation = instrumentation;\n }\n\n public static void agentmain(String args, Instrumentation instrumentation) {\n Agent.instrumentation = instrumentation;\n }\n\n public static void appendJarFile(JarFile file) throws IOException {\n if (instrumentation != null) {\n instrumentation.appendToSystemClassLoaderSearch(file);\n }\n }\n}\n</code></pre>\n\n<p><strong>Modify the MANIFEST.MF</strong></p>\n\n<p>Adding the reference to the agent:</p>\n\n<pre><code>Launcher-Agent-Class: agent.Agent\nAgent-Class: agent.Agent\nPremain-Class: agent.Agent\n</code></pre>\n\n<p>I actually use Netbeans, so <a href=\"https://stackoverflow.com/a/52728977/10448469\">this post</a> helps on how to change the manifest.mf</p>\n\n<p><strong>Running</strong></p>\n\n<p>The <code>Launcher-Agent-Class</code> is only supported on JDK 9+ and is responsible for loading the agent without explicitly defining it on the command line:</p>\n\n<pre><code> java -jar &lt;your jar&gt;\n</code></pre>\n\n<p>The way that works on JDK 6+ is defining the <code>-javaagent</code> argument:</p>\n\n<pre><code>java -javaagent:&lt;your jar&gt; -jar &lt;your jar&gt;\n</code></pre>\n\n<p><strong>Adding new Jar at Runtime</strong></p>\n\n<p>You can then add jar as necessary using the following command:</p>\n\n<pre><code>Agent.appendJarFile(new JarFile(&lt;your file&gt;));\n</code></pre>\n\n<p>I did not find any problems using this on documentation.</p>\n" }, { "answer_id": 52911129, "author": "steve212", "author_id": 10534683, "author_profile": "https://Stackoverflow.com/users/10534683", "pm_score": 2, "selected": false, "text": "<p>This can be a late response, I can do it as this (a simple example for fastutil-8.2.2.jar) using jhplot.Web class from DataMelt (<a href=\"http://jwork.org/dmelt\" rel=\"nofollow noreferrer\">http://jwork.org/dmelt</a>)</p>\n\n<pre><code>import jhplot.Web;\nWeb.load(\"http://central.maven.org/maven2/it/unimi/dsi/fastutil/8.2.2/fastutil-8.2.2.jar\"); // now you can start using this library\n</code></pre>\n\n<p>According to the documentation, this file will be download inside \"lib/user\" and then dynamically loaded, so you can start immediately using classes from this jar file in the same program.</p>\n" }, { "answer_id": 53111471, "author": "Anton Tananaev", "author_id": 2548565, "author_profile": "https://Stackoverflow.com/users/2548565", "pm_score": 4, "selected": false, "text": "<p>Here is a quick workaround for Allain's method to make it compatible with newer versions of Java:</p>\n\n<pre><code>ClassLoader classLoader = ClassLoader.getSystemClassLoader();\ntry {\n Method method = classLoader.getClass().getDeclaredMethod(\"addURL\", URL.class);\n method.setAccessible(true);\n method.invoke(classLoader, new File(jarPath).toURI().toURL());\n} catch (NoSuchMethodException e) {\n Method method = classLoader.getClass()\n .getDeclaredMethod(\"appendToClassPathForInstrumentation\", String.class);\n method.setAccessible(true);\n method.invoke(classLoader, jarPath);\n}\n</code></pre>\n\n<p>Note that it relies on knowledge of internal implementation of specific JVM, so it's not ideal and it's not a universal solution. But it's a quick and easy workaround if you know that you are going to use standard OpenJDK or Oracle JVM. It might also break at some point in future when new JVM version is released, so you need to keep that in mind.</p>\n" }, { "answer_id": 59743937, "author": "Mordechai", "author_id": 1751640, "author_profile": "https://Stackoverflow.com/users/1751640", "pm_score": 6, "selected": false, "text": "<p>While most solutions listed here are either hacks (pre JDK 9) hard to configure (agents) or just don't work anymore (post JDK 9) I find it really surprising that nobody mentioned a <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/ClassLoader.html#getSystemClassLoader()\" rel=\"noreferrer\">clearly documented method</a>.</p>\n<p>You can create a custom system class loader and then you're free to do whatever you wish. No reflection required and all classes share the same classloader.</p>\n<p>When starting the JVM add this flag:</p>\n<pre><code>java -Djava.system.class.loader=com.example.MyCustomClassLoader\n</code></pre>\n<p>The classloader must have a constructor accepting a classloader, which must be set as its parent. The constructor will be called on JVM startup and the real system classloader will be passed, the main class will be loaded by the custom loader.</p>\n<p>To add jars just call <code>ClassLoader.getSystemClassLoader()</code> and cast it to your class.</p>\n<p>Check out <a href=\"https://github.com/update4j/update4j/blob/master/src/main/java/org/update4j/DynamicClassLoader.java\" rel=\"noreferrer\">this implementation</a> for a carefully crafted classloader. Please note, you can change the <code>add()</code> method to public.</p>\n" }, { "answer_id": 60281394, "author": "Bằng Rikimaru", "author_id": 2028440, "author_profile": "https://Stackoverflow.com/users/2028440", "pm_score": 1, "selected": false, "text": "<p>I needed to load a jar file at runtime for both java 8 and java 9+ (above comments don't work for both of these versions). Here is the method to do it (using Spring Boot 1.5.2 if it may relate).</p>\n\n<pre><code>public static synchronized void loadLibrary(java.io.File jar) {\n try { \n java.net.URL url = jar.toURI().toURL();\n java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod(\"addURL\", new Class[]{java.net.URL.class});\n method.setAccessible(true); /*promote the method to public access*/\n method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});\n } catch (Exception ex) {\n throw new RuntimeException(\"Cannot load library from jar file '\" + jar.getAbsolutePath() + \"'. Reason: \" + ex.getMessage());\n }\n}\n</code></pre>\n" }, { "answer_id": 60662896, "author": "ZGorlock", "author_id": 7427882, "author_profile": "https://Stackoverflow.com/users/7427882", "pm_score": 2, "selected": false, "text": "<p>In case anyone searches for this in the future, this way works for me with OpenJDK 13.0.2.</p>\n\n<p>I have many classes that I need to instantiate dynamically at runtime, each potentially with a different classpath.</p>\n\n<p>In this code, I already have an object called pack, that holds some metadata about the class I am trying to load. The getObjectFile() method returns the location of the class file for the class. The getObjectRootPath() method returns the path to the bin/ directory containing the class files that include the class I am trying to instantiate. The getLibPath() method returns the path to a directory containing the jar files constituting the classpath for the module the class is a part of.</p>\n\n<pre><code>File object = new File(pack.getObjectFile()).getAbsoluteFile();\nObject packObject;\ntry {\n URLClassLoader classloader;\n\n List&lt;URL&gt; classpath = new ArrayList&lt;&gt;();\n classpath.add(new File(pack.getObjectRootPath()).toURI().toURL());\n for (File jar : FileUtils.listFiles(new File(pack.getLibPath()), new String[] {\"jar\"}, true)) {\n classpath.add(jar.toURI().toURL());\n }\n classloader = new URLClassLoader(classpath.toArray(new URL[] {}));\n\n Class&lt;?&gt; clazz = classloader.loadClass(object.getName());\n packObject = clazz.getDeclaredConstructor().newInstance();\n\n} catch (Exception e) {\n e.printStackTrace();\n throw e;\n}\nreturn packObject;\n</code></pre>\n\n<p>I was using the Maven dependency: org.xeustechnologies:jcl-core:2.8 to do this before, but after moving past JDK 1.8, it sometimes froze and never returned being stuck \"waiting for references\" at Reference::waitForReferencePendingList().</p>\n\n<p>I am also keeping a map of class loaders so that they can be reused if the class I am trying to instantiate is in the same module as a class that I have already instantiated, which I would recommend.</p>\n" }, { "answer_id": 62801788, "author": "Richard Kotal", "author_id": 5934449, "author_profile": "https://Stackoverflow.com/users/5934449", "pm_score": 1, "selected": false, "text": "<p>For dynamic uploading of jar files, you can use my modification of URLClassLoader. This modification has no problem with changing the jar file during application operation, like the standard URLClassloader. All loaded jar files are loaded into RAM and thus independent of the original file.</p>\n<p><a href=\"https://github.com/kotalr/b2b-jcl\" rel=\"nofollow noreferrer\">In-memory jar and JDBC class loader</a></p>\n" }, { "answer_id": 63094644, "author": "Sergio Santiago", "author_id": 1563297, "author_profile": "https://Stackoverflow.com/users/1563297", "pm_score": 3, "selected": false, "text": "<p>I know I'm late to the party, but I have been using <a href=\"https://github.com/pf4j/pf4j\" rel=\"noreferrer\">pf4j</a>, which is a plug-in framework, and it works pretty well.</p>\n<p>PF4J is a microframework and the aim is to keep the core simple but extensible.</p>\n<p>An example of plugin usage:</p>\n<p>Define an extension point in your application/plugin using ExtensionPoint interface marker:</p>\n<pre><code>public interface Greeting extends ExtensionPoint {\n\n String getGreeting();\n\n}\n</code></pre>\n<p>Create an extension using <code>@Extension</code> annotation:</p>\n<pre><code>@Extension\npublic class WelcomeGreeting implements Greeting {\n\n public String getGreeting() {\n return &quot;Welcome&quot;;\n }\n\n}\n</code></pre>\n<p>Then you can load and unload the plugin as you wish:</p>\n<pre><code>public static void main(String[] args) {\n\n // create the plugin manager\n PluginManager pluginManager = new JarPluginManager(); // or &quot;new ZipPluginManager() / new DefaultPluginManager()&quot;\n\n // start and load all plugins of application\n pluginManager.loadPlugins();\n pluginManager.startPlugins();\n\n // retrieve all extensions for &quot;Greeting&quot; extension point\n List&lt;Greeting&gt; greetings = pluginManager.getExtensions(Greeting.class);\n for (Greeting greeting : greetings) {\n System.out.println(&quot;&gt;&gt;&gt; &quot; + greeting.getGreeting());\n }\n\n // stop and unload all plugins\n pluginManager.stopPlugins();\n pluginManager.unloadPlugins();\n\n}\n</code></pre>\n<p>For further details please refer to the <a href=\"https://pf4j.org/\" rel=\"noreferrer\">documentation</a></p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own `ClassLoader`, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument. Any suggestions for simple code that does this?
The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader: ``` URLClassLoader child = new URLClassLoader( new URL[] {myJar.toURI().toURL()}, this.getClass().getClassLoader() ); Class classToLoad = Class.forName("com.MyClass", true, child); Method method = classToLoad.getDeclaredMethod("myMethod"); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance); ``` Painful, but there it is.
60,768
<p>I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error:</p> <p>Metadata file 'System.Data.Linq.dll' could not be found</p> <p>My code looks like:</p> <pre><code>CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll"); </code></pre> <p>Any ideas? </p>
[ { "answer_id": 60781, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": true, "text": "<p>That may be because this assembly is stored in a different location than mscorlib is. It should work if you provide a full path to the assembly. The most convenient way to get the full path is to let the .NET loader do the work for you. I would try something like this:</p>\n\n<pre><code>compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location);\n</code></pre>\n" }, { "answer_id": 61306, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "<p>This may be a silly answer, but are you sure the code is running on a machine with .NET Framework 3.5?</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error: Metadata file 'System.Data.Linq.dll' could not be found My code looks like: ``` CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll"); ``` Any ideas?
That may be because this assembly is stored in a different location than mscorlib is. It should work if you provide a full path to the assembly. The most convenient way to get the full path is to let the .NET loader do the work for you. I would try something like this: ``` compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location); ```
60,779
<p>Trying to do this sort of thing...</p> <pre><code>WHERE username LIKE '%$str%' </code></pre> <p>...but using bound parameters to prepared statements in PDO. e.g.:</p> <pre><code>$query = $db-&gt;prepare("select * from comments where comment like :search"); $query-&gt;bindParam(':search', $str); $query-&gt;execute(); </code></pre> <p>I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.</p> <p>I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?</p>
[ { "answer_id": 60782, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": true, "text": "<p>Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:</p>\n\n<pre><code>$str = \"%$str%\";\n$query = $db-&gt;prepare(\"select * from comments where comment like :search\");\n$query-&gt;bindParam(':search', $str);\n$query-&gt;execute();\n</code></pre>\n" }, { "answer_id": 15377644, "author": "Dominic P", "author_id": 931860, "author_profile": "https://Stackoverflow.com/users/931860", "pm_score": 2, "selected": false, "text": "<p>5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:</p>\n\n<pre><code>$query = $db-&gt;prepare(\"select * FROM table WHERE field LIKE CONCAT('%',:search,'%')\");\n$query-&gt;bindParam(':search', $str);\n$query-&gt;execute();\n</code></pre>\n\n<p>I'm not sure if there will be a performance hit due to the overhead of calling the <code>CONCAT</code> function, but I wanted to pass this along as an option. Hopefully it will help someone.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
Trying to do this sort of thing... ``` WHERE username LIKE '%$str%' ``` ...but using bound parameters to prepared statements in PDO. e.g.: ``` $query = $db->prepare("select * from comments where comment like :search"); $query->bindParam(':search', $str); $query->execute(); ``` I've tried numerous permutations of single quotes and % signs and it's just getting cross with me. I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine: ``` $str = "%$str%"; $query = $db->prepare("select * from comments where comment like :search"); $query->bindParam(':search', $str); $query->execute(); ```
60,785
<p>How can I show a grey transparent overlay in C#?<br> It should overlay other process which are not owned by the application doing the overlay.</p>
[ { "answer_id": 60782, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": true, "text": "<p>Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:</p>\n\n<pre><code>$str = \"%$str%\";\n$query = $db-&gt;prepare(\"select * from comments where comment like :search\");\n$query-&gt;bindParam(':search', $str);\n$query-&gt;execute();\n</code></pre>\n" }, { "answer_id": 15377644, "author": "Dominic P", "author_id": 931860, "author_profile": "https://Stackoverflow.com/users/931860", "pm_score": 2, "selected": false, "text": "<p>5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:</p>\n\n<pre><code>$query = $db-&gt;prepare(\"select * FROM table WHERE field LIKE CONCAT('%',:search,'%')\");\n$query-&gt;bindParam(':search', $str);\n$query-&gt;execute();\n</code></pre>\n\n<p>I'm not sure if there will be a performance hit due to the overhead of calling the <code>CONCAT</code> function, but I wanted to pass this along as an option. Hopefully it will help someone.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
How can I show a grey transparent overlay in C#? It should overlay other process which are not owned by the application doing the overlay.
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine: ``` $str = "%$str%"; $query = $db->prepare("select * from comments where comment like :search"); $query->bindParam(':search', $str); $query->execute(); ```
60,802
<p>I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?</p> <p>Code:</p> <pre><code>IQueryable&lt;AgendaItem&gt; items = _agendaRepository.GetAgendaItems(location) .Where(item =&gt; item.Minutes.Contains(query) || item.Description.Contains(query)); int total = items.Count(); var results = items .OrderBy(item =&gt; item.Agenda.Date) .ThenBy(item =&gt; item.OutcomeType) .ThenBy(item =&gt; item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) .ToArray(); return new SearchResult(query, total, results); </code></pre> <p>I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.</p> <p>Error I'm receiving:</p> <pre> [SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'. Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392 [ADOException: could not execute query [ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ] Positional parameters: #0>1 #0>%Core% #0>%Core% [SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87 NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342 NHibernate.Impl.CriteriaImpl.List(IList results) +41 NHibernate.Impl.CriteriaImpl.List() +35 NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22 NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27 </pre>
[ { "answer_id": 61081, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<p>although i dont think it'd make a difference, what happens if you do your linq like this:</p>\n\n<p>(from i in items orderby i.prop1, i.prop2, i.prop3).Skip(...).Take(...).ToArray();</p>\n" }, { "answer_id": 86686, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 4, "selected": true, "text": "<p>This looks to me like a bug with Linq to NHybernate. One possible workaround is to convert to an array before sorting. A potentially big downside is that you can't limit the results using Skip() and Take() before enumerating, so this may not be sufficient for you.</p>\n\n<pre><code>var results = items\n .ToArray()\n .OrderBy(item =&gt; item.Agenda.Date)\n .ThenBy(item =&gt; item.OutcomeType)\n .ThenBy(item =&gt; item.OutcomeNumber)\n .Skip((page - 1)*pageSize)\n .Take(pageSize)\n</code></pre>\n" }, { "answer_id": 51985649, "author": "Alexander Levinson", "author_id": 4715783, "author_profile": "https://Stackoverflow.com/users/4715783", "pm_score": 0, "selected": false, "text": "<p>Turning it first into array might be an acceptable solution in case if your result set is comparatively small. But if you want to make SQL server do the job, you better do it this way:</p>\n\n<pre><code>var results = items\n .OrderBy(item =&gt; item.Agenda.Date).Asc\n .ThenBy(item =&gt; item.OutcomeType).Asc\n .ThenBy(item =&gt; item.OutcomeNumber).Asc\n .Skip((page - 1)*pageSize)\n .Take(pageSize)\n .ToArray();\n</code></pre>\n\n<p>You should always add Asc or Desc modifier afterwards whenever you use OrderBy or OrderByAlias method in NHibernate dialect of Linq.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around? Code: ``` IQueryable<AgendaItem> items = _agendaRepository.GetAgendaItems(location) .Where(item => item.Minutes.Contains(query) || item.Description.Contains(query)); int total = items.Count(); var results = items .OrderBy(item => item.Agenda.Date) .ThenBy(item => item.OutcomeType) .ThenBy(item => item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) .ToArray(); return new SearchResult(query, total, results); ``` I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls. Error I'm receiving: ``` [SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'. Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392 [ADOException: could not execute query [ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ] Positional parameters: #0>1 #0>%Core% #0>%Core% [SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87 NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342 NHibernate.Impl.CriteriaImpl.List(IList results) +41 NHibernate.Impl.CriteriaImpl.List() +35 NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22 NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27 ```
This looks to me like a bug with Linq to NHybernate. One possible workaround is to convert to an array before sorting. A potentially big downside is that you can't limit the results using Skip() and Take() before enumerating, so this may not be sufficient for you. ``` var results = items .ToArray() .OrderBy(item => item.Agenda.Date) .ThenBy(item => item.OutcomeType) .ThenBy(item => item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) ```
60,805
<p>How do I select one or more random rows from a table using SQLAlchemy? </p>
[ { "answer_id": 60811, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": -1, "selected": false, "text": "<p>Theres a couple of ways through SQL, depending on which data base is being used.</p>\n\n<p>(I think SQLAlchemy can use all these anyways)</p>\n\n<p>mysql:</p>\n\n<pre><code>SELECT colum FROM table\nORDER BY RAND()\nLIMIT 1\n</code></pre>\n\n<p>PostgreSQL:</p>\n\n<pre><code>SELECT column FROM table\nORDER BY RANDOM()\nLIMIT 1\n</code></pre>\n\n<p>MSSQL:</p>\n\n<pre><code>SELECT TOP 1 column FROM table\nORDER BY NEWID()\n</code></pre>\n\n<p>IBM DB2:</p>\n\n<pre><code>SELECT column, RAND() as IDX\nFROM table\nORDER BY IDX FETCH FIRST 1 ROWS ONLY\n</code></pre>\n\n<p>Oracle:</p>\n\n<pre><code>SELECT column FROM\n(SELECT column FROM table\nORDER BY dbms_random.value)\nWHERE rownum = 1\n</code></pre>\n\n<p>However I don't know of any standard way</p>\n" }, { "answer_id": 60815, "author": "Łukasz", "author_id": 4999, "author_profile": "https://Stackoverflow.com/users/4999", "pm_score": 8, "selected": true, "text": "<p>This is very much a database-specific issue.</p>\n\n<p>I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:</p>\n\n<pre><code>from sqlalchemy.sql.expression import func, select\n\nselect.order_by(func.random()) # for PostgreSQL, SQLite\n\nselect.order_by(func.rand()) # for MySQL\n\nselect.order_by('dbms_random.value') # For Oracle\n</code></pre>\n\n<p>Next, you need to limit the query by the number of records you need (for example using <code>.limit()</code>).</p>\n\n<p>Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; <a href=\"http://www.depesz.com/index.php/2007/09/16/my-thoughts-on-getting-random-row/\" rel=\"noreferrer\">here</a> is good article about it.</p>\n" }, { "answer_id": 390676, "author": "David Raznick", "author_id": 20842, "author_profile": "https://Stackoverflow.com/users/20842", "pm_score": 5, "selected": false, "text": "<p>If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.</p>\n\n<pre><code>import random\nrand = random.randrange(0, session.query(Table).count()) \nrow = session.query(Table)[rand]\n</code></pre>\n\n<p>This is cheating slightly but thats why you use an orm.</p>\n" }, { "answer_id": 14906244, "author": "GuySoft", "author_id": 311268, "author_profile": "https://Stackoverflow.com/users/311268", "pm_score": 5, "selected": false, "text": "<p>There is a simple way to pull a random row that IS database independent.\nJust use .offset() . No need to pull all rows:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import random\nquery = DBSession.query(Table)\nrowCount = int(query.count())\nrandomRow = query.offset(int(rowCount*random.random())).first()\n</code></pre>\n\n<p>Where Table is your table (or you could put any query there).\nIf you want a few rows, then you can just run this multiple times, and make sure that each row is not identical to the previous.</p>\n" }, { "answer_id": 21242325, "author": "med116", "author_id": 1784279, "author_profile": "https://Stackoverflow.com/users/1784279", "pm_score": -1, "selected": false, "text": "<h2>this solution will select a single random row</h2>\n\n<p>This solution requires that the primary key is named id, it should be if its not already: </p>\n\n<pre><code>import random\nmax_model_id = YourModel.query.order_by(YourModel.id.desc())[0].id\nrandom_id = random.randrange(0,max_model_id)\nrandom_row = YourModel.query.get(random_id)\nprint random_row\n</code></pre>\n" }, { "answer_id": 33583008, "author": "Jeff Widman", "author_id": 770425, "author_profile": "https://Stackoverflow.com/users/770425", "pm_score": 5, "selected": false, "text": "<p>Here's four different variations, ordered from slowest to fastest. <code>timeit</code> results at the bottom:</p>\n\n<pre><code>from sqlalchemy.sql import func\nfrom sqlalchemy.orm import load_only\n\ndef simple_random():\n return random.choice(model_name.query.all())\n\ndef load_only_random():\n return random.choice(model_name.query.options(load_only('id')).all())\n\ndef order_by_random():\n return model_name.query.order_by(func.random()).first()\n\ndef optimized_random():\n return model_name.query.options(load_only('id')).offset(\n func.floor(\n func.random() *\n db.session.query(func.count(model_name.id))\n )\n ).limit(1).all()\n</code></pre>\n\n<p><code>timeit</code> results for 10,000 runs on my Macbook against a PostgreSQL table with 300 rows:</p>\n\n<pre><code>simple_random(): \n 90.09954111799925\nload_only_random():\n 65.94714171699889\norder_by_random():\n 23.17819356000109\noptimized_random():\n 19.87806927999918\n</code></pre>\n\n<p>You can easily see that using <code>func.random()</code> is far faster than returning all results to Python's <code>random.choice()</code>. </p>\n\n<p>Additionally, as the size of the table increases, the performance of <code>order_by_random()</code> will degrade significantly because an <code>ORDER BY</code> requires a full table scan versus the <code>COUNT</code> in <code>optimized_random()</code> can use an index.</p>\n" }, { "answer_id": 42780139, "author": "ChickenFeet", "author_id": 5387193, "author_profile": "https://Stackoverflow.com/users/5387193", "pm_score": 0, "selected": false, "text": "<p>This is the solution I use:</p>\n\n<pre><code>from random import randint\n\nrows_query = session.query(Table) # get all rows\nif rows_query.count() &gt; 0: # make sure there's at least 1 row\n rand_index = randint(0,rows_query.count()-1) # get random index to rows \n rand_row = rows_query.all()[rand_index] # use random index to get random row\n</code></pre>\n" }, { "answer_id": 50345203, "author": "Charles Wang", "author_id": 3155630, "author_profile": "https://Stackoverflow.com/users/3155630", "pm_score": 2, "selected": false, "text": "<p><strong>This is my function to select random row(s) of a table:</strong> </p>\n\n<pre><code>from sqlalchemy.sql.expression import func\n\ndef random_find_rows(sample_num):\n if not sample_num:\n return []\n\n session = DBSession()\n return session.query(Table).order_by(func.random()).limit(sample_num).all()\n</code></pre>\n" }, { "answer_id": 52692368, "author": "Ilja Everilä", "author_id": 2681632, "author_profile": "https://Stackoverflow.com/users/2681632", "pm_score": 3, "selected": false, "text": "<p>Some SQL DBMS, namely Microsoft SQL Server, DB2, and <a href=\"https://www.postgresql.org/docs/current/static/sql-select.html#SQL-FROM\" rel=\"nofollow noreferrer\">PostgreSQL</a> have implemented the SQL:2003 <code>TABLESAMPLE</code> clause. Support was added to SQLAlchemy <a href=\"https://bitbucket.org/zzzeek/sqlalchemy/issues/3718\" rel=\"nofollow noreferrer\">in version 1.1</a>. It allows returning a sample of a table using different sampling methods – the standard requires <code>SYSTEM</code> and <code>BERNOULLI</code>, which return a desired approximate percentage of a table.</p>\n<p>In SQLAlchemy <a href=\"https://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.FromClause.tablesample\" rel=\"nofollow noreferrer\"><code>FromClause.tablesample()</code></a> and <a href=\"https://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.tablesample\" rel=\"nofollow noreferrer\"><code>tablesample()</code></a> are used to produce a <a href=\"https://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.TableSample\" rel=\"nofollow noreferrer\"><code>TableSample</code></a> construct:</p>\n<pre><code># Approx. 1%, using SYSTEM method\nsample1 = mytable.tablesample(1)\n\n# Approx. 1%, using BERNOULLI method\nsample2 = mytable.tablesample(func.bernoulli(1))\n</code></pre>\n<p>There's a slight gotcha when used with mapped classes: the produced <code>TableSample</code> object must be aliased in order to be used to query model objects:</p>\n<pre><code>sample = aliased(MyModel, tablesample(MyModel, 1))\nres = session.query(sample).all()\n</code></pre>\n<hr />\n<p>Since many of the answers contain performance benchmarks, I'll include some simple tests here as well. Using a simple table in PostgreSQL with about a million rows and a single integer column, select (approx.) 1% sample:</p>\n<pre><code>In [24]: %%timeit\n ...: foo.select().\\\n ...: order_by(func.random()).\\\n ...: limit(select([func.round(func.count() * 0.01)]).\n ...: select_from(foo).\n ...: as_scalar()).\\\n ...: execute().\\\n ...: fetchall()\n ...: \n307 ms ± 5.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [25]: %timeit foo.tablesample(1).select().execute().fetchall()\n6.36 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [26]: %timeit foo.tablesample(func.bernoulli(1)).select().execute().fetchall()\n19.8 ms ± 381 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n<p>Before rushing to use <code>SYSTEM</code> sampling method one should know that it samples <em>pages</em>, not individual tuples, so it might not be suitable for small tables, for example, and may not produce as random results, if the table is clustered.</p>\n<hr />\n<p>If using a dialect that does not allow passing the sample percentage / number of rows and seed as parameters, and a driver that does not inline values, then either pass the values as literal SQL text <em>if they are static</em>, or inline them using a custom SQLA compiler extension:</p>\n<pre><code>from sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql import TableSample\n\n@compiles(TableSample)\ndef visit_tablesample(tablesample, self, asfrom=False, **kw):\n &quot;&quot;&quot; Compile `TableSample` with values inlined.\n &quot;&quot;&quot;\n kw_literal_binds = {**kw, &quot;literal_binds&quot;: True}\n text = &quot;%s TABLESAMPLE %s&quot; % (\n self.visit_alias(tablesample, asfrom=True, **kw),\n tablesample._get_method()._compiler_dispatch(self, **kw_literal_binds),\n )\n\n if tablesample.seed is not None:\n text += &quot; REPEATABLE (%s)&quot; % (\n tablesample.seed._compiler_dispatch(self, **kw_literal_binds)\n )\n\n return text\n\nfrom sqlalchemy import table, literal, text\n\n# Static percentage\nprint(table(&quot;tbl&quot;).tablesample(text(&quot;5 PERCENT&quot;)))\n# Compiler inlined values\nprint(table(&quot;tbl&quot;).tablesample(5, seed=literal(42)))\n</code></pre>\n" }, { "answer_id": 62321734, "author": "Anas", "author_id": 12861001, "author_profile": "https://Stackoverflow.com/users/12861001", "pm_score": -1, "selected": false, "text": "<p>Use this simplest method\nthis example on choosing a random question from the database:-</p>\n\n<pre><code>#first import the random module\nimport random\n\n#then choose what ever Model you want inside random.choise() method\nget_questions = random.choice(Question.query.all())\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
How do I select one or more random rows from a table using SQLAlchemy?
This is very much a database-specific issue. I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy: ``` from sqlalchemy.sql.expression import func, select select.order_by(func.random()) # for PostgreSQL, SQLite select.order_by(func.rand()) # for MySQL select.order_by('dbms_random.value') # For Oracle ``` Next, you need to limit the query by the number of records you need (for example using `.limit()`). Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; [here](http://www.depesz.com/index.php/2007/09/16/my-thoughts-on-getting-random-row/) is good article about it.
60,820
<p>Does anyone know of a way to find out how much memory an instance of an object is taking?</p> <p>For example, if I have an instance of the following object:</p> <pre><code>TestClass tc = new TestClass(); </code></pre> <p>Is there a way to find out how much memory the instance <code>tc</code> is taking?</p> <p>The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).</p> <p>There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools. </p>
[ { "answer_id": 60829, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p>I have good experiences with <a href=\"http://memprofiler.com/\" rel=\"nofollow noreferrer\">MemProfiler</a>. It gives you stack traces of when the object was created and all the graphs of why the object is still not garbage collected.</p>\n" }, { "answer_id": 60834, "author": "Alex Duggleby", "author_id": 5790, "author_profile": "https://Stackoverflow.com/users/5790", "pm_score": 3, "selected": false, "text": "<p>If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.</p>\n<p>Download here: <a href=\"https://github.com/MicrosoftArchive/clrprofiler\" rel=\"nofollow noreferrer\">https://github.com/MicrosoftArchive/clrprofiler</a></p>\n<p>If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here:\n<a href=\"http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx</a></p>\n<p>(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)</p>\n" }, { "answer_id": 60837, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=a362781c-3870-43be-8926-862b40aa0cd0&amp;displaylang=en\" rel=\"nofollow noreferrer\">CLR Profiler</a>, which is provide free by Microsoft does a very good job at this type of thing. </p>\n\n<p>An introduction to the whole profiler can be downloaded <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=CD5AA57C-9CD1-45AB-AA4B-8DC586D30938&amp;displaylang=en\" rel=\"nofollow noreferrer\">here</a>. Also the Patterns &amp; Practices team <a href=\"http://msdn.microsoft.com/en-us/library/ms979205.aspx\" rel=\"nofollow noreferrer\">put something</a> together a while back detailing how to use the profiler.</p>\n\n<p>It does a fairly reasonable job at showing you the different threads and objects created in those threads.</p>\n\n<p>Hope this sheds some light. Happy profiling!</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6301/" ]
Does anyone know of a way to find out how much memory an instance of an object is taking? For example, if I have an instance of the following object: ``` TestClass tc = new TestClass(); ``` Is there a way to find out how much memory the instance `tc` is taking? The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something). There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools.
If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek. Download here: <https://github.com/MicrosoftArchive/clrprofiler> If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here: <http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx> (It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)
60,825
<p>I am working on a web application, where I transfer data from the server to the browser in XML.</p> <p>Since I'm danish, I quickly run into problems with the characters <code>æøå</code>.</p> <p>I know that in html, I use the <code>"&amp;amp;aelig;&amp;amp;oslash;&amp;amp;aring;"</code> for <code>æøå</code>.</p> <p>however, as soon as the chars pass through JavaScript, I get black boxes with <code>"?"</code> in them when using <code>æøå</code>, and <code>"&amp;aelig;&amp;oslash;&amp;aring;"</code> is printed as is.</p> <p>I've made sure to set it to utf-8, but that isn't helping much.</p> <p>Ideally, I want it to work with any special characters (naturally).</p> <p>The example that isn't working is included below:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8"&gt; alert("&amp;aelig;&amp;oslash;&amp;aring;"); alert("æøå"); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What am I doing wrong?</p> <hr> <p>Ok, thanks to Grapefrukts answer, I got it working.</p> <p>I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP:</p> <p><code>utf8_encode($MyStringHere)</code></p>
[ { "answer_id": 60832, "author": "chryss", "author_id": 5169, "author_profile": "https://Stackoverflow.com/users/5169", "pm_score": 0, "selected": false, "text": "<p>This works as expected for me:</p>\n\n<pre><code>alert(\"&amp;aelig;&amp;oslash;&amp;aring;\");\n</code></pre>\n\n<p>... creates an alert containing the string \"&amp;aelig;&amp;oslash;&amp;aring;\" whereas</p>\n\n<pre><code>alert(\"æøå\");\n</code></pre>\n\n<p>... creates an alert with the non-ascii characters.</p>\n\n<p>Javascript is pretty utf-8 clean and doesn't tend to put obstacles in your way.</p>\n\n<p>Maybe you're putting this on a web server that serves it as ISO-8859-1? If you use Apache, in your Apache config file (or in .httaccess, if you can override), you should have a line</p>\n\n<pre><code>AddCharset utf-8 .js\n</code></pre>\n\n<p>(Note: edited to escape the ampersands... otherwise it didn't make sense.)</p>\n" }, { "answer_id": 60843, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "<p>I get \"&amp;aelig;&amp;oslash;&amp;aring;\" for the first one and some junk characters for the next. Could it be that the javascript is not mangling (or <a href=\"http://en.wikipedia.org/wiki/Mojibake\" rel=\"nofollow noreferrer\">mojibake</a>) your letters but the alert dialog uses the system default font, and the font is incapable of displaying the letters?</p>\n" }, { "answer_id": 60851, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 5, "selected": true, "text": "<p>Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work!</p>\n" }, { "answer_id": 67289, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 3, "selected": false, "text": "<p>You can also use <code>String.fromCharCode()</code> to output a character from a numeric entity.</p>\n\n<p>e.g. <code>String.fromCharCode( 8226 )</code> will create a bullet character.</p>\n" }, { "answer_id": 144878, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 5, "selected": false, "text": "<p>If you ever can't set the response encoding, you can use <code>\\u</code> escape sequence in the JavaScript string literal to display these characters.</p>\n\n<pre><code>alert(\"\\u00e6\\u00f8\\u00e5\")\n</code></pre>\n" }, { "answer_id": 17870496, "author": "Kayun Chantarasathaporn", "author_id": 2620771, "author_profile": "https://Stackoverflow.com/users/2620771", "pm_score": 1, "selected": false, "text": "<p>I use the code like this with Thai language. It's fine.</p>\n\n<p><code>$message</code> is my PHP variable.</p>\n\n<pre><code>echo(\"&lt;html&gt;&lt;head&gt;&lt;meta charset='utf-8'&gt;&lt;/head&gt;&lt;body&gt;&lt;script type='text/javascript'&gt;alert('\" . $message . \"');&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;\");\n</code></pre>\n\n<p>Hope this can help. Thank you.</p>\n\n<p>(I cannot post image of what I did as the system said \"I don't have enough reputation\", so I leave the image, here. <a href=\"http://goo.gl/9P3DtI\" rel=\"nofollow\">http://goo.gl/9P3DtI</a> Sorry for inconvenience.)</p>\n\n<p>Sorry for my weak English.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
I am working on a web application, where I transfer data from the server to the browser in XML. Since I'm danish, I quickly run into problems with the characters `æøå`. I know that in html, I use the `"&amp;aelig;&amp;oslash;&amp;aring;"` for `æøå`. however, as soon as the chars pass through JavaScript, I get black boxes with `"?"` in them when using `æøå`, and `"&aelig;&oslash;&aring;"` is printed as is. I've made sure to set it to utf-8, but that isn't helping much. Ideally, I want it to work with any special characters (naturally). The example that isn't working is included below: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" charset="utf-8"> alert("&aelig;&oslash;&aring;"); alert("æøå"); </script> </head> <body> </body> </html> ``` What am I doing wrong? --- Ok, thanks to Grapefrukts answer, I got it working. I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP: `utf8_encode($MyStringHere)`
Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work!
60,874
<p>I know a few advanced ways, to change directories. <code>pushd</code> and <code>popd</code> (directory stack) or <code>cd -</code> (change to last directory).</p> <p>But I am looking for quick way to achieve the following:</p> <p>Say, I am in a rather deep dir:</p> <pre><code>/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names </code></pre> <p>and I want to switch to </p> <pre><code>/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names </code></pre> <p>Is there a cool/quick/geeky way to do it (without the mouse)?</p>
[ { "answer_id": 60887, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": "<p>Do you mean that the path names are the same, and only one directory name changes (\"a\" becomes \"another\")? In that case:</p>\n\n<pre><code>cd ${PWD/a/another}\n</code></pre>\n\n<p>will switch to the other directory. <code>$PWD</code> holds your current directory, and <code>${var/foo/bar}</code> gives you <code>$var</code> with the string 'foo' replaced by 'bar'.</p>\n" }, { "answer_id": 60936, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>What about setting up your <code>CDPATH</code> variable?</p>\n" }, { "answer_id": 66331, "author": "slipset", "author_id": 9422, "author_profile": "https://Stackoverflow.com/users/9422", "pm_score": 1, "selected": false, "text": "<pre><code>cd ^/a/^/another/\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
I know a few advanced ways, to change directories. `pushd` and `popd` (directory stack) or `cd -` (change to last directory). But I am looking for quick way to achieve the following: Say, I am in a rather deep dir: ``` /this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names ``` and I want to switch to ``` /this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names ``` Is there a cool/quick/geeky way to do it (without the mouse)?
Do you mean that the path names are the same, and only one directory name changes ("a" becomes "another")? In that case: ``` cd ${PWD/a/another} ``` will switch to the other directory. `$PWD` holds your current directory, and `${var/foo/bar}` gives you `$var` with the string 'foo' replaced by 'bar'.
60,877
<p>I have a query where I wish to retrieve the oldest X records. At present my query is something like the following:</p> <pre><code>SELECT Id, Title, Comments, CreatedDate FROM MyTable WHERE CreatedDate &gt; @OlderThanDate ORDER BY CreatedDate DESC </code></pre> <p>I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.</p> <p>So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.</p>
[ { "answer_id": 60882, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 6, "selected": true, "text": "<p>Why not just use a subquery?</p>\n\n<pre><code>SELECT T1.* \nFROM\n(SELECT TOP X Id, Title, Comments, CreatedDate\nFROM MyTable\nWHERE CreatedDate > @OlderThanDate\nORDER BY CreatedDate) T1\nORDER BY CreatedDate DESC\n</code></pre>\n" }, { "answer_id": 60883, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 1, "selected": false, "text": "<p>Embed the query. You take the top x when sorted in ascending order (i.e. the oldest) and then re-sort those in descending order ... </p>\n\n<pre><code>select * \nfrom \n(\n SELECT top X Id, Title, Comments, CreatedDate\n FROM MyTable\n WHERE CreatedDate &gt; @OlderThanDate\n ORDER BY CreatedDate \n) a\norder by createddate desc \n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5086/" ]
I have a query where I wish to retrieve the oldest X records. At present my query is something like the following: ``` SELECT Id, Title, Comments, CreatedDate FROM MyTable WHERE CreatedDate > @OlderThanDate ORDER BY CreatedDate DESC ``` I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first. So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.
Why not just use a subquery? ``` SELECT T1.* FROM (SELECT TOP X Id, Title, Comments, CreatedDate FROM MyTable WHERE CreatedDate > @OlderThanDate ORDER BY CreatedDate) T1 ORDER BY CreatedDate DESC ```
60,893
<p>In my application I have <code>TextBox</code> in a <code>FormView</code> bound to a <code>LinqDataSource</code> like so:</p> <pre><code>&lt;asp:TextBox ID="MyTextBox" runat="server" Text='&lt;%# Bind("MyValue") %&gt;' AutoPostBack="True" ontextchanged="MyTextBox_TextChanged" /&gt; protected void MyTextBox_TextChanged(object sender, EventArgs e) { MyFormView.UpdateItem(false); } </code></pre> <p>This is inside an <code>UpdatePanel</code> so any change to the field is immediately persisted. Also, the value of <code>MyValue</code> is <code>decimal?</code>. This works fine unless I enter any string which cannot be converted to decimal into the field. In that case, the <code>UpdateItem</code> call throws: </p> <blockquote> <p><strong>LinqDataSourceValidationException</strong> - Failed to set one or more properties on type MyType. asdf is not a valid value for Decimal.</p> </blockquote> <p>I understand the problem, ASP.NET does not know how to convert from 'asdf' to decimal?. What I would like it to do is convert all these invalid values to null. What is the best way to do this?</p>
[ { "answer_id": 60902, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 1, "selected": false, "text": "<p>I find Robert Martin's <a href=\"http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd\" rel=\"nofollow noreferrer\">Test Driven Development</a> \n(TDD) approach helps with these concerns.</p>\n\n<p>Why?</p>\n\n<ul>\n<li>You only have to write enough code to pass the next test.</li>\n<li>I think testable code is cleaner.</li>\n<li>The design has to feed into tests which can help keep the design focused.</li>\n<li>When you do have to change (refactor) you have tests to fall back on</li>\n</ul>\n\n<p>Regardless of when the test are written (before or after) I find writing \nthe test helps you make practical decisions. E.g., we picked design A or B because \nA is more testable.</p>\n" }, { "answer_id": 60903, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 0, "selected": false, "text": "<p>That's why it's always easier to write nice \"acadamic papers\" talking about how Agile development is good, what are the \"best practices\" and so on.</p>\n\n<p>That's why you find a lot of \"suited engineers\" making up new software engineering techniques.</p>\n\n<p>Process is important, keeping best practices is cool but over any other thing, common sense drive design process. Software is developed by people so YAGNI really should be: </p>\n\n<p>I might not gonna needed but maybe I will because in my concrete bussiness/company/department this thing do happen or I will need it but I just haven't the time right no so quick and dirty hack to make the cash and keep my job, or I might need it and refactoring later will be a pain in the ass costing 10 times more than just doing it now from the scratch, and I have the time NOW.</p>\n\n<p>So use your common sense, trust it or trust the common sense of the people working for you. Don't take every academic paper as proven fact, experience is the best teacher and your company should improve their way or making things with time and its own experience.</p>\n\n<p><strong>Edit:</strong> Incidentally, TDD is the opposite of YAGNI you're building test before even knowing if you are gonna need them. Seriously, stop listening to academics!! There's no magical way to produce software.</p>\n" }, { "answer_id": 60916, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 1, "selected": false, "text": "<p>The 'traditional' XP answer is refactoring combined with automated unit testing.</p>\n\n<p>But it's a very interesting question philosophically. I don't believe you need to <em>avoid</em> technical debt, just keep it at a manageable level. Steve McConnell's article is good on this balance - the reason the analogy works is that it's normal and acceptable to build up financial debt in a company, as long as you accept the costs and risks - and technical debt is fine too.</p>\n\n<p>Maybe the answer itself also lies in the principle of YAGNI. You Ain't Gonna Need the technical debt paid off until you do, and that's when you do the refactor. When you're doing substantial work on an area of the system with technical debt, take a look at how much short-term difference it will make to do the redesign. If it's enough to make it worthwhile, pay it off. McConnell's suggestion of maintaining a debt list will help you to know when to make this consideration.</p>\n\n<p>I don't suppose there is an absolute answer to this - like many things it's a judgment call based on your experience, intuition and your analysis in each particular situation.</p>\n" }, { "answer_id": 60947, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>Surely being agile is going to keep your TD down for any given project?</p>\n\n<p>The fact that you are implementing what the customer wants, i.e. with their feedback, is keeping TD to a minimum,</p>\n" }, { "answer_id": 61464, "author": "Jack Bolding", "author_id": 5882, "author_profile": "https://Stackoverflow.com/users/5882", "pm_score": 2, "selected": false, "text": "<p>There was an interesting discussion of Technical Debt based on your definition of done on HanselMinutes a couple of weeks ago -- <a href=\"http://www.hanselminutes.com/default.aspx?showID=137\" rel=\"nofollow noreferrer\">What is Done</a>. The basics of the show were that if you re-define 'Done' to increase perceived velocity, then you will amass Technical Debt. The corollary of this is that if you do not have a proper definition of 'Done' then you most likely are acquiring a list of items that will need to be finished before release irrespective of the design methodology.</p>\n" }, { "answer_id": 74367, "author": "Steve Duitsman", "author_id": 4575, "author_profile": "https://Stackoverflow.com/users/4575", "pm_score": 2, "selected": false, "text": "<p>It seems that if you stick with the \"plan, do, adapt; plan, do, adapt\" idea of agile (iterations, iteration reviews) you would avoid those things by default. BDUF is just so contrary to the idea of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131479415\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">agile estimating &amp; planning</a> that if you are really agile, you wont be BDUF automatically.</p>\n\n<p>The purpose of release &amp; iteration planning meetings is to make sure you are adding the most valuable features to the project for that iteration. If you keep that in mind, you'll avoid YAGNI for free. </p>\n\n<p>I would very strongly recommend the Mike Cohn books on agile planning:</p>\n\n<ol>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321205685\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">User Stories Applied</a> </li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0131479415\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Estimating and Planning</a></li>\n</ol>\n\n<hr>\n\n<p><strong>Update:</strong> After your clarification about avoiding YAGNI and BDUF within an iteration...</p>\n\n<p><strong>BDUF</strong>...If I felt a feature was not clearly defined before I started work on it, I would create a small \"feature\" or story to account for the design type portion of the work needed. So that maybe the smaller story has a <a href=\"http://en.wikipedia.org/wiki/Story_points\" rel=\"nofollow noreferrer\">story point</a> estimate of 1 instead of the real feature's 5. That way, the design is time-boxed into the smaller story, and you will be driven to move on to the feature itself.</p>\n\n<p>To avoid <strong>violating YAGNI</strong> I would work to be very clear about what the customer expects for a feature within an iteration. Only do work that maps to what the customer expects. If you think something extra should be added, create a new feature for it, and add it to the <a href=\"http://en.wikipedia.org/wiki/Scrum_(development)#Documents\" rel=\"nofollow noreferrer\">backlog of work</a> to be done. You would then persuade the customer to see the benefit of it; just as the customer would push for a feature being done at a certain point in time. </p>\n" }, { "answer_id": 76038, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "<p>You seem to say that \"YAGNI\" implies \"quick and dirty\". I do not see that.</p>\n\n<p>As an agile programmer, I practice test-driven development, code review and continuous integration.</p>\n\n<ul>\n<li>Test-driven development (TDD), as a process, is a good way to avoid YAGNI. Code that's just there \"in case it will be useful\" tends to be untested and hard to test.</li>\n<li>TDD also largely removes the compulsion to BDUF: when your process is to start by sitting down and start doing something that actually delivers value, you cannot indulge in BDUF.</li>\n<li>TDD, as a design practice means that the big design will emerge as you gain experience with the problem, and refactor real code.</li>\n<li>Continous integration means that you design your process so your product is essentially releasable at any time. That means that you have a integrated quality process that tries to prevent the quality of the mainline from dropping.</li>\n</ul>\n\n<p>In my experience, the main forms of technical debt are:</p>\n\n<ul>\n<li>Code not covered by the automated test suite. Do not allow that to happen, except for very localized components that are especially hard to test. Untested code is broken code.</li>\n<li>Ugly code that violates the coding standard. Do not allow that to happen. That is one of the reasons why you need to build code review into the continous integration process.</li>\n<li>Code and tests that smell and need refactoring to be more easily modified or understood. This is the benign form of technical debt. Use your experience to know when to accumulate it, and when to repay it.</li>\n</ul>\n\n<p>Not sure if that answered your question, but I had fun writing it.</p>\n\n<blockquote>\n <p>Troy DeMonbreun commented:</p>\n \n <blockquote>\n <p>No, that wasn't my point... \"quick and dirty\" = (unintentionally risking Technical Debt while attempting to adhere to YAGNI\"). That does not mean YAGNI is only quick and dirty. The phrase \"quick and dirty\" is what I used to quote Martin Fowler in his description of Technical Debt</p>\n </blockquote>\n</blockquote>\n\n<p>Avoiding <a href=\"http://c2.com/xp/YouArentGonnaNeedIt.html\" rel=\"nofollow noreferrer\">YAGNI</a> is another way of saying <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a>. YAGNI increases the <a href=\"http://www.martinfowler.com/bliki/TechnicalDebt.html\" rel=\"nofollow noreferrer\">technical debt</a>. There is no tension between between avoiding YAGNI and keeping the technical debt low.</p>\n\n<p>I think I might still be missing the point of your question.</p>\n" }, { "answer_id": 387807, "author": "John Rayner", "author_id": 46473, "author_profile": "https://Stackoverflow.com/users/46473", "pm_score": 1, "selected": false, "text": "<p>Just do the <a href=\"http://www.xprogramming.com/Practices/PracSimplest.html\" rel=\"nofollow noreferrer\">simplest thing that works</a>. I agree with Ayende when he says that <a href=\"http://ayende.com/Blog/archive/2008/12/21/the-tests-has-no-value-by-themselves-my-most-successful.aspx\" rel=\"nofollow noreferrer\">the key to being agile</a> is to \"ship it, often\". A regular release cycle like this will mean that there is no time for BDUF and it will also dissuade developers from violating YAGNI.</p>\n" }, { "answer_id": 1506504, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 1, "selected": false, "text": "<p>Where I work, I believe the way we avoid the debt is by spinning through the cycle quickly, i.e. showing functionality to the would be end user and get either a sign off that it should be pushed to test or a rejection to say what was wrong giving an updated requirement. By doing this repeatedly within an iteration, a lot of changes can be found about what the user wants by trying this and that. </p>\n\n<p>A key point is to try to do exactly what the user wants as doing more violates YAGNI and brings in BDUF while the idea of refining the requirements over and over again is at the heart of Agile to my mind.</p>\n" }, { "answer_id": 45579080, "author": "Brad G.", "author_id": 8396288, "author_profile": "https://Stackoverflow.com/users/8396288", "pm_score": 0, "selected": false, "text": "<p>The problem may actually be at a higher level: with management and product owners concerned with deadlines as opposed to the developers themselves.</p>\n\n<p>At my last place of employment, I worked on legacy code but was in contact with people developing brand new code using (supposedly) Agile and TDD. </p>\n\n<p>Now TDD is supposed to be Red - Green - Refactor: write failing tests, do the minimum to pass the test, then rework the code to make it more maintainable while making sure it still passes the test.</p>\n\n<p><em>But</em>… progress was measured by how quickly user stories got implemented, i.e. how quickly new functionality got added. The thing about refactoring is it doesn’t add any new functionality. Yes, it is very important but it doesn’t have the same immediate impact as showing the product owner the new functionality or even the lines of test code to go with it.</p>\n\n<p>As deadlines loomed closer, and overtime became standard, there was the incentive to skimp on the refactoring part. The more one does this, the more quickly one gets thru the user stories, which seemed to be what management cared about.</p>\n\n<p>Now, this <em>did</em> lead to technical debt because on a number of occasions to get the next user story done it turned out to be necessary to go back and refactor - really rewrite - code for the previous bunch of user stories. Management became irate at this because from their point of view the user story in question did not look to be all that different from the previous ones so why was the estimate for it 10 times longer?</p>\n\n<p>(There was an ugly game theory aspect to things as well. If you or your team <em>were</em> conscientious about refactoring that didn't prevent you from getting stuck cleaning up after another team that <em>wasn't</em>. Of course, that other team looked better because they got more user stories done in the same amount of time.)</p>\n\n<p>My point here is perhaps TDD does not lead to technical debt if done properly. But for it to be done properly there must be genuine buy in from higher up.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
In my application I have `TextBox` in a `FormView` bound to a `LinqDataSource` like so: ``` <asp:TextBox ID="MyTextBox" runat="server" Text='<%# Bind("MyValue") %>' AutoPostBack="True" ontextchanged="MyTextBox_TextChanged" /> protected void MyTextBox_TextChanged(object sender, EventArgs e) { MyFormView.UpdateItem(false); } ``` This is inside an `UpdatePanel` so any change to the field is immediately persisted. Also, the value of `MyValue` is `decimal?`. This works fine unless I enter any string which cannot be converted to decimal into the field. In that case, the `UpdateItem` call throws: > > **LinqDataSourceValidationException** - > Failed to set one or more properties on type MyType. asdf is not a valid value for Decimal. > > > I understand the problem, ASP.NET does not know how to convert from 'asdf' to decimal?. What I would like it to do is convert all these invalid values to null. What is the best way to do this?
There was an interesting discussion of Technical Debt based on your definition of done on HanselMinutes a couple of weeks ago -- [What is Done](http://www.hanselminutes.com/default.aspx?showID=137). The basics of the show were that if you re-define 'Done' to increase perceived velocity, then you will amass Technical Debt. The corollary of this is that if you do not have a proper definition of 'Done' then you most likely are acquiring a list of items that will need to be finished before release irrespective of the design methodology.
60,910
<p>I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. </p>
[ { "answer_id": 60940, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 3, "selected": false, "text": "<p>From the <a href=\"http://www.emacswiki.org/cgi-bin/wiki/AquamacsFAQ#toc7\" rel=\"noreferrer\">EmacsWiki Aquamacs FAQ</a>:</p>\n<blockquote>\n<p>To change the font used to display the\ncurrent frame, go to the font panel.\nYou can do this with the keystroke\nApple-t, or via the menu: Options →\nShow/Hide → Font Panel. Once there,\nselect the font you want.</p>\n<p>To make the current frame’s font the\ndefault, go to Options → Frame\nAppearance Styles. Select “use current\nstyle for foo mode”, where foo is the\nmode of the current frame (e.g.,\nfoo=text for text mode), to use the\ncurrent style (including the font, but\nalso any other changes you’ve made to\nthe frame’s style) for all files of\nthis type. Select “use current style\nas default” to use the current style\nfor all files for whose major mode no\nspecial style has been defined.</p>\n</blockquote>\n<p>There are also recommendations for monospaced fonts - Monaco or &quot;Vera Sans Mono&quot;.</p>\n" }, { "answer_id": 60948, "author": "Natalie Weizenbaum", "author_id": 2518, "author_profile": "https://Stackoverflow.com/users/2518", "pm_score": 4, "selected": true, "text": "<p>This is what I have in my .emacs for OS X:</p>\n\n<pre><code>(set-default-font \"-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman\")\n</code></pre>\n\n<p>Now, I'm not sure Bitstream Vera comes standard on OS X, so you may have to either download it or choose a different font. You can search the X font names by running <code>(x-list-fonts \"searchterm\")</code> in an ELisp buffer (e.g. <code>*scratch*</code> - to run it, type it in and then type <code>C-j</code> on the same line).</p>\n" }, { "answer_id": 2424197, "author": "fikovnik", "author_id": 219584, "author_profile": "https://Stackoverflow.com/users/219584", "pm_score": 2, "selected": false, "text": "<p>this is the one I use:</p>\n\n<pre><code> -apple-DejaVu_Sans_Mono-medium-normal-normal-*-12-*-*-*-m-0-iso10646-1\n</code></pre>\n\n<p>You can set it in .emacs file like:</p>\n\n<pre><code>(set-default-font \"-apple-DejaVu_Sans_Mono-medium-normal-normal-*-12-*-*-*-m-0-iso10646-1\")\n</code></pre>\n\n<p>You can download it from <a href=\"http://dejavu-fonts.org/wiki/index.php?title=Download\" rel=\"nofollow noreferrer\">dejavu-fonts.org</a></p>\n" }, { "answer_id": 3615144, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 4, "selected": false, "text": "<p>In Aquamacs 2.1, you can set the font through Options->Appearance->Font for Text Mode... That brings up the standard font chooser window, choose the font you like. Then, when you exit out of emacs (C-x C-c) you'll be prompted to save options, hit \"y\".</p>\n" }, { "answer_id": 58135994, "author": "chrisinmtown", "author_id": 1630244, "author_profile": "https://Stackoverflow.com/users/1630244", "pm_score": 1, "selected": false, "text": "<p>Fast forward a decade, for recent Aquamacs like ver 3.3 please see the nice solution for setting a fixed-width by default at <a href=\"https://emacs.stackexchange.com/questions/45135/change-permanently-font-size-in-aquamacs\">https://emacs.stackexchange.com/questions/45135/change-permanently-font-size-in-aquamacs</a></p>\n\n<p>Here's the relevant bit for those who are REALLY impatient but please go upvote that answer, user @nega deserves credit here</p>\n\n<pre><code>(when window-system\n (setq initial-frame-alist nil) ;; Undo Aquamacs forced defaults\n (setq default-frame-alist nil) ;; Undo Aquamacs forced defaults\n (aquamacs-autoface-mode -1) ;; Use one face (font) everywhere\n (set-frame-font \"Menlo-12\") ;; Set the default font to Menlo size 12\n ;;(set-default-font \"Menlo-12\") ;; This would do the same.\n)\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change.
This is what I have in my .emacs for OS X: ``` (set-default-font "-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman") ``` Now, I'm not sure Bitstream Vera comes standard on OS X, so you may have to either download it or choose a different font. You can search the X font names by running `(x-list-fonts "searchterm")` in an ELisp buffer (e.g. `*scratch*` - to run it, type it in and then type `C-j` on the same line).
60,919
<p>Can I use this approach efficiently?</p> <pre><code>using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)) { cmd.Connection.Open(); // set up parameters and CommandType to StoredProcedure etc. etc. cmd.ExecuteNonQuery(); } </code></pre> <p>My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?</p>
[ { "answer_id": 60934, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 8, "selected": true, "text": "<p>No, Disposing of the <code>SqlCommand</code> will not effect the Connection. A better approach would be to also wrap the <code>SqlConnection</code> in a using block as well: </p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(connstring))\n{\n conn.Open();\n using (SqlCommand cmd = new SqlCommand(cmdstring, conn))\n {\n cmd.ExecuteNonQuery();\n }\n}\n</code></pre>\n\n<p>Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should \nbe disposed of as well, and likely more important to dispose of than a command. </p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>I just tested this: </p>\n\n<pre><code>SqlConnection conn = new SqlConnection(connstring);\nconn.Open();\n\nusing (SqlCommand cmd = new SqlCommand(\"select field from table where fieldid = 1\", conn))\n{\n Console.WriteLine(cmd.ExecuteScalar().ToString());\n}\n\nusing (SqlCommand cmd = new SqlCommand(\"select field from table where fieldid = 2\", conn))\n{\n Console.WriteLine(cmd.ExecuteScalar().ToString());\n}\n\nconn.Dispose(); \n</code></pre>\n\n<p>The first command was disposed when the using block was exited. The connection was still open and good for the second command. </p>\n\n<p><strong><em>So, disposing of the command definitely does not dispose of the connection it was using.</em></strong></p>\n" }, { "answer_id": 185227, "author": "user26320", "author_id": 26320, "author_profile": "https://Stackoverflow.com/users/26320", "pm_score": 4, "selected": false, "text": "<p>SqlCommand.Dispose will not be sufficient because many SqlCommand(s) can (re)use the same SqlConnection. Center your focus on the SqlConnection.</p>\n" }, { "answer_id": 5654064, "author": "Chuck Bevitt", "author_id": 704658, "author_profile": "https://Stackoverflow.com/users/704658", "pm_score": -1, "selected": false, "text": "<p>I use this pattern. I have this private method somewhere in my app:</p>\n\n<pre><code>private void DisposeCommand(SqlCommand cmd)\n{\n try\n {\n if (cmd != null)\n {\n if (cmd.Connection != null)\n {\n cmd.Connection.Close();\n cmd.Connection.Dispose();\n }\n cmd.Dispose();\n }\n }\n catch { } //don't blow up\n}\n</code></pre>\n\n<p>Then I always create SQL commands and connections in a try block (but without being wrapped in a using block) and always have a finally block as:</p>\n\n<pre><code> finally\n {\n DisposeCommand(cmd);\n }\n</code></pre>\n\n<p>The connection object being a property of the command object makes a using block awkward in this situation - but this pattern gets the job done without cluttering up your code.</p>\n" }, { "answer_id": 59635946, "author": "Keith Patrick", "author_id": 12670837, "author_profile": "https://Stackoverflow.com/users/12670837", "pm_score": 1, "selected": false, "text": "<p>Soooo many places get this wrong, even MS' own documentation. Just remember - in DB world, almost <em>everything</em> is backed by an unmanaged resource, so almost everything implements IDisposable. Assume a class does unless the compiler tells you otherwise.\nWrap your command in a using. Wrap your <em>connection</em> in a using. Create your connection off a DbProvider (get that from DbProviderFactories.GetFactory), and your command off your connection so that if you change your underlying DB, you only need to change the call to DBPF.GetFactory.\nSo your code should end up looking nice and symmetrical:</p>\n\n<pre><code>var provider = DbProviderFactories.GetFactory(\"System.Data.SqlClient\");// Or MS.Data.SqlClient\nusing (var connection = provider.CreateConnection())\n{\n connection.ConnectionString = \"...\";\n using (var command = connection.CreateCommand())\n {\n command.CommandText = \"...\";\n connection.Open();\n\n using (var reader = command.ExecuteReader())\n {\n...\n }\n }\n}\n</code></pre>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
Can I use this approach efficiently? ``` using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)) { cmd.Connection.Open(); // set up parameters and CommandType to StoredProcedure etc. etc. cmd.ExecuteNonQuery(); } ``` My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?
No, Disposing of the `SqlCommand` will not effect the Connection. A better approach would be to also wrap the `SqlConnection` in a using block as well: ``` using (SqlConnection conn = new SqlConnection(connstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdstring, conn)) { cmd.ExecuteNonQuery(); } } ``` Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should be disposed of as well, and likely more important to dispose of than a command. **EDIT:** I just tested this: ``` SqlConnection conn = new SqlConnection(connstring); conn.Open(); using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn)) { Console.WriteLine(cmd.ExecuteScalar().ToString()); } using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn)) { Console.WriteLine(cmd.ExecuteScalar().ToString()); } conn.Dispose(); ``` The first command was disposed when the using block was exited. The connection was still open and good for the second command. ***So, disposing of the command definitely does not dispose of the connection it was using.***
60,942
<p>I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:</p> <pre><code> proc2 -&gt; stdout / proc1 \ proc3 -&gt; stdout </code></pre> <p>I tried</p> <pre><code> proc1 | (proc2 &amp; proc3) </code></pre> <p>but it doesn't seem to work, i.e.</p> <pre><code> echo 123 | (tr 1 a &amp; tr 1 b) </code></pre> <p>writes</p> <pre><code> b23 </code></pre> <p>to stdout instead of </p> <pre><code> a23 b23 </code></pre>
[ { "answer_id": 60955, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": "<p><sup><em>Editor's note</em>:<br>\n - <code>&gt;(…)</code> is a <a href=\"http://mywiki.wooledge.org/ProcessSubstitution\" rel=\"noreferrer\"><em>process substitution</em></a> that is a <em>nonstandard shell feature</em> of <em>some</em> POSIX-compatible shells: <code>bash</code>, <code>ksh</code>, <code>zsh</code>.<br>\n - This answer accidentally sends the output process substitution's output through the pipeline <em>too</em>: <code>echo 123 | tee &gt;(tr 1 a) | tr 1 b</code>.<br>\n - Output from the process substitutions will be unpredictably interleaved, and, except in <code>zsh</code>, the pipeline may terminate before the commands inside <code>&gt;(…)</code> do.</sup></p>\n\n<p>In unix (or on a mac), use the <a href=\"http://en.wikipedia.org/wiki/Tee_(command)\" rel=\"noreferrer\"><code>tee</code> command</a>:</p>\n\n<pre><code>$ echo 123 | tee &gt;(tr 1 a) &gt;(tr 1 b) &gt;/dev/null\nb23\na23\n</code></pre>\n\n<p>Usually you would use <code>tee</code> to redirect output to multiple files, but using >(...) you can\nredirect to another process. So, in general,</p>\n\n<pre><code>$ proc1 | tee &gt;(proc2) ... &gt;(procN-1) &gt;(procN) &gt;/dev/null\n</code></pre>\n\n<p>will do what you want.</p>\n\n<p>Under windows, I don't think the built-in shell has an equivalent. Microsoft's <a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"noreferrer\">Windows PowerShell</a> has a <code>tee</code> command though. </p>\n" }, { "answer_id": 61716, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>Since @dF: mentioned that PowerShell has tee, I thought I'd show a way to do this in PowerShell. </p>\n\n<pre><code>PS &gt; \"123\" | % { \n $_.Replace( \"1\", \"a\"), \n $_.Replace( \"2\", \"b\" ) \n}\n\na23\n1b3\n</code></pre>\n\n<p>Note that each object coming out of the first command is processed before the next object is created. This can allow scaling to very large inputs.</p>\n" }, { "answer_id": 190777, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "<p>Like dF said, <code>bash</code> allows to use the <code>&gt;(…)</code> construct running a command in place of a filename. (There is also the <code>&lt;(…)</code> construct to substitute the <em>output</em> of another command in place of a filename, but that is irrelevant now, I mention it just for completeness).</p>\n\n<p>If you don't have bash, or running on a system with an older version of bash, you can do manually what bash does, by making use of FIFO files.</p>\n\n<p>The generic way to achieve what you want, is:</p>\n\n<ul>\n<li>decide how many processes should receive the output of your command, and create as many FIFOs, preferably on a global temporary folder: </li>\n</ul>\n\n<pre>\n subprocesses=\"a b c d\"\n mypid=$$\n for i in $subprocesses # this way we are compatible with all sh-derived shells \n do\n mkfifo /tmp/pipe.$mypid.$i\n done\n</pre>\n\n<ul>\n<li>start all your subprocesses waiting input from the FIFOs:</li>\n</ul>\n\n<pre>\n for i in $subprocesses\n do\n tr 1 $i &lt;/tmp/pipe.$mypid.$i & # background!\n done\n</pre>\n\n<ul>\n<li>execute your command teeing to the FIFOs:</li>\n</ul>\n\n<pre>\n proc1 | tee $(for i in $subprocesses; do echo /tmp/pipe.$mypid.$i; done)\n</pre>\n\n<ul>\n<li>finally, remove the FIFOs:</li>\n</ul>\n\n<pre>\n for i in $subprocesses; do rm /tmp/pipe.$mypid.$i; done\n</pre>\n\n<p>NOTE: for compatibility reasons, I would do the <code>$(…)</code> with backquotes, but I couldn't do it writing this answer (the backquote is used in SO). Normally, the <code>$(…)</code> is old enough to work even in old versions of ksh, but if it doesn't, enclose the <code>…</code> part in backquotes.</p>\n" }, { "answer_id": 16541914, "author": "munish", "author_id": 730858, "author_profile": "https://Stackoverflow.com/users/730858", "pm_score": -1, "selected": false, "text": "<p>another way to do would be,</p>\n\n<pre><code> eval `echo '&amp;&amp; echo 123 |'{'tr 1 a','tr 1 b'} | sed -n 's/^&amp;&amp;//gp'`\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>a23\nb23\n</code></pre>\n\n<p>no need to create a subshell here</p>\n" }, { "answer_id": 43906764, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 4, "selected": false, "text": "<h3>Unix (<code>bash</code>, <code>ksh</code>, <code>zsh</code>)</h3>\n\n<p><a href=\"https://stackoverflow.com/q/60942/45375\">dF.'s answer</a> contains the <em>seed</em> of an answer based on <code>tee</code> and <em>output</em> <a href=\"http://mywiki.wooledge.org/ProcessSubstitution\" rel=\"noreferrer\">process substitutions</a><br>\n(<code>&gt;(...)</code>) that <em>may or may not</em> work, depending on your requirements:</p>\n\n<p><sup>Note that process substitutions are a <em>nonstandard</em> feature that (mostly)\n POSIX-features-only shells such as <code>dash</code> (which acts as <code>/bin/sh</code> on Ubuntu,\n for instance), do <em>not</em> support. Shell scripts targeting <code>/bin/sh</code> should <em>not</em> rely on them.</sup></p>\n\n<pre><code>echo 123 | tee &gt;(tr 1 a) &gt;(tr 1 b) &gt;/dev/null\n</code></pre>\n\n<p>The <strong>pitfalls</strong> of this approach are:</p>\n\n<ul>\n<li><p><strong>unpredictable, asynchronous output behavior</strong>: the output streams from the commands inside the output process substitutions <code>&gt;(...)</code> interleave in unpredictable ways.</p></li>\n<li><p>In <code>bash</code> and <code>ksh</code> (as opposed to <code>zsh</code> - but see exception below):</p>\n\n<ul>\n<li><strong>output may arrive <em>after</em> the command has finished.</strong></li>\n<li><strong>subsequent commands may start executing <em>before</em> the commands in the process substitutions have finished</strong> - <code>bash</code> and <code>ksh</code> do <em>not</em> wait for the output process substitution-spawned processes to finish, at least by default. </li>\n<li><a href=\"https://stackoverflow.com/users/173250/jmb\">jmb</a> puts it well in a comment on dF.'s answer:</li>\n</ul></li>\n</ul>\n\n<blockquote>\n <p>be aware that the commands started inside <code>&gt;(...)</code> are dissociated from the original shell, and you can't easily determine when they finish; the <code>tee</code> will finish after writing everything, but the substituted processes will still be consuming the data from various buffers in the kernel and file I/O, plus whatever time is taken by their internal handling of data. You can encounter race conditions if your outer shell then goes on to rely on anything produced by the sub-processes.</p>\n</blockquote>\n\n<ul>\n<li><p><strong><code>zsh</code></strong> is the only shell that <strong><em>does</em> by default wait for the processes run in the output process substitutions to finish</strong>, <em>except</em> if it is <em>stderr</em> that is redirected to one (<code>2&gt; &gt;(...)</code>).</p></li>\n<li><p><strong><code>ksh</code></strong> (at least as of version <code>93u+</code>) allows use of argument-less <code>wait</code> to wait for the output process substitution-spawned processes to finish.<br>\nNote that in an interactive session that could result in waiting for any pending <em>background jobs</em> too, however.</p></li>\n<li><p><strong><code>bash v4.4+</code></strong> can wait for the <em>most recently</em> launched output process substitution with <code>wait $!</code>, but argument-less <code>wait</code> does <em>not</em> work, making this unsuitable for a command with <em>multiple</em> output process substitutions.</p></li>\n<li><p>However, <strong><code>bash</code> and <code>ksh</code> can be <em>forced</em> to wait</strong> by piping the command to <strong><code>| cat</code></strong>, but note that this makes the command run in a <em>subshell</em>. <em>Caveats</em>:</p>\n\n<ul>\n<li><p><code>ksh</code> (as of <code>ksh 93u+</code>) doesn't support sending <em>stderr</em> to an output process substitution (<code>2&gt; &gt;(...)</code>); such an attempt is <em>silently ignored</em>.</p></li>\n<li><p>While <code>zsh</code> is (commendably) synchronous <em>by default</em> with the (far more common) <em>stdout</em> output process substitutions, even the <code>| cat</code> technique cannot make them synchronous with <em>stderr</em> output process substitutions (<code>2&gt; &gt;(...)</code>).</p></li>\n</ul></li>\n<li><p>However, <strong>even if you ensure <em>synchronous execution</em>, the problem of <em>unpredictably interleaved output</em> remains.</strong></p></li>\n</ul>\n\n<p>The following command, when run in <code>bash</code> or <code>ksh</code>, illustrates the problematic behaviors (you may have to run it several times to see <em>both</em> symptoms): The <code>AFTER</code> will typically print <em>before</em> output from the output substitutions, and the output from the latter can be interleaved unpredictably.</p>\n\n<pre><code>printf 'line %s\\n' {1..30} | tee &gt;(cat -n) &gt;(cat -n) &gt;/dev/null; echo AFTER\n</code></pre>\n\n<p><strong>In short</strong>:</p>\n\n<ul>\n<li><p>Guaranteeing a particular per-command output sequence:</p>\n\n<ul>\n<li>Neither <code>bash</code> nor <code>ksh</code> nor <code>zsh</code> support that.</li>\n</ul></li>\n<li><p>Synchronous execution:</p>\n\n<ul>\n<li>Doable, except with <em>stderr</em>-sourced output process substitutions:\n\n<ul>\n<li>In <code>zsh</code>, they're <em>invariably</em> asynchronous.</li>\n<li>In <code>ksh</code>, they <em>don't work at all</em>.</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>If you can live with these limitations, using output process substitutions is a viable option (e.g., if all of them write to separate output files).</p>\n\n<hr>\n\n<p>Note that <strong><a href=\"https://stackoverflow.com/a/190777/45375\">tzot's much more cumbersome, but potentially POSIX-compliant solution</a> also exhibits unpredictable output behavior</strong>; however, by using <code>wait</code> you can ensure that subsequent commands do not start executing until all background processes have finished.<br>\n<strong>See bottom</strong> for <strong>a more robust, synchronous, serialized-output implementation</strong>.</p>\n\n<hr>\n\n<p><strong>The only <em>straightforward</em> <code>bash</code> solution <em>with predictable output behavior</em></strong> is the following, which, however, is <strong>prohibitively slow with large input sets</strong>, because shell loops are inherently slow.<br>\nAlso note that this <strong><em>alternates</em> the output lines from the target commands</strong>.</p>\n\n<pre><code>while IFS= read -r line; do \n tr 1 a &lt;&lt;&lt;\"$line\"\n tr 1 b &lt;&lt;&lt;\"$line\"\ndone &lt; &lt;(echo '123')\n</code></pre>\n\n<hr>\n\n<h3>Unix (using GNU Parallel)</h3>\n\n<p>Installing <a href=\"https://www.gnu.org/software/parallel/\" rel=\"noreferrer\">GNU <code>parallel</code></a> enables a <strong>robust solution</strong> with <strong>serialized (per-command) output</strong> that additionally allows <strong>parallel execution</strong>:</p>\n\n<pre><code>$ echo '123' | parallel --pipe --tee {} ::: 'tr 1 a' 'tr 1 b'\na23\nb23\n</code></pre>\n\n<p><code>parallel</code> by default ensures that output from the different commands doesn't interleave (this behavior can be modified - see <code>man parallel</code>).</p>\n\n<p><sup>Note: Some Linux distros come with a <em>different</em> <code>parallel</code> utility, which won't work with the command above; use <code>parallel --version</code> to determine which one, if any, you have.</sup></p>\n\n<hr>\n\n<h3>Windows</h3>\n\n<p><a href=\"https://stackoverflow.com/a/61716/45375\">Jay Bazuzi's helpful answer</a> shows how to do it in <strong>PowerShell</strong>. That said: his answer is the analog of the looping <code>bash</code> answer above, it will be <strong>prohibitively slow with large input sets</strong> and also <strong><em>alternates</em> the output lines from the target commands</strong>.</p>\n\n<hr>\n\n<hr>\n\n<h3><code>bash</code>-based, but otherwise portable Unix solution with synchronous execution and output serialization</h3>\n\n<p>The following is a simple, but reasonably robust implementation of the approach presented in <a href=\"https://stackoverflow.com/a/190777/45375\">tzot's answer</a> that additionally provides:</p>\n\n<ul>\n<li>synchronous execution</li>\n<li>serialized (grouped) output</li>\n</ul>\n\n<p>While not strictly POSIX compliant, because it is a <code>bash</code> script, it should be <strong>portable to any Unix platform that has <code>bash</code></strong>.</p>\n\n<p>Note: You can find a more full-fledged implementation released under the MIT license in <a href=\"https://gist.github.com/mklement0/a9ca81f1d4e170fc1544706147663f64\" rel=\"noreferrer\">this Gist</a>.</p>\n\n<p>If you save the code below as script <code>fanout</code>, make it executable and put int your <code>PATH</code>, the command from the question would work as follows:</p>\n\n<pre><code>$ echo 123 | fanout 'tr 1 a' 'tr 1 b'\n# tr 1 a\na23\n# tr 1 b\nb23\n</code></pre>\n\n<p><strong><code>fanout</code> script source code</strong>:</p>\n\n<pre><code>#!/usr/bin/env bash\n\n# The commands to pipe to, passed as a single string each.\naCmds=( \"$@\" )\n\n# Create a temp. directory to hold all FIFOs and captured output.\ntmpDir=\"${TMPDIR:-/tmp}/$kTHIS_NAME-$$-$(date +%s)-$RANDOM\"\nmkdir \"$tmpDir\" || exit\n# Set up a trap that automatically removes the temp dir. when this script\n# exits.\ntrap 'rm -rf \"$tmpDir\"' EXIT \n\n# Determine the number padding for the sequential FIFO / output-capture names, \n# so that *alphabetic* sorting, as done by *globbing* is equivalent to\n# *numerical* sorting.\nmaxNdx=$(( $# - 1 ))\nfmtString=\"%0${#maxNdx}d\"\n\n# Create the FIFO and output-capture filename arrays\naFifos=() aOutFiles=()\nfor (( i = 0; i &lt;= maxNdx; ++i )); do\n printf -v suffix \"$fmtString\" $i\n aFifos[i]=\"$tmpDir/fifo-$suffix\"\n aOutFiles[i]=\"$tmpDir/out-$suffix\"\ndone\n\n# Create the FIFOs.\nmkfifo \"${aFifos[@]}\" || exit\n\n# Start all commands in the background, each reading from a dedicated FIFO.\nfor (( i = 0; i &lt;= maxNdx; ++i )); do\n fifo=${aFifos[i]}\n outFile=${aOutFiles[i]}\n cmd=${aCmds[i]}\n printf '# %s\\n' \"$cmd\" &gt; \"$outFile\"\n eval \"$cmd\" &lt; \"$fifo\" &gt;&gt; \"$outFile\" &amp;\ndone\n\n# Now tee stdin to all FIFOs.\ntee \"${aFifos[@]}\" &gt;/dev/null || exit\n\n# Wait for all background processes to finish.\nwait\n\n# Print all captured stdout output, grouped by target command, in sequences.\ncat \"${aOutFiles[@]}\"\n</code></pre>\n" }, { "answer_id": 62188317, "author": "exic", "author_id": 332451, "author_profile": "https://Stackoverflow.com/users/332451", "pm_score": 1, "selected": false, "text": "<p>You can also save the output in a variable and use that for the other processes:</p>\n\n<pre><code>out=$(proc1); echo \"$out\" | proc2; echo \"$out\" | proc3\n</code></pre>\n\n<p>However, that works only if </p>\n\n<ol>\n<li><code>proc1</code> terminates at some point :-)</li>\n<li><code>proc1</code> doesn't produce too much output (don't know what the limits are there but it's probably your RAM)</li>\n</ol>\n\n<p>But it is easy to remember and leaves you with more options on the output you get from the processes you spawned there, e. g.:</p>\n\n<pre><code>out=$(proc1); echo $(echo \"$out\" | proc2) / $(echo \"$out\" | proc3) | bc\n</code></pre>\n\n<p>I had difficulties doing something like that with the <code>| tee &gt;(proc2) &gt;(proc3) &gt;/dev/null</code> approach.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085/" ]
I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3: ``` proc2 -> stdout / proc1 \ proc3 -> stdout ``` I tried ``` proc1 | (proc2 & proc3) ``` but it doesn't seem to work, i.e. ``` echo 123 | (tr 1 a & tr 1 b) ``` writes ``` b23 ``` to stdout instead of ``` a23 b23 ```
*Editor's note*: - `>(…)` is a [*process substitution*](http://mywiki.wooledge.org/ProcessSubstitution) that is a *nonstandard shell feature* of *some* POSIX-compatible shells: `bash`, `ksh`, `zsh`. - This answer accidentally sends the output process substitution's output through the pipeline *too*: `echo 123 | tee >(tr 1 a) | tr 1 b`. - Output from the process substitutions will be unpredictably interleaved, and, except in `zsh`, the pipeline may terminate before the commands inside `>(…)` do. In unix (or on a mac), use the [`tee` command](http://en.wikipedia.org/wiki/Tee_(command)): ``` $ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null b23 a23 ``` Usually you would use `tee` to redirect output to multiple files, but using >(...) you can redirect to another process. So, in general, ``` $ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null ``` will do what you want. Under windows, I don't think the built-in shell has an equivalent. Microsoft's [Windows PowerShell](http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx) has a `tee` command though.
60,944
<p>The below HTML/CSS/Javascript (jQuery) code displays the <code>#makes</code> select box. Selecting an option displays the <code>#models</code> select box with relevant options. The <code>#makes</code> select box sits off-center and the <code>#models</code> select box fills the empty space when it is displayed. </p> <p>How do you style the form so that the <code>#makes</code> select box is centered when it is the only form element displayed, but when both select boxes are displayed, they are both centered within the container?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var cars = [ { "makes" : "Honda", "models" : ['Accord','CRV','Pilot'] }, { "makes" :"Toyota", "models" : ['Prius','Camry','Corolla'] } ]; $(function() { vehicles = [] ; for(var i = 0; i &lt; cars.length; i++) { vehicles[cars[i].makes] = cars[i].models ; } var options = ''; for (var i = 0; i &lt; cars.length; i++) { options += '&lt;option value="' + cars[i].makes + '"&gt;' + cars[i].makes + '&lt;/option&gt;'; } $("#make").html(options); // populate select box with array $("#make").bind("click", function() { $("#model").children().remove() ; // clear select box var options = ''; for (var i = 0; i &lt; vehicles[this.value].length; i++) { options += '&lt;option value="' + vehicles[this.value][i] + '"&gt;' + vehicles[this.value][i] + '&lt;/option&gt;'; } $("#model").html(options); // populate select box with array $("#models").addClass("show"); }); // bind end });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hide { display: none; } .show { display: inline; } fieldset { border: #206ba4 1px solid; } fieldset legend { margin-top: -.4em; font-size: 20px; font-weight: bold; color: #206ba4; } fieldset fieldset { position: relative; margin-top: 25px; padding-top: .75em; background-color: #ebf4fa; } body { margin: 0; padding: 0; font-family: Verdana; font-size: 12px; text-align: center; } #wrapper { margin: 40px auto 0; } #myFieldset { width: 213px; } #area { margin: 20px; } #area select { width: 75px; float: left; } #area label { display: block; font-size: 1.1em; font-weight: bold; color: #000; } #area #selection { display: block; } #makes { margin: 5px; } #models { margin: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="wrapper"&gt; &lt;fieldset id="myFieldset"&gt; &lt;legend&gt;Cars&lt;/legend&gt; &lt;fieldset id="area"&gt; &lt;label&gt;Select Make:&lt;/label&gt; &lt;div id="selection"&gt; &lt;div id="makes"&gt; &lt;select id="make"size="2"&gt;&lt;/select&gt; &lt;/div&gt; &lt;div class="hide" id="models"&gt; &lt;select id="model" size="3"&gt;&lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/fieldset&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 61009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Floating the select boxes changes their display properties to \"block\". If you have no reason to float them, simply remove the \"float: left\" declaration, and add \"text-align: center\" to #makes and #models.</p>\n" }, { "answer_id": 61029, "author": "Nick Higgs", "author_id": 3187, "author_profile": "https://Stackoverflow.com/users/3187", "pm_score": 2, "selected": true, "text": "<p>It's not entirely clear from your question what layout you're trying to achieve, but judging by that fact that you have applied \"float:left\" to the select elements, it looks like you want the select elements to appear side by side. If this is the case, you can achieve this by doing the following:</p>\n\n<ul>\n<li>To centrally align elements you need to add \"text-align:center\" to the containing block level element, in this case #selection.</li>\n<li>The position of elements that are floating is not affected by \"text-align\" declarations, so remove the \"float:left\" declaration from the select elements.</li>\n<li>In order for the #make and #model divs to sit side by side with out the use of floats they must be displayed as inline elements, so add \"display:inline\" to both #make and #model (note that this will lose the vertical margin on those elements, so you might need to make some other changes to get the exact layout you want).</li>\n</ul>\n\n<p>As select elements are displayed inline by default, an alternative to the last step is to remove the #make and #model divs and and apply the \"show\" and \"hide\" classes to the model select element directly.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
The below HTML/CSS/Javascript (jQuery) code displays the `#makes` select box. Selecting an option displays the `#models` select box with relevant options. The `#makes` select box sits off-center and the `#models` select box fills the empty space when it is displayed. How do you style the form so that the `#makes` select box is centered when it is the only form element displayed, but when both select boxes are displayed, they are both centered within the container? ```js var cars = [ { "makes" : "Honda", "models" : ['Accord','CRV','Pilot'] }, { "makes" :"Toyota", "models" : ['Prius','Camry','Corolla'] } ]; $(function() { vehicles = [] ; for(var i = 0; i < cars.length; i++) { vehicles[cars[i].makes] = cars[i].models ; } var options = ''; for (var i = 0; i < cars.length; i++) { options += '<option value="' + cars[i].makes + '">' + cars[i].makes + '</option>'; } $("#make").html(options); // populate select box with array $("#make").bind("click", function() { $("#model").children().remove() ; // clear select box var options = ''; for (var i = 0; i < vehicles[this.value].length; i++) { options += '<option value="' + vehicles[this.value][i] + '">' + vehicles[this.value][i] + '</option>'; } $("#model").html(options); // populate select box with array $("#models").addClass("show"); }); // bind end }); ``` ```css .hide { display: none; } .show { display: inline; } fieldset { border: #206ba4 1px solid; } fieldset legend { margin-top: -.4em; font-size: 20px; font-weight: bold; color: #206ba4; } fieldset fieldset { position: relative; margin-top: 25px; padding-top: .75em; background-color: #ebf4fa; } body { margin: 0; padding: 0; font-family: Verdana; font-size: 12px; text-align: center; } #wrapper { margin: 40px auto 0; } #myFieldset { width: 213px; } #area { margin: 20px; } #area select { width: 75px; float: left; } #area label { display: block; font-size: 1.1em; font-weight: bold; color: #000; } #area #selection { display: block; } #makes { margin: 5px; } #models { margin: 5px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <div id="wrapper"> <fieldset id="myFieldset"> <legend>Cars</legend> <fieldset id="area"> <label>Select Make:</label> <div id="selection"> <div id="makes"> <select id="make"size="2"></select> </div> <div class="hide" id="models"> <select id="model" size="3"></select> </div> </div> </fieldset> </fieldset> </div> ```
It's not entirely clear from your question what layout you're trying to achieve, but judging by that fact that you have applied "float:left" to the select elements, it looks like you want the select elements to appear side by side. If this is the case, you can achieve this by doing the following: * To centrally align elements you need to add "text-align:center" to the containing block level element, in this case #selection. * The position of elements that are floating is not affected by "text-align" declarations, so remove the "float:left" declaration from the select elements. * In order for the #make and #model divs to sit side by side with out the use of floats they must be displayed as inline elements, so add "display:inline" to both #make and #model (note that this will lose the vertical margin on those elements, so you might need to make some other changes to get the exact layout you want). As select elements are displayed inline by default, an alternative to the last step is to remove the #make and #model divs and and apply the "show" and "hide" classes to the model select element directly.
60,977
<p>Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.</p> <p>Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem.</p> <p>Solution that I know are:</p> <p>a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed.</p> <p>b) Delete the whole project and re-check it out from svn.</p> <p>Does anyone know how I can get around this problem?</p> <p>Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes?</p> <p>Or perhaps there is a recursive modification date reset tool that can be used in this situation?</p>
[ { "answer_id": 60984, "author": "Michael Neale", "author_id": 699, "author_profile": "https://Stackoverflow.com/users/699", "pm_score": 0, "selected": false, "text": "<p>I don't use windows - but surely there is something like awk or grep that you can use to find the \"future\" timestamped files, and then \"touch\" them so they have the right time - even a perl script.</p>\n" }, { "answer_id": 60985, "author": "Maximilian", "author_id": 1733, "author_profile": "https://Stackoverflow.com/users/1733", "pm_score": 1, "selected": false, "text": "<p>I don't know if this works in your situation but how about you don't move your clock forward, but wrap your gettime method (or whatever you're using) and make it return the future time that you need?</p>\n" }, { "answer_id": 61015, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 1, "selected": false, "text": "<p>Install <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">Unix Utils</a></p>\n\n<pre><code>touch temp\nfind . -newer temp -exec touch {} ;\nrm temp\n</code></pre>\n\n<p>Make sure to use the full path when calling find or it will probably use Windows' find.exe instead. This is untested in the Windows shell -- you might need to modify the syntax a bit.</p>\n" }, { "answer_id": 61016, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>I would recommend using a virtual machine where you can mess with the clock to your heart's content and it won't affect your development machine. Two free ones are <a href=\"http://www.microsoft.com/Windows/products/winfamily/virtualpc/default.mspx\" rel=\"nofollow noreferrer\">Virtual PC</a> from Microsoft and <a href=\"http://www.virtualbox.org/\" rel=\"nofollow noreferrer\">VirtualBox</a> from Sun.</p>\n" }, { "answer_id": 61105, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": true, "text": "<p>If this was my problem, I'd look for ways to avoid mucking with the system time. Isolating the code under unit tests, or a virtual machine, or something.</p>\n\n<p>However, because I love <a href=\"https://stackoverflow.com/questions/52487/the-most-amazing-pieces-of-software-in-the-world#53414\">PowerShell</a>:</p>\n\n<pre><code>Get-ChildItem -r . | \n ? { $_.LastWriteTime -gt ([DateTime]::Now) } | \n Set-ItemProperty -Name \"LastWriteTime\" -Value ([DateTime]::Now)\n</code></pre>\n" }, { "answer_id": 65297, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "<p>1) Use a build system that doesn't use timestamps to detect modifications, like <a href=\"http://www.scons.org\" rel=\"nofollow noreferrer\">scons</a></p>\n\n<p>2) Use <a href=\"http://ccache.samba.org/\" rel=\"nofollow noreferrer\">ccache</a> to speed up your build system that does use timestamps (and rebuild all).</p>\n\n<p>In either case it is using md5sum's to verify that a file has been modified, not timestamps.</p>\n" } ]
2008/09/13
[ "https://Stackoverflow.com/questions/60977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time. Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem. Solution that I know are: a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed. b) Delete the whole project and re-check it out from svn. Does anyone know how I can get around this problem? Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes? Or perhaps there is a recursive modification date reset tool that can be used in this situation?
If this was my problem, I'd look for ways to avoid mucking with the system time. Isolating the code under unit tests, or a virtual machine, or something. However, because I love [PowerShell](https://stackoverflow.com/questions/52487/the-most-amazing-pieces-of-software-in-the-world#53414): ``` Get-ChildItem -r . | ? { $_.LastWriteTime -gt ([DateTime]::Now) } | Set-ItemProperty -Name "LastWriteTime" -Value ([DateTime]::Now) ```
61,000
<p>I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.</p> <p>I recently used a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">Maven structure</a> for a java project, but I am not sure it's the best structure for a non-maven driven project.</p> <p>So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. </p> <p>As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public_html ?</p>
[ { "answer_id": 61003, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 0, "selected": false, "text": "<p>I just found a interesting document about Directory structures on Zend website:<br>\n<a href=\"http://framework.zend.com/wiki/display/ZFDEV/Choosing+Your+Application%27s+Directory+Layout\" rel=\"nofollow noreferrer\">http://framework.zend.com/wiki/display/ZFDEV/Choosing+Your+Application%27s+Directory+Layout</a></p>\n" }, { "answer_id": 61060, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "<p>Although we don't use Maven, we use the Maven directory structure.</p>\n\n<p>We've found that it accurately reflects the concepts we need (e.g. separation of deployment code from test code, code from data, installers from code). Also we figure that <em>if</em> someday we switched to Maven, most of our process would remain the same.</p>\n" }, { "answer_id": 4540307, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 4, "selected": true, "text": "<p>After a couple years working with different structures I recently found a structure that hols most variations for me:</p>\n\n<pre><code>/project_name (everything goes here)\n /web (htdocs)\n /img\n /css\n /app (usually some framework or sensitive code)\n /lib (externa libs)\n /vendor_1\n /vendor_2\n /tmp\n /cache\n /sql (sql scripts usually with maybe diagrams)\n /scripts\n /doc (usually an empty directory)\n</code></pre>\n" }, { "answer_id": 8537457, "author": "Sridhar Sarnobat", "author_id": 714112, "author_profile": "https://Stackoverflow.com/users/714112", "pm_score": 0, "selected": false, "text": "<p>A 2011 update:\n<a href=\"http://java.sun.com/blueprints/code/projectconventions.html\" rel=\"nofollow\">http://java.sun.com/blueprints/code/projectconventions.html</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc. I recently used a [Maven structure](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html) for a java project, but I am not sure it's the best structure for a non-maven driven project. So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public\_html ?
After a couple years working with different structures I recently found a structure that hols most variations for me: ``` /project_name (everything goes here) /web (htdocs) /img /css /app (usually some framework or sensitive code) /lib (externa libs) /vendor_1 /vendor_2 /tmp /cache /sql (sql scripts usually with maybe diagrams) /scripts /doc (usually an empty directory) ```
61,002
<p>I'd like to script, preferably in rake, the following actions into a single command:</p> <ol> <li>Get the version of my local git repository.</li> <li>Git pull the latest code.</li> <li>Git diff from the version I extracted in step #1 to what is now in my local repository.</li> </ol> <p>In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.</p>
[ { "answer_id": 61004, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>This is very similar to a question I asked about <a href=\"https://stackoverflow.com/questions/53569/how-to-get-the-changes-on-a-branch-in-git\">how to get changes on a branch in git</a>. Note that the behaviour of git diff vs. git log is inconsistently different when using two dots vs. three dots. But, for your application you can use:</p>\n\n<pre><code>git fetch\ngit diff ...origin\n</code></pre>\n\n<p>After that, a <code>git pull</code> will merge the changes into your HEAD.</p>\n" }, { "answer_id": 61477, "author": "Greg", "author_id": 108, "author_profile": "https://Stackoverflow.com/users/108", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/61002/how-can-i-generate-a-git-diff-of-whats-changed-since-the-last-time-i-pulled#61004\">Greg's</a> way should work (not me, other Greg :P). Regarding your comment, origin is a configuration variable that is set by Git when you clone the central repository to your local machine. Essentially, a Git repository remembers where it came from. You can, however, set these variables manually if you need to using git-config.</p>\n\n<pre><code>git config remote.origin.url &lt;url&gt;\n</code></pre>\n\n<p>where url is the remote path to your central repository.</p>\n\n<p>Here is an example batch file that should work (I haven't tested it).</p>\n\n<pre><code>@ECHO off\n\n:: Retrieve the changes, but don't merge them.\ngit fetch\n\n:: Look at the new changes\ngit diff ...origin\n\n:: Ask if you want to merge the new changes into HEAD\nset /p PULL=Do you wish to pull the changes? (Y/N)\nIF /I %PULL%==Y git pull\n</code></pre>\n" }, { "answer_id": 62303, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 8, "selected": true, "text": "<p>You could do this fairly simply with refspecs.</p>\n\n<pre><code>git pull origin\ngit diff @{1}..\n</code></pre>\n\n<p>That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:</p>\n\n<pre><code>current=`git rev-parse HEAD`\ngit pull origin\ngit diff $current..\n</code></pre>\n\n<p>I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:</p>\n\n<pre><code>git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..\n</code></pre>\n" }, { "answer_id": 2831146, "author": "Clintm", "author_id": 3384609, "author_profile": "https://Stackoverflow.com/users/3384609", "pm_score": 2, "selected": false, "text": "<p>If you drop this into your bash profile you'll be able to run grin (git remote incoming) and grout (git remote outgoing) to see diffs of commits that are incoming and outgoing for origin master.</p>\n\n<pre><code>function parse_git_branch {\n git branch --no-color 2&gt; /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'\n}\nfunction gd2 { \n echo branch \\($1\\) has these commits and \\($2\\) does not \n git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\nfunction grin {\n git fetch origin master\n gd2 FETCH_HEAD $(parse_git_branch)\n}\nfunction grout {\n git fetch origin master\n gd2 $(parse_git_branch) FETCH_HEAD\n}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ]
I'd like to script, preferably in rake, the following actions into a single command: 1. Get the version of my local git repository. 2. Git pull the latest code. 3. Git diff from the version I extracted in step #1 to what is now in my local repository. In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.
You could do this fairly simply with refspecs. ``` git pull origin git diff @{1}.. ``` That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version: ``` current=`git rev-parse HEAD` git pull origin git diff $current.. ``` I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch: ``` git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}.. ```
61,005
<p>What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?</p>
[ { "answer_id": 61004, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>This is very similar to a question I asked about <a href=\"https://stackoverflow.com/questions/53569/how-to-get-the-changes-on-a-branch-in-git\">how to get changes on a branch in git</a>. Note that the behaviour of git diff vs. git log is inconsistently different when using two dots vs. three dots. But, for your application you can use:</p>\n\n<pre><code>git fetch\ngit diff ...origin\n</code></pre>\n\n<p>After that, a <code>git pull</code> will merge the changes into your HEAD.</p>\n" }, { "answer_id": 61477, "author": "Greg", "author_id": 108, "author_profile": "https://Stackoverflow.com/users/108", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/61002/how-can-i-generate-a-git-diff-of-whats-changed-since-the-last-time-i-pulled#61004\">Greg's</a> way should work (not me, other Greg :P). Regarding your comment, origin is a configuration variable that is set by Git when you clone the central repository to your local machine. Essentially, a Git repository remembers where it came from. You can, however, set these variables manually if you need to using git-config.</p>\n\n<pre><code>git config remote.origin.url &lt;url&gt;\n</code></pre>\n\n<p>where url is the remote path to your central repository.</p>\n\n<p>Here is an example batch file that should work (I haven't tested it).</p>\n\n<pre><code>@ECHO off\n\n:: Retrieve the changes, but don't merge them.\ngit fetch\n\n:: Look at the new changes\ngit diff ...origin\n\n:: Ask if you want to merge the new changes into HEAD\nset /p PULL=Do you wish to pull the changes? (Y/N)\nIF /I %PULL%==Y git pull\n</code></pre>\n" }, { "answer_id": 62303, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 8, "selected": true, "text": "<p>You could do this fairly simply with refspecs.</p>\n\n<pre><code>git pull origin\ngit diff @{1}..\n</code></pre>\n\n<p>That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:</p>\n\n<pre><code>current=`git rev-parse HEAD`\ngit pull origin\ngit diff $current..\n</code></pre>\n\n<p>I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:</p>\n\n<pre><code>git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..\n</code></pre>\n" }, { "answer_id": 2831146, "author": "Clintm", "author_id": 3384609, "author_profile": "https://Stackoverflow.com/users/3384609", "pm_score": 2, "selected": false, "text": "<p>If you drop this into your bash profile you'll be able to run grin (git remote incoming) and grout (git remote outgoing) to see diffs of commits that are incoming and outgoing for origin master.</p>\n\n<pre><code>function parse_git_branch {\n git branch --no-color 2&gt; /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/\\1/'\n}\nfunction gd2 { \n echo branch \\($1\\) has these commits and \\($2\\) does not \n git log $2..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local\n}\nfunction grin {\n git fetch origin master\n gd2 FETCH_HEAD $(parse_git_branch)\n}\nfunction grout {\n git fetch origin master\n gd2 $(parse_git_branch) FETCH_HEAD\n}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?
You could do this fairly simply with refspecs. ``` git pull origin git diff @{1}.. ``` That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version: ``` current=`git rev-parse HEAD` git pull origin git diff $current.. ``` I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch: ``` git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}.. ```
61,051
<p>You can use more than one css class in an HTML tag in current web browsers, e.g.:</p> <pre><code>&lt;div class="style1 style2 style3"&gt;foo bar&lt;/div&gt; </code></pre> <p>This hasn't always worked; with which versions did the major browsers begin correctly supporting this feature?</p>
[ { "answer_id": 61053, "author": "Wayne Kao", "author_id": 3284, "author_profile": "https://Stackoverflow.com/users/3284", "pm_score": 1, "selected": false, "text": "<p>Apparently IE 6 doesn't handle these correctly if you have CSS selectors that contain multiple class names:\n<a href=\"http://www.ryanbrill.com/archives/multiple-classes-in-ie/\" rel=\"nofollow noreferrer\">http://www.ryanbrill.com/archives/multiple-classes-in-ie/</a></p>\n" }, { "answer_id": 61055, "author": "Nathan", "author_id": 6062, "author_profile": "https://Stackoverflow.com/users/6062", "pm_score": 2, "selected": false, "text": "<p>I believe Firefox has always supported this, at least since v1.5 anyway. IE only added full support in v7. IE6 does partially support it, but its pretty buggy, so don't count on it working properly. </p>\n" }, { "answer_id": 61058, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://www.blooberry.com/indexdot/css/syntax/selectors/spechtml.htm\" rel=\"nofollow noreferrer\">blooberry</a>, IE4 and Netscape 4.x do not support this. <a href=\"http://www.w3.org/TR/1998/REC-html40-19980424/struct/global.html#h-7.5.2\" rel=\"nofollow noreferrer\">HTML 4.0 spec</a> says</p>\n<blockquote>\n<p>class = cdata-list [CS]</p>\n<p>This attribute\nassigns a class name or set of class\nnames to an element. Any number of\nelements may be assigned the same\nclass name or names. Multiple class\nnames must be separated by white space\ncharacters.</p>\n</blockquote>\n" }, { "answer_id": 61414, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 4, "selected": true, "text": "<p>@Wayne Kao - IE6 has no problem reading more than one class name on an element, and applying styles that belong to each class. What the article is referring to is creating new styles based on the combination of class names.</p>\n\n<pre><code>&lt;div class=\"bold italic\"&gt;content&lt;/div&gt;\n\n.bold {\n font-weight: 800;\n}\n\n.italic {\n font-style: italic;\n{\n</code></pre>\n\n<p>IE6 would apply both bold and italic styles to the div. However, say we wanted all elements that have bold and italic classes to also be purple. In Firefox (or possibly IE7, not sure), we could write something like this:</p>\n\n<pre><code>.bold.italic {\n color: purple;\n}\n</code></pre>\n\n<p>That would not work in IE6. </p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3283/" ]
You can use more than one css class in an HTML tag in current web browsers, e.g.: ``` <div class="style1 style2 style3">foo bar</div> ``` This hasn't always worked; with which versions did the major browsers begin correctly supporting this feature?
@Wayne Kao - IE6 has no problem reading more than one class name on an element, and applying styles that belong to each class. What the article is referring to is creating new styles based on the combination of class names. ``` <div class="bold italic">content</div> .bold { font-weight: 800; } .italic { font-style: italic; { ``` IE6 would apply both bold and italic styles to the div. However, say we wanted all elements that have bold and italic classes to also be purple. In Firefox (or possibly IE7, not sure), we could write something like this: ``` .bold.italic { color: purple; } ``` That would not work in IE6.
61,084
<p>I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.</p> <pre><code>XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement("url", new XElement("loc", "http://www.example.com/page"), new XElement("lastmod", "2008-09-14")))); </code></pre> <p>The result is ...</p> <pre><code>&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt; &lt;url xmlns=""&gt; &lt;loc&gt;http://www.example.com/page&lt;/loc&gt; &lt;lastmod&gt;2008-09-14&lt;/lastmod&gt; &lt;/url&gt; &lt;/urlset&gt; </code></pre> <p>I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?</p>
[ { "answer_id": 61106, "author": "Anheledir", "author_id": 5703, "author_profile": "https://Stackoverflow.com/users/5703", "pm_score": 2, "selected": false, "text": "<p>If one element uses a namespace, they all must use one. In case you don't define one on your own the framework will add a empty namespace as you have noticed. And, sadly, there is no switch or something similiar to suppress this \"feature\".</p>\n\n<p>So, there seems to be no better method as to strip it out. Using <em>Replace(\" xmlns=\\\"\\\"\", \"\")</em> could be a little bit faster than executing a RegEx.</p>\n" }, { "answer_id": 61141, "author": "Micah", "author_id": 6209, "author_profile": "https://Stackoverflow.com/users/6209", "pm_score": 6, "selected": true, "text": "<p>The \"more correct way\" would be:</p>\n\n<pre><code>XDocument xdoc = new XDocument(new XDeclaration(\"1.0\", \"utf-8\", \"true\"),\nnew XElement(ns + \"urlset\",\nnew XElement(ns + \"url\",\n new XElement(ns + \"loc\", \"http://www.example.com/page\"),\n new XElement(ns + \"lastmod\", \"2008-09-14\"))));\n</code></pre>\n\n<p>Same as your code, but with the \"ns +\" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is:</p>\n\n<pre><code>&lt;urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.example.com/page&lt;/loc&gt;\n &lt;lastmod&gt;2008-09-14&lt;/lastmod&gt;\n &lt;/url&gt;\n&lt;/urlset&gt;\n</code></pre>\n\n<p>which is, if I'm not mistaken, what you want.</p>\n" }, { "answer_id": 777327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I stumbled across this post while dealing with a similar problem in VB.NET. I was using XML literals and it took me some searching to figure out how to make this solution work with the XML literal construction and not just the functional construction.</p>\n\n<p>The solution is to import the XML namespace at the top of the file.</p>\n\n<pre><code>Imports &lt;xmlns:ns=\"x-schema:tsSchema.xml\"&gt;\n</code></pre>\n\n<p>And then prefix all of my XML literals in the query expression with the imported namespace. This removes the empty namespace that were appearing on the elements when I saved my output.</p>\n\n<pre><code>Dim output As XDocument = &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n &lt;XML ID=\"Microsoft Search Thesaurus\"&gt;\n &lt;thesaurus xmlns=\"x-schema:tsSchema.xml\"&gt;\n &lt;diacritics_sensitive&gt;0&lt;/diacritics_sensitive&gt;\n &lt;%= From tg In termGroups _\n Select &lt;ns:expansion&gt;\n &lt;%= From t In tg _\n Select &lt;ns:sub&gt;&lt;%= t %&gt;&lt;/ns:sub&gt; %&gt;\n &lt;/ns:expansion&gt; %&gt;\n &lt;/thesaurus&gt;\n &lt;/XML&gt;\n\n output.Save(\"C:\\thesaurus.xml\")\n</code></pre>\n\n<p>I hope this helps someone. Despite bumps in the road like this, the XLinq API is pretty darn cool.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4449/" ]
I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g. ``` XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement("url", new XElement("loc", "http://www.example.com/page"), new XElement("lastmod", "2008-09-14")))); ``` The result is ... ``` <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url xmlns=""> <loc>http://www.example.com/page</loc> <lastmod>2008-09-14</lastmod> </url> </urlset> ``` I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?
The "more correct way" would be: ``` XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement(ns + "urlset", new XElement(ns + "url", new XElement(ns + "loc", "http://www.example.com/page"), new XElement(ns + "lastmod", "2008-09-14")))); ``` Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is: ``` <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.example.com/page</loc> <lastmod>2008-09-14</lastmod> </url> </urlset> ``` which is, if I'm not mistaken, what you want.
61,085
<p>I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to?</p> <p>By the way, my machine is the standard Mac OS X Leopard install with PHP activated.</p> <p>@Tom Martin</p> <p>Thank you for your reply. I just ran your code and it looks like PHP runs as user _www. I then tried chowning the database to be owned by _www, but that didn't work either.</p> <p>I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write?</p> <p>I've decided to include the code in question. This is going to be more or less a port of <a href="https://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper">Grant's script</a> to PHP. So far it's just the Questions section:</p> <pre><code>&lt;?php $db = new PDO('sqlite:test.db'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652"); $page = curl_exec($ch); preg_match('/summarycount"&gt;.*?([,\d]+)&lt;\/div&gt;.*?Reputation/s', $page, $rep); $rep = preg_replace("/,/", "", $rep[1]); preg_match('/iv class="summarycount".{10,60} (\d+)&lt;\/d.{10,140}Badges/s', $page, $badge); $badge = $badge[1]; $qreg = '/question-summary narrow.*?vote-count-post"&gt;&lt;strong.*?&gt;(-?\d*).*?\/questions\/(\d*).*?&gt;(.*?)&lt;\/a&gt;/s'; preg_match_all($qreg, $page, $questions, PREG_SET_ORDER); $areg = '/(answer-summary"&gt;&lt;a href="\/questions\/(\d*).*?votes.*?&gt;(-?\d+).*?href.*?&gt;(.*?)&lt;.a)/s'; preg_match_all($areg, $page, $answers, PREG_SET_ORDER); echo "&lt;h3&gt;Questions:&lt;/h3&gt;\n"; echo "&lt;table cellpadding=\"3\"&gt;\n"; foreach ($questions as $q) { $query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;'; $dbitem = $db-&gt;query($query)-&gt;fetch(PDO::FETCH_ASSOC); if ($dbitem['count(id)'] &gt; 0) { $lastQ = $q[1] - $dbitem['votes']; if ($lastQ == 0) { $lastQ = ""; } $query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'"; $db-&gt;exec($query); } else { $query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')"; echo "$query\n"; $db-&gt;exec($query); $lastQ = "(NEW)"; } echo "&lt;tr&gt;&lt;td&gt;$lastQ&lt;/td&gt;&lt;td align=\"right\"&gt;$q[1]&lt;/td&gt;&lt;td&gt;$q[3]&lt;/td&gt;&lt;/tr&gt;\n"; } echo "&lt;/table&gt;"; ?&gt; </code></pre>
[ { "answer_id": 61102, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 1, "selected": false, "text": "<p>I think PHP commonly runs as the user \"nodody\". Not sure about on Mac though. If Mac has whoami you could try <code>echo exec('whoami');</code> to find out.</p>\n" }, { "answer_id": 61243, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 5, "selected": true, "text": "<p>Kyle, in order for PDO/Sqlite to work you need write permission to directory where your database resides.</p>\n\n<p>Also, I see you perform multiple selects in loop. This may be ok if you are building something small and not heavy loaded. Otherwise I'd suggest building single query that returns multiple rows and process them in separate loop.</p>\n" }, { "answer_id": 1352234, "author": "Karl Blessing", "author_id": 165436, "author_profile": "https://Stackoverflow.com/users/165436", "pm_score": 0, "selected": false, "text": "<p>@Tom\nDepends on how the hosting is setup, If the server runs PHP as an Apache Module then its likely that it is 'nobody' (usually whatever user apache is setup as). But if PHP is setup as cgi (such as fast-cgi) and the server runs SuExec then php runs as the same user who owns the files. </p>\n\n<p>Eitherway the folder that will contain the database must be writable by the script, either by being the same user, or by having write permission set to the php user. </p>\n\n<p>@Michal\nThat aside, one could use beginTransaction(); perform all the actions needed then comit(); to actually comit them. </p>\n" }, { "answer_id": 3470364, "author": "paolo_O", "author_id": 418707, "author_profile": "https://Stackoverflow.com/users/418707", "pm_score": 0, "selected": false, "text": "<p>Well, I had the same problem now and figured it out by a mistake: just put every inserting piece of SQL instruction inside a <code>try...catch</code> block that it goes. It makes you do it right way otherwise it doesn't work. Well, it works now. Good luck for anyone else with this problem(as I used this thread myself to try to solve my problem).</p>\n" }, { "answer_id": 3695324, "author": "user445622", "author_id": 445622, "author_profile": "https://Stackoverflow.com/users/445622", "pm_score": 1, "selected": false, "text": "<p>For those who have encountered read-only issues with SQLite on OS X:</p>\n\n<p>1) Determine the Apache <strong>httpd</strong> user and group the user belongs to: </p>\n\n<blockquote>\n <p>grep \"^User\" /private/etc/apache2/httpd.conf<br>\n groups _www</p>\n</blockquote>\n\n<p>2) Create a subdirectory in <strong>/Library/WebServer/Documents</strong> for your database(s) and change the group to the httpd's group:</p>\n\n<blockquote>\n <p>sudo chgrp _www /Library/WebServer/Documents/db</p>\n</blockquote>\n\n<p>A less secure option is to open permissions on <strong>/Library/WebServer/Documents</strong>:</p>\n\n<blockquote>\n <p>sudo chmod a+w /Library/WebServer/Documents</p>\n</blockquote>\n" }, { "answer_id": 4280229, "author": "Attilio", "author_id": 520558, "author_profile": "https://Stackoverflow.com/users/520558", "pm_score": 2, "selected": false, "text": "<p>I found the answer on the <a href=\"http://www.php.net/manual/en/ref.pdo-sqlite.php#57356\" rel=\"nofollow\">PHP manual</a> \"The folder that houses the database file must be writeable.\"</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to? By the way, my machine is the standard Mac OS X Leopard install with PHP activated. @Tom Martin Thank you for your reply. I just ran your code and it looks like PHP runs as user \_www. I then tried chowning the database to be owned by \_www, but that didn't work either. I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write? I've decided to include the code in question. This is going to be more or less a port of [Grant's script](https://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper) to PHP. So far it's just the Questions section: ``` <?php $db = new PDO('sqlite:test.db'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652"); $page = curl_exec($ch); preg_match('/summarycount">.*?([,\d]+)<\/div>.*?Reputation/s', $page, $rep); $rep = preg_replace("/,/", "", $rep[1]); preg_match('/iv class="summarycount".{10,60} (\d+)<\/d.{10,140}Badges/s', $page, $badge); $badge = $badge[1]; $qreg = '/question-summary narrow.*?vote-count-post"><strong.*?>(-?\d*).*?\/questions\/(\d*).*?>(.*?)<\/a>/s'; preg_match_all($qreg, $page, $questions, PREG_SET_ORDER); $areg = '/(answer-summary"><a href="\/questions\/(\d*).*?votes.*?>(-?\d+).*?href.*?>(.*?)<.a)/s'; preg_match_all($areg, $page, $answers, PREG_SET_ORDER); echo "<h3>Questions:</h3>\n"; echo "<table cellpadding=\"3\">\n"; foreach ($questions as $q) { $query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;'; $dbitem = $db->query($query)->fetch(PDO::FETCH_ASSOC); if ($dbitem['count(id)'] > 0) { $lastQ = $q[1] - $dbitem['votes']; if ($lastQ == 0) { $lastQ = ""; } $query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'"; $db->exec($query); } else { $query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')"; echo "$query\n"; $db->exec($query); $lastQ = "(NEW)"; } echo "<tr><td>$lastQ</td><td align=\"right\">$q[1]</td><td>$q[3]</td></tr>\n"; } echo "</table>"; ?> ```
Kyle, in order for PDO/Sqlite to work you need write permission to directory where your database resides. Also, I see you perform multiple selects in loop. This may be ok if you are building something small and not heavy loaded. Otherwise I'd suggest building single query that returns multiple rows and process them in separate loop.
61,088
<p><strong>What "Hidden Features" of JavaScript do you think every programmer should know?</strong></p> <p>After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.</p> <ul> <li><a href="https://stackoverflow.com/questions/954327/">Hidden Features of HTML</a></li> <li><a href="https://stackoverflow.com/questions/628407">Hidden Features of CSS</a></li> <li><a href="https://stackoverflow.com/questions/61401/">Hidden Features of PHP</a></li> <li><a href="https://stackoverflow.com/questions/54929/">Hidden Features of ASP.NET</a></li> <li><a href="https://stackoverflow.com/questions/9033/">Hidden Features of C#</a></li> <li><a href="https://stackoverflow.com/questions/15496/">Hidden Features of Java</a></li> <li><a href="https://stackoverflow.com/questions/101268/">Hidden Features of Python</a></li> </ul> <p>Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.</p>
[ { "answer_id": 61094, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 8, "selected": false, "text": "<p>Functions are first class citizens in JavaScript:</p>\n\n<pre><code>var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };\n\nvar sum = function(x,y,z) {\n return x+y+z;\n};\n\nalert( passFunAndApply(sum,3,4,5) ); // 12\n</code></pre>\n\n<p><a href=\"http://www.ibm.com/developerworks/library/wa-javascript.html\" rel=\"nofollow noreferrer\">Functional programming techniques can be used to write elegant javascript</a>.</p>\n\n<p>Particularly, functions can be passed as parameters, e.g. <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter\" rel=\"nofollow noreferrer\">Array.filter()</a> accepts a callback:</p>\n\n<pre><code>[1, 2, -1].filter(function(element, index, array) { return element &gt; 0 });\n// -&gt; [1,2]\n</code></pre>\n\n<p>You can also declare a \"private\" function that only exists within the scope of a specific function:</p>\n\n<pre><code>function PrintName() {\n var privateFunction = function() { return \"Steve\"; };\n return privateFunction();\n}\n</code></pre>\n" }, { "answer_id": 61097, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 7, "selected": false, "text": "<p><strong>Private Methods</strong></p>\n\n<p>An object can have private methods.</p>\n\n<pre><code>function Person(firstName, lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n\n // A private method only visible from within this constructor\n function calcFullName() {\n return firstName + \" \" + lastName; \n }\n\n // A public method available to everyone\n this.sayHello = function () {\n alert(calcFullName());\n }\n}\n\n//Usage:\nvar person1 = new Person(\"Bob\", \"Loblaw\");\nperson1.sayHello();\n\n// This fails since the method is not visible from this scope\nalert(person1.calcFullName());\n</code></pre>\n" }, { "answer_id": 61118, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": false, "text": "<p><strong><code>with</code></strong>.</p>\n<p>It's rarely used, and frankly, rarely useful... But, in limited circumstances, it does have its uses.</p>\n<p>For instance: object literals are quite handy for quickly setting up properties on a <em>new</em> object. But what if you need to change <em>half</em> of the properties on an existing object?</p>\n<pre><code>var user = \n{\n fname: 'Rocket', \n mname: 'Aloysus',\n lname: 'Squirrel', \n city: 'Fresno', \n state: 'California'\n};\n\n// ...\n\nwith (user)\n{\n mname = 'J';\n city = 'Frostbite Falls';\n state = 'Minnesota';\n}\n</code></pre>\n<p>Alan Storm points out that this can be somewhat dangerous: if the object used as context doesn't <em>have</em> one of the properties being assigned to, it will be resolved in the outer scope, possibly creating or overwriting a global variable. This is especially dangerous if you're used to writing code to work with objects where properties with default or empty values are left undefined:</p>\n<pre><code>var user = \n{\n fname: &quot;John&quot;,\n// mname definition skipped - no middle name\n lname: &quot;Doe&quot;\n};\n\nwith (user)\n{\n mname = &quot;Q&quot;; // creates / modifies global variable &quot;mname&quot;\n}\n</code></pre>\n<p>Therefore, it is probably a good idea to avoid the use of the <code>with</code> statement for such assignment.</p>\n<h3>See also: <a href=\"https://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement\">Are there legitimate uses for JavaScript’s “with” statement?</a></h3>\n" }, { "answer_id": 61125, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 7, "selected": false, "text": "<p><strong>You can access object properties with <code>[]</code> instead of <code>.</code></strong></p>\n\n<p>This allows you look up a property matching a variable.</p>\n\n<pre><code>obj = {a:\"test\"};\nvar propname = \"a\";\nvar b = obj[propname]; // \"test\"\n</code></pre>\n\n<p>You can also use this to get/set object properties whose name is not a legal identifier.</p>\n\n<pre><code>obj[\"class\"] = \"test\"; // class is a reserved word; obj.class would be illegal.\nobj[\"two words\"] = \"test2\"; // using dot operator not possible with the space.\n</code></pre>\n\n<p>Some people don't know this and end up using <strong>eval()</strong> like this, which is a <em>really bad idea</em>:</p>\n\n<pre><code>var propname = \"a\";\nvar a = eval(\"obj.\" + propname);\n</code></pre>\n\n<p>This is harder to read, harder to find errors in (can't use jslint), slower to execute, and can lead to XSS exploits.</p>\n" }, { "answer_id": 61129, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 6, "selected": false, "text": "<p>\"<a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2008/09/08/quot-extension-method-quot-in-javascript.aspx\" rel=\"nofollow noreferrer\">Extension methods in JavaScript</a>\" via the prototype property.</p>\n\n<pre><code>Array.prototype.contains = function(value) { \n for (var i = 0; i &lt; this.length; i++) { \n if (this[i] == value) return true; \n } \n return false; \n}\n</code></pre>\n\n<p>This will add a <code>contains</code> method to all <code>Array</code> objects. You can call this method using this syntax </p>\n\n<pre><code>var stringArray = [\"foo\", \"bar\", \"foobar\"];\nstringArray.contains(\"foobar\");\n</code></pre>\n" }, { "answer_id": 61158, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 7, "selected": false, "text": "<p><strong>Assigning default values to variables</strong></p>\n\n<p>You can use the logical or operator <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators\" rel=\"nofollow noreferrer\"><code>||</code></a> in an assignment expression to provide a default value:</p>\n\n<pre><code>var a = b || c;\n</code></pre>\n\n<p>The <code>a</code> variable will get the value of <code>c</code> only if <code>b</code> is <em>falsy</em> (if is <code>null</code>, <code>false</code>, <code>undefined</code>, <code>0</code>, <code>empty string</code>, or <code>NaN</code>), otherwise <code>a</code> will get the value of <code>b</code>.</p>\n\n<p>This is often useful in functions, when you want to give a default value to an argument in case isn't supplied:</p>\n\n<pre><code>function example(arg1) {\n arg1 || (arg1 = 'default value');\n}\n</code></pre>\n\n<p>Example IE fallback in event handlers:</p>\n\n<pre><code>function onClick(e) {\n e || (e = window.event);\n}\n</code></pre>\n\n<hr>\n\n<p>The following language features have been with us for a long time, all JavaScript implementations support them, but they weren't part of the specification until <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">ECMAScript 5th Edition</a>:</p>\n\n<p><strong>The <code>debugger</code> statement</strong></p>\n\n<p>Described in: <em>&sect; 12.15 The debugger statement</em></p>\n\n<p>This statement allows you to put <em>breakpoints programmatically</em> in your code just by:</p>\n\n<pre><code>// ...\ndebugger;\n// ...\n</code></pre>\n\n<p>If a debugger is present or active, it will cause it to break immediately, right on that line.</p>\n\n<p>Otherwise, if the debugger is not present or active this statement has no observable effect.</p>\n\n<p><strong>Multiline String literals</strong></p>\n\n<p>Described in: <em>&sect; 7.8.4 String Literals</em></p>\n\n<pre><code>var str = \"This is a \\\nreally, really \\\nlong line!\";\n</code></pre>\n\n<p>You have to be careful because the character next to the <code>\\</code> <em>must</em> be a line terminator, if you have a space after the <code>\\</code> for example, the code will <em>look</em> exactly the same, but it will raise a <code>SyntaxError</code>.</p>\n" }, { "answer_id": 61165, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "<p>It's surprising how many people don't realize that it's object oriented as well.</p>\n" }, { "answer_id": 61173, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Block_Statement\" rel=\"nofollow noreferrer\">JavaScript does not have block scope</a> (but it has <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Function_expressions\" rel=\"nofollow noreferrer\">closure</a> so let's call it even?).</p>\n\n<pre><code>var x = 1;\n{\n var x = 2;\n}\nalert(x); // outputs 2\n</code></pre>\n" }, { "answer_id": 61193, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 5, "selected": false, "text": "<p>How about <strong>closures</strong> in JavaScript (similar to anonymous methods in C# v2.0+). You can create a function that creates a function or \"expression\".</p>\n\n<p>Example of <strong>closures</strong>:</p>\n\n<pre><code>//Takes a function that filters numbers and calls the function on \n//it to build up a list of numbers that satisfy the function.\nfunction filter(filterFunction, numbers)\n{\n var filteredNumbers = [];\n\n for (var index = 0; index &lt; numbers.length; index++)\n {\n if (filterFunction(numbers[index]) == true)\n {\n filteredNumbers.push(numbers[index]);\n }\n }\n return filteredNumbers;\n}\n\n//Creates a function (closure) that will remember the value \"lowerBound\" \n//that gets passed in and keep a copy of it.\nfunction buildGreaterThanFunction(lowerBound)\n{\n return function (numberToCheck) {\n return (numberToCheck &gt; lowerBound) ? true : false;\n };\n}\n\nvar numbers = [1, 15, 20, 4, 11, 9, 77, 102, 6];\n\nvar greaterThan7 = buildGreaterThanFunction(7);\nvar greaterThan15 = buildGreaterThanFunction(15);\n\nnumbers = filter(greaterThan7, numbers);\nalert('Greater Than 7: ' + numbers);\n\nnumbers = filter(greaterThan15, numbers);\nalert('Greater Than 15: ' + numbers);\n</code></pre>\n" }, { "answer_id": 61196, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 5, "selected": false, "text": "<p>You can also <strong>extend (inherit) classes and override properties/methods</strong> using the prototype chain <strong>spoon16</strong> alluded to.</p>\n\n<p>In the following example we create a class Pet and define some properties. We also override the .toString() method inherited from Object.</p>\n\n<p>After this we create a Dog class which <strong>extends Pet and overrides the .toString()</strong> method again changing it's behavior (polymorphism). In addition we add some other properties to the child class.</p>\n\n<p>After this we check the inheritance chain to show off that Dog is still of type Dog, of type Pet, and of type Object.</p>\n\n<pre><code>// Defines a Pet class constructor \nfunction Pet(name) \n{\n this.getName = function() { return name; };\n this.setName = function(newName) { name = newName; };\n}\n\n// Adds the Pet.toString() function for all Pet objects\nPet.prototype.toString = function() \n{\n return 'This pets name is: ' + this.getName();\n};\n// end of class Pet\n\n// Define Dog class constructor (Dog : Pet) \nfunction Dog(name, breed) \n{\n // think Dog : base(name) \n Pet.call(this, name);\n this.getBreed = function() { return breed; };\n}\n\n// this makes Dog.prototype inherit from Pet.prototype\nDog.prototype = new Pet();\n\n// Currently Pet.prototype.constructor\n// points to Pet. We want our Dog instances'\n// constructor to point to Dog.\nDog.prototype.constructor = Dog;\n\n// Now we override Pet.prototype.toString\nDog.prototype.toString = function() \n{\n return 'This dogs name is: ' + this.getName() + \n ', and its breed is: ' + this.getBreed();\n};\n// end of class Dog\n\nvar parrotty = new Pet('Parrotty the Parrot');\nvar dog = new Dog('Buddy', 'Great Dane');\n// test the new toString()\nalert(parrotty);\nalert(dog);\n\n// Testing instanceof (similar to the `is` operator)\nalert('Is dog instance of Dog? ' + (dog instanceof Dog)); //true\nalert('Is dog instance of Pet? ' + (dog instanceof Pet)); //true\nalert('Is dog instance of Object? ' + (dog instanceof Object)); //true\n</code></pre>\n\n<p>Both answers to this question were codes modified from a <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163419.aspx\" rel=\"nofollow noreferrer\">great MSDN article by Ray Djajadinata.</a></p>\n" }, { "answer_id": 61260, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 7, "selected": false, "text": "<p>Functions are objects and therefore can have properties.</p>\n\n<pre>\nfn = function(x) {\n // ...\n}\n\nfn.foo = 1;\n\nfn.next = function(y) {\n //\n}\n</pre>\n" }, { "answer_id": 61545, "author": "Martin Clarke", "author_id": 2422, "author_profile": "https://Stackoverflow.com/users/2422", "pm_score": 8, "selected": false, "text": "<p>I could quote most of Douglas Crockford's excellent book\n<a href=\"https://rads.stackoverflow.com/amzn/click/com/0596517742\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">JavaScript: The Good Parts</a>.</p>\n\n<p>But I'll take just one for you, always use <code>===</code> and <code>!==</code> instead of <code>==</code> and <code>!=</code></p>\n\n<pre><code>alert('' == '0'); //false\nalert(0 == ''); // true\nalert(0 =='0'); // true\n</code></pre>\n\n<p><code>==</code> is not transitive. If you use <code>===</code> it would give false for \nall of these statements as expected.</p>\n" }, { "answer_id": 61584, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "<p>Javascript has static variables inside functions:</p>\n\n<pre><code>function someFunction(){\n var Static = arguments.callee;\n Static.someStaticVariable = (Static.someStaticVariable || 0) + 1;\n alert(Static.someStaticVariable);\n}\nsomeFunction() //Alerts 1\nsomeFunction() //Alerts 2\nsomeFunction() //Alerts 3\n</code></pre>\n\n<p>It also has static variables inside Objects:</p>\n\n<pre><code>function Obj(){\n this.Static = arguments.callee;\n}\na = new Obj();\na.Static.name = \"a\";\nb = new Obj();\nalert(b.Static.name); //Alerts b\n</code></pre>\n" }, { "answer_id": 64404, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 3, "selected": false, "text": "<p><code>undefined</code> is undefined. So you can do this:</p>\n\n<pre><code>if (obj.field === undefined) /* ... */\n</code></pre>\n" }, { "answer_id": 64912, "author": "Vitaly Sharovatov", "author_id": 6647, "author_profile": "https://Stackoverflow.com/users/6647", "pm_score": 2, "selected": false, "text": "<p>As Marius already pointed, you can have public static variables in functions. </p>\n\n<p>I usually use them to create functions that are executed only once, or to cache some complex calculation results.</p>\n\n<p>Here's the example of my old \"singleton\" approach:</p>\n\n<pre><code>var singleton = function(){ \n\n if (typeof arguments.callee.__instance__ == 'undefined') { \n\n arguments.callee.__instance__ = new function(){\n\n //this creates a random private variable.\n //this could be a complicated calculation or DOM traversing that takes long\n //or anything that needs to be \"cached\"\n var rnd = Math.random();\n\n //just a \"public\" function showing the private variable value\n this.smth = function(){ alert('it is an object with a rand num=' + rnd); };\n\n };\n\n }\n\n return arguments.callee.__instance__;\n\n};\n\n\nvar a = new singleton;\nvar b = new singleton;\n\na.smth(); \nb.smth();\n</code></pre>\n\n<p>As you may see, in both cases the constructor is run only once.</p>\n\n<p>For example, I used this approach back in 2004 when I had to\ncreate a modal dialog box with a gray background that\ncovered the whole page (something like <a href=\"http://en.wikipedia.org/wiki/Lightbox_(JavaScript)\" rel=\"nofollow noreferrer\">Lightbox</a>). Internet\nExplorer 5.5 and 6 have the highest stacking context for\n&lt;select&gt; or &lt;iframe&gt; elements due to their\n\"windowed\" nature; so if the page contained select elements,\nthe only way to cover them was to create an iframe and\nposition it \"on top\" of the page. So the whole script was\nquite complex and a little bit slow (it used filter:\nexpressions to set opacity for the covering iframe). The\n\"shim\" script had only one \".show()\" method, which created\nthe shim only once and cached it in the static variable :)</p>\n" }, { "answer_id": 64950, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 4, "selected": false, "text": "<p>The way JavaScript works with Date() just excites me!</p>\n\n<pre><code>function isLeapYear(year) {\n return (new Date(year, 1, 29, 0, 0).getMonth() != 2);\n}\n</code></pre>\n\n<p>This is really \"hidden feature\".</p>\n\n<p>Edit: Removed \"?\" condition as suggested in comments for politcorrecteness. \nWas: ... new Date(year, 1, 29, 0, 0).getMonth() != 2 ? true : false ...\nPlease look at comments for details.</p>\n" }, { "answer_id": 65002, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>All functions are actually instances of the built-in <strong>Function</strong> type, which has a constructor that takes a string containing the function definition, so you can actually define functions at run-time by e.g., concatenating strings:</p>\n\n<pre><code>//e.g., createAddFunction(\"a\",\"b\") returns function(a,b) { return a+b; }\nfunction createAddFunction(paramName1, paramName2)\n { return new Function( paramName1, paramName2\n ,\"return \"+ paramName1 +\" + \"+ paramName2 +\";\");\n }\n</code></pre>\n\n<p>Also, for user-defined functions, <strong>Function.toString()</strong> returns the function definition as a literal string.</p>\n" }, { "answer_id": 65028, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": false, "text": "<p>You don't need to define any parameters for a function. You can just use the function's <code>arguments</code> array-like object.</p>\n\n<pre><code>function sum() {\n var retval = 0;\n for (var i = 0, len = arguments.length; i &lt; len; ++i) {\n retval += arguments[i];\n }\n return retval;\n}\n\nsum(1, 2, 3) // returns 6\n</code></pre>\n" }, { "answer_id": 65064, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "<p>All objects in Javascript are implemented as hashtables, so their properties can be accessed through the indexer and vice-versa. Also, you can enumerate all the properties using the <strong>for/in</strong> operator:</p>\n\n<pre><code>var x = {a: 0};\nx[\"a\"]; //returns 0\n\nx[\"b\"] = 1;\nx.b; //returns 1\n\nfor (p in x) document.write(p+\";\"); //writes \"a;b;\"\n</code></pre>\n" }, { "answer_id": 65124, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": false, "text": "<p>You can use the <strong>in</strong> operator to check if a key exists in an object:</p>\n\n<pre><code>var x = 1;\nvar y = 3;\nvar list = {0:0, 1:0, 2:0};\nx in list; //true\ny in list; //false\n1 in list; //true\ny in {3:0, 4:0, 5:0}; //true\n</code></pre>\n\n<p>If you find the object literals too ugly you can combine it with the parameterless function tip:</p>\n\n<pre><code>function list()\n { var x = {};\n for(var i=0; i &lt; arguments.length; ++i) x[arguments[i]] = 0;\n return x\n }\n\n 5 in list(1,2,3,4,5) //true\n</code></pre>\n" }, { "answer_id": 65415, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 4, "selected": false, "text": "<p>JavaScript uses a simple object literal:</p>\n\n<pre><code>var x = { intValue: 5, strValue: \"foo\" };\n</code></pre>\n\n<p>This constructs a full-fledged object.</p>\n\n<p>JavaScript uses prototype-based object orientation and provides the ability to extend types at runtime:</p>\n\n<pre><code>String.prototype.doubleLength = function() {\n return this.length * 2;\n}\n\nalert(\"foo\".doubleLength());\n</code></pre>\n\n<p>An object delegates all access to attributes that it doesn't contain itself to its \"prototype\", another object. This can be used to implement inheritance, but is actually more powerful (even if more cumbersome):</p>\n\n<pre><code>/* \"Constructor\" */\nfunction foo() {\n this.intValue = 5;\n}\n\n/* Create the prototype that includes everything\n * common to all objects created be the foo function.\n */\nfoo.prototype = {\n method: function() {\n alert(this.intValue);\n }\n}\n\nvar f = new foo();\nf.method();\n</code></pre>\n" }, { "answer_id": 67614, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 7, "selected": false, "text": "<p>Maybe a little obvious to some...</p>\n\n<p>Install <a href=\"http://en.wikipedia.org/wiki/Firebug_(Firefox_extension)\" rel=\"nofollow noreferrer\">Firebug</a> and use console.log(\"hello\"). So much better than using random alert();'s which I remember doing a lot a few years ago.</p>\n" }, { "answer_id": 68961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>One of my favorites is constructor type checking:</p>\n\n<pre><code>function getObjectType( obj ) { \n return obj.constructor.name; \n} \n\nwindow.onload = function() { \n alert( getObjectType( \"Hello World!\" ) ); \n function Cat() { \n // some code here... \n } \n alert( getObjectType( new Cat() ) ); \n}\n</code></pre>\n\n<p>So instead of the tired old [Object object] you often get with the typeof keyword, you can actually get real object types based upon the constructor.</p>\n\n<p>Another one is using variable arguments as a way to \"overload\" functions. All you are doing is using an expression to detect the number of arguments and returning overloaded output:</p>\n\n<pre><code>function myFunction( message, iteration ) { \n if ( arguments.length == 2 ) { \n for ( i = 0; i &lt; iteration; i++ ) { \n alert( message ); \n } \n } else { \n alert( message ); \n } \n} \n\nwindow.onload = function() { \n myFunction( \"Hello World!\", 3 ); \n}\n</code></pre>\n\n<p>Finally, I would say assignment operator shorthand. I learned this from the source of the jQuery framework... the old way:</p>\n\n<pre><code>var a, b, c, d;\nb = a;\nc = b;\nd = c;\n</code></pre>\n\n<p>The new (shorthand) way:</p>\n\n<pre><code>var a, b, c, d;\nd = c = b = a;\n</code></pre>\n\n<p>Good fun :)</p>\n" }, { "answer_id": 75844, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 3, "selected": false, "text": "<p>This one is super hidden, and only occasionally useful ;-)</p>\n\n<p>You can use the prototype chain to create an object that delegates to another object without changing the original object.</p>\n\n<pre><code>var o1 = { foo: 1, bar: 'abc' };\nfunction f() {}\nf.prototype = o1;\no2 = new f();\nassert( o2.foo === 1 );\nassert( o2.bar === 'abc' );\no2.foo = 2;\no2.baz = true;\nassert( o2.foo === 2 );\n// o1 is unchanged by assignment to o2\nassert( o1.foo === 1 );\nassert( o2.baz );\n</code></pre>\n\n<p>This only covers 'simple' values on o1. If you modify an array or another object, then the prototype no longer 'protects' the original object. Beware anytime you have an {} or [] in a Class definition/prototype.</p>\n" }, { "answer_id": 78155, "author": "user14079", "author_id": 14079, "author_profile": "https://Stackoverflow.com/users/14079", "pm_score": 4, "selected": false, "text": "<p>Timestamps in JavaScript:</p>\n\n<pre><code>// Usual Way\nvar d = new Date();\ntimestamp = d.getTime();\n\n// Shorter Way\ntimestamp = (new Date()).getTime();\n\n// Shortest Way\ntimestamp = +new Date();\n</code></pre>\n" }, { "answer_id": 78290, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": false, "text": "<p>Function.toString() (implicit):</p>\n\n<pre><code>function x() {\n alert(\"Hello World\");\n}\neval (\"x = \" + (x + \"\").replace(\n 'Hello World',\n 'STACK OVERFLOW BWAHAHA\"); x(\"'));\nx();\n</code></pre>\n" }, { "answer_id": 104424, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 5, "selected": false, "text": "<p>Private variables with a Public Interface</p>\n\n<p>It uses a neat little trick with a self-calling function definition.\nEverything inside the object which is returned is available in the public interface, while everything else is private.</p>\n\n<pre><code>var test = function () {\n //private members\n var x = 1;\n var y = function () {\n return x * 2;\n };\n //public interface\n return {\n setx : function (newx) {\n x = newx;\n },\n gety : function () {\n return y();\n }\n }\n}();\n\nassert(undefined == test.x);\nassert(undefined == test.y);\nassert(2 == test.gety());\ntest.setx(5);\nassert(10 == test.gety());\n</code></pre>\n" }, { "answer_id": 105603, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 6, "selected": false, "text": "<p>Methods (or functions) can be called on object that are not of the type they were designed to work with. This is great to call native (fast) methods on custom objects.</p>\n\n<pre><code>var listNodes = document.getElementsByTagName('a');\nlistNodes.sort(function(a, b){ ... });\n</code></pre>\n\n<p>This code crashes because <code>listNodes</code> is not an <code>Array</code></p>\n\n<pre><code>Array.prototype.sort.apply(listNodes, [function(a, b){ ... }]);\n</code></pre>\n\n<p>This code works because <code>listNodes</code> defines enough array-like properties (length, [] operator) to be used by <code>sort()</code>.</p>\n" }, { "answer_id": 109360, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 5, "selected": false, "text": "<p>Numbers are also objects. So you can do cool stuff like:</p>\n\n<pre><code>// convert to base 2\n(5).toString(2) // returns \"101\"\n\n// provide built in iteration\nNumber.prototype.times = function(funct){\n if(typeof funct === 'function') {\n for(var i = 0;i &lt; Math.floor(this);i++) {\n funct(i);\n }\n }\n return this;\n}\n\n\n(5).times(function(i){\n string += i+\" \";\n});\n// string now equals \"0 1 2 3 4 \"\n\nvar x = 1000;\n\nx.times(function(i){\n document.body.innerHTML += '&lt;p&gt;paragraph #'+i+'&lt;/p&gt;';\n});\n// adds 1000 parapraphs to the document\n</code></pre>\n" }, { "answer_id": 110337, "author": "user19745", "author_id": 19745, "author_profile": "https://Stackoverflow.com/users/19745", "pm_score": 3, "selected": false, "text": "<p>You can do almost anything between parentheses if you separate statements with commas:</p>\n\n<pre><code>var z = ( x = \"can you do crazy things with parenthesis\", ( y = x.split(\" \"), [ y[1], y[0] ].concat( y.slice(2) ) ).join(\" \") )\n\nalert(x + \"\\n\" + y + \"\\n\" + z)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>can you do crazy things with parenthesis\ncan,you,do,crazy,things,with,parenthesis\nyou can do crazy things with parenthesis\n</code></pre>\n" }, { "answer_id": 112295, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 3, "selected": false, "text": "<p>The concept of truthy and falsy values. You don't need to do something like</p>\n\n<p>if(someVar === undefined || someVar === null) ...</p>\n\n<p>Simply do:</p>\n\n<p>if(!someVar).</p>\n\n<p>Every value has a corresponding boolean representation.</p>\n" }, { "answer_id": 114695, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>You can execute an object's method on any object, regardless of whether it has that method or not. Of course it might not always work (if the method assumes the object has something it doesn't), but it can be extremely useful. For example:</p>\n\n<pre><code>function(){\n arguments.push('foo') // This errors, arguments is not a proper array and has no push method\n Array.prototype.push.apply(arguments, ['foo']) // Works!\n}\n</code></pre>\n" }, { "answer_id": 115587, "author": "jrockway", "author_id": 8457, "author_profile": "https://Stackoverflow.com/users/8457", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://code.google.com/p/joose-js/\" rel=\"nofollow noreferrer\">Joose</a> is a nice object system if you would like Class-based OO that feels somewhat like CLOS.</p>\n\n<pre><code>// Create a class called Point\nClass(\"Point\", {\n has: {\n x: {\n is: \"rw\",\n init: 0\n },\n y: {\n is: \"rw\",\n init: 0\n }\n },\n methods: {\n clear: function () {\n this.setX(0);\n this.setY(0);\n }\n }\n})\n\n// Use the class\nvar point = new Point();\npoint.setX(10)\npoint.setY(20);\npoint.clear();\n</code></pre>\n" }, { "answer_id": 115622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>All your \"hidden\" features are right here on the Mozilla wiki: <a href=\"http://developer.mozilla.org/en/JavaScript\" rel=\"nofollow noreferrer\">http://developer.mozilla.org/en/JavaScript</a>.</p>\n\n<p>There's <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference\" rel=\"nofollow noreferrer\">the core JavaScript 1.5 reference</a>, <a href=\"http://developer.mozilla.org/en/New_in_JavaScript_1.6\" rel=\"nofollow noreferrer\">what's new in JavaScript 1.6</a>, what's <a href=\"http://developer.mozilla.org/en/New_in_JavaScript_1.7\" rel=\"nofollow noreferrer\">new in JavaScript 1.7</a>, and also what's <a href=\"http://developer.mozilla.org/en/New_in_JavaScript_1.8\" rel=\"nofollow noreferrer\">new in JavaScript 1.8</a>. Look through all of those for examples that actually work and are <em>not</em> wrong.</p>\n" }, { "answer_id": 115798, "author": "amix", "author_id": 20081, "author_profile": "https://Stackoverflow.com/users/20081", "pm_score": 3, "selected": false, "text": "<p>Visit:</p>\n\n<ul>\n<li><a href=\"http://images.google.com/images?q=disco\" rel=\"nofollow noreferrer\">http://images.google.com/images?q=disco</a> </li>\n</ul>\n\n<p>Paste this JavaScript code into your web browser's address bar:</p>\n\n<ul>\n<li><a href=\"http://amix.dk/upload/awt/spin.txt\" rel=\"nofollow noreferrer\">http://amix.dk/upload/awt/spin.txt</a></li>\n<li><a href=\"http://amix.dk/upload/awt/disco.txt\" rel=\"nofollow noreferrer\">http://amix.dk/upload/awt/disco.txt</a></li>\n</ul>\n\n<p>Enjoy the JavaScript disco show :-p</p>\n" }, { "answer_id": 116790, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 5, "selected": false, "text": "<p>Some would call this a matter of taste, but:</p>\n\n<pre><code>aWizz = wizz || \"default\";\n// same as: if (wizz) { aWizz = wizz; } else { aWizz = \"default\"; }\n</code></pre>\n\n<p>The trinary operator can be chained to act like Scheme's (cond ...):</p>\n\n<pre><code>(cond (predicate (action ...))\n (predicate2 (action2 ...))\n (#t default ))\n</code></pre>\n\n<p>can be written as...</p>\n\n<pre><code>predicate ? action( ... ) :\npredicate2 ? action2( ... ) :\n default;\n</code></pre>\n\n<p>This is very \"functional\", as it branches your code without side effects. So instead of:</p>\n\n<pre><code>if (predicate) {\n foo = \"one\";\n} else if (predicate2) {\n foo = \"two\";\n} else {\n foo = \"default\";\n}\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>foo = predicate ? \"one\" :\n predicate2 ? \"two\" :\n \"default\";\n</code></pre>\n\n<p>Works nice with recursion, too :)</p>\n" }, { "answer_id": 117022, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 5, "selected": false, "text": "<p>Off the top of my head...</p>\n\n<p><strong>Functions</strong></p>\n\n<p>arguments.callee refers to the function that hosts the \"arguments\" variable, so it can be used to recurse anonymous functions:</p>\n\n<pre><code>var recurse = function() {\n if (condition) arguments.callee(); //calls recurse() again\n}\n</code></pre>\n\n<p>That's useful if you want to do something like this:</p>\n\n<pre><code>//do something to all array items within an array recursively\nmyArray.forEach(function(item) {\n if (item instanceof Array) item.forEach(arguments.callee)\n else {/*...*/}\n})\n</code></pre>\n\n<p><strong>Objects</strong></p>\n\n<p>An interesting thing about object members: they can have any string as their names:</p>\n\n<pre><code>//these are normal object members\nvar obj = {\n a : function() {},\n b : function() {}\n}\n//but we can do this too\nvar rules = {\n \".layout .widget\" : function(element) {},\n \"a[href]\" : function(element) {}\n}\n/* \nthis snippet searches the page for elements that\nmatch the CSS selectors and applies the respective function to them:\n*/\nfor (var item in rules) {\n var elements = document.querySelectorAll(rules[item]);\n for (var e, i = 0; e = elements[i++];) rules[item](e);\n}\n</code></pre>\n\n<p><strong>Strings</strong></p>\n\n<p><em>String.split</em> can take regular expressions as parameters:</p>\n\n<pre><code>\"hello world with spaces\".split(/\\s+/g);\n//returns an array: [\"hello\", \"world\", \"with\", \"spaces\"]\n</code></pre>\n\n<p><em>String.replace</em> can take a regular expression as a search parameter and a function as a replacement parameter:</p>\n\n<pre><code>var i = 1;\n\"foo bar baz \".replace(/\\s+/g, function() {return i++});\n//returns \"foo1bar2baz3\"\n</code></pre>\n" }, { "answer_id": 117922, "author": "treat your mods well", "author_id": 20772, "author_profile": "https://Stackoverflow.com/users/20772", "pm_score": 1, "selected": false, "text": "<p>You can redefine large parts of the runtime environment on the fly, such as <a href=\"http://directwebremoting.org/blog/joe/2007/03/05/json_is_not_as_safe_as_people_think_it_is.html\" rel=\"nofollow noreferrer\">modifying the <code>Array</code> constructor</a> or defining <code>undefined</code>. Not that you should, but it <em>can</em> be a powerful feature.</p>\n\n<p>A somewhat less dangerous form of this is the addition of helper methods to existing objects. You can <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf#Compatibility\" rel=\"nofollow noreferrer\">make IE6 \"natively\" support indexOf on arrays</a>, for example.</p>\n" }, { "answer_id": 117951, "author": "David Leonard", "author_id": 19502, "author_profile": "https://Stackoverflow.com/users/19502", "pm_score": 6, "selected": false, "text": "<p>Here are some interesting things:</p>\n\n<ul>\n<li>Comparing <code>NaN</code> with anything (even <code>NaN</code>) is always false, that includes <code>==</code>, <code>&lt;</code> and <code>&gt;</code>.</li>\n<li><code>NaN</code> Stands for Not a Number but if you ask for the type it actually returns a number.</li>\n<li><code>Array.sort</code> can take a comparator function and is called by a quicksort-like driver (depends on implementation).</li>\n<li>Regular expression \"constants\" can maintain state, like the last thing they matched.</li>\n<li>Some versions of JavaScript allow you to access <code>$0</code>, <code>$1</code>, <code>$2</code> members on a regex.</li>\n<li><code>null</code> is unlike anything else. It is neither an object, a boolean, a number, a string, nor <code>undefined</code>. It's a bit like an \"alternate\" <code>undefined</code>. (Note: <code>typeof null == \"object\"</code>)</li>\n<li>In the outermost context, <code>this</code> yields the otherwise unnameable [Global] object.</li>\n<li>Declaring a variable with <code>var</code>, instead of just relying on automatic declaration of the variable gives the runtime a real chance of optimizing access to that variable</li>\n<li>The <code>with</code> construct will destroy such optimzations</li>\n<li>Variable names can contain Unicode characters.</li>\n<li>JavaScript regular expressions are not actually regular. They are based on Perl's regexs, and it is possible to construct expressions with lookaheads that take a very, very long time to evaluate.</li>\n<li>Blocks can be labeled and used as the targets of <code>break</code>. Loops can be labeled and used as the target of <code>continue</code>.</li>\n<li>Arrays are not sparse. Setting the 1000th element of an otherwise empty array should fill it with <code>undefined</code>. (depends on implementation)</li>\n<li><code>if (new Boolean(false)) {...}</code> will execute the <code>{...}</code> block</li>\n<li>Javascript's regular expression engine's are implementation specific: e.g. it is possible to write \"non-portable\" regular expressions. </li>\n</ul>\n\n<p><em>[updated a little in response to good comments; please see comments]</em></p>\n" }, { "answer_id": 118150, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>Also mentioned in Crockford's \"Javascript: The Good Parts\":</p>\n\n<p><code>parseInt()</code> is dangerous. If you pass it a string without informing it of the proper base it may return unexpected numbers. For example <code>parseInt('010')</code> returns 8, not 10. Passing a base to parseInt makes it work correctly:</p>\n\n<pre><code>parseInt('010') // returns 8! (in FF3)\nparseInt('010', 10); // returns 10 because we've informed it which base to work with.\n</code></pre>\n" }, { "answer_id": 118556, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "<p>There are several answers in this thread showing how to \nextend the Array object via its prototype. This is a BAD \nIDEA, because it breaks the <code>for (i in a)</code> statement.</p>\n\n<p>So is it okay if you don't happen to use <code>for (i in a)</code> \nanywhere in your code? Well, only if your own code is the \nonly code that you are running, which is not too likely \ninside a browser. I'm afraid that if folks start extending \ntheir Array objects like this, Stack Overflow will start \noverflowing with a bunch of mysterious JavaScript bugs.</p>\n\n<p>See helpful details <a href=\"http://web-graphics.com/2006/05/23/on-modifying-prototypes-of-javascript-built-ins/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 123136, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": false, "text": "<p>Here's a couple of shortcuts:</p>\n\n<pre><code>var a = []; // equivalent to new Array()\nvar o = {}; // equivalent to new Object()\n</code></pre>\n" }, { "answer_id": 128867, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 7, "selected": false, "text": "<p>I'd have to say self-executing functions.</p>\n\n<pre><code>(function() { alert(\"hi there\");})();\n</code></pre>\n\n<p>Because Javascript <a href=\"https://stackoverflow.com/questions/61088/hidden-features-of-javascript/61173#61173\">doesn't have block scope</a>, you can use a self-executing function if you want to define local variables:</p>\n\n<pre><code>(function() {\n var myvar = 2;\n alert(myvar);\n})();\n</code></pre>\n\n<p>Here, <code>myvar</code> is does not interfere with or pollute the global scope, and disappears when the function terminates.</p>\n" }, { "answer_id": 143666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The == operator has a very special property, that creates this disturbing equality (Yes, I know in other dynamic languages like Perl this behavior would be expected but JavaScript ususally does not try to be smart in comparisons):</p>\n\n<pre><code>&gt;&gt;&gt; 1 == true\ntrue\n&gt;&gt;&gt; 0 == false\ntrue\n&gt;&gt;&gt; 2 == true\nfalse\n</code></pre>\n" }, { "answer_id": 152545, "author": "Rob", "author_id": 11715, "author_profile": "https://Stackoverflow.com/users/11715", "pm_score": 4, "selected": false, "text": "<p>Prevent annoying errors while testing in Internet Explorer when using console.log() for Firebug:</p>\n\n<pre><code>function log(message) {\n (console || { log: function(s) { alert(s); }).log(message);\n}\n</code></pre>\n" }, { "answer_id": 155730, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": false, "text": "<p><code>let</code>.</p>\n\n<p>Counterpart to <a href=\"https://stackoverflow.com/questions/61088/hidden-features-of-javascript#61173\">var's lack of block-scoping</a> is <code>let</code>, <a href=\"http://developer.mozilla.org/en/New_in_JavaScript_1.7#Block_scope_with_let\" rel=\"nofollow noreferrer\">introduced in JavaScript 1.7</a>.</p>\n\n<blockquote>\n <ul>\n <li>The let statement provides a way to associate values with variables\n within the scope of a block, without\n affecting the values of like-named\n variables outside the block.</li>\n <li>The let expression lets you establish variables scoped only to a\n single expression.</li>\n <li>The let definition defines variables whose scope is constrained\n to the block in which they're defined.\n This syntax is very much like the\n syntax used for var.</li>\n <li>You can also use let to establish variables that exist only within the\n context of a for loop.</li>\n </ul>\n</blockquote>\n\n<pre><code> function varTest() {\n var x = 31;\n if (true) {\n var x = 71; // same variable!\n alert(x); // 71\n }\n alert(x); // 71\n }\n\n function letTest() {\n let x = 31;\n if (true) {\n let x = 71; // different variable\n alert(x); // 71\n }\n alert(x); // 31\n }\n</code></pre>\n\n<p>As of 2008, JavaScript 1.7 is supported in FireFox 2.0+ and Safari 3.x.</p>\n" }, { "answer_id": 155761, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://developer.mozilla.org/en/New_in_JavaScript_1.7#Generators_and_iterators\" rel=\"nofollow noreferrer\">Generators and Iterators</a> (works only in Firefox 2+ and Safari).</p>\n\n<pre><code>function fib() {\n var i = 0, j = 1;\n while (true) {\n yield i;\n var t = i;\n i = j;\n j += t;\n }\n}\n\nvar g = fib();\nfor (var i = 0; i &lt; 10; i++) {\n document.write(g.next() + \"&lt;br&gt;\\n\");\n}\n</code></pre>\n\n<blockquote>\n <p>The function containing the <code>yield</code>\n keyword is a generator. When you call\n it, its formal parameters are bound to\n actual arguments, but its body isn't\n actually evaluated. Instead, a\n generator-iterator is returned. Each\n call to the generator-iterator's\n <code>next()</code> method performs another pass\n through the iterative algorithm. Each\n step's value is the value specified by\n the <code>yield</code> keyword. Think of <code>yield</code> as\n the generator-iterator version of\n return, indicating the boundary\n between each iteration of the\n algorithm. Each time you call <code>next()</code>,\n the generator code resumes from the\n statement following the <code>yield</code>.</p>\n \n <p>In normal usage, iterator objects are\n \"invisible\"; you won't need to operate\n on them explicitly, but will instead\n use JavaScript's <code>for...in</code> and <code>for each...in</code> statements to loop naturally\n over the keys and/or values of\n objects.</p>\n</blockquote>\n\n<pre><code>var objectWithIterator = getObjectSomehow();\n\nfor (var i in objectWithIterator)\n{\n document.write(objectWithIterator[i] + \"&lt;br&gt;\\n\");\n}\n</code></pre>\n" }, { "answer_id": 155805, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": false, "text": "<p>To properly remove a property from an object, you should delete the property instead of just setting it to <em>undefined</em>:</p>\n\n<pre><code>var obj = { prop1: 42, prop2: 43 };\n\nobj.prop2 = undefined;\n\nfor (var key in obj) {\n ...\n</code></pre>\n\n<p>The property <em>prop2</em> will still be part of the iteration. If you want to completely get rid of <em>prop2</em>, you should instead do:</p>\n\n<pre><code>delete obj.prop2;\n</code></pre>\n\n<p>The property <em>prop2</em> will no longer will make an appearance when you're iterating through the properties.</p>\n" }, { "answer_id": 156290, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 7, "selected": false, "text": "<p>If you're Googling for a decent JavaScript reference on a given topic, include the \"mdc\" keyword in your query and your first results will be from the Mozilla Developer Center. I don't carry any offline references or books with me. I always use the \"mdc\" keyword trick to directly get to what I'm looking for. For example:</p>\n\n<p>Google: <a href=\"http://www.google.com/search?q=javascript+array+sort+mdc\" rel=\"nofollow noreferrer\">javascript array sort mdc</a><br>\n(in most cases you may omit \"javascript\")</p>\n\n<p><strong>Update:</strong> Mozilla Developer <strong>Center</strong> has been renamed to Mozilla Developer <strong>Network</strong>. The \"mdc\" keyword trick still works, but soon enough we may have to <strong>start using \"mdn\" instead</strong>.</p>\n" }, { "answer_id": 158462, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "<p>If you blindly <code>eval()</code> a JSON string to deserialize it, you may run into problems:</p>\n\n<ol>\n<li>It's not secure. The string may contain malicious function calls!</li>\n<li><p>If you don't enclose the JSON string in parentheses, property names can be mistaken as labels, resulting in unexpected behaviour or a syntax error:</p>\n\n<pre><code>eval(\"{ \\\"foo\\\": 42 }\"); // syntax error: invalid label\neval(\"({ \\\"foo\\\": 42 })\"); // OK\n</code></pre></li>\n</ol>\n" }, { "answer_id": 170904, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>function l(f,n){n&amp;&amp;l(f,n-1,f(n));}</p>\n \n <p>l( function( loop ){ alert( loop ); },\n 5 );</p>\n</blockquote>\n\n<p>alerts 5, 4, 3, 2, 1</p>\n" }, { "answer_id": 179154, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>To convert a floating point number to an integer, you can use one of the following cryptic hacks (please don't):</p>\n\n<ol>\n<li><code>3.14 &gt;&gt; 0</code> (via <a href=\"https://stackoverflow.com/questions/173070/29999999999999999-5\">2.9999999999999999 &gt;&gt; .5?</a>)</li>\n<li><code>3.14 | 0</code> (via <a href=\"https://stackoverflow.com/questions/131406/what-is-the-best-method-to-convert-to-an-integer-in-javascript\">What is the best method to convert floating point to an integer in JavaScript?</a>)</li>\n<li><code>3.14 &amp; -1</code></li>\n<li><code>3.14 ^ 0</code></li>\n<li><code>~~3.14</code></li>\n</ol>\n\n<p>Basically, applying any binary operation on the float that won't change the final value (i.e. identity function) ends up converting the float to an integer.</p>\n" }, { "answer_id": 182493, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p><strong>jQuery and JavaScript:</strong></p>\n\n<p>Variable-names can contain a number of odd characters. I use the $ character to identify variables containing jQuery objects:</p>\n\n<pre><code>var $links = $(\"a\");\n\n$links.hide();\n</code></pre>\n\n<p>jQuery's pattern of chaining objects is quite nice, but applying this pattern can get a bit confusing. Fortunately JavaScript allows you to break lines, like so:</p>\n\n<pre><code>$(\"a\")\n.hide()\n.fadeIn()\n.fadeOut()\n.hide();\n</code></pre>\n\n<p><strong>General JavaScript:</strong></p>\n\n<p>I find it useful to emulate scope by using self-executing functions:</p>\n\n<pre><code>function test()\n{\n // scope of test()\n\n (function()\n {\n // scope inside the scope of test()\n }());\n\n // scope of test()\n}\n</code></pre>\n" }, { "answer_id": 224227, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 3, "selected": false, "text": "<p>Function statements and function expressions are handled differently.</p>\n\n<pre><code>function blarg(a) {return a;} // statement\nbleep = function(b) {return b;} //expression\n</code></pre>\n\n<p>All function statements are parsed before code is run - a function at the bottom of a JavaScript file will be available in the first statement. On the other hand, it won't be able to take advantage of certain dynamic context, such as surrounding <code>with</code> statements - the <code>with</code> hasn't been executed when the function is parsed.</p>\n\n<p>Function expressions execute inline, right where they are encountered. They aren't available before that time, but they can take advantage of dynamic context.</p>\n" }, { "answer_id": 238770, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 5, "selected": false, "text": "<p><strong>Prototypal inheritance</strong> (popularized by Douglas Crockford) completely revolutionizes the way you think about loads of things in Javascript.</p>\n\n<pre><code>Object.beget = (function(Function){\n return function(Object){\n Function.prototype = Object;\n return new Function;\n }\n})(function(){});\n</code></pre>\n\n<p>It's a killer! Pity how almost no one uses it.</p>\n\n<p>It allows you to \"beget\" new instances of any object, extend them, while maintaining a (live) prototypical inheritance link to their other properties. Example:</p>\n\n<pre><code>var A = {\n foo : 'greetings'\n}; \nvar B = Object.beget(A);\n\nalert(B.foo); // 'greetings'\n\n// changes and additionns to A are reflected in B\nA.foo = 'hello';\nalert(B.foo); // 'hello'\n\nA.bar = 'world';\nalert(B.bar); // 'world'\n\n\n// ...but not the other way around\nB.foo = 'wazzap';\nalert(A.foo); // 'hello'\n\nB.bar = 'universe';\nalert(A.bar); // 'world'\n</code></pre>\n" }, { "answer_id": 302545, "author": "bbrown", "author_id": 20595, "author_profile": "https://Stackoverflow.com/users/20595", "pm_score": 3, "selected": false, "text": "<p><code>window.name</code>'s value persists across page changes, can be read by the parent window if in same domain (if in an iframe, use <code>document.getElementById(\"your frame's ID\").contentWindow.name</code> to access it), and is limited only by available memory.</p>\n" }, { "answer_id": 347540, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 5, "selected": false, "text": "<p>Be sure to use the <strong>hasOwnProperty</strong> method when iterating through an object's properties:</p>\n\n<pre><code>for (p in anObject) {\n if (anObject.hasOwnProperty(p)) {\n //Do stuff with p here\n }\n}\n</code></pre>\n\n<p>This is done so that you will only access the <strong>direct properties of <em>anObject</em></strong>, and not use the properties that are down the prototype chain.</p>\n" }, { "answer_id": 347552, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 4, "selected": false, "text": "<p>When you want to remove an element from an array, one can use the <strong><em>delete</em></strong> operator, as such:</p>\n\n<pre><code>var numbers = [1,2,3,4,5];\ndelete numbers[3];\n//numbers is now [1,2,3,undefined,5]\n</code></pre>\n\n<p>As you can see, the element was removed, but a hole was left in the array since the element was replaced with an <em>undefined</em> value.</p>\n\n<p>Thus, to work around this problem, instead of using <em>delete</em>, use the <strong><em>splice</em></strong> array method...as such:</p>\n\n<pre><code>var numbers = [1,2,3,4,5];\nnumbers.splice(3,1);\n//numbers is now [1,2,3,5]\n</code></pre>\n\n<p>The first argument of <strong><em>splice</em></strong> is an ordinal in the array [index], and the second is the number of elements to delete.</p>\n" }, { "answer_id": 414508, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 3, "selected": false, "text": "<p>Microsofts <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"nofollow noreferrer\">gift to JavaScript</a>: AJAX</p>\n\n<pre><code>AJAXCall('http://www.abcd.com/')\n\nfunction AJAXCall(url) {\n var client = new XMLHttpRequest();\n client.onreadystatechange = handlerFunc;\n client.open(\"GET\", url);\n client.send();\n}\n\nfunction handlerFunc() {\n if(this.readyState == 4 &amp;&amp; this.status == 200) {\n if(this.responseXML != null)\n document.write(this.responseXML)\n }\n}\n</code></pre>\n" }, { "answer_id": 460884, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 2, "selected": false, "text": "<p>Large loops are faster in <code>while</code>-condition and backwards - that is, if the order of the loop doesn't matter to you. In about 50% of my code, it usually doesn't.</p>\n\n<p>i.e. </p>\n\n<pre><code>var i, len = 100000;\n\nfor (var i = 0; i &lt; len; i++) {\n // do stuff\n}\n</code></pre>\n\n<p>Is slower than:</p>\n\n<pre><code>i = len;\nwhile (i--) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 476923, "author": "Paweł Witkowski Photography", "author_id": 58260, "author_profile": "https://Stackoverflow.com/users/58260", "pm_score": 2, "selected": false, "text": "<p>There is also an almost unknown JavaScript syntax:</p>\n\n<pre><code>var a;\na=alert(5),7;\nalert(a); // alerts undefined\na=7,alert(5);\nalert(a); // alerts 7\n\na=(3,6);\nalert(a); // alerts 6\n</code></pre>\n\n<p>More about this <a href=\"https://stackoverflow.com/questions/476218/javascript-syntax-of-a-object-object\">here</a>.</p>\n" }, { "answer_id": 490143, "author": "Breton", "author_id": 51101, "author_profile": "https://Stackoverflow.com/users/51101", "pm_score": 5, "selected": false, "text": "<p>You can use objects instead of switches most of the time.</p>\n\n<pre><code>function getInnerText(o){\n return o === null? null : {\n string: o,\n array: o.map(getInnerText).join(\"\"),\n object:getInnerText(o[\"childNodes\"])\n }[typeis(o)];\n}\n</code></pre>\n\n<p>Update: if you're concerned about the cases evaluating in advance being inefficient (why are you worried about efficiency this early on in the design of the program??) then you can do something like this:</p>\n\n<pre><code>function getInnerText(o){\n return o === null? null : {\n string: function() { return o;},\n array: function() { return o.map(getInnerText).join(\"\"); },\n object: function () { return getInnerText(o[\"childNodes\"]; ) }\n }[typeis(o)]();\n}\n</code></pre>\n\n<p>This is more onerous to type (or read) than either a switch or an object, but it preserves the benefits of using an object instead of a switch, detailed in the comments section below. This style also makes it more straightforward to spin this out into a proper \"class\" once it grows up enough.</p>\n\n<p>update2: with proposed syntax extensions for ES.next, this becomes</p>\n\n<pre><code>let getInnerText = o -&gt; ({\n string: o -&gt; o,\n array: o -&gt; o.map(getInnerText).join(\"\"),\n object: o -&gt; getInnerText(o[\"childNodes\"])\n}[ typeis o ] || (-&gt;null) )(o);\n</code></pre>\n" }, { "answer_id": 490169, "author": "Ionuț G. Stan", "author_id": 58808, "author_profile": "https://Stackoverflow.com/users/58808", "pm_score": 5, "selected": false, "text": "<p>You may catch exceptions depending on their type. Quoted from <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/try...catch\" rel=\"nofollow noreferrer\">MDC</a>:</p>\n\n<pre><code>try {\n myroutine(); // may throw three exceptions\n} catch (e if e instanceof TypeError) {\n // statements to handle TypeError exceptions\n} catch (e if e instanceof RangeError) {\n // statements to handle RangeError exceptions\n} catch (e if e instanceof EvalError) {\n // statements to handle EvalError exceptions\n} catch (e) {\n // statements to handle any unspecified exceptions\n logMyErrors(e); // pass exception object to error handler\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> Conditional catch clauses are a Netscape (and hence Mozilla/Firefox) extension that is not part of the ECMAScript specification and hence cannot be relied upon except on particular browsers.</p>\n" }, { "answer_id": 490546, "author": "Breton", "author_id": 51101, "author_profile": "https://Stackoverflow.com/users/51101", "pm_score": 3, "selected": false, "text": "<p>You can turn \"any* object with integer properties, and a length property into an array proper, and thus endow it with all array methods such as push, pop, splice, map, filter, reduce, etc.</p>\n\n<pre><code>Array.prototype.slice.call({\"0\":\"foo\", \"1\":\"bar\", 2:\"baz\", \"length\":3 }) \n</code></pre>\n\n<p>// returns [\"foo\", \"bar\", \"baz\"]</p>\n\n<p>This works with jQuery objects, html collections, and Array objects from other frames (as one possible solution to the whole array type thing). I say, if it's got a length property, you can turn it into an array and it doesn't matter. There's lots of non array objects with a length property, beyond the arguments object.</p>\n" }, { "answer_id": 625580, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p><strong>Syntactic sugar: in-line for-loop closures</strong></p>\n\n<pre><code>var i;\n\nfor (i = 0; i &lt; 10; i++) (function ()\n{\n // do something with i\n}());\n</code></pre>\n\n<p>Breaks almost all of Douglas Crockford's code-conventions, but I think it's quite nice to look at, never the less :)</p>\n\n<hr>\n\n<p>Alternative:</p>\n\n<pre><code>var i;\n\nfor (i = 0; i &lt; 10; i++) (function (j)\n{\n // do something with j\n}(i));\n</code></pre>\n" }, { "answer_id": 628728, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "<p>This seems to only work on Firefox (SpiderMonkey). Inside a function:</p>\n\n<ul>\n<li><code>arguments[-2]</code> gives the number of arguments (same as <code>arguments.length</code>)</li>\n<li><code>arguments[-3]</code> gives the function that was called (same as <code>arguments.callee</code>)</li>\n</ul>\n" }, { "answer_id": 645331, "author": "nickytonline", "author_id": 77814, "author_profile": "https://Stackoverflow.com/users/77814", "pm_score": 2, "selected": false, "text": "<p>Existence checks. So often I see stuff like this</p>\n\n<pre><code>var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length &gt; 0) {\n // do something\n}\n</code></pre>\n\n<p>instead for example just do this:</p>\n\n<pre><code>var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length) { // if length is not equal to 0, this will be true\n // do something\n}\n</code></pre>\n\n<p>There's all kinds of existence checks you can do, but this was just a simple example to illustrate a point</p>\n\n<p>Here's an example on how to use a default value.</p>\n\n<pre><code>function (someArgument) {\n someArgument || (someArgument = \"This is the deault value\");\n}\n</code></pre>\n\n<p>That's my two cents. There's other nuggets, but that's it for now.</p>\n" }, { "answer_id": 692380, "author": "Lucent", "author_id": 6385, "author_profile": "https://Stackoverflow.com/users/6385", "pm_score": 4, "selected": false, "text": "<p>You never have to use <code>eval()</code> to assemble global variable names.</p>\n\n<p>That is, if you have several globals (for whatever reason) named <code>spec_grapes, spec_apples</code>, you do not have to access them with <code>eval(\"spec_\" + var)</code>.</p>\n\n<p>All globals are members of <code>window[]</code>, so you can do <code>window[\"spec_\" + var]</code>.</p>\n" }, { "answer_id": 731342, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "<h2>You can iterate over Arrays using \"for in\"</h2>\n\n<p>Mark Cidade pointed out the usefullness of the \"for in\" loop :</p>\n\n<pre><code>// creating an object (the short way, to use it like a hashmap)\nvar diner = {\n\"fruit\":\"apple\"\n\"veggetable\"=\"bean\"\n}\n\n// looping over its properties\nfor (meal_name in diner ) {\n document.write(meal_name+\"&lt;br \\n&gt;\");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>fruit\nveggetable\n</code></pre>\n\n<p>But there is more. Since you can use an object like an associative array, you can process keys and values,\njust like a foreach loop :</p>\n\n<pre><code>// looping over its properties and values\nfor (meal_name in diner ) {\n document.write(meal_name+\" : \"+diner[meal_name]+\"&lt;br \\n&gt;\");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>fruit : apple\nveggetable : bean\n</code></pre>\n\n<p>And since Array are objects too, you can iterate other array the exact same way :</p>\n\n<pre><code>var my_array = ['a', 'b', 'c'];\nfor (index in my_array ) {\n document.write(index+\" : \"+my_array[index]+\"&lt;br \\n&gt;\");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>0 : a\n1 : b\n3 : c\n</code></pre>\n\n<h2>You can remove easily an known element from an array</h2>\n\n<pre><code>var arr = ['a', 'b', 'c', 'd'];\nvar pos = arr.indexOf('c');\npos &gt; -1 &amp;&amp; arr.splice( pos, 1 );\n</code></pre>\n\n<h2>You can shuffle easily an array</h2>\n\n<p><strike><code>arr.sort(function() Math.random() - 0.5);</code></strike> – not really random distribution, see comments.</p>\n" }, { "answer_id": 731411, "author": "David", "author_id": 21909, "author_profile": "https://Stackoverflow.com/users/21909", "pm_score": 3, "selected": false, "text": "<p>The parentheses are optional when creating new \"objects\".</p>\n\n<pre><code>function Animal () {\n\n}\n\nvar animal = new Animal();\nvar animal = new Animal;\n</code></pre>\n\n<p>Same thing.</p>\n" }, { "answer_id": 841201, "author": "username", "author_id": 4939, "author_profile": "https://Stackoverflow.com/users/4939", "pm_score": 4, "selected": false, "text": "<p>You can assign local variables using [] on the left hand side. Comes in handy if you want to return more than one value from a function without creating a needless array.</p>\n\n<pre><code>function fn(){\n var cat = \"meow\";\n var dog = \"woof\";\n return [cat,dog];\n};\n\nvar [cat,dog] = fn(); // Handy!\n\nalert(cat);\nalert(dog);\n</code></pre>\n\n<p><s>It's part of core JS but somehow I never realized till this year.</s></p>\n" }, { "answer_id": 843499, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://code.google.com/p/jslibs/wiki/JavascriptTips\" rel=\"nofollow noreferrer\">JavaScript tips</a> or the <a href=\"http://code.google.com/p/jslibs/\" rel=\"nofollow noreferrer\">jslibs project</a>.</p>\n" }, { "answer_id": 865753, "author": "Sebastian Schuth", "author_id": 107339, "author_profile": "https://Stackoverflow.com/users/107339", "pm_score": 2, "selected": false, "text": "<p>Maybe one of the lesser-known ones:</p>\n\n<p>arguments.callee.caller + Function#toString()</p>\n\n<pre><code>function called(){\n alert(\"Go called by:\\n\"+arguments.callee.caller.toString());\n}\n\nfunction iDoTheCall(){\n called();\n}\n\niDoTheCall();\n</code></pre>\n\n<p>Prints out the source code of <code>iDoTheCall</code> --\nDeprecated, but can be useful sometimes when alerting is your only option....</p>\n" }, { "answer_id": 955784, "author": "pawelsto", "author_id": 109208, "author_profile": "https://Stackoverflow.com/users/109208", "pm_score": 1, "selected": false, "text": "<p>You can bind a JavaScript object as a HTML element attribute.</p>\n\n<pre><code>&lt;div id=\"jsTest\"&gt;Klick Me&lt;/div&gt;\n&lt;script type=\"text/javascript\"&gt;\n var someVariable = 'I was klicked';\n var divElement = document.getElementById('jsTest');\n // binding function/object or anything as attribute\n divElement.controller = function() { someVariable += '*'; alert('You can change instance data:\\n' + someVariable ); };\n var onclickFunct = new Function( 'this.controller();' ); // Works in Firefox and Internet Explorer.\n divElement.onclick = onclickFunct;\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 1024826, "author": "Metal", "author_id": 75025, "author_profile": "https://Stackoverflow.com/users/75025", "pm_score": 3, "selected": false, "text": "<p>If you're attempting to sandbox javascript code, and disable every possible way to evaluate strings into javascript code, be aware that blocking all the obvious eval/document.write/new Function/setTimeout/setInterval/innerHTML and other DOM manipulations isn't enough.</p>\n\n<p>Given any object o, <code>o.constructor.constructor(\"alert('hi')\")()</code> will bring up an alert dialog with the word \"hi\" in it.</p>\n\n<p>You could rewrite it as</p>\n\n<pre><code>var Z=\"constructor\";\nZ[Z][Z](\"alert('hi')\")();\n</code></pre>\n\n<p>Fun stuff.</p>\n" }, { "answer_id": 1025127, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The fastest loops in JavaScript are while(i--) ones. In all browsers.\nSo if it's not that important for order in which elements of your loop get processed you should be using while(i--) form:</p>\n\n<pre><code>var names = new Array(1024), i = names.length;\nwhile(i--)\n names[i] = \"John\" + i;\n</code></pre>\n\n<p>Also, if you have to use for() loop going forward, remember always to cache .length property:</p>\n\n<pre><code>var birds = new Array(1024); \nfor(var i = 0, j = birds.length; i &lt; j; i++)\n birds[i].fly();\n</code></pre>\n\n<p>To join large strings use Arrays (it's faster):</p>\n\n<pre><code>var largeString = new Array(1024), i = largeString.length;\nwhile(i--) {\n // It's faster than for() loop with largeString.push(), obviously :)\n largeString[i] = i.toString(16);\n}\n\nlargeString = largeString.join(\"\");\n</code></pre>\n\n<p>It's much faster than <code>largeString += \"something\"</code> inside an loop.</p>\n" }, { "answer_id": 1025990, "author": "Justin Johnson", "author_id": 126562, "author_profile": "https://Stackoverflow.com/users/126562", "pm_score": 1, "selected": false, "text": "<p>The coalescing operator is very cool and makes for some clean, concise code, especially when you chain it together: <code>a || b || c || \"default\";</code> The gotcha is that since it works by evaluating to bool rather than null, if values that evaluate to false are valid, they'll often times get over looked. Not to worry, in these cases just revert to the good ol' ternary operator. </p>\n\n<p>I often see code that has given up and used global instead of static variables, so here's how (in an example of what I suppose you could call a generic singleton factory):</p>\n\n<pre><code>var getInstance = function(objectName) {\n if ( !getInstance.instances ) {\n getInstance.instances = {};\n }\n\n if ( !getInstance.instances[objectName] ) {\n getInstance.instances[objectName] = new window[objectName];\n }\n\n return getInstance.instances[objectName];\n};\n</code></pre>\n\n<p>Also, note the <code>new window[objectName];</code> which was the key to generically instantiating objects by name. I just figured that out 2 months ago.</p>\n\n<p>In the same spirit, when working with the DOM, I often bury functioning parameters and/or flags into DOM nodes when I first initialize whatever functionality I'm adding. I'll add an example if someone squawks.</p>\n\n<p>Surprisingly, no one on the first page has mentioned <code>hasOwnProperty</code>, which is a shame. When using <code>in</code> for iteration, it's good, defensive programming to use the <code>hasOwnProperty</code> method on the container being iterated over to make sure that the member names being used are the ones that you expect.</p>\n\n<pre><code>var x = [1,2,3];\nfor ( i in x ) {\n if ( !x.hasOwnProperty(i) ) { continue; }\n console.log(i, x[i]);\n}\n</code></pre>\n\n<p><a href=\"http://ajaxian.com/archives/fun-with-browsers-for-in-loop\" rel=\"nofollow noreferrer\">Read here</a> for more on this.</p>\n\n<p>Lastly, <code>with</code> is almost always a bad idea.</p>\n" }, { "answer_id": 1043658, "author": "Blixt", "author_id": 119081, "author_profile": "https://Stackoverflow.com/users/119081", "pm_score": 1, "selected": false, "text": "<p>You can make \"classes\" that have private (inaccessible outside the \"class\" definition) static and non-static members, in addition to public members, using closures.</p>\n\n<p>Note that there are two types of public members in the code below. Instance-specific (defined in the constructor) that have access to private <em>instance</em> members, and shared members (defined in the <code>prototype</code> object) that only have access to private <em>static</em> members.</p>\n\n<pre><code>var MyClass = (function () {\n // private static\n var nextId = 1;\n\n // constructor\n var cls = function () {\n // private\n var id = nextId++;\n var name = 'Unknown';\n\n // public (this instance only)\n this.get_id = function () { return id; };\n\n this.get_name = function () { return name; };\n this.set_name = function (value) {\n if (typeof value != 'string')\n throw 'Name must be a string';\n if (value.length &lt; 2 || value.length &gt; 20)\n throw 'Name must be 2-20 characters long.';\n name = value;\n };\n };\n\n // public static\n cls.get_nextId = function () {\n return nextId;\n };\n\n // public (shared across instances)\n cls.prototype = {\n announce: function () {\n alert('Hi there! My id is ' + this.get_id() + ' and my name is \"' + this.get_name() + '\"!\\r\\n' +\n 'The next fellow\\'s id will be ' + MyClass.get_nextId() + '!');\n }\n };\n\n return cls;\n})();\n</code></pre>\n\n<p>To test this code:</p>\n\n<pre><code>var mc1 = new MyClass();\nmc1.set_name('Bob');\n\nvar mc2 = new MyClass();\nmc2.set_name('Anne');\n\nmc1.announce();\nmc2.announce();\n</code></pre>\n\n<p>If you have Firebug you'll find that there is no way to get access to the private members other than to set a breakpoint inside the closure that defines them.</p>\n\n<p>This pattern is very useful when defining classes that need strict validation on values, and complete control of state changes.</p>\n\n<p>To extend this class, you would put <code>MyClass.call(this);</code> at the top of the constructor in the extending class. You would also need to <strong>copy</strong> the <code>MyClass.prototype</code> object (don't reuse it, as you would change the members of <code>MyClass</code> as well.</p>\n\n<p>If you were to replace the <code>announce</code> method, you would call <code>MyClass.announce</code> from it like so: <code>MyClass.prototype.announce.call(this);</code></p>\n" }, { "answer_id": 1131595, "author": "RaYell", "author_id": 137467, "author_profile": "https://Stackoverflow.com/users/137467", "pm_score": 2, "selected": false, "text": "<p>JavaScript <code>typeof</code> operator used with arrays or nulls always returns <code>object</code> value which in some cases may not be what programmer would expect.</p>\n\n<p>Here's a function that will return proper values for those items as well. Array recognition was copied from Douglas Crockford's book \"JavaScript: The Good Parts\".</p>\n\n<pre><code>function typeOf (value) {\n var type = typeof value;\n if (type === 'object') {\n if (value === null) {\n type = 'null';\n } else if (typeof value.length === 'number' &amp;&amp; \n typeof value.splice === 'function' &amp;&amp; \n !value.propertyIsEnumerable('length')) {\n type = 'array';\n }\n }\n return type;\n}\n</code></pre>\n" }, { "answer_id": 1162208, "author": "gotch4", "author_id": 138606, "author_profile": "https://Stackoverflow.com/users/138606", "pm_score": 1, "selected": false, "text": "<p>Using <strong>Function.apply</strong> to specify the object that the function will work on:</p>\n\n<p>Suppose you have the class</p>\n\n<pre><code>function myClass(){\n this.fun = function(){\n do something;\n };\n}\n</code></pre>\n\n<p>if later you do:</p>\n\n<pre><code>var a = new myClass();\nvar b = new myClass();\n\nmyClass.fun.apply(b); //this will be like b.fun();\n</code></pre>\n\n<p>You can even specify an array of call parameters as a secondo argument</p>\n\n<p>look this: <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply</a></p>\n" }, { "answer_id": 1176498, "author": "outis", "author_id": 90527, "author_profile": "https://Stackoverflow.com/users/90527", "pm_score": 1, "selected": false, "text": "<p>My first submission is not so much a hidden feature as a rarely used application of the property re-definition feature. Because you can redefine an object's methods, you can cache the result of a method call, which is useful if the calculation is expensive and you want lazy evaluation. This gives the simplest form of <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a>.</p>\n\n<pre><code>function Circle(r) {\n this.setR(r);\n}\n\nCircle.prototype = {\n recalcArea: function() {\n this.area=function() {\n area = this.r * this.r * Math.PI;\n this.area = function() {return area;}\n return area;\n }\n },\n setR: function (r) {\n this.r = r;\n this.invalidateR();\n },\n invalidateR: function() {\n this.recalcArea();\n }\n}\n</code></pre>\n\n<p>Refactor the code that caches the result into a method and you get:</p>\n\n<pre><code>Object.prototype.cacheResult = function(name, _get) {\n this[name] = function() {\n var result = _get.apply(this, arguments);\n this[name] = function() {\n return result;\n }\n return result;\n };\n};\n\nfunction Circle(r) {\n this.setR(r);\n}\n\nCircle.prototype = {\n recalcArea: function() {\n this.cacheResult('area', function() { return this.r * this.r * Math.PI; });\n },\n setR: function (r) {\n this.r = r;\n this.invalidateR();\n },\n invalidateR: function() {\n this.recalcArea();\n }\n}\n</code></pre>\n\n<p>If you want a memoized function, you can have that instead. Property re-definition isn't involved.</p>\n\n<pre><code>Object.prototype.memoize = function(name, implementation) {\n this[name] = function() {\n var argStr = Array.toString.call(arguments);\n if (typeof(this[name].memo[argStr]) == 'undefined') {\n this[name].memo[argStr] = implementation.apply(this, arguments);\n }\n return this[name].memo[argStr];\n }\n};\n</code></pre>\n\n<p>Note that this relies on the standard array toString conversion and often won't work properly. Fixing it is left as an exercise for the reader.</p>\n\n<p>My second submission is getters and setters. I'm surprised they haven't been mentioned yet. Because the official standard differs from the de facto standard (defineProperty vs. <strong>define[GS]etter</strong>) and Internet Explorer barely supports the official standard, they aren't generally useful. Maybe that's why they weren't mentioned. Note that you can combine getters and result caching rather nicely:</p>\n\n<pre><code>Object.prototype.defineCacher = function(name, _get) {\n this.__defineGetter__(name, function() {\n var result = _get.call(this);\n this.__defineGetter__(name, function() { return result; });\n return result;\n })\n};\n\nfunction Circle(r) {\n this.r = r;\n}\n\nCircle.prototype = {\n invalidateR: function() {\n this.recalcArea();\n },\n recalcArea: function() {\n this.defineCacher('area', function() {return this.r * this.r * Math.PI; });\n },\n get r() { return this._r; }\n set r(r) { this._r = r; this.invalidateR(); }\n}\n\nvar unit = new Circle(1);\nunit.area;\n</code></pre>\n\n<p>Efficiently combining getters, setters and result caching is a little messier because you have to prevent the invalidation or do without automatic invalidation on set, which is what the following example does. It's mostly an issue if changing one property will invalidate multiple others (imagine there's a \"diameter\" property in these examples).</p>\n\n<pre><code>Object.prototype.defineRecalcer = function(name, _get) {\n var recalcFunc;\n this[recalcFunc='recalc'+name.toCapitalized()] = function() {\n this.defineCacher(name, _get);\n };\n this[recalcFunc]();\n this.__defineSetter__(name, function(value) {\n _set.call(this, value);\n this.__defineGetter__(name, function() {return value; });\n });\n};\n\nfunction Circle(r) {\n this.defineRecalcer('area',\n function() {return this.r * this.r * Math.PI;},\n function(area) {this._r = Math.sqrt(area / Math.PI);},\n );\n this.r = r;\n}\n\nCircle.prototype = {\n invalidateR: function() {\n this.recalcArea();\n },\n get r() { return this._r; }\n set r(r) { this._r = r; this.invalidateR(); }\n}\n</code></pre>\n" }, { "answer_id": 1211874, "author": "Fabian Jakobs", "author_id": 129322, "author_profile": "https://Stackoverflow.com/users/129322", "pm_score": 3, "selected": false, "text": "<p><strong>The <a href=\"http://yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"nofollow noreferrer\">Module Pattern</a></strong></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n(function() {\n\nfunction init() {\n // ...\n}\n\nwindow.onload = init;\n})();\n&lt;/script&gt;\n</code></pre>\n\n<p>Variables and functions declared without the <code>var</code> statement or outside of a function will be defined in the global scope. If a variable/function of the same name already exists it will be silently overridden, which can lead to very hard to find errors. A common solution is to wrap the whole code body into an anonymous function and immediately execute it. This way all variables/functions are defined in the scope of the anonymous function and don't leak into the global scope.</p>\n\n<p>To explicitly define a variable/function in the global scope they have to be prefixed with <code>window</code>:</p>\n\n<pre><code>window.GLOBAL_VAR = 12;\nwindow.global_function = function() {};\n</code></pre>\n" }, { "answer_id": 1211921, "author": "Fabian Jakobs", "author_id": 129322, "author_profile": "https://Stackoverflow.com/users/129322", "pm_score": 3, "selected": false, "text": "<p><strong><a href=\"http://www.dustindiaz.com/namespace-your-javascript/\" rel=\"nofollow noreferrer\">Namespaces</a></strong></p>\n\n<p>In larger JavaScript applications or frameworks it can be useful to organize the code in namespaces. JavaScript doesn't have a module or namespace concept buildin but it is easy to emulate using JavaScript objects. This would create a namespace called <code>ns</code>and attaches the function <code>foo</code>to it.</p>\n\n<pre><code>if (!window.ns) {\n window.ns = {};\n}\n\nwindow.ns.foo = function() {};\n</code></pre>\n\n<p>It is common to use the same global namespace prefix throughout a project and use sub namespaces for each JavaScript file. The name of the sub namespace often matches the file's name.</p>\n\n<p>The header of a file called <code>ns/button.js</code>could look like this:</p>\n\n<pre><code>if (!window.ns) {\n window.ns = {};\n}\nif (!window.ns.button) {\n window.ns.button = {};\n}\n\n// attach methods to the ns.button namespace\nwindow.ns.button.create = function() {};\n</code></pre>\n" }, { "answer_id": 1318068, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here's a simple way of thinking about 'this'. 'This' inside a function will refer to future object instances of the function, usually created with operator new. So clearly 'this' of an inner function will never refer to an instance of an outer function. </p>\n\n<p>The above should keep one out of trouble. But there are more complicated things you can do with 'this.' </p>\n\n<hr>\n\n<p>Example 1:</p>\n\n<pre><code>\n function DriveIn()\n {\n this.car = 'Honda';\n alert(this.food); //'food' is the attribute of a future object \n //and DriveIn does not define it.\n }\n\n var A = {food:'chili', q:DriveIn}; //create object A whose q attribute \n //is the function DriveIn;\n\n alert(A.car); //displays 'undefined' \n A.q(); //displays 'chili' but also defines this.car.\n alert(A.car); //displays 'Honda' \n\n</code></pre>\n\n<hr>\n\n<p>The Rule of This: </p>\n\n<p>Whenever a function is called as the attribute of an object, any occurrence of 'this' inside the function (but outside any inner functions) refers to the object.</p>\n\n<p>We need to make clear that \"The Rule of This\" applies even when operator new is used. Behind the scenes new attaches 'this' to the object through the object's constructor attribute.</p>\n\n<hr>\n\n<p>Example 2: </p>\n\n<pre><code>\n function Insect ()\n {\n this.bug = \"bee\";\n this.bugFood = function()\n {\n alert(\"nectar\");\n }\n }\n\n var B = new Insect();\n alert(B.constructor); //displays \"Insect\"; By \"The Rule of This\" any\n //ocurrence of 'this' inside Insect now refers \n //to B. \n</code></pre>\n\n<p>To make this even clearer, we can create an Insect instance without using operator new.</p>\n\n<p>Example 3:</p>\n\n<pre><code> \n var C = {constructor:Insect}; //Assign the constructor attribute of C, \n //the value Insect.\n C.constructor(); //Call Insect through the attribute. \n //C is now an Insect instance as though it \n //were created with operator new. [*]\n alert(C.bug); //Displays \"bee.\" \n C.bugFood(); //Displays \"nectar.\" \n\n</code></pre> \n\n<p>[*] The only actual difference I can discern is that in example 3, 'constructor' is an enumerable attribute. When operator new is used 'constructor' becomes an attribute but is not enumerable. An attribute is enumerable if the for-in operation \"for(var name in object)\" returns the name of the attribute.</p>\n" }, { "answer_id": 1365822, "author": "pramodc84", "author_id": 40614, "author_profile": "https://Stackoverflow.com/users/40614", "pm_score": 6, "selected": false, "text": "<p><strong><em>Know how many parameters are expected by a function</em></strong></p>\n\n<pre><code>function add_nums(num1, num2, num3 ){\n return num1 + num2 + num3;\n}\nadd_nums.length // 3 is the number of parameters expected.\n</code></pre>\n\n<p><strong><em>Know how many parameters are received by the function</em></strong></p>\n\n<pre><code>function add_many_nums(){\n return arguments.length;\n} \nadd_many_nums(2,1,122,12,21,89); //returns 6\n</code></pre>\n" }, { "answer_id": 1394655, "author": "vsync", "author_id": 104380, "author_profile": "https://Stackoverflow.com/users/104380", "pm_score": -1, "selected": false, "text": "<p>Well, it's not much of a feature, but it is very useful:</p>\n\n<p>Shows selectable and formatted alerts:</p>\n\n<pre><code>alert(prompt('',something.innerHTML ));\n</code></pre>\n" }, { "answer_id": 1416391, "author": "Kris Kowal", "author_id": 42586, "author_profile": "https://Stackoverflow.com/users/42586", "pm_score": 2, "selected": false, "text": "<p>These are not <em>always</em> a good idea, but you can convert most things with terse expressions. The important point here is that not every value in JavaScript is an object, so these expressions will succeed where member access on non-objects like null and undefined will fail. Particularly, beware that typeof null == \"object\", but you can't null.toString(), or (\"name\" in null).</p>\n\n<p>Convert anything to a Number:</p>\n\n<pre><code>+anything\nNumber(anything)\n</code></pre>\n\n<p>Convert anything to an unsigned four-byte integer:</p>\n\n<pre><code>anything &gt;&gt;&gt; 0\n</code></pre>\n\n<p>Convert anything to a String:</p>\n\n<pre><code>'' + anything\nString(anything)\n</code></pre>\n\n<p>Convert anything to a Boolean:</p>\n\n<pre><code>!!anything\nBoolean(anything)\n</code></pre>\n\n<p>Also, using the type name without \"new\" behaves differently for String, Number, and Boolean, returning a primitive number, string, or boolean value, but with \"new\" these will returned \"boxed\" object types, which are nearly useless.</p>\n" }, { "answer_id": 1462261, "author": "Seth", "author_id": 65295, "author_profile": "https://Stackoverflow.com/users/65295", "pm_score": 4, "selected": false, "text": "<p>My favorite trick is using <code>apply</code> to perform a callback to an object's method and maintain the correct \"this\" variable. </p>\n\n<pre><code>function MakeCallback(obj, method) {\n return function() {\n method.apply(obj, arguments);\n };\n}\n\nvar SomeClass = function() { \n this.a = 1;\n};\nSomeClass.prototype.addXToA = function(x) {\n this.a = this.a + x;\n};\n\nvar myObj = new SomeClass();\n\nbrokenCallback = myObj.addXToA;\nbrokenCallback(1); // Won't work, wrong \"this\" variable\nalert(myObj.a); // 1\n\n\nvar myCallback = MakeCallback(myObj, myObj.addXToA);\nmyCallback(1); // Works as expected because of apply\nalert(myObj.a); // 2\n</code></pre>\n" }, { "answer_id": 1682820, "author": "Lyubomyr Shaydariv", "author_id": 166589, "author_profile": "https://Stackoverflow.com/users/166589", "pm_score": 2, "selected": false, "text": "<p>Hm, I didn't read the whole topic though it's quite interesting for me, but let me make a little donation:</p>\n\n<pre><code>// forget the debug alerts\nvar alertToFirebugConsole = function() {\n if ( window.console &amp;&amp; window.console.log ) {\n window.alert = console.log;\n }\n}\n</code></pre>\n" }, { "answer_id": 1712004, "author": "Kenneth J", "author_id": 195456, "author_profile": "https://Stackoverflow.com/users/195456", "pm_score": 1, "selected": false, "text": "<p>function can have methods.</p>\n\n<p>I use this pattern of AJAX form submissions.</p>\n\n<pre><code>var fn = (function() {\n var ready = true;\n function fnX() {\n ready = false;\n // AJAX return function\n function Success() {\n ready = true;\n }\n Success();\n return \"this is a test\";\n }\n\n fnX.IsReady = function() {\n return ready;\n }\n return fnX;\n })();\n\n if (fn.IsReady()) {\n fn();\n }\n</code></pre>\n" }, { "answer_id": 2042069, "author": "Anil Namde", "author_id": 237743, "author_profile": "https://Stackoverflow.com/users/237743", "pm_score": 2, "selected": false, "text": "<p>JavaScript is considered to be very good at exposing all its object so no matter if its window object itself.</p>\n\n<p>So if i would like to override the browser alert with JQuery/YUI div popup which too accepts string as parameter it can be done simply using following snippet.</p>\n\n<pre>\n<code>\nfunction divPopup(str)\n{\n //code to show the divPopup\n}\nwindow.alert = divPopup;\n</code>\n</pre>\n\n<p>With this change all the calls to the alert() will show the good new div based popup instead of the browser specific alert.</p>\n" }, { "answer_id": 2047391, "author": "slebetman", "author_id": 167735, "author_profile": "https://Stackoverflow.com/users/167735", "pm_score": 4, "selected": false, "text": "<p><strong>The Zen of Closures</strong></p>\n\n<p>Other people have mentioned closures. But it's surprising how many people know about closures, write code using closures, yet still have the wrong perception of what closures really are. Some people confuse first-class functions with closures. Yet others see it as a kind of static variable.</p>\n\n<p>To me a closure is a kind of <em>'private'</em> global variable. That is, a kind of variable that some functions see as global but other functions can't see. Now, I know this is playing fast and loose with the description of the underlying mechanism but that is how it feels like and behaves. To illustrate:</p>\n\n<pre><code>// Say you want three functions to share a single variable:\n\n// Use a self-calling function to create scope:\n(function(){\n\n var counter = 0; // this is the variable we want to share;\n\n // Declare global functions using function expressions:\n increment = function(){\n return ++counter;\n }\n decrement = function(){\n return --counter;\n }\n value = function(){\n return counter;\n }\n})()\n</code></pre>\n\n<p>now the three function <code>increment</code>, <code>decrement</code> and <code>value</code> share the variable <code>counter</code> without <code>counter</code> being an actual global variable. This is the true nature of closures:</p>\n\n<pre><code>increment();\nincrement();\ndecrement();\nalert(value()); // will output 1\n</code></pre>\n\n<p>The above is not a really useful use of closures. In fact, I'd say that using it this way is an anti-pattern. But it is useful in understanding the nature of closures. For example, most people get caught when they try to do something like the following:</p>\n\n<pre><code>for (var i=1;i&lt;=10;i++) {\n document.getElementById('span'+i).onclick = function () {\n alert('this is span number '+i);\n }\n}\n// ALL spans will generate alert: this span is span number 10\n</code></pre>\n\n<p>That's because they don't understand the nature of closures. They think that they are passing the value of <code>i</code> into the functions when in fact the functions are sharing a single variable <code>i</code>. Like I said before, a special kind of global variable.</p>\n\n<p>To get around this you need <em>detach</em>* the closure:</p>\n\n<pre><code>function makeClickHandler (j) {\n return function () {alert('this is span number '+j)};\n}\n\nfor (var i=1;i&lt;=10;i++) {\n document.getElementById('span'+i).onclick = makeClickHandler(i);\n}\n// this works because i is passed by reference \n// (or value in this case, since it is a number)\n// instead of being captured by a closure\n</code></pre>\n\n<p>*note: I don't know the correct terminology here.</p>\n" }, { "answer_id": 2243631, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 6, "selected": false, "text": "<p>I know I'm late to the party, but I just can't believe the <code>+</code> operator's usefulness hasn't been mentioned beyond \"convert anything to a number\". Maybe that's how well hidden a feature it is?</p>\n\n<pre><code>// Quick hex to dec conversion:\n+\"0xFF\"; // -&gt; 255\n\n// Get a timestamp for now, the equivalent of `new Date().getTime()`:\n+new Date();\n\n// Safer parsing than parseFloat()/parseInt()\nparseInt(\"1,000\"); // -&gt; 1, not 1000\n+\"1,000\"; // -&gt; NaN, much better for testing user input\nparseInt(\"010\"); // -&gt; 8, because of the octal literal prefix\n+\"010\"; // -&gt; 10, `Number()` doesn't parse octal literals \n\n// A use case for this would be rare, but still useful in cases\n// for shortening something like if (someVar === null) someVar = 0;\n+null; // -&gt; 0;\n\n// Boolean to integer\n+true; // -&gt; 1;\n+false; // -&gt; 0;\n\n// Other useful tidbits:\n+\"1e10\"; // -&gt; 10000000000\n+\"1e-4\"; // -&gt; 0.0001\n+\"-12\"; // -&gt; -12\n</code></pre>\n\n<p>Of course, you can do all this using <code>Number()</code> instead, but the <code>+</code> operator is so much prettier!</p>\n\n<p>You can also define a numeric return value for an object by overriding the prototype's <code>valueOf()</code> method. Any number conversion performed on that object will not result in <code>NaN</code>, but the return value of the <code>valueOf()</code> method:</p>\n\n<pre><code>var rnd = {\n \"valueOf\": function () { return Math.floor(Math.random()*1000); }\n};\n+rnd; // -&gt; 442;\n+rnd; // -&gt; 727;\n+rnd; // -&gt; 718;\n</code></pre>\n" }, { "answer_id": 2303653, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<h2>JavaScript versatility - Overriding default functionality</h2>\n\n<p><br />\nHere's the code for overriding the <code>window.alert</code> function with jQuery UI's <a href=\"http://jqueryui.com/demos/dialog/\" rel=\"nofollow noreferrer\">Dialog widget</a>. I did this as a jQuery plug-in. And you can read about it on my blog; <a href=\"http://roosteronacid.com/blog/index.php/2010/01/20/jquery-plug-in-personalized-alert-messages/\" rel=\"nofollow noreferrer\"><em>altAlert, a jQuery plug-in for personalized alert messages</em></a>.</p>\n\n<pre><code>jQuery.altAlert = function (options) \n{ \n var defaults = { \n title: \"Alert\", \n buttons: { \n \"Ok\": function() \n { \n jQuery(this).dialog(\"close\"); \n } \n } \n }; \n\n jQuery.extend(defaults, options); \n\n delete defaults.autoOpen; \n\n window.alert = function () \n { \n jQuery(\"&lt;div /&gt;\", {\n html: arguments[0].replace(/\\n/, \"&lt;br /&gt;\")\n }).dialog(defaults); \n }; \n};\n</code></pre>\n" }, { "answer_id": 2479026, "author": "adamJLev", "author_id": 26192, "author_profile": "https://Stackoverflow.com/users/26192", "pm_score": 1, "selected": false, "text": "<p>Simple self-contained function return value caching:</p>\n\n<pre><code>function isRunningLocally(){\n var runningLocally = ....; // Might be an expensive check, check whatever needs to be checked.\n\n return (isRunningLocally = function(){\n return runningLocally;\n })();\n},\n</code></pre>\n\n<p>The expensive part is only performed on the first call, and after that all the function does is return this value. Of course this is only useful for functions that will always return the same thing.</p>\n" }, { "answer_id": 2709783, "author": "Harmen", "author_id": 176603, "author_profile": "https://Stackoverflow.com/users/176603", "pm_score": 4, "selected": false, "text": "<p>In a function, you can return the function itself:</p>\n\n<pre><code>function showSomething(a){\n alert(a);\n return arguments.callee;\n}\n\n// Alerts: 'a', 'b', 'c'\nshowSomething('a')('b')('c');\n\n// Or what about this:\n(function (a){\n alert(a);\n return arguments.callee;\n}​)('a')('b')('c');​​​​\n</code></pre>\n\n<p>I don't know when it could be useful, anyway, it's pretty weird and fun:</p>\n\n<pre><code>var count = function(counter){\n alert(counter);\n if(counter &lt; 10){\n return arguments.callee(counter+1);\n }\n return arguments.callee;\n};\n\ncount(5)(9); // Will alert 5, 6, 7, 8, 9, 10 and 9, 10\n</code></pre>\n\n<hr>\n\n<p>Actually, the <a href=\"https://github.com/jed/fab\" rel=\"nofollow noreferrer\">FAB framework</a> for Node.js seems to have implemented this feature; see <a href=\"https://stackoverflow.com/questions/3799238/javascript-fab-framework-on-node-js\">this topic</a> for example.</p>\n" }, { "answer_id": 2920211, "author": "wnrph", "author_id": 345520, "author_profile": "https://Stackoverflow.com/users/345520", "pm_score": 1, "selected": false, "text": "<p>Closures:</p>\n\n<pre><code>function f() { \n var a; \n function closureGet(){ return a; }\n function closureSet(val){ a=val;}\n return [closureGet,closureSet];\n}\n\n[closureGet,closureSet]=f(); \nclosureSet(5);\nalert(closureGet()); // gives 5\n\nclosureSet(15);\nalert(closureGet()); // gives 15\n</code></pre>\n\n<p>The closure thing here is not the so-called destructuring assignment (<code>[c,d] = [1,3]</code> is equivalent to <code>c=1; d=3;</code>) but the fact that the occurences of <code>a</code> in closureGet and closureSet still refer to the same variable. Even after closureSet has assigned <code>a</code> a new value!</p>\n" }, { "answer_id": 2921079, "author": "Tgr", "author_id": 323407, "author_profile": "https://Stackoverflow.com/users/323407", "pm_score": 3, "selected": false, "text": "<p>This is a hidden feature of jQuery, not Javascript, but since there will never be a \"hidden features of jQuery\" question...</p>\n\n<p>You can define your own <code>:something</code> selectors in jQuery:</p>\n\n<pre><code>$.extend($.expr[':'], {\n foo: function(node, index, args, stack) {\n // decide if selectors matches node, return true or false\n }\n});\n</code></pre>\n\n<p>For selections using <code>:foo</code>, such as <code>$('div.block:foo(\"bar,baz\") span')</code>, the function <code>foo</code> will be called for all nodes which match the already processed part of the selector. The meaning of the arguments:</p>\n\n<ul>\n<li><code>node</code> holds the current node</li>\n<li><code>index</code> is the index of the node in the node set</li>\n<li><code>args</code> is an array that is useful if the selector has an argument or multiple names:\n\n<ul>\n<li><code>args[0]</code> is the whole selector text (e.g. <code>:foo(\"bar, baz\")</code>)</li>\n<li><code>args[1]</code> is the selector name (e.g. <code>foo</code>)</li>\n<li><code>args[2]</code> is the quote character used to wrap the argument \n(e.g. <code>\"</code> for <code>:foo(\"bar, baz\")</code>) or an empty string if there is no quoting \n(<code>:foo(bar, baz)</code>) or undefined if there is no argument</li>\n<li><code>args[3]</code> is the argument, including any quotes, (e.g. <code>\"bar, baz\"</code>) \nor undefined if there are no arguments</li>\n</ul></li>\n<li><code>stack</code> is the node set (an array holding all nodes which are matched at that point)</li>\n</ul>\n\n<p>The function should return <code>true</code> if the selector matches, <code>false</code> otherwise.</p>\n\n<p>For example, the following code will enable selecting nodes based on a full-text regexp search:</p>\n\n<pre><code>$.extend($.expr[':'], {\n matches: function(node, index, args, stack) {\n if (!args.re) { // args is a good place for caching\n var re = args[3];\n if (args[2]) { // get rid of quotes\n re = re.slice(1,-1);\n }\n var separator = re[0];\n var pos = re.lastIndexOf(separator);\n var modifiers = re.substr(pos+1);\n var code = re.substr(1, pos-1);\n args.re = new RegExp(code, modifiers);\n }\n return $(node).text().match(args.re);\n }\n});\n\n// find the answers on this page which contain /**/-style comments\n$('.answer .post-text code:matches(!/\\\\*[\\\\s\\\\S]*\\\\*/!)');\n</code></pre>\n\n<p>You could reach a similar effect with the callback version of <a href=\"http://api.jquery.com/filter/\" rel=\"nofollow noreferrer\">.filter()</a>, but custom selectors are much more flexible and usually more readable.</p>\n" }, { "answer_id": 3110886, "author": "Edgar Klerks", "author_id": 375367, "author_profile": "https://Stackoverflow.com/users/375367", "pm_score": 1, "selected": false, "text": "<p>When you are write callbacks you have a lot of code, which will look like this: </p>\n\n<pre><code>callback: function(){\n stuff(arg1,arg2);\n}\n</code></pre>\n\n<p>You can use the function below, to make it somewhat cleaner. </p>\n\n<pre><code>callback: _(stuff, arg1, arg2) \n</code></pre>\n\n<p>It uses a less well known function of the Function object of javascript, apply. </p>\n\n<p>It also shows another character you can use as functionname: _.</p>\n\n<pre><code>function _(){\n var func;\n var args = new Array();\n for(var i = 0; i &lt; arguments.length; i++){\n if( i == 0){\n func = arguments[i];\n } else {\n args.push(arguments[i]);\n }\n }\n return function(){\n return func.apply(func, args);\n }\n}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
**What "Hidden Features" of JavaScript do you think every programmer should know?** After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript. * [Hidden Features of HTML](https://stackoverflow.com/questions/954327/) * [Hidden Features of CSS](https://stackoverflow.com/questions/628407) * [Hidden Features of PHP](https://stackoverflow.com/questions/61401/) * [Hidden Features of ASP.NET](https://stackoverflow.com/questions/54929/) * [Hidden Features of C#](https://stackoverflow.com/questions/9033/) * [Hidden Features of Java](https://stackoverflow.com/questions/15496/) * [Hidden Features of Python](https://stackoverflow.com/questions/101268/) Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.
You don't need to define any parameters for a function. You can just use the function's `arguments` array-like object. ``` function sum() { var retval = 0; for (var i = 0, len = arguments.length; i < len; ++i) { retval += arguments[i]; } return retval; } sum(1, 2, 3) // returns 6 ```
61,110
<p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p> <p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p> <pre><code>public class DirtyWorkaround { private class DirtyWriter : TextWriter { private TextWriter stdoutWriter; private StreamWriter fileWriter; public DirtyWriter(string path, TextWriter stdoutWriter) { this.stdoutWriter = stdoutWriter; this.fileWriter = new StreamWriter(path); } override public void Write(string s) { stdoutWriter.Write(s); fileWriter.Write(s); fileWriter.Flush(); } // Same as above for WriteLine() and WriteLine(string), // plus whatever methods I need to override to inherit // from TextWriter (Encoding.Get I guess). } public static void Main(string[] args) { using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) { Console.SetOut(dw); // Teh codez } } } </code></pre> <p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p> <p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>
[ { "answer_id": 61119, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>I don't think there's anything wrong with your approach.</p>\n\n<p>If you wanted reusable code, consider implementing a class called <code>MultiWriter</code> or somesuch that takes as input two (or N?) <code>TextWriter</code> streams and distributes all writs, flushes, etc. to those streams. Then you can do this file/console thing, but just as easily you can split any output stream. Useful!</p>\n" }, { "answer_id": 61123, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "<p>Probably not what you want, but just in case... Apparently, <a href=\"http://en.wikipedia.org/wiki/Tee_(command)#Windows_PowerShell\" rel=\"nofollow noreferrer\">PowerShell implements</a> a version of the venerable <code>tee</code> command. Which is pretty much intended for exactly this purpose. So... smoke 'em if you got 'em.</p>\n" }, { "answer_id": 61134, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 4, "selected": true, "text": "<p>The perfect solution for this is to use <a href=\"http://logging.apache.org/log4net/\" rel=\"noreferrer\">log4net</a> with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime. </p>\n" }, { "answer_id": 61160, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>I would say mimic the diagnostics that .NET itself uses (Trace and Debug).</p>\n\n<p>Create a \"output\" class that can have different classes that adhere to a text output interface. You report to the output class, it automatically sends the output given to the classes you have added (ConsoleOutput, TextFileOutput, WhateverOutput).. And so on.. This also leaves you open to add other \"output\" types (such as xml/xslt to get a nicely formatted report?).</p>\n\n<p>Check out the <a href=\"http://msdn.microsoft.com/en-us/library/sk36c28t.aspx\" rel=\"nofollow noreferrer\">Trace Listeners Collection</a> to see what I mean.</p>\n" }, { "answer_id": 61164, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>Consider refactoring your application to separate the user-interaction portions from the business logic. In my experience, such a separation is quite beneficial to the structure of your program.</p>\n\n<p>For the particular problem you're trying to solve here, it becomes straightforward for the user-interaction part to change its behavior from <code>Console.WriteLine</code> to file I/O.</p>\n" }, { "answer_id": 369254, "author": "Rob Parker", "author_id": 181460, "author_profile": "https://Stackoverflow.com/users/181460", "pm_score": 0, "selected": false, "text": "<p>I'm working on implementing a similar feature to capture output sent to the Console and save it to a log while still passing the output in real time to the normal Console so it doesn't break the application (eg. if it's a console application!).</p>\n\n<p>If you're still trying to do this in your own code by saving the console output (as opposed to using a logging system to save just the information you really care about), I think you can avoid the flush after each write, as long as you also override Flush() and make sure it flushes the original <code>stdoutWriter</code> you saved as well as your <code>fileWriter</code>. You want to do this in case the application is trying to flush a partial line to the console for immediate display (such as an input prompt, a progress indicator, etc), to override the normal line-buffering.</p>\n\n<p>If that approach has problems with your console output being buffered too long, you might need to make sure that WriteLine() flushes <code>stdoutWriter</code> (but probably doesn't need to flush <code>fileWriter</code> except when your Flush() override is called). But I would think that the original <code>Console.Out</code> (actually going to the console) would automatically flush its buffer upon a newline, so you shouldn't have to force it.</p>\n\n<p>You might also want to override Close() to (flush and) close your <code>fileWriter</code> (and probably <code>stdoutWriter</code> as well), but I'm not sure if that's really needed or if a Close() in the base TextWriter would issue a Flush() (which you would already override) and you might rely on application exit to close your file. You should probably test that it gets flushed on exit, to be sure. And be aware that an abnormal exit (crash) likely won't flush buffered output. If that's an issue, flushing <code>fileWriter</code> on newline may be desirable, but that's another tricky can of worms to work out.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4850/" ]
I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution. The workaround I use while I don't find a cleaner approach is to subclass `TextWriter` overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this: ``` public class DirtyWorkaround { private class DirtyWriter : TextWriter { private TextWriter stdoutWriter; private StreamWriter fileWriter; public DirtyWriter(string path, TextWriter stdoutWriter) { this.stdoutWriter = stdoutWriter; this.fileWriter = new StreamWriter(path); } override public void Write(string s) { stdoutWriter.Write(s); fileWriter.Write(s); fileWriter.Flush(); } // Same as above for WriteLine() and WriteLine(string), // plus whatever methods I need to override to inherit // from TextWriter (Encoding.Get I guess). } public static void Main(string[] args) { using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) { Console.SetOut(dw); // Teh codez } } } ``` See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer. Also, excuse inaccuracies with the above code (had to write it *ad hoc*, sorry ;).
The perfect solution for this is to use [log4net](http://logging.apache.org/log4net/) with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime.
61,143
<p>Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. </p>
[ { "answer_id": 61149, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<p>Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.</p>\n\n<pre><code> public void HandleTreeItems(Action&lt;TreeItem&gt; item, TreeItem parent)\n {\n if (parent.Children.Count &gt; 0)\n {\n foreach (TreeItem ti in parent.Children)\n {\n HandleTreeItems(item, ti);\n }\n }\n\n item(parent);\n }\n</code></pre>\n\n<p>Now to call it, passing in the lambda that handles one item, by printing its name to the console.</p>\n\n<pre><code>HandleTreeItems(item =&gt; { Console.WriteLine(item.Name); }, TreeItemRoot);\n</code></pre>\n" }, { "answer_id": 61206, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>A proper solution, and indeed the idiomatic solution in many functional programming languages, would be the use of a <a href=\"https://en.wikipedia.org/wiki/Fixed-point_combinator\" rel=\"nofollow noreferrer\">fixed-point combinator</a>. In a nutshell: a fixed-point combinator answers the question “how do I define an anonymous function to be recursive?”. But the solution is so nontrivial that whole articles are written to explain them.</p>\n\n<p>A simple, pragmatic alternative is to “go back in time” to the antics of C: declaration before definition. Try the following (the “factorial” function):</p>\n\n<pre><code>Func&lt;int, int&gt; fact = null;\nfact = x =&gt; (x == 0) ? 1 : x * fact(x - 1);\n</code></pre>\n\n<p>Works like a charm.</p>\n\n<p>Or, for a pre-order tree traversal on an object of class <code>TreeNode</code> which implements <code>IEnumerable&lt;TreeNode&gt;</code> appropriately to go over its children:</p>\n\n<pre><code>Action&lt;TreeNode, Action&lt;TreeNode&gt;&gt; preorderTraverse = null;\npreorderTraverse = (node, action) =&gt; {\n action(node);\n foreach (var child in node) preorderTraverse(child, action);\n};\n</code></pre>\n" }, { "answer_id": 61244, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>A simple alternative is to “go back in time” to the antics of C and C++: declaration before definition. Try the following:</p>\n\n<pre><code>Func&lt;int, int&gt; fact = null;\nfact = x =&gt; (x == 0) ? 1 : x * fact(x - 1);\n</code></pre>\n \n <p>Works like a charm.</p>\n</blockquote>\n\n<p>Yes, that does work, with one little caveat. C# has mutable references. So make sure you don't accidentally do something like this:</p>\n\n<pre><code>Func&lt;int, int&gt; fact = null;\nfact = x =&gt; (x == 0) ? 1 : x * fact(x - 1);\n\n// Make a new reference to the factorial function\nFunc&lt;int, int&gt; myFact = fact;\n\n// Use the new reference to calculate the factorial of 4\nmyFact(4); // returns 24\n\n// Modify the old reference\nfact = x =&gt; x;\n\n// Again, use the new reference to calculate\nmyFact(4); // returns 12\n</code></pre>\n\n<p>Of course, this example is a bit contrived, but this could happen when using mutable references. If you use the combinators from <a href=\"https://stackoverflow.com/questions/61143/recursive-lambda-expression-to-traverse-a-tree-in-c#61162\">aku</a>'s links, this won't be possible.</p>\n" }, { "answer_id": 61257, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 7, "selected": true, "text": "<p>Ok, I found some free time finally.<br>\nHere we go: </p>\n\n<pre><code>class TreeNode\n{\n public string Value { get; set;}\n public List&lt;TreeNode&gt; Nodes { get; set;}\n\n\n public TreeNode()\n {\n Nodes = new List&lt;TreeNode&gt;();\n }\n}\n\nAction&lt;TreeNode&gt; traverse = null;\n\ntraverse = (n) =&gt; { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};\n\nvar root = new TreeNode { Value = \"Root\" };\nroot.Nodes.Add(new TreeNode { Value = \"ChildA\"} );\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = \"ChildA1\" });\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = \"ChildA2\" });\nroot.Nodes.Add(new TreeNode { Value = \"ChildB\"} );\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = \"ChildB1\" });\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = \"ChildB2\" });\n\ntraverse(root);\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ]
Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
Ok, I found some free time finally. Here we go: ``` class TreeNode { public string Value { get; set;} public List<TreeNode> Nodes { get; set;} public TreeNode() { Nodes = new List<TreeNode>(); } } Action<TreeNode> traverse = null; traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);}; var root = new TreeNode { Value = "Root" }; root.Nodes.Add(new TreeNode { Value = "ChildA"} ); root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" }); root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" }); root.Nodes.Add(new TreeNode { Value = "ChildB"} ); root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" }); root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" }); traverse(root); ```
61,150
<p>My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. </p> <p>So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it <code>staticInit</code>. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock <code>staticInit</code> with <a href="https://jmockit.github.io/" rel="noreferrer">JMockit</a> to not do anything. Let's see this in example.</p> <pre><code>public class ClassWithStaticInit { static { System.out.println("static initializer."); } } </code></pre> <p>Will be changed to</p> <pre><code>public class ClassWithStaticInit { static { staticInit(); } private static void staticInit() { System.out.println("static initialized."); } } </code></pre> <p>So that we can do the following in a <a href="https://junit.org/junit5/" rel="noreferrer">JUnit</a>.</p> <pre><code>public class DependentClassTest { public static class MockClassWithStaticInit { public static void staticInit() { } } @BeforeClass public static void setUpBeforeClass() { Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class); } } </code></pre> <p>However this solution also comes with its own problems. You can't run <code>DependentClassTest</code> and <code>ClassWithStaticInitTest</code> on the same JVM since you actually want the static block to run for <code>ClassWithStaticInitTest</code>.</p> <p>What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?</p>
[ { "answer_id": 61153, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 3, "selected": false, "text": "<p>Sounds to me like you are treating a symptom: poor design with dependencies on static initialization. Maybe some refactoring is the real solution. It sounds like you've already done a little refactoring with your <code>staticInit()</code> function, but maybe that function needs to be called from the constructor, not from a static initializer. If you can do away with static initializers period, you will be better off. Only you can make this decision (<em>I can't see your codebase</em>) but some refactoring will definitely help.</p>\n\n<p>As for mocking, I use EasyMock, but I have run into the same issue. Side effects of static initializers in legacy code make testing difficult. Our answer was to refactor out the static initializer.</p>\n" }, { "answer_id": 61177, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 1, "selected": false, "text": "<p>I suppose you really want some kind of factory instead of the static initializer.</p>\n\n<p>Some mix of a singleton and an abstract factory would probably be able to get you the same functionality as today, and with good testability, but that would add quite a lot of boiler-plate code, so it might be better to just try to refactor the static stuff away completely or if you could at least get away with some less complex solution. </p>\n\n<p>Hard to tell if it´s possible without seeing your code though.</p>\n" }, { "answer_id": 61190, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 2, "selected": false, "text": "<p>You could write your test code in Groovy and easily mock the static method using metaprogramming.</p>\n\n<pre><code>Math.metaClass.'static'.max = { int a, int b -&gt; \n a + b\n}\n\nMath.max 1, 2\n</code></pre>\n\n<p>If you can't use Groovy, you will really need to refactoring the code (maybe to inject something like a initializator).</p>\n\n<p>Kind Regards</p>\n" }, { "answer_id": 61215, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 4, "selected": true, "text": "<p>When I run into this problem, I usually do the same thing you describe, except I make the static method protected so I can invoke it manually. On top of this, I make sure that the method can be invoked multiple times without problems (otherwise it is no better than the static initializer as far as the tests go).</p>\n\n<p>This works reasonably well, and I can actually test that the static initializer method does what I expect/want it to do. Sometimes it is just easiest to have some static initialization code, and it just isn't worth it to build an overly complex system to replace it.</p>\n\n<p>When I use this mechanism, I make sure to document that the protected method is only exposed for testing purposes, with the hopes that it won't be used by other developers. This of course may not be a viable solution, for example if the class' interface is externally visible (either as a sub-component of some kind for other teams, or as a public framework). It is a simple solution to the problem though, and doesn't require a third party library to set up (which I like).</p>\n" }, { "answer_id": 61389, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 1, "selected": false, "text": "<p>I'm not super knowledgeable in Mock frameworks so please correct me if I'm wrong but couldn't you possibly have two different Mock objects to cover the situations that you mention? Such as</p>\n\n<pre><code>public static class MockClassWithEmptyStaticInit {\n public static void staticInit() {\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public static class MockClassWithStaticInit {\n public static void staticInit() {\n System.out.println(\"static initialized.\");\n }\n}\n</code></pre>\n\n<p>Then you can use them in your different test cases</p>\n\n<pre><code>@BeforeClass\npublic static void setUpBeforeClass() {\n Mockit.redefineMethods(ClassWithStaticInit.class, \n MockClassWithEmptyStaticInit.class);\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>@BeforeClass\npublic static void setUpBeforeClass() {\n Mockit.redefineMethods(ClassWithStaticInit.class, \n MockClassWithStaticInit.class);\n}\n</code></pre>\n\n<p>respectively.</p>\n" }, { "answer_id": 144876, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 4, "selected": false, "text": "<p>This is going to get into more \"Advanced\" JMockit. It turns out, you can redefine static initialization blocks in JMockit by creating a <code>public void $clinit()</code> method. So, instead of making this change</p>\n\n<pre><code>public class ClassWithStaticInit {\n static {\n staticInit();\n }\n\n private static void staticInit() {\n System.out.println(\"static initialized.\");\n }\n}\n</code></pre>\n\n<p>we might as well leave <code>ClassWithStaticInit</code> as is and do the following in the <code>MockClassWithStaticInit</code>:</p>\n\n<pre><code>public static class MockClassWithStaticInit {\n public void $clinit() {\n }\n}\n</code></pre>\n\n<p>This will in fact allow us to not make any changes in the existing classes.</p>\n" }, { "answer_id": 489018, "author": "Jan Kronquist", "author_id": 43935, "author_profile": "https://Stackoverflow.com/users/43935", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://powermock.org\" rel=\"noreferrer\">PowerMock</a> is another mock framework that extends EasyMock and Mockito. With PowerMock you can easily <a href=\"http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior\" rel=\"noreferrer\">remove unwanted behavior</a> from a class, for example a static initializer. In your example you simply add the following annotations to your JUnit test case:</p>\n\n<pre><code>@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"some.package.ClassWithStaticInit\")\n</code></pre>\n\n<p>PowerMock does not use a Java agent and therefore does not require modification of the JVM startup parameters. You simple add the jar file and the above annotations. </p>\n" }, { "answer_id": 7242341, "author": "matsev", "author_id": 303598, "author_profile": "https://Stackoverflow.com/users/303598", "pm_score": 4, "selected": false, "text": "<p>Occasionally, I find static initilizers in classes that my code depends on. If I cannot refactor the code, I use <a href=\"http://code.google.com/p/powermock/\" rel=\"noreferrer\">PowerMock</a>'s <code>@SuppressStaticInitializationFor</code> annotation to suppress the static initializer:</p>\n\n<pre><code>@RunWith(PowerMockRunner.class)\n@SuppressStaticInitializationFor(\"com.example.ClassWithStaticInit\")\npublic class ClassWithStaticInitTest {\n\n ClassWithStaticInit tested;\n\n @Before\n public void setUp() {\n tested = new ClassWithStaticInit();\n }\n\n @Test\n public void testSuppressStaticInitializer() {\n asserNotNull(tested);\n }\n\n // more tests...\n}\n</code></pre>\n\n<p>Read more about <a href=\"http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior\" rel=\"noreferrer\">suppressing unwanted behaviour</a>.</p>\n\n<p>Disclaimer: PowerMock is an open source project developed by two colleagues of mine. </p>\n" }, { "answer_id": 33737521, "author": "KidCrippler", "author_id": 223365, "author_profile": "https://Stackoverflow.com/users/223365", "pm_score": 0, "selected": false, "text": "<p>Not really an answer, but just wondering - isn't there any way to \"reverse\" the call to <code>Mockit.redefineMethods</code>?<br>\nIf no such explicit method exists, shouldn't executing it again in the following fashion do the trick?</p>\n\n<pre><code>Mockit.redefineMethods(ClassWithStaticInit.class, ClassWithStaticInit.class);\n</code></pre>\n\n<p>If such a method exists, you could execute it in the class' <code>@AfterClass</code> method, and test <code>ClassWithStaticInitTest</code> with the \"original\" static initializer block, as if nothing has changed, from the same JVM.</p>\n\n<p>This is just a hunch though, so I may be missing something.</p>\n" }, { "answer_id": 64216523, "author": "Sebastian Luna", "author_id": 7845889, "author_profile": "https://Stackoverflow.com/users/7845889", "pm_score": 0, "selected": false, "text": "<p>You can use PowerMock to execute the private method call like:</p>\n<pre><code>ClassWithStaticInit staticInitClass = new ClassWithStaticInit()\nWhitebox.invokeMethod(staticInitClass, &quot;staticInit&quot;);\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3087/" ]
My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it `staticInit`. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock `staticInit` with [JMockit](https://jmockit.github.io/) to not do anything. Let's see this in example. ``` public class ClassWithStaticInit { static { System.out.println("static initializer."); } } ``` Will be changed to ``` public class ClassWithStaticInit { static { staticInit(); } private static void staticInit() { System.out.println("static initialized."); } } ``` So that we can do the following in a [JUnit](https://junit.org/junit5/). ``` public class DependentClassTest { public static class MockClassWithStaticInit { public static void staticInit() { } } @BeforeClass public static void setUpBeforeClass() { Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class); } } ``` However this solution also comes with its own problems. You can't run `DependentClassTest` and `ClassWithStaticInitTest` on the same JVM since you actually want the static block to run for `ClassWithStaticInitTest`. What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?
When I run into this problem, I usually do the same thing you describe, except I make the static method protected so I can invoke it manually. On top of this, I make sure that the method can be invoked multiple times without problems (otherwise it is no better than the static initializer as far as the tests go). This works reasonably well, and I can actually test that the static initializer method does what I expect/want it to do. Sometimes it is just easiest to have some static initialization code, and it just isn't worth it to build an overly complex system to replace it. When I use this mechanism, I make sure to document that the protected method is only exposed for testing purposes, with the hopes that it won't be used by other developers. This of course may not be a viable solution, for example if the class' interface is externally visible (either as a sub-component of some kind for other teams, or as a public framework). It is a simple solution to the problem though, and doesn't require a third party library to set up (which I like).
61,155
<p>I'm trying to place this menu on the left hand side of the page:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="left-menu" style="left: 123px; top: 355px"&gt; &lt;ul&gt; &lt;li&gt; Categories &lt;/li&gt; &lt;li&gt; Weapons &lt;/li&gt; &lt;li&gt; Armor &lt;/li&gt; &lt;li&gt; Manuals &lt;/li&gt; &lt;li&gt; Sustenance &lt;/li&gt; &lt;li&gt; Test &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The problem is that if I use absolute or fixed values, different screen sizes will render the navigation bar differently. I also have a second <code>div</code> that contains all the main content which also needs to be moved to the right, so far I'm using relative values which seems to work no matter the screen size.</p>
[ { "answer_id": 61157, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>I think you're supposed to use the <strong>float</strong> property for positioning things like that. <a href=\"http://css.maxdesign.com.au/floatutorial/\" rel=\"nofollow noreferrer\">You can read about it here.</a></p>\n" }, { "answer_id": 61167, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>You should use the float and clear CSS attributes to get the desired effect. </p>\n\n<p>First I defined styles for the called left and right for the two columns in my layout and a style called clearer used to reset the page flow.</p>\n\n<pre>\n&lt;style type=\"text/css\"&gt;\n.left {\n float: left;\n width: 200px;\n}\n.right {\n float: right;\n width: 800px;\n}\n.clear {\n clear: both;\n height: 1px;\n}\n&lt;/style&gt;\n</pre>\n\n<p>Then I use them to layout my page.</p>\n\n<pre>\n&lt;div&gt;\n &lt;div class=\"left\"&gt;\n &lt;ul&gt;\n &lt;li&gt;Categories&lt;/li&gt;\n &lt;li&gt;Weapons&lt;/li&gt;\n &lt;li&gt;Armor&lt;/li&gt;\n &lt;li&gt;Manuals&lt;/li&gt;\n &lt;li&gt;Sustenance&lt;/li&gt;\n &lt;li&gt;Test&lt;/li&gt;\n &lt;/ul&gt; \n &lt;/div&gt;\n &lt;div class=\"right\"&gt;\n Blah Blah Blah....\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"clear\" /&gt;\n</pre>\n" }, { "answer_id": 61200, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p><code>float</code> is indeed the right property to achieve this. However, the example given by bmatthews68 can be improved. The most important thing about floating boxes is that they <em>must</em> specify an explicit width. This can be rather inconvenient but this is the way CSS works. However, notice that <code>px</code> is a unit of measure that has no place in the world of HTML/CSS, at least not to specify widths.</p>\n\n<p>Always resort to measures that will work with different font sizes, i.e. either use <code>em</code> or <code>%</code>. Now, if the menu is implemented as a floating body, then this means that the main content floats “around” it. If the main content is higher than the menu, this might not be what you want:</p>\n\n<p><a href=\"http://page.mi.fu-berlin.de/krudolph/stuff/float1.png\">float1 http://page.mi.fu-berlin.de/krudolph/stuff/float1.png</a></p>\n\n<pre><code>&lt;div style=\"width: 10em; float: left;\"&gt;Left&lt;/div&gt;\n&lt;div&gt;Right, spanning&lt;br/&gt; multiple lines&lt;/div&gt;\n</code></pre>\n\n<p>You can correct this behaviour by giving the main content a <code>margin-left</code> equal to the width of the menu:</p>\n\n<p><a href=\"http://page.mi.fu-berlin.de/krudolph/stuff/float2.png\">float2 http://page.mi.fu-berlin.de/krudolph/stuff/float2.png</a></p>\n\n<pre><code>&lt;div style=\"width: 10em; float: left;\"&gt;Left&lt;/div&gt;\n&lt;div style=\"margin-left: 10em;\"&gt;Right, spanning&lt;br/&gt; multiple lines&lt;/div&gt;\n</code></pre>\n\n<p>In most cases you also want to give the main content a <code>padding-left</code> so it doesn't “stick” to the menu too closely.</p>\n\n<p>By the way, it's trivial to change the above so that the menu is on the right side instead of the left: simply change every occurrence of the word “left” to “right”.</p>\n\n<p>Ah, one last thing. If the menu's content is higher than the main content, it will render oddly because <code>float</code> does some odd things. In that case, you will have to clear the box that comes below the floating body, as in bmatthews68's example.</p>\n\n<p>/EDIT: Damn, HTML doesn't work the way the preview showed it. Well, I've included pictures instead.</p>\n" }, { "answer_id": 61438, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 2, "selected": false, "text": "<p>All the answers saying to use floats (with explicit widths) are correct. But to answer the original question, what is the best way to position a <code>&lt;div&gt;</code>? It depends.</p>\n\n<p>CSS is highly contextual, and the flow of a page is dependent on the structure of your HTML. Normal flow is how elements, and their children, will layout top to bottom (for block elements) and left to right (for inline elements) inside their containing block (usually the parent). This is how the majority of your layout should work. You will tend to rely on <code>width</code>, <code>margin</code>, and <code>padding</code> to define the spacing and layout of the elements to the other elements around it (be they <code>&lt;div&gt;</code>, <code>&lt;ul&gt;</code>, <code>&lt;p&gt;</code>, or otherwise, HTML is mostly semantic at this point). </p>\n\n<p>Using styles like <code>float</code> or <code>absolute</code> or <code>relative</code> positioning can help you achieve very specific goals of your layout, but it's important to know how to use them. As has been explained, <code>float</code> is generally used to place block elements next to each other, and it really good for multi-column layouts.</p>\n\n<p>I won't go into more details here, but you might want to check out the following:</p>\n\n<ul>\n<li><a href=\"http://reference.sitepoint.com/css\" rel=\"nofollow noreferrer\">SitePoint CSS References</a> - probably the most straightforward and complete CSS reference I've found online.</li>\n<li><a href=\"http://www.w3.org/TR/CSS21/visuren.html\" rel=\"nofollow noreferrer\">W3C CSS2.1 Visual Formatting Model</a> - Yes, its a tough read, but it does explain everything.</li>\n</ul>\n" }, { "answer_id": 15769430, "author": "Eng Maisa", "author_id": 2214827, "author_profile": "https://Stackoverflow.com/users/2214827", "pm_score": 0, "selected": false, "text": "<p>you can use float</p>\n\n<pre><code>&lt;div class=\"left-menu\"&gt;\n&lt;ul&gt;\n&lt;li&gt; Categories &lt;/li&gt;\n&lt;li&gt; Weapons &lt;/li&gt;\n&lt;li&gt; Armor &lt;/li&gt;\n&lt;li&gt; Manuals &lt;/li&gt;\n&lt;li&gt; Sustenance &lt;/li&gt;\n&lt;li&gt; Test &lt;/li&gt;\n&lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>in css file</p>\n\n<pre><code>.left-menu{float:left;width:200px;}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
I'm trying to place this menu on the left hand side of the page: ```html <div class="left-menu" style="left: 123px; top: 355px"> <ul> <li> Categories </li> <li> Weapons </li> <li> Armor </li> <li> Manuals </li> <li> Sustenance </li> <li> Test </li> </ul> </div> ``` The problem is that if I use absolute or fixed values, different screen sizes will render the navigation bar differently. I also have a second `div` that contains all the main content which also needs to be moved to the right, so far I'm using relative values which seems to work no matter the screen size.
`float` is indeed the right property to achieve this. However, the example given by bmatthews68 can be improved. The most important thing about floating boxes is that they *must* specify an explicit width. This can be rather inconvenient but this is the way CSS works. However, notice that `px` is a unit of measure that has no place in the world of HTML/CSS, at least not to specify widths. Always resort to measures that will work with different font sizes, i.e. either use `em` or `%`. Now, if the menu is implemented as a floating body, then this means that the main content floats “around” it. If the main content is higher than the menu, this might not be what you want: [float1 http://page.mi.fu-berlin.de/krudolph/stuff/float1.png](http://page.mi.fu-berlin.de/krudolph/stuff/float1.png) ``` <div style="width: 10em; float: left;">Left</div> <div>Right, spanning<br/> multiple lines</div> ``` You can correct this behaviour by giving the main content a `margin-left` equal to the width of the menu: [float2 http://page.mi.fu-berlin.de/krudolph/stuff/float2.png](http://page.mi.fu-berlin.de/krudolph/stuff/float2.png) ``` <div style="width: 10em; float: left;">Left</div> <div style="margin-left: 10em;">Right, spanning<br/> multiple lines</div> ``` In most cases you also want to give the main content a `padding-left` so it doesn't “stick” to the menu too closely. By the way, it's trivial to change the above so that the menu is on the right side instead of the left: simply change every occurrence of the word “left” to “right”. Ah, one last thing. If the menu's content is higher than the main content, it will render oddly because `float` does some odd things. In that case, you will have to clear the box that comes below the floating body, as in bmatthews68's example. /EDIT: Damn, HTML doesn't work the way the preview showed it. Well, I've included pictures instead.
61,176
<p>I want to access messages in Gmail from a Java application using <a href="http://www.ing.iac.es/~docs/external/java/javamail/javadocs/index.html" rel="nofollow noreferrer">JavaMail</a> and <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>. Why am I getting a <em><a href="https://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html" rel="nofollow noreferrer">SocketTimeoutException</a></em> ?</p> <p>Here is my code:</p> <pre><code>Properties props = System.getProperties(); props.setProperty("mail.imap.host", "imap.gmail.com"); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.connectiontimeout", "5000"); props.setProperty("mail.imap.timeout", "5000"); try { Session session = Session.getDefaultInstance(props, new MyAuthenticator()); URLName urlName = new URLName("imap://[email protected]:[email protected]"); Store store = session.getStore(urlName); if (!store.isConnected()) { store.connect(); } } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1); } catch (MessagingException e) { e.printStackTrace(); System.exit(2); } </code></pre> <p>I have set the timeout values so that it wouldn't take "forever" to timeout. Also, <em>MyAuthenticator</em> also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>.)</p>
[ { "answer_id": 61179, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>You have to connect to GMail using SSL only. Setting the following properties will force that for you. </p>\n\n<pre>\nprops.setProperty(\"mail.imap.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\");\nprops.setProperty(\"mail.imap.socketFactory.fallback\", \"false\");\n</pre>\n" }, { "answer_id": 61185, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>In JavaMail, you can use <code>imaps</code> as the URL scheme to use IMAP over SSL. (See <code>SSLNOTES.txt</code> in your JavaMail distribution for more details.) For example, <code>imaps://username%[email protected]/INBOX</code>.</p>\n\n<p>Similarly, use <code>smtps</code> to send emails via Gmail. e.g., <code>smtps://username%[email protected]/</code>. Again, read <code>SSLNOTES.txt</code> for more details. Hope it helps!</p>\n" }, { "answer_id": 61469, "author": "Dave", "author_id": 2512222, "author_profile": "https://Stackoverflow.com/users/2512222", "pm_score": 6, "selected": false, "text": "<p>Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now.</p>\n\n<pre><code>Properties props = System.getProperties();\nprops.setProperty(\"mail.store.protocol\", \"imaps\");\ntry {\n Session session = Session.getDefaultInstance(props, null);\n Store store = session.getStore(\"imaps\");\n store.connect(\"imap.gmail.com\", \"&lt;username&gt;@gmail.com\", \"&lt;password&gt;\");\n ...\n} catch (NoSuchProviderException e) {\n e.printStackTrace();\n System.exit(1);\n} catch (MessagingException e) {\n e.printStackTrace();\n System.exit(2);\n}\n</code></pre>\n\n<p>This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.</p>\n" }, { "answer_id": 69724, "author": "Adisesha", "author_id": 11092, "author_profile": "https://Stackoverflow.com/users/11092", "pm_score": 1, "selected": false, "text": "<p>Check <a href=\"http://g4j.sourceforge.net/\" rel=\"nofollow noreferrer\">http://g4j.sourceforge.net/</a>. There is a minimal gmail client built using this API.</p>\n" }, { "answer_id": 112173, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 2, "selected": false, "text": "<p>If you'd like more sample code on using JavaMail with Gmail (e.g. converting Gmail labels to IMAP folder names, or using IMAP IDLE), do check out my program <a href=\"http://gmailassistant.sourceforge.net/\" rel=\"nofollow noreferrer\">GmailAssistant</a> on <a href=\"http://www.sourceforge.net/\" rel=\"nofollow noreferrer\">SourceForge</a>.</p>\n" }, { "answer_id": 260650, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>URLName server = new URLName(\"imaps://&lt;gmail-user-name&gt;:&lt;gmail-pass&gt;@imap.gmail.com/INBOX\");\n</code></pre>\n" }, { "answer_id": 2385657, "author": "Fu Cheng", "author_id": 221847, "author_profile": "https://Stackoverflow.com/users/221847", "pm_score": 1, "selected": false, "text": "<p>I used following properties to get the store and It works well.</p>\n\n<p><code>\"mail.imaps.host\" : \"imap.gmail.com\" <br>\n\"mail.store.protocol\" : \"imaps\" <br>\n\"mail.imaps.port\" : \"993\"\n</code></p>\n" }, { "answer_id": 3952463, "author": "hd1", "author_id": 783412, "author_profile": "https://Stackoverflow.com/users/783412", "pm_score": 0, "selected": false, "text": "<p>You need to have JSSE installed to use SSL with Java</p>\n" }, { "answer_id": 9888150, "author": "WhyNotHugo", "author_id": 107510, "author_profile": "https://Stackoverflow.com/users/107510", "pm_score": 3, "selected": false, "text": "<p>You need to use the following properties for imaps:</p>\n\n<pre><code>props.setProperty(\"mail.imaps.host\", \"imap.gmail.com\");\nprops.setProperty(\"mail.imaps.port\", \"993\");\nprops.setProperty(\"mail.imaps.connectiontimeout\", \"5000\");\nprops.setProperty(\"mail.imaps.timeout\", \"5000\");\n</code></pre>\n\n<p>Notices it's \"imaps\", not \"imap\", since the protocol you're using is imaps (IMAP + SSL)</p>\n" }, { "answer_id": 31214560, "author": "lboix", "author_id": 2920131, "author_profile": "https://Stackoverflow.com/users/2920131", "pm_score": 2, "selected": false, "text": "<p>Here is what worked for my team and I, given a classic account [email protected] and a business account [email protected] :</p>\n<pre><code> final Properties properties = new Properties();\n properties.put(&quot;mail.imap.ssl.enable&quot;, &quot;true&quot;);\n\n imapSession = Session.getInstance(properties, null);\n imapSession.setDebug(false);\n imapStore = imapSession.getStore(&quot;imap&quot;);\n\n imapStore.connect(&quot;imap.gmail.com&quot;, USERNAME, &quot;password&quot;);\n</code></pre>\n<p>with USERNAME = &quot;nickname&quot; in the classic case, and USERNAME = &quot;[email protected]&quot; in the business account case.</p>\n<p>In the classic case, don't forget to lower the account security here : <a href=\"https://www.google.com/settings/security/lesssecureapps\" rel=\"nofollow noreferrer\">https://www.google.com/settings/security/lesssecureapps</a></p>\n<p>In both cases check in GMail <em>Settings =&gt; Forwarding POP / IMAP</em> if IMAP is enabled for the account.</p>\n<p>Hope it helps!</p>\n<p>To go further :</p>\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail\" rel=\"nofollow noreferrer\">http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail</a></li>\n<li><a href=\"https://support.google.com/mail/accounts/answer/78754\" rel=\"nofollow noreferrer\">https://support.google.com/mail/accounts/answer/78754</a></li>\n</ul>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2512222/" ]
I want to access messages in Gmail from a Java application using [JavaMail](http://www.ing.iac.es/~docs/external/java/javamail/javadocs/index.html) and [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol). Why am I getting a *[SocketTimeoutException](https://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html)* ? Here is my code: ``` Properties props = System.getProperties(); props.setProperty("mail.imap.host", "imap.gmail.com"); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.connectiontimeout", "5000"); props.setProperty("mail.imap.timeout", "5000"); try { Session session = Session.getDefaultInstance(props, new MyAuthenticator()); URLName urlName = new URLName("imap://[email protected]:[email protected]"); Store store = session.getStore(urlName); if (!store.isConnected()) { store.connect(); } } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1); } catch (MessagingException e) { e.printStackTrace(); System.exit(2); } ``` I have set the timeout values so that it wouldn't take "forever" to timeout. Also, *MyAuthenticator* also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol).)
Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now. ``` Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", "<username>@gmail.com", "<password>"); ... } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1); } catch (MessagingException e) { e.printStackTrace(); System.exit(2); } ``` This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.
61,212
<p>How do I delete untracked local files from the current working tree?</p>
[ { "answer_id": 61213, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-clean.html\" rel=\"noreferrer\">git-clean</a> is what you are looking for. It is used to remove untracked files from the working tree.</p>\n" }, { "answer_id": 61214, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 9, "selected": false, "text": "<p><a href=\"http://git-scm.com/docs/git-clean\" rel=\"noreferrer\"><code>git-clean</code> - Remove untracked files from the working tree</a></p>\n" }, { "answer_id": 64966, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 14, "selected": true, "text": "<blockquote>\n<h2><a href=\"https://git-scm.com/docs/git-clean\" rel=\"noreferrer\">git-clean</a> - Remove untracked files from the working tree</h2>\n<h3>Synopsis</h3>\n<pre><code>git clean [-d] [-f] [-i] [-n] [-q] [-e &lt;pattern&gt;] [-x | -X] [--] &lt;path&gt;…​\n</code></pre>\n<h3>Description</h3>\n<p>Cleans the working tree by recursively removing files that are not under version control, <strong>starting from the current directory</strong>.</p>\n<p>Normally, only files unknown to Git are removed, but if the <code>-x</code> option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.</p>\n<p>If any optional <code>&lt;path&gt;...</code> arguments are given, only those paths are affected.</p>\n</blockquote>\n<hr />\n<p>Step 1 is to show what will be deleted by using the <code>-n</code> option:</p>\n<pre><code># Print out the list of files and directories which will be removed (dry run)\ngit clean -n -d\n</code></pre>\n<p>Clean Step - <strong>beware: this will delete files</strong>:</p>\n<pre><code># Delete the files from the repository\ngit clean -f\n</code></pre>\n<ul>\n<li>To remove directories, run <code>git clean -f -d</code> or <code>git clean -fd</code></li>\n<li>To remove ignored files, run <code>git clean -f -X</code> or <code>git clean -fX</code></li>\n<li>To remove ignored and non-ignored files, run <code>git clean -f -x</code> or <code>git clean -fx</code></li>\n</ul>\n<p><strong>Note</strong> the case difference on the <code>X</code> for the two latter commands.</p>\n<p>If <code>clean.requireForce</code> is set to &quot;true&quot; (the default) in your configuration, one needs to specify <code>-f</code> otherwise nothing will actually happen.</p>\n<p>Again see the <a href=\"http://git-scm.com/docs/git-clean\" rel=\"noreferrer\"><code>git-clean</code></a> docs for more information.</p>\n<hr />\n<blockquote>\n<h3>Options</h3>\n<p><strong><code>-f</code>, <code>--force</code></strong></p>\n<p>If the Git configuration variable clean.requireForce is not set to\nfalse, git clean will refuse to run unless given <code>-f</code>, <code>-n</code> or <code>-i</code>.</p>\n<p><strong><code>-x</code></strong></p>\n<p>Don’t use the standard ignore rules read from .gitignore (per\ndirectory) and <code>$GIT_DIR/info/exclude</code>, but do still use the ignore\nrules given with <code>-e</code> options. This allows removing all untracked files,\nincluding build products. This can be used (possibly in conjunction\nwith git reset) to create a pristine working directory to test a clean\nbuild.</p>\n<p><strong><code>-X</code></strong></p>\n<p>Remove only files ignored by Git. This may be useful to rebuild\neverything from scratch, but keep manually created files.</p>\n<p><strong><code>-n</code>, <code>--dry-run</code></strong></p>\n<p>Don’t actually remove anything, just show what would be done.</p>\n<p><strong><code>-d</code></strong></p>\n<p>Remove untracked directories in addition to untracked files. If an\nuntracked directory is managed by a different Git repository, it is\nnot removed by default. Use <code>-f</code> option twice if you really want to\nremove such a directory.</p>\n</blockquote>\n" }, { "answer_id": 912737, "author": "robert.berger", "author_id": 108743, "author_profile": "https://Stackoverflow.com/users/108743", "pm_score": 10, "selected": false, "text": "<p>Use <code>git clean -f -d</code> to make sure that <strong>directories</strong> are also removed.</p>\n\n<ol>\n<li><p>Don’t actually remove anything, just show what would be done.</p>\n\n<pre><code>git clean -n\n</code></pre>\n\n<p>or </p>\n\n<pre><code>git clean --dry-run\n</code></pre></li>\n<li><p>Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use the <code>-f</code> option twice if you really want to remove such a directory.</p>\n\n<pre><code>git clean -fd\n</code></pre></li>\n</ol>\n\n<p>You can then check if your files are really gone with <code>git status</code>.</p>\n" }, { "answer_id": 14521765, "author": "Michał Szajbe", "author_id": 369894, "author_profile": "https://Stackoverflow.com/users/369894", "pm_score": 8, "selected": false, "text": "<p>If untracked directory is a git repository of its own (e.g. submodule), you need to use <code>-f</code> twice:</p>\n\n<p><code>git clean -d -f -f</code></p>\n" }, { "answer_id": 18974433, "author": "Vijay C", "author_id": 255721, "author_profile": "https://Stackoverflow.com/users/255721", "pm_score": 7, "selected": false, "text": "<p>If needed to remove untracked files from particular subdirectory,</p>\n\n<pre><code>git clean -f {dir_path}\n</code></pre>\n\n<p>And combined way to delete untracked dir/files and ignored files. </p>\n\n<pre><code>git clean -fxd {dir_path}\n</code></pre>\n\n<p>after this you will have modified files only in <code>git status</code>.</p>\n" }, { "answer_id": 20195320, "author": "Oscar Fraxedas", "author_id": 1074245, "author_profile": "https://Stackoverflow.com/users/1074245", "pm_score": 7, "selected": false, "text": "<p>This is what I always use:</p>\n\n<pre><code>git clean -fdx\n</code></pre>\n\n<p>For a very large project you might want to run it a couple of times.</p>\n" }, { "answer_id": 20846779, "author": "SystematicFrank", "author_id": 253098, "author_profile": "https://Stackoverflow.com/users/253098", "pm_score": 9, "selected": false, "text": "<p>I am surprised nobody mentioned this before:</p>\n\n<pre><code>git clean -i\n</code></pre>\n\n<p>That stands for <em>interactive</em> and you will get a quick overview of what is going to be deleted offering you the possibility to include/exclude the affected files. Overall, still faster than running the mandatory <code>--dry-run</code> before the real cleaning.</p>\n\n<p>You will have to toss in a <code>-d</code> if you also want to take care of empty folders. At the end, it makes for a nice alias:</p>\n\n<pre><code>git iclean\n</code></pre>\n\n<p>That being said, the extra hand holding of interactive commands can be tiring for experienced users. These days I just use the already mentioned <code>git clean -fd</code> </p>\n" }, { "answer_id": 21057032, "author": "hiroshi", "author_id": 338986, "author_profile": "https://Stackoverflow.com/users/338986", "pm_score": 7, "selected": false, "text": "<p>I like <code>git stash push -u</code> because you can undo them all with <code>git stash pop</code>.</p>\n\n<p>EDIT: Also I found a way to show untracked file in a stash (e.g. <code>git show stash@{0}^3</code>) <a href=\"https://stackoverflow.com/a/12681856/338986\">https://stackoverflow.com/a/12681856/338986</a></p>\n\n<p>EDIT2: <code>git stash save</code> is deprecated in favor of <code>push</code>. Thanks @script-wolf.</p>\n" }, { "answer_id": 28082580, "author": "Pooja", "author_id": 3446107, "author_profile": "https://Stackoverflow.com/users/3446107", "pm_score": 6, "selected": false, "text": "<p><code>git clean -fd</code> removes directory</p>\n\n<p><code>git clean -fX</code> removes ignored files</p>\n\n<p><code>git clean -fx</code> removes ignored and un-ignored files</p>\n\n<p>can be used all above options in combination as </p>\n\n<p><code>git clean -fdXx</code> </p>\n\n<p>check git manual for more help</p>\n" }, { "answer_id": 29667299, "author": "Chhabilal", "author_id": 2554162, "author_profile": "https://Stackoverflow.com/users/2554162", "pm_score": 5, "selected": false, "text": "<p>A better way is to use: git clean</p>\n\n<pre><code>git clean -d -x -f\n</code></pre>\n\n<p>This removes untracked files, including directories <code>(-d)</code> and files ignored by <code>git (-x)</code>.</p>\n\n<p>Also, replace the <code>-f</code> argument with <code>-n</code> to perform a <code>dry-run</code> or <code>-i</code> for interactive mode and it will tell you what will be removed.</p>\n" }, { "answer_id": 34049725, "author": "Nikita Leonov", "author_id": 723050, "author_profile": "https://Stackoverflow.com/users/723050", "pm_score": 5, "selected": false, "text": "<p><code>git clean -f -d -x $(git rev-parse --show-cdup)</code> applies clean to the root directory, no matter where you call it within a repository directory tree. I use it all the time as it does not force you to leave the folder where you working now and allows to clean &amp; commit right from the place where you are.</p>\n\n<p>Be sure that flags <code>-f</code>, <code>-d</code>, <code>-x</code> match your needs:</p>\n\n<pre><code>-d\n Remove untracked directories in addition to untracked files. If an\n untracked directory is managed by a different Git repository, it is\n not removed by default. Use -f option twice if you really want to\n remove such a directory.\n\n-f, --force\n If the Git configuration variable clean.requireForce is not set to\n false, git clean will refuse to delete files or directories unless\n given -f, -n or -i. Git will refuse to delete directories with .git\n sub directory or file unless a second -f is given. This affects\n also git submodules where the storage area of the removed submodule\n under .git/modules/ is not removed until -f is given twice.\n\n-x\n Don't use the standard ignore rules read from .gitignore (per\n directory) and $GIT_DIR/info/exclude, but do still use the ignore\n rules given with -e options. This allows removing all untracked\n files, including build products. This can be used (possibly in\n conjunction with git reset) to create a pristine working directory\n to test a clean build.\n</code></pre>\n\n<p>There are other flags as well available, just check <code>git clean --help</code>.</p>\n" }, { "answer_id": 35427633, "author": "Omar Mowafi", "author_id": 1350159, "author_profile": "https://Stackoverflow.com/users/1350159", "pm_score": 4, "selected": false, "text": "<p>To know what will be deleted before actually deleting:</p>\n\n<p><code>git clean -d -n</code></p>\n\n<p>It will output something like:</p>\n\n<p><strong>Would remove sample.txt</strong></p>\n\n<p>To delete everything listed in the output of the previous command:</p>\n\n<p><code>git clean -d -f</code></p>\n\n<p>It will output something like:</p>\n\n<p><strong>Removing sample.txt</strong></p>\n" }, { "answer_id": 35539401, "author": "thybzi", "author_id": 3027390, "author_profile": "https://Stackoverflow.com/users/3027390", "pm_score": 5, "selected": false, "text": "<p>A lifehack for such situation I just invented and tried (that works perfectly):</p>\n\n<pre><code>git add .\ngit reset --hard HEAD\n</code></pre>\n\n<p><strong>Beware!</strong> Be sure to <strong>commit any needed changes</strong> (even in non-untracked files) <strong>before performing this</strong>.</p>\n" }, { "answer_id": 35737150, "author": "JD Brennan", "author_id": 304712, "author_profile": "https://Stackoverflow.com/users/304712", "pm_score": 4, "selected": false, "text": "<p>If you just want to delete the files listed as untracked by 'git status'</p>\n\n<pre><code>git stash save -u\ngit stash drop \"stash@{0}\"\n</code></pre>\n\n<p>I prefer this to 'git clean' because 'git clean' will delete files\nignored by git, so your next build will have to rebuild everything\nand you may lose your IDE settings too.</p>\n" }, { "answer_id": 37614185, "author": "Thanga", "author_id": 5678086, "author_profile": "https://Stackoverflow.com/users/5678086", "pm_score": 9, "selected": false, "text": "<h2>Simple Way to remove untracked files</h2>\n\n<p>To remove all untracked files, The simple\nway is to <strong>add all of them first</strong> and <strong>reset the repo</strong> as below</p>\n\n<pre><code>git add --all\ngit reset --hard HEAD\n</code></pre>\n\n<hr>\n" }, { "answer_id": 38978877, "author": "rahul286", "author_id": 156336, "author_profile": "https://Stackoverflow.com/users/156336", "pm_score": 5, "selected": false, "text": "<p>For me only following worked:</p>\n\n<pre><code>git clean -ffdx\n</code></pre>\n\n<p>In all other cases, I was getting message <em>\"Skipping Directory\"</em> for some subdirectories. </p>\n" }, { "answer_id": 39968630, "author": "kujiy", "author_id": 5815086, "author_profile": "https://Stackoverflow.com/users/5815086", "pm_score": 4, "selected": false, "text": "<p>Normal <code>git clean</code> command doesn't remove untracked files with my <code>git version 2.9.0.windows.1</code>.</p>\n\n<pre><code>$ git clean -fdx # doesn't remove untracked files\n$ git clean -fdx * # Append star then it works!\n</code></pre>\n" }, { "answer_id": 40235858, "author": "Gaurav", "author_id": 3809978, "author_profile": "https://Stackoverflow.com/users/3809978", "pm_score": 4, "selected": false, "text": "<p>To remove the untracked files you should first use command to view the files that will be affected by cleaning </p>\n\n<pre><code>git clean -fdn\n</code></pre>\n\n<p>This will show you the list of files that will be deleted. Now to actually delete those files use this command:</p>\n\n<pre><code>git clean -fd\n</code></pre>\n" }, { "answer_id": 41187216, "author": "Gnanasekar S", "author_id": 6859356, "author_profile": "https://Stackoverflow.com/users/6859356", "pm_score": 2, "selected": false, "text": "<p><em>Note: First navigate to the directory and checkout the branch you want to clean.</em></p>\n\n<p><code>-i</code> interactive mode and it will tell you what will be removed and you can choose an action from the list.</p>\n\n<ol>\n<li><p>To clean <strong>files</strong> only [Folders will not be listed and will not be cleaned]: \n<code>$ git clean -i</code></p></li>\n<li><p>To clean <strong>files and folders</strong>:\n<code>$ git clean -d -i</code></p></li>\n</ol>\n\n<p><code>-d</code> including directories.</p>\n\n<hr>\n\n<p>If you choose <code>c</code> from the list. The files/folders will be deleted that are not tracked and will also remove files/folders that you mess-up.*</p>\n\n<p>For instance: If you restructure the folder in your remote and pull the changes to your local computer. files/folders that are created by others initially will be in past folder and in the new one that you restructure.</p>\n" }, { "answer_id": 42185640, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "<p><strong>Remove all extra folders and files in this repo + submodules</strong></p>\n\n<p>This gets you in same state as fresh clone.</p>\n\n<pre><code>git clean -ffdx\n</code></pre>\n\n<p><strong>Remove all extra folders and files in this repo but not its submodules</strong></p>\n\n<pre><code>git clean -fdx\n</code></pre>\n\n<p><strong>Remove extra folders but not files (ex. build or logs folder)</strong></p>\n\n<pre><code>git clean -fd\n</code></pre>\n\n<p><strong>Remove extra folders + ignored files (but not newly added files)</strong></p>\n\n<p>If file wasn't ignored and not yet checked-in then it stays. Note the capital X.</p>\n\n<pre><code>git clean -fdX\n</code></pre>\n\n<p><strong>New interactive mode</strong></p>\n\n<pre><code>git clean\n</code></pre>\n" }, { "answer_id": 42269293, "author": "Vaisakh VM", "author_id": 1905008, "author_profile": "https://Stackoverflow.com/users/1905008", "pm_score": 4, "selected": false, "text": "<p><code>git clean -f to remove untracked files from working directory.</code></p>\n\n<p>I have covered some basics here in my blog, <a href=\"https://vaisakh.github.io/2017/02/14/git-intro-basic-commands.html\" rel=\"noreferrer\">git-intro-basic-commands</a></p>\n" }, { "answer_id": 42564993, "author": "bit_cracker007", "author_id": 1098479, "author_profile": "https://Stackoverflow.com/users/1098479", "pm_score": 5, "selected": false, "text": "<p><strong><em>User interactive approach:</em></strong> </p>\n\n<pre><code>git clean -i -fd\n\nRemove .classpath [y/N]? N\nRemove .gitignore [y/N]? N\nRemove .project [y/N]? N\nRemove .settings/ [y/N]? N\nRemove src/com/arsdumpgenerator/inspector/ [y/N]? y\nRemove src/com/arsdumpgenerator/manifest/ [y/N]? y\nRemove src/com/arsdumpgenerator/s3/ [y/N]? y\nRemove tst/com/arsdumpgenerator/manifest/ [y/N]? y\nRemove tst/com/arsdumpgenerator/s3/ [y/N]? y\n</code></pre>\n\n<p>-i for interactive<br>\n-f for force<br>\n-d for directory<br>\n-x for ignored files(add if required)<br><br>\n<strong>Note:</strong> <em>Add <strong>-n</strong> or <strong>--dry-run</strong> to just check what it will do.</em></p>\n" }, { "answer_id": 45220636, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 6, "selected": false, "text": "<p><strong>OK,</strong> deleting <strong>unwanted untracked files and folders</strong> are easy using <code>git</code> in command line, just do it like this:</p>\n\n<pre><code>git clean -fd\n</code></pre>\n\n<p><strong>Double check</strong> before doing it as it will delete the files and folders without making any history...</p>\n\n<p>Also in this case, <code>-f</code> stands for force and <code>-d</code> stands for directory...</p>\n\n<p>So, if you want to delete files only, you can use <code>-f</code> only:</p>\n\n<pre><code>git clean -f\n</code></pre>\n\n<p>If you want to <strong>delete</strong>(directories) and files, you can delete only untracked directories and files like this:</p>\n\n<pre><code>git clean -fd\n</code></pre>\n\n<p>Also, you can use <code>-x</code> flag for including the files which are ignored by git. This would be helpful if you want to delete everything.</p>\n\n<p>And adding <code>-i</code> flag, makes git asking you for permission for deleting files one by one on the go.</p>\n\n<p>If you not sure and want to check things first, add <code>-n</code> flag.</p>\n\n<p>Use <code>-q</code> if you don't want to see any report after successful deletion.</p>\n\n<p>I also create the image below to make it more memorable, especially I have seen many people confuse <code>-f</code> for cleaning folder sometimes or mix it up somehow!</p>\n\n<p><br>\n<a href=\"https://i.stack.imgur.com/3W563.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3W563.png\" alt=\"deleting unwanted untracked files and folder\"></a> </p>\n" }, { "answer_id": 45558196, "author": "Vivek", "author_id": 4199462, "author_profile": "https://Stackoverflow.com/users/4199462", "pm_score": 0, "selected": false, "text": "<p>use <code>git reset HEAD &lt;file&gt;</code> to unstage a file</p>\n" }, { "answer_id": 45994347, "author": "Mohideen bin Mohammed", "author_id": 4453737, "author_profile": "https://Stackoverflow.com/users/4453737", "pm_score": 4, "selected": false, "text": "<p>uggested Command for <strong>Removing Untracked Files from git docs</strong> is <strong>git clean</strong> </p>\n\n<p><strong>git clean</strong> - Remove untracked files from the working tree</p>\n\n<p><strong>Suggested Method:</strong> Interative Mode by using <code>git clean -i</code>\nso we can have control over it. let see remaining available options.</p>\n\n<p><strong>Available Options:</strong></p>\n\n<pre><code>git clean \n -d -f -i -n -q -e -x -X (can use either)\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p><strong>1.</strong> <strong>-d</strong></p>\n\n<p>Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository,\n it is not removed by default. Use -f option twice if you really want to remove such a directory.</p>\n\n<p><strong>2. -f, --force</strong></p>\n\n<p>If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given -f, -n or\n -i.</p>\n\n<p><strong>3. -i, --interactive</strong></p>\n\n<p>Show what would be done and clean files interactively. See “Interactive mode” for details.</p>\n\n<p><strong>4. -n, --dry-run</strong></p>\n\n<p>Don’t actually remove anything, just show what would be done.</p>\n\n<p><strong>5. -q, --quiet</strong></p>\n\n<p>Be quiet, only report errors, but not the files that are successfully removed.</p>\n\n<p><strong>6. -e , --exclude=</strong></p>\n\n<p>In addition to those found in .gitignore (per directory) and $GIT_DIR/info/exclude, also consider these patterns to be in the\n set of the ignore rules in effect.</p>\n\n<p><strong>7. -x</strong></p>\n\n<p>Don’t use the standard ignore rules read from .gitignore (per directory) and $GIT_DIR/info/exclude, but do still use the ignore\n rules given with -e options. This allows removing all untracked files, including build products. This can be used (possibly in\n conjunction with git reset) to create a pristine working directory to test a clean build.</p>\n\n<p><strong>8. -X</strong></p>\n\n<p>Remove only files ignored by Git. This may be useful to rebuild everything from scratch, but keep manually created files.</p>\n" }, { "answer_id": 46409906, "author": "Sergey", "author_id": 739731, "author_profile": "https://Stackoverflow.com/users/739731", "pm_score": 3, "selected": false, "text": "<blockquote>\n <h2><strong>Clean out git repository and all submodules recursively</strong></h2>\n \n <p>The following command will clean out\n the current git repository and all its submodules recursively:</p>\n\n<pre><code>(git clean -d -x -f &amp;&amp; git submodule foreach --recursive git clean -d -x -f)\n</code></pre>\n</blockquote>\n" }, { "answer_id": 46868431, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 7, "selected": false, "text": "<h1>Be careful while running `git clean` command.</h1>\n<h2><strong>Always use</strong> <code>-n</code> first</h2>\n<p>Always use <code>-n</code> before running the clean command as it will show you what files would get removed.</p>\n<p><code>-d</code> Normally, when no is specified, git clean will not recurse into untracked directories to avoid removing too much. Specify -d to have it recurse into such directories as well. If any paths are specified, -d is irrelevant; all untracked files matching the specified paths (with exceptions for nested git directories mentioned under --force) will be removed.</p>\n<p><code>-f</code> | <code>--force</code>\nIf the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f or -i. Git will refuse to modify untracked nested git repositories (directories with a .git subdirectory) unless a second -f is given.</p>\n<pre><code>git clean -n -d \ngit clean -n -d -f\n</code></pre>\n<p>Now run without <code>-n</code> if output was what you intend to remove.</p>\n<pre><code>git clean -d -f\n</code></pre>\n<p>By default, <code>git clean</code> will only remove untracked files that are not ignored. Any file that matches a pattern in your .gitignore or other ignore files will not be removed. If you want to remove those files too, you can add a <code>-x</code> to the clean command.</p>\n<pre><code>git clean -f -d -x\n</code></pre>\n<p>There is also interactive mode available <code>-i</code> with the clean command</p>\n<pre><code>git clean -x -i\n</code></pre>\n<h1>Alternatively</h1>\nIf you are not 100% sure that deleting your uncommitted work is safe, you could use stashing instead\n<pre><code>git stash --all\n</code></pre>\n<p>Before you use <code>stash --all</code> note:\nIf the <code>--all</code> option is used, then the <strong>ignored files</strong> are stashed and cleaned in addition to the <strong>untracked files</strong>.</p>\n<pre><code>git stash push --keep-index\n</code></pre>\n<p>If the --keep-index option is used, all changes already added to the index are left intact. Your staged changes remain in your workspace, but at the same time, they are also saved into your stash.</p>\n<p>Calling <code>git stash</code> without any arguments is equivalent to <code>git stash push</code>.</p>\n<pre><code>git stash push -m &quot;name your stash&quot; // before git stash save (deprecated)\n</code></pre>\n<p>Stashing based on the used flags can clear your directory from unstaged / staged files by writing them to stash storage. I give’s flexibility to retrieve the files at any point in time using <strong>stash</strong> with <strong>apply</strong> or <strong>pop</strong>. Then if you are fine with removing your stashed files you could run:</p>\n<pre><code>git stash drop // or clean\n</code></pre>\n<p>To see full instruction on how to work with stash see this <a href=\"https://stackoverflow.com/questions/11269256/how-to-name-and-retrieve-a-stash-by-name-in-git\">How to name and retrieve a stash by name in git?</a></p>\n<p><a href=\"https://i.stack.imgur.com/G356U.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/G356U.jpg\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 47070614, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 3, "selected": false, "text": "<p><strong>oh-my-zsh</strong> with <strong>zsh</strong> provides those great aliases via the git plugin. They can be used in bash as well.</p>\n\n<p><code>gclean='git clean -fd'</code><br>\n<code>gpristine='git reset --hard &amp;&amp; git clean -dfx'</code></p>\n\n<ul>\n<li><code>gclean</code> <em>removes untracked directories in addition to untracked files</em>.</li>\n<li><code>gpristine</code> hard reset the local changes, remove untracked directories, \nuntracked files and <em>don't use the standard ignore rules read from .gitignore (per directory) and $GIT_DIR/info/exclude, but do still use the ignore rules given with -e options. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with git reset) to create a pristine working directory to test a clean build</em>.</li>\n</ul>\n" }, { "answer_id": 47627685, "author": "Elangovan", "author_id": 2614459, "author_profile": "https://Stackoverflow.com/users/2614459", "pm_score": 3, "selected": false, "text": "<p>We can easily removed local untracked files from the current git working tree by using below git comments.</p>\n\n<pre><code>git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [&lt;commit&gt;]\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>git reset --hard HEAD\n</code></pre>\n\n<p><strong>Links :</strong></p>\n\n<ol>\n<li><a href=\"https://git-scm.com/docs/git-reset\" rel=\"noreferrer\">https://git-scm.com/docs/git-reset</a></li>\n<li><a href=\"https://stackoverflow.com/questions/9529078/how-do-i-use-git-reset-hard-head-to-revert-to-a-previous-commit\">How do I use &#39;git reset --hard HEAD&#39; to revert to a previous commit?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1628088/reset-local-repository-branch-to-be-just-like-remote-repository-head\">Reset local repository branch to be just like remote repository HEAD</a></li>\n<li><a href=\"https://jwiegley.github.io/git-from-the-bottom-up/3-Reset/4-doing-a-hard-reset.html\" rel=\"noreferrer\">https://jwiegley.github.io/git-from-the-bottom-up/3-Reset/4-doing-a-hard-reset.html</a> </li>\n</ol>\n" }, { "answer_id": 50404741, "author": "Sudhir Vishwakarma", "author_id": 493356, "author_profile": "https://Stackoverflow.com/users/493356", "pm_score": 3, "selected": false, "text": "<pre><code>git clean -f\n</code></pre>\n\n<p>will remove the untracked files from the current git </p>\n\n<pre><code>git clean -fd\n</code></pre>\n\n<p>when you want to remove directories and files, this will delete only untracked directories and files</p>\n" }, { "answer_id": 51873385, "author": "Gediminas", "author_id": 1412149, "author_profile": "https://Stackoverflow.com/users/1412149", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I haved failed using most popular answers here - git doesn't delete\n untracked files from the repository anyway. No idea why. This is my\n super simplified answer without SPECIAL GIT COMMANDS!</p>\n</blockquote>\n\n<p>Mission: delete untracked files from git repository:</p>\n\n<ol>\n<li>Move files and folders elsewhere from your local project folder for a while</li>\n<li>Delete all lines in .gitignore about these files and folders for the commit</li>\n<li>Git add . </li>\n<li>Git commit -m “Cleaning repository from untracked files”</li>\n<li>Git push</li>\n</ol>\n\n<p>All files and folders has been deleted from the repository. </p>\n\n<p>Lets restore them on localhost if you need them:</p>\n\n<ol>\n<li>Move back all files and folders you have moved temporary to the local project folder again</li>\n<li>Move back all lines about these files and folders to .gitignore</li>\n<li>Git add .</li>\n<li>Git commit -m “Checking or files not appearing again in git repository”</li>\n<li>Git push</li>\n</ol>\n\n<p>You are done!</p>\n" }, { "answer_id": 53244015, "author": "Zia", "author_id": 2931121, "author_profile": "https://Stackoverflow.com/users/2931121", "pm_score": 2, "selected": false, "text": "<p>I like to use <code>git stash</code> command, later you can get stashed files and changes.\n<code>git clean</code> is also a good option but totally depends on your requirement.\nhere is the explanation of git stash and git clean,<a href=\"https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning\" rel=\"nofollow noreferrer\">7.3 Git Tools - Stashing and Cleaning</a></p>\n" }, { "answer_id": 55831043, "author": "victorm1710", "author_id": 680032, "author_profile": "https://Stackoverflow.com/users/680032", "pm_score": 1, "selected": false, "text": "<p>If nothing else works, to simply remove all the changes listed by the \"git status\" command one can use the following combo:</p>\n\n<p><code>git add -A &amp;&amp; git commit -m temp &amp;&amp; git reset --hard HEAD^</code></p>\n\n<p>This will first stage all of your changes then create a temporary commit and then discard it.</p>\n" }, { "answer_id": 56520858, "author": "Thirdy", "author_id": 5118429, "author_profile": "https://Stackoverflow.com/users/5118429", "pm_score": -1, "selected": false, "text": "<p>I use this:</p>\n\n<ol>\n<li><code>git status</code></li>\n<li>copy the path of the file</li>\n<li><code>rm &lt;path of file&gt;</code></li>\n</ol>\n\n<p>My project has a lot of generated files created by a giant ANT build script. Using <code>git clean</code> would create chaos.</p>\n" }, { "answer_id": 59435746, "author": "ideasman42", "author_id": 432509, "author_profile": "https://Stackoverflow.com/users/432509", "pm_score": 0, "selected": false, "text": "<p>This can be done using a shell script, I use this scrtipt that lists what will be removed, then lets me confirm the operation.</p>\n\n<p>This is useful since I sometimes have patches or other files I'd like to check on before wiping everything away.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\nreadarray -t -d '' FILES &lt; &lt;(git ls-files -z --other --directory)\nif [ \"$FILES\" = \"\" ]; then\n echo \"Nothing to clean!\"\n exit 0\nfi\necho -e \"Dirty files:\\n\"\nprintf ' %s\\n' \"${FILES[@]}\"\nDO_REMOVE=0\nwhile true; do\n echo \"\"\n read -p \"Remove ${#FILES[@]} files? [y/n]: \" choice\n case \"$choice\" in\n y|Y )\n DO_REMOVE=1\n break ;;\n n|N )\n echo \"Exiting!\"\n break ;;\n * ) echo \"Invalid input, expected [Y/y/N/n]\"\n continue ;;\n esac\ndone\n\nif [ \"$DO_REMOVE\" -eq 1 ];then\n echo \"Removing!\"\n for f in \"${FILES[@]}\"; do\n rm -rfv -- \"$f\"\n done\nfi\n</code></pre>\n" }, { "answer_id": 61917678, "author": "Rajeev Shetty", "author_id": 3932147, "author_profile": "https://Stackoverflow.com/users/3932147", "pm_score": 5, "selected": false, "text": "<p>To remove Untracked files :</p>\n\n<pre><code>git add .\ngit reset --hard HEAD\n</code></pre>\n" }, { "answer_id": 63590924, "author": "Samir Kape", "author_id": 8312897, "author_profile": "https://Stackoverflow.com/users/8312897", "pm_score": 1, "selected": false, "text": "<p>usage: git clean [-d] [-f] [-i] [-n] [-q] [-e ] [-x | -X] [--] ...</p>\n<pre><code>-q, --quiet do not print names of files removed\n-n, --dry-run dry run\n-f, --force force\n-i, --interactive interactive cleaning\n-d remove whole directories\n-e, --exclude &lt;pattern&gt;\n add &lt;pattern&gt; to ignore rules\n-x remove ignored files, too\n-X remove only ignored files\n</code></pre>\n" }, { "answer_id": 64769771, "author": "KARTHIKEYAN.A", "author_id": 4652706, "author_profile": "https://Stackoverflow.com/users/4652706", "pm_score": 3, "selected": false, "text": "<p>To remove complete changes <strong>git clean -f -d</strong></p>\n<pre><code>$ git clean -f -d\nRemoving client/app/helpers/base64.js\nRemoving files/\nRemoving package.json.bak\n\nwhere \n-f is force \n-d is a directory \n</code></pre>\n" }, { "answer_id": 67098568, "author": "jenny", "author_id": 6409591, "author_profile": "https://Stackoverflow.com/users/6409591", "pm_score": 4, "selected": false, "text": "<p><code>git add --all</code>, <code>git stash</code> and <code>git stash drop</code>, try these three commands in this order inorder to remove all untracked files. By adding all those untracked files to git and stashing them will move all those untracked files to stash list and dropping out top one i.e., stash@{0} will remove the stashed changes from stash list.</p>\n" }, { "answer_id": 68547440, "author": "Ahmet Emrebas", "author_id": 12603032, "author_profile": "https://Stackoverflow.com/users/12603032", "pm_score": 3, "selected": false, "text": "<p>I think the safe and easy way is this!</p>\n<pre><code>git add .\ngit stash \n</code></pre>\n<p>For more information\n<a href=\"https://www.atlassian.com/git/tutorials/saving-changes/git-stash#stashing-your-work\" rel=\"noreferrer\">https://www.atlassian.com/git/tutorials/saving-changes/git-stash#stashing-your-work</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How do I delete untracked local files from the current working tree?
> > [git-clean](https://git-scm.com/docs/git-clean) - Remove untracked files from the working tree > ---------------------------------------------------------------------------------------------- > > > ### Synopsis > > > > ``` > git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>…​ > > ``` > > ### Description > > > Cleans the working tree by recursively removing files that are not under version control, **starting from the current directory**. > > > Normally, only files unknown to Git are removed, but if the `-x` option is specified, ignored files are also removed. This can, for example, be useful to remove all build products. > > > If any optional `<path>...` arguments are given, only those paths are affected. > > > --- Step 1 is to show what will be deleted by using the `-n` option: ``` # Print out the list of files and directories which will be removed (dry run) git clean -n -d ``` Clean Step - **beware: this will delete files**: ``` # Delete the files from the repository git clean -f ``` * To remove directories, run `git clean -f -d` or `git clean -fd` * To remove ignored files, run `git clean -f -X` or `git clean -fX` * To remove ignored and non-ignored files, run `git clean -f -x` or `git clean -fx` **Note** the case difference on the `X` for the two latter commands. If `clean.requireForce` is set to "true" (the default) in your configuration, one needs to specify `-f` otherwise nothing will actually happen. Again see the [`git-clean`](http://git-scm.com/docs/git-clean) docs for more information. --- > > ### Options > > > **`-f`, `--force`** > > > If the Git configuration variable clean.requireForce is not set to > false, git clean will refuse to run unless given `-f`, `-n` or `-i`. > > > **`-x`** > > > Don’t use the standard ignore rules read from .gitignore (per > directory) and `$GIT_DIR/info/exclude`, but do still use the ignore > rules given with `-e` options. This allows removing all untracked files, > including build products. This can be used (possibly in conjunction > with git reset) to create a pristine working directory to test a clean > build. > > > **`-X`** > > > Remove only files ignored by Git. This may be useful to rebuild > everything from scratch, but keep manually created files. > > > **`-n`, `--dry-run`** > > > Don’t actually remove anything, just show what would be done. > > > **`-d`** > > > Remove untracked directories in addition to untracked files. If an > untracked directory is managed by a different Git repository, it is > not removed by default. Use `-f` option twice if you really want to > remove such a directory. > > >
61,217
<p>This question is a follow up to my <a href="https://stackoverflow.com/questions/56279/export-aspx-to-html">previous question</a> about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object:</p> <pre><code>WebClient ww = new WebClient(); ww.DownloadString("Login.aspx?UserName=&amp;Password="); string html = ww.DownloadString("Internal.aspx"); </code></pre> <p>But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be?</p>
[ { "answer_id": 61221, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<p>Well does opening the page in a brower with \"Login.aspx?UserName=&amp;Password=\" normaly work?<br>\nSome pages may not allow login using data provided in the url, and that it must be entered in the login form on the page and then submitted.</p>\n" }, { "answer_id": 61226, "author": "Lea Cohen", "author_id": 278, "author_profile": "https://Stackoverflow.com/users/278", "pm_score": 0, "selected": false, "text": "<p>@Fire Lancer: I asked myself that same question during my tests, so I checked, and it does work from a browser.</p>\n" }, { "answer_id": 61231, "author": "NakedBrunch", "author_id": 3742, "author_profile": "https://Stackoverflow.com/users/3742", "pm_score": 2, "selected": false, "text": "<p>Try setting the credentials property of the WebClient object</p>\n\n<pre><code>WebClient ww = new WebClient();\nww.Credentials = CredentialCache.DefaultCredentials;\nww.DownloadString(\"Login.aspx?UserName=&amp;Password=\");\nstring html = ww.DownloadString(\"Internal.aspx\");\n</code></pre>\n" }, { "answer_id": 61599, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<p>The only other reason I can think of then is that the web page is intentionally blocking it from loggin in. If you have access to the code, take a look at the loggin system used to see if theres anything designed to block such logins.</p>\n" }, { "answer_id": 66374, "author": "Lea Cohen", "author_id": 278, "author_profile": "https://Stackoverflow.com/users/278", "pm_score": 0, "selected": false, "text": "<p>As the aspx page I was trying to get was in my own projct, I could use the Server.Execute method. More details in <a href=\"https://stackoverflow.com/questions/56279/export-aspx-to-html#66312\">my answer</a> to my original question</p>\n" }, { "answer_id": 66448, "author": "Scott Gowell", "author_id": 6943, "author_profile": "https://Stackoverflow.com/users/6943", "pm_score": 2, "selected": true, "text": "<p>Just pass valid login parameters to a given URI. Should help you out. </p>\n\n<p><strong>If you don't have login information you shouldn't be trying to circumvent it.</strong></p>\n\n<pre>public static string HttpPost( string URI, string Parameters )\n {\n System.Net.WebRequest req = System.Net.WebRequest.Create( URI );\n req.ContentType = \"application/x-www-form-urlencoded\";\n req.Method = \"POST\";\n byte[] bytes = System.Text.Encoding.ASCII.GetBytes( Parameters );\n req.ContentLength = bytes.Length;\n System.IO.Stream os = req.GetRequestStream();\n os.Write( bytes, 0, bytes.Length );\n os.Close();\n System.Net.WebResponse resp = req.GetResponse();\n if ( resp == null ) return null;\n System.IO.StreamReader sr = new System.IO.StreamReader( resp.GetResponseStream() );\n return sr.ReadToEnd().Trim();\n }\n</pre>\n" }, { "answer_id": 125253, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 0, "selected": false, "text": "<p>Use Firefox with the <a href=\"http://livehttpheaders.mozdev.org/\" rel=\"nofollow noreferrer\">LiveHttpHeaders</a> plugin.<br>\nThis will allow you to login via an actual browser and see EXACTLY what is being sent to the server. My first question would be to verify that it isn't expecting a POST from the form. The example URL you are loading is sending the info via a querystring GET. </p>\n" }, { "answer_id": 125263, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://www.fiddler2.com\" rel=\"nofollow noreferrer\">Fiddler</a> to see the HTTP requests and responses that happen when you do it manually through the browser.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278/" ]
This question is a follow up to my [previous question](https://stackoverflow.com/questions/56279/export-aspx-to-html) about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object: ``` WebClient ww = new WebClient(); ww.DownloadString("Login.aspx?UserName=&Password="); string html = ww.DownloadString("Internal.aspx"); ``` But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be?
Just pass valid login parameters to a given URI. Should help you out. **If you don't have login information you shouldn't be trying to circumvent it.** ``` public static string HttpPost( string URI, string Parameters ) { System.Net.WebRequest req = System.Net.WebRequest.Create( URI ); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes( Parameters ); req.ContentLength = bytes.Length; System.IO.Stream os = req.GetRequestStream(); os.Write( bytes, 0, bytes.Length ); os.Close(); System.Net.WebResponse resp = req.GetResponse(); if ( resp == null ) return null; System.IO.StreamReader sr = new System.IO.StreamReader( resp.GetResponseStream() ); return sr.ReadToEnd().Trim(); } ```
61,219
<p>I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...).</p> <p>He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.:</p> <pre><code>Debug.Assert(i &gt; 3, "i &gt; 3", "This means I got a bad parameter"); </code></pre> <p>Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i &lt;= 3 must never happen because of the flobittyjam widgitification process".</p> <p>So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things.</p> <p>But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this:</p> <pre><code>Debug.Assert(i &gt; 3, "i must be greater than 3 because of the flibbity widgit status"); if (i &lt;= 3) { throw new ArgumentOutOfRangeException("i", "i must be &gt; 3 because... i=" + i.ToString()); } </code></pre> <p>What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation...</p> <pre><code>double interestAmount = loan.GetInterest(); Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc"); </code></pre> <p>...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?</p>
[ { "answer_id": 61223, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>IMO it's a loss of development time only. Properly implemented exception gives you a clear picture of what happened. I saw <em>too much</em> applications showing obscure \"Assertion failed: i &lt; 10\" errors. I see assertion as a temporary solution. In my opinion no assertions should be in a final version of a program. In my practice I used assertions for quick and dirty checks. Final version of the code should take erroneous situation into account and behave accordingly. If something bad happens you have 2 choices: handle it or leave it. Function should throw an exception with meaningful description if wrong parameters passed in. I see no points in duplication of validation logic.</p>\n" }, { "answer_id": 61225, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "<p>Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the <code>ArgumentOutOfRangeException</code> thrown as necessary.</p>\n\n<p>Assertions are for testing for \"impossible\" situations, i.e., things that you (in your program logic) <em>assume</em> are true. The assertions are there to tell you if these assumptions are broken for any reason.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 61237, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 2, "selected": false, "text": "<p>I use explicit checks that throw exceptions on <em>public</em> and <em>protected</em> methods and assertions on private methods.</p>\n\n<p>Usually, the explicit checks guard the private methods from seeing incorrect values anyway. So really, the assert is checking for a condition that should be impossible. If an assert does fire, it tells me the there is a defect in the validation logic contained within one of the public routines on the class.</p>\n" }, { "answer_id": 61266, "author": "hwiechers", "author_id": 5883, "author_profile": "https://Stackoverflow.com/users/5883", "pm_score": 4, "selected": false, "text": "<p>There is a communication aspect to asserts vs exception throwing.</p>\n\n<p>Let's say we have a User class with a Name property and a ToString method.</p>\n\n<p>If ToString is implemented like this:</p>\n\n<pre><code>public string ToString()\n{\n Debug.Assert(Name != null);\n return Name;\n}\n</code></pre>\n\n<p>It says that Name should never null and there is a bug in the User class if it is.</p>\n\n<p>If ToString is implement like this:</p>\n\n<pre><code>public string ToString()\n{\n if ( Name == null )\n {\n throw new InvalidOperationException(\"Name is null\");\n }\n\n return Name;\n}\n</code></pre>\n\n<p>It says that the caller is using ToString incorrectly if Name is null and should check that before calling.</p>\n\n<p>The implementation with both</p>\n\n<pre><code>public string ToString()\n{\n Debug.Assert(Name != null);\n if ( Name == null )\n {\n throw new InvalidOperationException(\"Name is null\");\n }\n\n return Name;\n}\n</code></pre>\n\n<p>says that if Name is null there bug in the User class, but we want to handle it anyway. (The user doesn't need to check Name before calling.) I think this is the kind of safety Robbins was recommending.</p>\n" }, { "answer_id": 61678, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 2, "selected": false, "text": "<p>An exception can be caught and swallowed making the error invisible to testing. That can't happen with Debug.Assert.</p>\n<p>No one should ever have a catch handler that catches all exceptions, but people do it anyway, and sometimes it is unavoidable. If your code is invoked from COM, the interop layer catches all exceptions and turns them into COM error codes, meaning you won't see your unhandled exceptions. Asserts don't suffer from this.</p>\n<p>Also when the exception would be unhandled, a still better practice is to take a mini-dump. One area where VB is more powerful than C# is that you can use an exception filter to snap a mini-dump when the exception is in flight, and leave the rest of the exception handling unchanged. <a href=\"http://blogs.msdn.com/greggm/archive/2008/04/21/exception-filter-inject.aspx\" rel=\"nofollow noreferrer\">Gregg Miskelly's blog post on exception filter inject</a> provides a useful way to do this from c#.</p>\n<p>One other note on assets ... they inteact poorly with Unit testing the error conditions in your code. It is worthwhile to have a wrapper to turn off the assert for your unit tests.</p>\n" }, { "answer_id": 2033826, "author": "Luca", "author_id": 161554, "author_profile": "https://Stackoverflow.com/users/161554", "pm_score": 0, "selected": false, "text": "<p>Here is by 2 cents.</p>\n\n<p>I think that the best way is to use both assertions and exceptions. The main differences between the two methods, imho, if that Assert statements can be removed easily from the application text (defines, conditional attributes...), while Exception thrown are dependent (tipically) by a conditional code which is harder to remove (multine section with preprocessor conditionals).</p>\n\n<p>Every application exception shall be handled correctly, while assertions shall be satisfied only during the algorithm developement and testing.</p>\n\n<p>If you pass an null object reference as routine parameter, and you use this value, you get a null pointer exception. Indeed: why you should write an assertion? It's a waste of time in this case.\nBut what about private class members used in class routines? When these value are set somewhere, is better to check with an assertion if a null value is set. That's only because when you use the member, you get a null pointer exception but you don't know how the value was set. This cause a restart of the program breaking on all entry point use to set the private member.</p>\n\n<p>Exception are more usefull, but they can be (imho) very heavy to manage and there is the possibility to use too much exceptions. And they requires additional check, maybe undesired to optimize the code.\nPersonally I use exceptions only whenever the code requires a deep catch control (catch statements are very low in the call stack) or whenever the function parameters are not hardcoded in the code.</p>\n" }, { "answer_id": 2033938, "author": "Mark Simpson", "author_id": 83891, "author_profile": "https://Stackoverflow.com/users/83891", "pm_score": 3, "selected": false, "text": "<p>I've thought about this long and hard when it comes to providing guidance on debug vs. assert with respect to testing concerns.</p>\n\n<p>You should be able to test your class with erroneous input, bad state, invalid order of operations and any other conceivable error condition and an assert should <strong>never</strong> trip. Each assert is checking something should <strong>always</strong> be true regardless of the inputs or computations performed. </p>\n\n<p>Good rules of thumb I've arrived at:</p>\n\n<ol>\n<li><p>Asserts are not a replacement for robust code that functions correctly independent of configuration. They are complementary.</p></li>\n<li><p>Asserts should never be tripped during a unit test run, even when feeding in invalid values or testing error conditions. The code should handle these conditions without an assert occurring.</p></li>\n<li><p>If an assert trips (either in a unit test or during testing), the class is bugged. </p></li>\n</ol>\n\n<p>For all other errors -- typically down to environment (network connection lost) or misuse (caller passed a null value) -- it's much nicer and more understandable to use hard checks &amp; exceptions. If an exception occurs, the caller knows it's likely their fault. If an assert occurs, the caller knows it's likely a bug in the code where the assert is located.</p>\n\n<p>Regarding duplication: I agree. I don't see why you would replicate the validation with a Debug.Assert AND an exception check. Not only does it add some noise to the code and muddy the waters regarding who is at fault, but it a form of repetition. </p>\n" }, { "answer_id": 5964259, "author": "Tim Abell", "author_id": 10245, "author_profile": "https://Stackoverflow.com/users/10245", "pm_score": 1, "selected": false, "text": "<p>Example of a good use of Assert:</p>\n\n<pre><code>Debug.Assert(flibbles.count() &lt; 1000000, \"too many flibbles\"); // indicate something is awry\nlog.warning(\"flibble count reached \" + flibbles.count()); // log in production as early warning\n</code></pre>\n\n<p>I personally think that Assert should <strong>only</strong> be used when you know something is outside <em>desirable</em> limits, but you can be sure it's reasonably safe to continue. In all other circumstances (feel free point out circumstances I haven't thought of) use exceptions to fail hard and fast.</p>\n\n<p>The key tradeoff for me is whether you want to bring down a live/production system with an Exception to avoid corruption and make troubleshooting easier, or whether you have encountered a situation that should never be allowed to continue unnoticed in test/debug versions but could be allowed to continue in production (logging a warning of course).</p>\n\n<p>cf. <a href=\"http://c2.com/cgi/wiki?FailFast\" rel=\"nofollow noreferrer\">http://c2.com/cgi/wiki?FailFast</a>\ncopied and modified from java question: <a href=\"https://stackoverflow.com/questions/1276308/exception-vs-assertion/5963988#5963988\">Exception Vs Assertion</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004/" ]
I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...). He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.: ``` Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter"); ``` Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i <= 3 must never happen because of the flobittyjam widgitification process". So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things. But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this: ``` Debug.Assert(i > 3, "i must be greater than 3 because of the flibbity widgit status"); if (i <= 3) { throw new ArgumentOutOfRangeException("i", "i must be > 3 because... i=" + i.ToString()); } ``` What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation... ``` double interestAmount = loan.GetInterest(); Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc"); ``` ...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?
Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the `ArgumentOutOfRangeException` thrown as necessary. Assertions are for testing for "impossible" situations, i.e., things that you (in your program logic) *assume* are true. The assertions are there to tell you if these assumptions are broken for any reason. Hope this helps!
61,227
<p>If I have: </p> <pre><code>signed char * p; </code></pre> <p>and I do a comparison:</p> <pre><code>if ( *p == 0xFF ) break; </code></pre> <p>it will never catch 0XFF, but if I replace it with -1 it will:</p> <pre><code>if ( *p == (signed char)0xFF ) break; </code></pre> <p>How can this happen? Is it something with the sign flag? I though that <code>0xFF == -1 == 255</code>.</p>
[ { "answer_id": 61229, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>The value <code>0xFF</code> is a signed int value. C will promote the <code>*p</code> to an <code>int</code> when doing the comparison, so the first if statement is equivalent to:</p>\n\n<pre><code>if( -1 == 255 ) break;\n</code></pre>\n\n<p>which is of course false. By using <code>(signed char)0xFF</code> the statement is equivalent to:</p>\n\n<pre><code>if( -1 == -1 ) break;\n</code></pre>\n\n<p>which works as you expect. The key point here is that the comparison is done with <code>int</code> types instead of <code>signed char</code> types.</p>\n" }, { "answer_id": 61230, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 2, "selected": false, "text": "<p>It casts to an int for the first comparison since 0xFF is still considered an int, meaning your char is -128 to 127, but the 0xFF is still 255.</p>\n\n<p>In the second case your telling it that 0xFF is really an signed char, not an int</p>\n" }, { "answer_id": 61232, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 2, "selected": false, "text": "<p>Integer literals have signed int type. Since 0xFF is a signed int, the compiler converts *p to a signed int and then does the comparison.</p>\n\n<p>When *p is -1, which is then converted from a signed char to a signed int, it is still -1 which has a representation of 0xFFFFFFFF, which is not equal to 0xFF.</p>\n" }, { "answer_id": 61234, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 1, "selected": false, "text": "<p>0xff will be seen as an integer constant, with the value of 255. You should always pay attention to these kind of comparison between different types. If you want to be sure that the compiler will generate the right code, you should use the typecast:</p>\n\n<pre>\nif( *p == (signed char)0xFF ) break;\n</pre>\n\n<p>Anyway, <b>beware</b> that the next statement will <b>not</b> work the same way:</p>\n\n<pre>\nif( (int)*p == 0xFF ) break;\n</pre>\n\n<p>Also, maybe it would be a better idea to avoid signed chars, or, it you must use signed chars, to compare them with signed values such as -1 in this case:</p>\n\n<pre>\nif( *p == -1 ) break;\n</pre>\n\n<p>0xff==-1 only if those values would be assigned to some char (or unsigned char) variables:</p>\n\n<pre>\nchar a=0xff;\nchar b=-1;\nif(a==b) break;\n</pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ]
If I have: ``` signed char * p; ``` and I do a comparison: ``` if ( *p == 0xFF ) break; ``` it will never catch 0XFF, but if I replace it with -1 it will: ``` if ( *p == (signed char)0xFF ) break; ``` How can this happen? Is it something with the sign flag? I though that `0xFF == -1 == 255`.
The value `0xFF` is a signed int value. C will promote the `*p` to an `int` when doing the comparison, so the first if statement is equivalent to: ``` if( -1 == 255 ) break; ``` which is of course false. By using `(signed char)0xFF` the statement is equivalent to: ``` if( -1 == -1 ) break; ``` which works as you expect. The key point here is that the comparison is done with `int` types instead of `signed char` types.
61,233
<p>What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:</p> <pre><code>INSERT INTO some_table (column1, column2, column3) SELECT Rows.n.value('(@column1)[1]', 'varchar(20)'), Rows.n.value('(@column2)[1]', 'nvarchar(100)'), Rows.n.value('(@column3)[1]', 'int'), FROM @xml.nodes('//Rows') Rows(n) </code></pre> <p>However I find that this is getting very slow for even moderate size xml data.</p>
[ { "answer_id": 61246, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what is the best method. I used OPENXML construction:</p>\n\n<pre><code>INSERT INTO Test\nSELECT Id, Data \nFROM OPENXML (@XmlDocument, '/Root/blah',2)\nWITH (Id int '@ID',\n Data varchar(10) '@DATA')\n</code></pre>\n\n<p>To speed it up, you can create XML indices. You can set index specifically for <strong>value</strong> function performance optimization. Also you can use typed xml columns, which performs better.</p>\n" }, { "answer_id": 631578, "author": "DannykPowell", "author_id": 67617, "author_profile": "https://Stackoverflow.com/users/67617", "pm_score": 1, "selected": false, "text": "<p>This isn't an answer, more an addition to this question - I have just come across the same problem and I can give figures as edg asks for in the comment.</p>\n\n<p>My test has xml which results in 244 records being inserted - so 244 nodes.</p>\n\n<p>The code that I am rewriting takes on average 0.4 seconds to run.(10 tests run, spread from .56 secs to .344 secs) Performance is not the main reason the code is being rewritten, but the new code needs to perform as well or better. This old code loops the xml nodes, calling a sp to insert once per loop</p>\n\n<p>The new code is pretty much just a single sp; pass the xml in; shred it.</p>\n\n<p>Tests with the new code switched in show the new sp takes on average 3.7 seconds - almost 10 times slower.</p>\n\n<p>My query is in the form posted in this question; </p>\n\n<pre><code>INSERT INTO some_table (column1, column2, column3)\nSELECT\nRows.n.value('(@column1)[1]', 'varchar(20)'),\nRows.n.value('(@column2)[1]', 'nvarchar(100)'),\nRows.n.value('(@column3)[1]', 'int'),\nFROM @xml.nodes('//Rows') Rows(n)\n</code></pre>\n\n<p>The execution plan appears to show that for each column, sql server is doing a separate \"Table Valued Function [XMLReader]\" returning all 244 rows, joining all back up with Nested Loops(Inner Join). So In my case where I am shredding from/ inserting into about 30 columns, this appears to happen separately 30 times.</p>\n\n<p>I am going to have to dump this code, I don't think any optimisation is going to get over this method being inherently slow. I am going to try the sp_xml_preparedocument/OPENXML method and see if the performance is better for that. If anyone comes across this question from a web search (as I did) I would highly advise you to do some performance testing before using this type of shredding in SQL Server</p>\n" }, { "answer_id": 631621, "author": "si618", "author_id": 44540, "author_profile": "https://Stackoverflow.com/users/44540", "pm_score": 0, "selected": false, "text": "<p>There is an <a href=\"http://msdn.microsoft.com/en-us/library/ms171769.aspx\" rel=\"nofollow noreferrer\">XML Bulk load</a> COM object (<a href=\"http://msdn.microsoft.com/en-us/library/ms171878.aspx\" rel=\"nofollow noreferrer\">.NET Example</a>) </p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ms171721.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>You can insert XML data into a SQL\n Server database by using an INSERT\n statement and the OPENXML function;\n however, the Bulk Load utility\n provides better performance when you\n need to insert large amounts of XML\n data.</p>\n</blockquote>\n" }, { "answer_id": 631854, "author": "Eddie Groves", "author_id": 5769, "author_profile": "https://Stackoverflow.com/users/5769", "pm_score": 0, "selected": false, "text": "<p>My current solution for large XML sets (> 500 nodes) is to use SQL Bulk Copy (System.Data.SqlClient.SqlBulkCopy) by using a DataSet to load the XML into memory and then pass the table to SqlBulkCopy (defining a XML schema helps).</p>\n\n<p>Obviously there a pitfalls such as needlessly using a DataSet and loading the whole document into memory first. I would like to go further in the future and implement my own IDataReader to bypass the DataSet method but currently the DataSet is \"good enough\" for the job. </p>\n\n<p>Basically I never found a solution to my original question regarding the slow performance for that type of XML shredding. It could be slow due to the typed xml queries being inherently slow or something to do with transactions and the the SQL Server log. I guess the typed xml functions were never designed for operating on non-trivial node sizes.</p>\n\n<p>XML Bulk Load: I tried this and it <em>was</em> fast but I had trouble getting the COM dll to work under 64bit environments and I generally try to avoid COM dlls that no longer appear to be supported.</p>\n\n<p>sp_xml_preparedocument/OPENXML: I never went down this road so would be interested to see how it performs.</p>\n" }, { "answer_id": 4671129, "author": "Dan", "author_id": 572994, "author_profile": "https://Stackoverflow.com/users/572994", "pm_score": 7, "selected": true, "text": "<p>Stumbled across this question whilst having a very similar problem, I'd been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up.</p>\n\n<p>However, after a little more research I found that having typed the XML using a schema and created an XML Index (I'd bulk inserted into a table) the same query completed in ~ 0.04ms.</p>\n\n<p>How's that for a performance improvement!</p>\n\n<p>Code to create a schema:</p>\n\n<pre><code>IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema')\nDROP XML SCHEMA COLLECTION [MyXmlSchema]\nGO\n\nDECLARE @MySchema XML\nSET @MySchema = \n(\n SELECT * FROM OPENROWSET\n (\n BULK 'C:\\Path\\To\\Schema\\MySchema.xsd', SINGLE_CLOB \n ) AS xmlData\n)\n\nCREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema \nGO\n</code></pre>\n\n<p>Code to create the table with a typed XML column:</p>\n\n<pre><code>CREATE TABLE [dbo].[XmlFiles] (\n [Id] [uniqueidentifier] NOT NULL,\n\n -- Data from CV element \n [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL,\n\nCONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED \n(\n [Id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n</code></pre>\n\n<p>Code to create Index</p>\n\n<pre><code>CREATE PRIMARY XML INDEX PXML_Data\nON [dbo].[XmlFiles] (Data)\n</code></pre>\n\n<p>There are a few things to bear in mind though. SQL Server's implementation of Schema doesn't support xsd:include. This means that if you have a schema which references other schema, you'll have to copy all of these into a single schema and add that.</p>\n\n<p>Also I would get an error:</p>\n\n<pre><code>XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'.\n</code></pre>\n\n<p>if I tried to navigate above the node I had selected with the nodes function. E.g.</p>\n\n<pre><code>SELECT\n ,C.value('CVElementId[1]', 'INT') AS [CVElementId]\n ,C.value('../SequenceNumber[1]', 'INT') AS [Level]\nFROM \n [dbo].[XmlFiles]\nCROSS APPLY\n [Data].nodes('/CVSet/Level/CVElement') AS T(C)\n</code></pre>\n\n<p>Found that the best way to handle this was to use the OUTER APPLY to in effect perform an \"outer join\" on the XML.</p>\n\n<pre><code>SELECT\n ,C.value('CVElementId[1]', 'INT') AS [CVElementId]\n ,B.value('SequenceNumber[1]', 'INT') AS [Level]\nFROM \n [dbo].[XmlFiles]\nCROSS APPLY\n [Data].nodes('/CVSet/Level') AS T(B)\nOUTER APPLY\n B.nodes ('CVElement') AS S(C)\n</code></pre>\n\n<p>Hope that that helps someone as that's pretty much been my day.</p>\n" }, { "answer_id": 6405333, "author": "Tao", "author_id": 74296, "author_profile": "https://Stackoverflow.com/users/74296", "pm_score": 2, "selected": false, "text": "<p>I wouldn't claim this is the \"best\" solution, but I've written a generic SQL CLR procedure for this exact purpose - it takes a \"tabular\" Xml structure (such as that returned by FOR XML RAW) and outputs a resultset.</p>\n\n<p>It does not require any customization / knowledge of the structure of the \"table\" in the Xml, and turns out to be extremely fast / efficient (although this wasn't a design goal). I just shredded a 25MB (untyped) xml variable in under 20 seconds, returning 25,000 rows of a pretty wide table.</p>\n\n<p>Hope this helps someone:\n<a href=\"http://architectshack.com/ClrXmlShredder.ashx\" rel=\"nofollow\">http://architectshack.com/ClrXmlShredder.ashx</a></p>\n" }, { "answer_id": 9794641, "author": "edhubbell", "author_id": 1054938, "author_profile": "https://Stackoverflow.com/users/1054938", "pm_score": 2, "selected": false, "text": "<p>We had a similar issue here. Our DBA (SP, you the man) took a look at my code, made a little tweak to the syntax, and we got the speed we had been expecting. It was unusual because my select from XML was plenty fast, but the insert was way slow. So try this syntax instead:</p>\n\n<pre><code>INSERT INTO some_table (column1, column2, column3)\n SELECT \n Rows.n.value(N'(@column1/text())[1]', 'varchar(20)'), \n Rows.n.value(N'(@column2/text())[1]', 'nvarchar(100)'), \n Rows.n.value(N'(@column3/text())[1]', 'int')\n FROM @xml.nodes('//Rows') Rows(n) \n</code></pre>\n\n<p>So specifying the text() parameter really seems to make a difference in performance. Took our insert of 2K rows from 'I must have written that wrong - let me stop it' to about 3 seconds. Which was 2x faster than the raw insert statements we had been running through the connection.</p>\n" }, { "answer_id": 18264248, "author": "jccprj", "author_id": 2687849, "author_profile": "https://Stackoverflow.com/users/2687849", "pm_score": 3, "selected": false, "text": "<p>in my case i'm running SQL 2005 SP2 (9.0).</p>\n\n<p>The only thing that helped was adding OPTION ( OPTIMIZE FOR ( @your_xml_var = NULL ) ).\nExplanation is on the link below.</p>\n\n<p>Example:</p>\n\n<pre><code>INSERT INTO @tbl (Tbl_ID, Name, Value, ParamData)\nSELECT 1,\n tbl.cols.value('name[1]', 'nvarchar(255)'),\n tbl.cols.value('value[1]', 'nvarchar(255)'),\n tbl.cols.query('./paramdata[1]')\nFROM @xml.nodes('//root') as tbl(cols) OPTION ( OPTIMIZE FOR ( @xml = NULL ) )\n</code></pre>\n\n<p><a href=\"https://connect.microsoft.com/SQLServer/feedback/details/562092/an-insert-statement-using-xml-nodes-is-very-very-very-slow-in-sql2008-sp1\" rel=\"noreferrer\">https://connect.microsoft.com/SQLServer/feedback/details/562092/an-insert-statement-using-xml-nodes-is-very-very-very-slow-in-sql2008-sp1</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so: ``` INSERT INTO some_table (column1, column2, column3) SELECT Rows.n.value('(@column1)[1]', 'varchar(20)'), Rows.n.value('(@column2)[1]', 'nvarchar(100)'), Rows.n.value('(@column3)[1]', 'int'), FROM @xml.nodes('//Rows') Rows(n) ``` However I find that this is getting very slow for even moderate size xml data.
Stumbled across this question whilst having a very similar problem, I'd been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up. However, after a little more research I found that having typed the XML using a schema and created an XML Index (I'd bulk inserted into a table) the same query completed in ~ 0.04ms. How's that for a performance improvement! Code to create a schema: ``` IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema') DROP XML SCHEMA COLLECTION [MyXmlSchema] GO DECLARE @MySchema XML SET @MySchema = ( SELECT * FROM OPENROWSET ( BULK 'C:\Path\To\Schema\MySchema.xsd', SINGLE_CLOB ) AS xmlData ) CREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema GO ``` Code to create the table with a typed XML column: ``` CREATE TABLE [dbo].[XmlFiles] ( [Id] [uniqueidentifier] NOT NULL, -- Data from CV element [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL, CONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ``` Code to create Index ``` CREATE PRIMARY XML INDEX PXML_Data ON [dbo].[XmlFiles] (Data) ``` There are a few things to bear in mind though. SQL Server's implementation of Schema doesn't support xsd:include. This means that if you have a schema which references other schema, you'll have to copy all of these into a single schema and add that. Also I would get an error: ``` XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'. ``` if I tried to navigate above the node I had selected with the nodes function. E.g. ``` SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,C.value('../SequenceNumber[1]', 'INT') AS [Level] FROM [dbo].[XmlFiles] CROSS APPLY [Data].nodes('/CVSet/Level/CVElement') AS T(C) ``` Found that the best way to handle this was to use the OUTER APPLY to in effect perform an "outer join" on the XML. ``` SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,B.value('SequenceNumber[1]', 'INT') AS [Level] FROM [dbo].[XmlFiles] CROSS APPLY [Data].nodes('/CVSet/Level') AS T(B) OUTER APPLY B.nodes ('CVElement') AS S(C) ``` Hope that that helps someone as that's pretty much been my day.
61,256
<p>I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message:</p> <pre><code>Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat 192.168.123.254:8080 </code></pre> <p>Which roughly translates to "cant connect to 192.168.123.254:8080"</p> <p>The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used.</p> <p><strong>How do I prevent the IIS from using a proxy?</strong></p> <p>I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined.</p> <p>The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user?</p> <p>What can I do, where else i could check?</p>
[ { "answer_id": 61296, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 0, "selected": false, "text": "<p>IIS is a destination. The configuration issue is in whatever is doing the call (acting like a client). If you are using the built-in .Net communication methods you will need to make the adjustment inside of ... Wait for it ... Internet Explorer. </p>\n\n<p>Yep! That little bugger has bitten me more times than I care to remember. I used to have to switch the proxy server settings in IE 5 or 6 times a day as I switched between internal and external servers. Newer versions of IE have a much better \"don't use proxy server\" set of rules.</p>\n\n<p>-- Clarification --\nAs it seems that the user ID used by IIS is using this setting, you'll probably need to search the registry for where the proxy information is stored for each user ID and/or the default.</p>\n" }, { "answer_id": 61329, "author": "hwiechers", "author_id": 5883, "author_profile": "https://Stackoverflow.com/users/5883", "pm_score": 5, "selected": true, "text": "<p>Proxy use can be configured in the web.config.\nThe system.net/defaultProxy element will let you specify whether a proxy is used by default or provide a bypass list.</p>\n\n<p>For more info see: <a href=\"http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx\" rel=\"noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx</a></a></p>\n" }, { "answer_id": 1387843, "author": "Daniel Bowen", "author_id": 84435, "author_profile": "https://Stackoverflow.com/users/84435", "pm_score": 1, "selected": false, "text": "<p>Some group policy settings that may be relevant:</p>\n\n<p><em>Root \\ Local computer policy \\ Computer configuration \\ Administrative templates \\ Windows components \\ Internet Explorer \\ Make proxy settings per-machine</em> -- by default this is disabled, meaning individual users on the server have customised proxy settings.</p>\n\n<p><em>Root \\ Local computer policy \\ User configuration \\ Windows settings \\ Internet Explorer maintenance \\ Connection</em>. In \"Automatic Browser Configuration\" the value \"Automatically detect configuration settings\" -- you can set this off to prevent the process trying to detect proxy settings automatically.</p>\n\n<p>That said, using the defaultProxy setting as shown in hwiechers' answer would seem to be a better way of doing it, not affecting other processes or users on the machine.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6297/" ]
I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message: ``` Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat 192.168.123.254:8080 ``` Which roughly translates to "cant connect to 192.168.123.254:8080" The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used. **How do I prevent the IIS from using a proxy?** I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined. The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user? What can I do, where else i could check?
Proxy use can be configured in the web.config. The system.net/defaultProxy element will let you specify whether a proxy is used by default or provide a bypass list. For more info see: [<http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx>](http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx)
61,262
<p>Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.<br> Now you want to create a class or use a symbol which is defined in multiple namespaces, e.g. <code>System.Windows.Controls.Image</code> &amp; <code>System.Drawing.Image</code></p> <p>Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?</p> <p><em>(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)</em></p>
[ { "answer_id": 61264, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": true, "text": "<p>Use alias</p>\n<pre><code>using System.Windows.Controls;\nusing Drawing = System.Drawing;\n\n...\n\nImage img = ... //System.Windows.Controls.Image\nDrawing.Image img2 = ... //System.Drawing.Image\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive\" rel=\"nofollow noreferrer\">C# using directive</a></p>\n" }, { "answer_id": 61265, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p>This page has a very good writeup on namespaces and the using-statement:</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/Namespaces.aspx\" rel=\"noreferrer\">http://www.blackwasp.co.uk/Namespaces.aspx</a></p>\n\n<p>You want to read the part about \"Creating Aliases\" that will allow you to make an alias for one or both of the name spaces and reference them with that like this:</p>\n\n<pre><code>using ControlImage = System.Windows.Controls.Image;\nusing System.Drawing.Image;\n\nControlImage.Image myImage = new ControlImage.Image();\nmyImage.Width = 200;\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file. Now you want to create a class or use a symbol which is defined in multiple namespaces, e.g. `System.Windows.Controls.Image` & `System.Drawing.Image` Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here? *(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)*
Use alias ``` using System.Windows.Controls; using Drawing = System.Drawing; ... Image img = ... //System.Windows.Controls.Image Drawing.Image img2 = ... //System.Drawing.Image ``` [C# using directive](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive)
61,278
<p>What method do you use when you want to get performance data about specific code paths?</p>
[ { "answer_id": 61279, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": true, "text": "<p>This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.</p>\n\n<ol>\n<li>The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).</li>\n<li>It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.</li>\n<li>Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.</li>\n</ol>\n\n<hr>\n\n<p>I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DbgView</a>), including how many times the code was executed (and the average time spent of course)).</p>\n\n<pre><code>#pragma once\n#include &lt;tchar.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;sstream&gt;\n#include &lt;boost/noncopyable.hpp&gt;\n\nnamespace scope_timer {\n class time_collector : boost::noncopyable {\n __int64 total;\n LARGE_INTEGER start;\n size_t times;\n const TCHAR* name;\n\n double cpu_frequency()\n { // cache the CPU frequency, which doesn't change.\n static double ret = 0; // store as double so devision later on is floating point and not truncating\n if (ret == 0) {\n LARGE_INTEGER freq;\n QueryPerformanceFrequency(&amp;freq);\n ret = static_cast&lt;double&gt;(freq.QuadPart);\n }\n return ret;\n }\n bool in_use;\n\n public:\n time_collector(const TCHAR* n)\n : times(0)\n , name(n)\n , total(0)\n , start(LARGE_INTEGER())\n , in_use(false)\n {\n }\n\n ~time_collector()\n {\n std::basic_ostringstream&lt;TCHAR&gt; msg;\n msg &lt;&lt; _T(\"scope_timer&gt; \") &lt;&lt; name &lt;&lt; _T(\" called: \");\n\n double seconds = total / cpu_frequency();\n double average = seconds / times;\n\n msg &lt;&lt; times &lt;&lt; _T(\" times total time: \") &lt;&lt; seconds &lt;&lt; _T(\" seconds \")\n &lt;&lt; _T(\" (avg \") &lt;&lt; average &lt;&lt;_T(\")\\n\");\n OutputDebugString(msg.str().c_str());\n }\n\n void add_time(__int64 ticks)\n {\n total += ticks;\n ++times;\n in_use = false;\n }\n\n bool aquire()\n {\n if (in_use)\n return false;\n in_use = true;\n return true;\n }\n };\n\n class one_time : boost::noncopyable {\n LARGE_INTEGER start;\n time_collector* collector;\n public:\n one_time(time_collector&amp; tc)\n {\n if (tc.aquire()) {\n collector = &amp;tc;\n QueryPerformanceCounter(&amp;start);\n }\n else\n collector = 0;\n }\n\n ~one_time()\n {\n if (collector) {\n LARGE_INTEGER end;\n QueryPerformanceCounter(&amp;end);\n collector-&gt;add_time(end.QuadPart - start.QuadPart);\n }\n }\n };\n}\n\n// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)\n#define TIME_THIS_SCOPE(name) \\\n static scope_timer::time_collector st_time_collector_##name(_T(#name)); \\\n scope_timer::one_time st_one_time_##name(st_time_collector_##name)\n</code></pre>\n" }, { "answer_id": 61281, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Well, I have two code snippets. In <a href=\"http://en.wikipedia.org/wiki/Pseudocode\" rel=\"nofollow noreferrer\">pseudocode</a> they are looking like (it's a simplified version, I'm using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">QueryPerformanceFrequency</a> actually):</p>\n\n<h3>First snippet:</h3>\n\n<pre><code>Timer timer = new Timer\ntimer.Start\n</code></pre>\n\n<h3>Second snippet:</h3>\n\n<pre><code>timer.Stop\nshow elapsed time\n</code></pre>\n\n<p>A bit of hot-keys kung fu, and I can say how much time this piece of code stole from my CPU.</p>\n" }, { "answer_id": 61282, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>The article <em>Code profiler and optimizations</em> has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods.</p>\n" }, { "answer_id": 61303, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 2, "selected": false, "text": "<p>I do my profiles by creating two classes: <code>cProfile</code> and <code>cProfileManager</code>.</p>\n\n<p><code>cProfileManager</code> will hold all the data that resulted from <code>cProfile</code>.</p>\n\n<p><code>cProfile</code> with have the following requirements:</p>\n\n<ul>\n<li><code>cProfile</code> has a constructor which initializes the current time.</li>\n<li><code>cProfile</code> has a deconstructor which sends the total time the class was alive to <code>cProfileManager</code></li>\n</ul>\n\n<p>To use these profile classes, I first make an instance of <code>cProfileManager</code>. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a <code>cProfile</code> instance. When the code block ends, <code>cProfile</code> will send the time it took for the block of code to finish to <code>cProfileManager</code>.</p>\n\n<p><strong>Example Code</strong>\nHere's an example of the code (simplified):</p>\n\n<pre><code>class cProfile\n{\n cProfile()\n {\n TimeStart = GetTime();\n };\n\n ~cProfile()\n {\n ProfileManager-&gt;AddProfile (GetTime() - TimeStart);\n }\n\n float TimeStart;\n}\n</code></pre>\n\n<p>To use <code>cProfile</code>, I would do something like this:</p>\n\n<pre><code>int main()\n{\n printf(\"Start test\");\n {\n cProfile Profile;\n Calculate();\n }\n ProfileManager-&gt;OutputData();\n}\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>void foobar()\n{\n cProfile ProfileFoobar;\n\n foo();\n {\n cProfile ProfileBarCheck;\n while (bar())\n {\n cProfile ProfileSpam;\n spam();\n }\n }\n}\n</code></pre>\n\n<p><strong>Technical Note</strong></p>\n\n<p>This code is actually an abuse of the way scoping, constructors and deconstructors work in <a href=\"http://en.wikipedia.org/wiki/C_%28programming_language%29\" rel=\"nofollow noreferrer\">C++</a>. <code>cProfile</code> exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, <code>cProfile</code> records the result.</p>\n\n<p><strong>Additional Enhancements</strong></p>\n\n<ul>\n<li><p>You can add a string parameter to the constructor so you can do something like this:\ncProfile Profile(\"Profile for complicated calculation\");</p></li>\n<li><p>You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).</p>\n\n<p>Example:</p>\n\n<p>#define START_PROFILE cProfile Profile(); {\n#define END_PROFILE }</p></li>\n<li><p><code>cProfileManager</code> can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.</p></li>\n<li><p>Don't forget to add a check to skip profiling if you are in debug mode.</p></li>\n</ul>\n" }, { "answer_id": 231590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have a quick-and-dirty profiling class that can be used in profiling in even the most tight inner loops. The emphasis is on extreme light weight and simple code. The class allocates a two-dimensional array of fixed size. I then add \"checkpoint\" calls all over the place. When checkpoint N is reached immediately after checkpoint M, I add the time elapsed (in microseconds) to the array item [M,N]. Since this is designed to profile tight loops, I also have \"start of iteration\" call that resets the the \"last checkpoint\" variable. At the end of test, the <code>dumpResults()</code> call produces the list of all pairs of checkpoints that followed each other, together with total time accounted for and unaccounted for.</p>\n" }, { "answer_id": 231614, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "<p>Note, the following is all written specifically for Windows.</p>\n\n<p>I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference. My timer class doesn't dump the elapsed time when the Timer object falls out of scope. Instead, it accumulates the elapsed times in to an collection. I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer's constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min. I also added a Clear() static member function which clears the collection &amp; lets you start over again.</p>\n\n<p><strong>How to use the Timer class (psudocode):</strong></p>\n\n<pre><code>int CInsertBuffer::Read(char* pBuf)\n{\n // TIMER NOTES: Avg Execution Time = ~1 ms\n Timer timer(\"BufferRead\");\n : :\n return -1;\n}\n</code></pre>\n\n<p><strong>Sample output :</strong></p>\n\n<pre><code>Timer Precision = 418.0095 ps\n\n=== Item Trials Ttl Time Avg Time Mean Time StdDev ===\n AddTrade 500 7 ms 14 us 12 us 24 us\n BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s\n BufferWrite 516 511 us 991 ns 482 ns 11 us\n ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s\n ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s\n Insert 515 4.26 s 8 ms 5 ms 27 ms\n recv 101 18.54 s 0.18 s 2603 ns 1.63 s\n</code></pre>\n\n<p><strong>file Timer.inl :</strong></p>\n\n<pre><code>#include &lt;map&gt;\n#include \"x:\\utils\\stlext\\stringext.h\"\n#include &lt;iterator&gt;\n#include &lt;set&gt;\n#include &lt;vector&gt;\n#include &lt;numeric&gt;\n#include \"x:\\utils\\stlext\\algorithmext.h\"\n#include &lt;math.h&gt;\n\n class Timer\n {\n public:\n Timer(const char* name)\n {\n label = std::safe_string(name);\n QueryPerformanceCounter(&amp;startTime);\n }\n\n virtual ~Timer()\n {\n QueryPerformanceCounter(&amp;stopTime);\n __int64 clocks = stopTime.QuadPart-startTime.QuadPart;\n double elapsed = (double)clocks/(double)TimerFreq();\n TimeMap().insert(std::make_pair(label,elapsed));\n };\n\n static std::string Dump(bool ClipboardAlso=true)\n {\n static const std::string loc = \"Timer::Dump\";\n\n if( TimeMap().empty() )\n {\n return \"No trials\\r\\n\";\n }\n\n std::string ret = std::formatstr(\"\\r\\n\\r\\nTimer Precision = %s\\r\\n\\r\\n\", format_elapsed(1.0/(double)TimerFreq()).c_str());\n\n // get a list of keys\n typedef std::set&lt;std::string&gt; keyset;\n keyset keys;\n std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());\n\n size_t maxrows = 0;\n\n typedef std::vector&lt;std::string&gt; strings;\n strings lines;\n\n static const size_t tabWidth = 9;\n\n std::string head = std::formatstr(\"=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===\", tabWidth*2, tabWidth*2, \"Item\", tabWidth, tabWidth, \"Trials\", tabWidth, tabWidth, \"Ttl Time\", tabWidth, tabWidth, \"Avg Time\", tabWidth, tabWidth, \"Mean Time\", tabWidth, tabWidth, \"StdDev\");\n ret += std::formatstr(\"\\r\\n%s\\r\\n\", head.c_str());\n if( ClipboardAlso ) \n lines.push_back(\"Item\\tTrials\\tTtl Time\\tAvg Time\\tMean Time\\tStdDev\\r\\n\");\n // dump the values for each key\n {for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )\n {\n time_type ttl = 0;\n ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));\n size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));\n if( num &gt; maxrows ) \n maxrows = num;\n time_type avg = ttl / num;\n\n // compute mean\n std::vector&lt;time_type&gt; sortedTimes;\n std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));\n std::sort(sortedTimes.begin(), sortedTimes.end());\n size_t mid = (size_t)floor((double)num/2.0);\n double mean = ( num &gt; 1 &amp;&amp; (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];\n // compute variance\n double sum = 0.0;\n if( num &gt; 1 )\n {\n for( std::vector&lt;time_type&gt;::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )\n sum += pow(*timeIt-mean,2.0);\n }\n // compute std dev\n double stddev = num &gt; 1 ? sqrt(sum/((double)num-1.0)) : 0.0;\n\n ret += std::formatstr(\" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\\r\\n\", tabWidth*2, tabWidth*2, key-&gt;c_str(), tabWidth, tabWidth, std::formatstr(\"%d\",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str()); \n if( ClipboardAlso )\n lines.push_back(std::formatstr(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\r\\n\", key-&gt;c_str(), std::formatstr(\"%d\",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str())); \n\n }\n }\n ret += std::formatstr(\"%s\\r\\n\", std::string(head.length(),'=').c_str());\n\n if( ClipboardAlso )\n {\n // dump header row of data block\n lines.push_back(\"\");\n {\n std::string s;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n s.append(\"\\t\");\n s.append(*key);\n }\n s.append(\"\\r\\n\");\n lines.push_back(s);\n }\n\n // blow out the flat map of time values to a seperate vector of times for each key\n typedef std::map&lt;std::string, std::vector&lt;time_type&gt; &gt; nodematrix;\n nodematrix nodes;\n for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )\n nodes[time-&gt;first].push_back(time-&gt;second);\n\n // dump each data point\n for( size_t row = 0; row &lt; maxrows; ++row )\n {\n std::string rowDump;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n rowDump.append(\"\\t\");\n if( nodes[*key].size() &gt; row )\n rowDump.append(std::formatstr(\"%f\", nodes[*key][row]));\n }\n rowDump.append(\"\\r\\n\");\n lines.push_back(rowDump);\n }\n\n // dump to the clipboard\n std::string dump;\n for( strings::iterator s = lines.begin(); s != lines.end(); ++s )\n {\n dump.append(*s);\n }\n\n OpenClipboard(0);\n EmptyClipboard();\n HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);\n if( hg != 0 )\n {\n char* buf = (char*)GlobalLock(hg);\n if( buf != 0 )\n {\n std::copy(dump.begin(), dump.end(), buf);\n buf[dump.length()] = 0;\n GlobalUnlock(hg);\n SetClipboardData(CF_TEXT, hg);\n }\n }\n CloseClipboard();\n }\n\n return ret;\n }\n\n static void Reset()\n {\n TimeMap().clear();\n }\n\n static std::string format_elapsed(double d) \n {\n if( d &lt; 0.00000001 )\n {\n // show in ps with 4 digits\n return std::formatstr(\"%0.4f ps\", d * 1000000000000.0);\n }\n if( d &lt; 0.00001 )\n {\n // show in ns\n return std::formatstr(\"%0.0f ns\", d * 1000000000.0);\n }\n if( d &lt; 0.001 )\n {\n // show in us\n return std::formatstr(\"%0.0f us\", d * 1000000.0);\n }\n if( d &lt; 0.1 )\n {\n // show in ms\n return std::formatstr(\"%0.0f ms\", d * 1000.0);\n }\n if( d &lt;= 60.0 )\n {\n // show in seconds\n return std::formatstr(\"%0.2f s\", d);\n }\n if( d &lt; 3600.0 )\n {\n // show in min:sec\n return std::formatstr(\"%01.0f:%02.2f\", floor(d/60.0), fmod(d,60.0));\n }\n // show in h:min:sec\n return std::formatstr(\"%01.0f:%02.0f:%02.2f\", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));\n }\n\n private:\n static __int64 TimerFreq()\n {\n static __int64 freq = 0;\n static bool init = false;\n if( !init )\n {\n LARGE_INTEGER li;\n QueryPerformanceFrequency(&amp;li);\n freq = li.QuadPart;\n init = true;\n }\n return freq;\n }\n LARGE_INTEGER startTime, stopTime;\n std::string label;\n\n typedef std::string key_type;\n typedef double time_type;\n typedef std::multimap&lt;key_type, time_type&gt; Times;\n// static Times times;\n static Times&amp; TimeMap()\n {\n static Times times_;\n return times_;\n }\n\n struct extract_key : public std::unary_function&lt;Times::value_type, key_type&gt;\n {\n std::string operator()(Times::value_type const &amp; r) const\n {\n return r.first;\n }\n };\n\n struct extract_val : public std::unary_function&lt;Times::value_type, time_type&gt;\n {\n time_type operator()(Times::value_type const &amp; r) const\n {\n return r.second;\n }\n };\n struct match_key : public std::unary_function&lt;Times::value_type, bool&gt;\n {\n match_key(key_type const &amp; key_) : key(key_) {};\n bool operator()(Times::value_type const &amp; rhs) const\n {\n return key == rhs.first;\n }\n private:\n match_key&amp; operator=(match_key&amp;) { return * this; }\n const key_type key;\n };\n\n struct accum_key : public std::binary_function&lt;time_type, Times::value_type, time_type&gt;\n {\n accum_key(key_type const &amp; key_) : key(key_), n(0) {};\n time_type operator()(time_type const &amp; v, Times::value_type const &amp; rhs) const\n {\n if( key == rhs.first )\n {\n ++n;\n return rhs.second + v;\n }\n return v;\n }\n private:\n accum_key&amp; operator=(accum_key&amp;) { return * this; }\n const Times::key_type key;\n mutable size_t n;\n };\n };\n</code></pre>\n\n<p><strong>file stringext.h (provides formatstr() function):</strong></p>\n\n<pre><code>namespace std\n{\n /* ---\n\n Formatted Print\n\n template&lt;class C&gt;\n int strprintf(basic_string&lt;C&gt;* pString, const C* pFmt, ...);\n\n template&lt;class C&gt;\n int vstrprintf(basic_string&lt;C&gt;* pString, const C* pFmt, va_list args);\n\n Returns :\n\n # characters printed to output\n\n\n Effects :\n\n Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your\n documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(), \n but instead of accepting a variable paramater list it accepts a va_list argument.\n\n Requires :\n\n pString is a pointer to a basic_string&lt;&gt;\n\n --- */\n\n template&lt;class char_type&gt; int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);\n\n template&lt;&gt; inline int vprintf_generic&lt;char&gt;(char* buffer, size_t bufferSize, const char* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template&lt;&gt; inline int vprintf_generic&lt;wchar_t&gt;(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnwprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template&lt;class Type, class Traits&gt;\n inline int vstringprintf(basic_string&lt;Type,Traits&gt; &amp; outStr, const Type* format, va_list args)\n {\n // prologue\n static const size_t ChunkSize = 1024;\n size_t curBufSize = 0;\n outStr.erase(); \n\n if( !format )\n {\n return 0;\n }\n\n // keep trying to write the string to an ever-increasing buffer until\n // either we get the string written or we run out of memory\n while( bool cont = true )\n {\n // allocate a local buffer\n curBufSize += ChunkSize;\n std::ref_ptr&lt;Type&gt; localBuffer = new Type[curBufSize];\n if( localBuffer.get() == 0 )\n {\n // we ran out of memory -- nice goin'!\n return -1;\n }\n // format output to local buffer\n int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);\n if( -1 == i )\n {\n // the buffer wasn't big enough -- try again\n continue;\n }\n else if( i &lt; 0 )\n {\n // something wierd happened -- bail\n return i;\n }\n // if we get to this point the string was written completely -- stop looping\n outStr.assign(localBuffer.get(),i);\n return i;\n }\n // unreachable code\n return -1;\n };\n\n // provided for backward-compatibility\n template&lt;class Type, class Traits&gt;\n inline int vstrprintf(basic_string&lt;Type,Traits&gt; * outStr, const Type* format, va_list args)\n {\n return vstringprintf(*outStr, format, args);\n }\n\n template&lt;class Char, class Traits&gt;\n inline int stringprintf(std::basic_string&lt;Char, Traits&gt; &amp; outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(outString, format, args);\n va_end(args);\n return retval;\n }\n\n // old function provided for backward-compatibility\n template&lt;class Char, class Traits&gt;\n inline int strprintf(std::basic_string&lt;Char, Traits&gt; * outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(*outString, format, args);\n va_end(args);\n return retval;\n }\n\n /* ---\n\n Inline Formatted Print\n\n string strprintf(const char* Format, ...);\n\n Returns :\n\n Formatted string\n\n\n Effects :\n\n Writes formatted data to a string. formatstr() works the same as sprintf(); see your\n documentation for sprintf() for details of operation. \n\n --- */\n\n template&lt;class Char&gt;\n inline std::basic_string&lt;Char&gt; formatstr(const Char * format, ...)\n {\n std::string outString;\n\n va_list args;\n va_start(args, format);\n vstringprintf(outString, format, args);\n va_end(args);\n return outString;\n }\n};\n</code></pre>\n\n<p><strong>File algorithmext.h (provides transform_if() function) :</strong></p>\n\n<pre><code>/* ---\n\nTransform\n25.2.3\n\n template&lt;class InputIterator, class OutputIterator, class UnaryOperation, class Predicate&gt;\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)\n\n template&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)\n\nRequires: \n\n T is of type EqualityComparable (20.1.1) \n op and binary_op have no side effects\n\nEffects :\n\n Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:\n 1: op( *(first1 + (i - result)) \n 2: binary_op( *(first1 + (i - result), *(first2 + (i - result))\n\nReturns :\n\n result + (last1 - first1)\n\nComplexity :\n\n At most last1 - first1 applications of op or binary_op\n\n--- */\n\ntemplate&lt;class InputIterator, class OutputIterator, class UnaryFunction, class Predicate&gt;\nOutputIterator transform_if(InputIterator first, \n InputIterator last, \n OutputIterator result, \n UnaryFunction f, \n Predicate pred)\n{\n for (; first != last; ++first)\n {\n if( pred(*first) )\n *result++ = f(*first);\n }\n return result; \n}\n\ntemplate&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\nOutputIterator transform_if(InputIterator1 first1, \n InputIterator1 last1, \n InputIterator2 first2, \n OutputIterator result, \n BinaryOperation binary_op, \n Predicate pred)\n{\n for (; first1 != last1 ; ++first1, ++first2)\n {\n if( pred(*first1) )\n *result++ = binary_op(*first1,*first2);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 44489926, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 0, "selected": false, "text": "<p>I wrote a simple cross-platform class called <a href=\"http://www.plflib.org/nanotimer.htm\" rel=\"nofollow noreferrer\">nanotimer</a> for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).</p>\n\n<p>Basic usage:</p>\n\n<pre><code>plf::timer t;\ntimer.start();\n\n// stuff\n\ndouble elapsed = t.get_elapsed_ns(); // Get nanoseconds\n</code></pre>\n\n<p>start() also restarts the timer when necessary. \"Pausing\" the timer can be achieved by storing the elapsed time, then restarting the timer when \"unpausing\" and adding to the stored result the next time you check elapsed time.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
What method do you use when you want to get performance data about specific code paths?
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. 1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). 2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now. 3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't. --- I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)). ``` #pragma once #include <tchar.h> #include <windows.h> #include <sstream> #include <boost/noncopyable.hpp> namespace scope_timer { class time_collector : boost::noncopyable { __int64 total; LARGE_INTEGER start; size_t times; const TCHAR* name; double cpu_frequency() { // cache the CPU frequency, which doesn't change. static double ret = 0; // store as double so devision later on is floating point and not truncating if (ret == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); ret = static_cast<double>(freq.QuadPart); } return ret; } bool in_use; public: time_collector(const TCHAR* n) : times(0) , name(n) , total(0) , start(LARGE_INTEGER()) , in_use(false) { } ~time_collector() { std::basic_ostringstream<TCHAR> msg; msg << _T("scope_timer> ") << name << _T(" called: "); double seconds = total / cpu_frequency(); double average = seconds / times; msg << times << _T(" times total time: ") << seconds << _T(" seconds ") << _T(" (avg ") << average <<_T(")\n"); OutputDebugString(msg.str().c_str()); } void add_time(__int64 ticks) { total += ticks; ++times; in_use = false; } bool aquire() { if (in_use) return false; in_use = true; return true; } }; class one_time : boost::noncopyable { LARGE_INTEGER start; time_collector* collector; public: one_time(time_collector& tc) { if (tc.aquire()) { collector = &tc; QueryPerformanceCounter(&start); } else collector = 0; } ~one_time() { if (collector) { LARGE_INTEGER end; QueryPerformanceCounter(&end); collector->add_time(end.QuadPart - start.QuadPart); } } }; } // Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number) #define TIME_THIS_SCOPE(name) \ static scope_timer::time_collector st_time_collector_##name(_T(#name)); \ scope_timer::one_time st_one_time_##name(st_time_collector_##name) ```
61,307
<p>I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?</p>
[ { "answer_id": 61279, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": true, "text": "<p>This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.</p>\n\n<ol>\n<li>The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).</li>\n<li>It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.</li>\n<li>Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.</li>\n</ol>\n\n<hr>\n\n<p>I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DbgView</a>), including how many times the code was executed (and the average time spent of course)).</p>\n\n<pre><code>#pragma once\n#include &lt;tchar.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;sstream&gt;\n#include &lt;boost/noncopyable.hpp&gt;\n\nnamespace scope_timer {\n class time_collector : boost::noncopyable {\n __int64 total;\n LARGE_INTEGER start;\n size_t times;\n const TCHAR* name;\n\n double cpu_frequency()\n { // cache the CPU frequency, which doesn't change.\n static double ret = 0; // store as double so devision later on is floating point and not truncating\n if (ret == 0) {\n LARGE_INTEGER freq;\n QueryPerformanceFrequency(&amp;freq);\n ret = static_cast&lt;double&gt;(freq.QuadPart);\n }\n return ret;\n }\n bool in_use;\n\n public:\n time_collector(const TCHAR* n)\n : times(0)\n , name(n)\n , total(0)\n , start(LARGE_INTEGER())\n , in_use(false)\n {\n }\n\n ~time_collector()\n {\n std::basic_ostringstream&lt;TCHAR&gt; msg;\n msg &lt;&lt; _T(\"scope_timer&gt; \") &lt;&lt; name &lt;&lt; _T(\" called: \");\n\n double seconds = total / cpu_frequency();\n double average = seconds / times;\n\n msg &lt;&lt; times &lt;&lt; _T(\" times total time: \") &lt;&lt; seconds &lt;&lt; _T(\" seconds \")\n &lt;&lt; _T(\" (avg \") &lt;&lt; average &lt;&lt;_T(\")\\n\");\n OutputDebugString(msg.str().c_str());\n }\n\n void add_time(__int64 ticks)\n {\n total += ticks;\n ++times;\n in_use = false;\n }\n\n bool aquire()\n {\n if (in_use)\n return false;\n in_use = true;\n return true;\n }\n };\n\n class one_time : boost::noncopyable {\n LARGE_INTEGER start;\n time_collector* collector;\n public:\n one_time(time_collector&amp; tc)\n {\n if (tc.aquire()) {\n collector = &amp;tc;\n QueryPerformanceCounter(&amp;start);\n }\n else\n collector = 0;\n }\n\n ~one_time()\n {\n if (collector) {\n LARGE_INTEGER end;\n QueryPerformanceCounter(&amp;end);\n collector-&gt;add_time(end.QuadPart - start.QuadPart);\n }\n }\n };\n}\n\n// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)\n#define TIME_THIS_SCOPE(name) \\\n static scope_timer::time_collector st_time_collector_##name(_T(#name)); \\\n scope_timer::one_time st_one_time_##name(st_time_collector_##name)\n</code></pre>\n" }, { "answer_id": 61281, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Well, I have two code snippets. In <a href=\"http://en.wikipedia.org/wiki/Pseudocode\" rel=\"nofollow noreferrer\">pseudocode</a> they are looking like (it's a simplified version, I'm using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">QueryPerformanceFrequency</a> actually):</p>\n\n<h3>First snippet:</h3>\n\n<pre><code>Timer timer = new Timer\ntimer.Start\n</code></pre>\n\n<h3>Second snippet:</h3>\n\n<pre><code>timer.Stop\nshow elapsed time\n</code></pre>\n\n<p>A bit of hot-keys kung fu, and I can say how much time this piece of code stole from my CPU.</p>\n" }, { "answer_id": 61282, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>The article <em>Code profiler and optimizations</em> has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods.</p>\n" }, { "answer_id": 61303, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 2, "selected": false, "text": "<p>I do my profiles by creating two classes: <code>cProfile</code> and <code>cProfileManager</code>.</p>\n\n<p><code>cProfileManager</code> will hold all the data that resulted from <code>cProfile</code>.</p>\n\n<p><code>cProfile</code> with have the following requirements:</p>\n\n<ul>\n<li><code>cProfile</code> has a constructor which initializes the current time.</li>\n<li><code>cProfile</code> has a deconstructor which sends the total time the class was alive to <code>cProfileManager</code></li>\n</ul>\n\n<p>To use these profile classes, I first make an instance of <code>cProfileManager</code>. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a <code>cProfile</code> instance. When the code block ends, <code>cProfile</code> will send the time it took for the block of code to finish to <code>cProfileManager</code>.</p>\n\n<p><strong>Example Code</strong>\nHere's an example of the code (simplified):</p>\n\n<pre><code>class cProfile\n{\n cProfile()\n {\n TimeStart = GetTime();\n };\n\n ~cProfile()\n {\n ProfileManager-&gt;AddProfile (GetTime() - TimeStart);\n }\n\n float TimeStart;\n}\n</code></pre>\n\n<p>To use <code>cProfile</code>, I would do something like this:</p>\n\n<pre><code>int main()\n{\n printf(\"Start test\");\n {\n cProfile Profile;\n Calculate();\n }\n ProfileManager-&gt;OutputData();\n}\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>void foobar()\n{\n cProfile ProfileFoobar;\n\n foo();\n {\n cProfile ProfileBarCheck;\n while (bar())\n {\n cProfile ProfileSpam;\n spam();\n }\n }\n}\n</code></pre>\n\n<p><strong>Technical Note</strong></p>\n\n<p>This code is actually an abuse of the way scoping, constructors and deconstructors work in <a href=\"http://en.wikipedia.org/wiki/C_%28programming_language%29\" rel=\"nofollow noreferrer\">C++</a>. <code>cProfile</code> exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, <code>cProfile</code> records the result.</p>\n\n<p><strong>Additional Enhancements</strong></p>\n\n<ul>\n<li><p>You can add a string parameter to the constructor so you can do something like this:\ncProfile Profile(\"Profile for complicated calculation\");</p></li>\n<li><p>You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).</p>\n\n<p>Example:</p>\n\n<p>#define START_PROFILE cProfile Profile(); {\n#define END_PROFILE }</p></li>\n<li><p><code>cProfileManager</code> can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.</p></li>\n<li><p>Don't forget to add a check to skip profiling if you are in debug mode.</p></li>\n</ul>\n" }, { "answer_id": 231590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have a quick-and-dirty profiling class that can be used in profiling in even the most tight inner loops. The emphasis is on extreme light weight and simple code. The class allocates a two-dimensional array of fixed size. I then add \"checkpoint\" calls all over the place. When checkpoint N is reached immediately after checkpoint M, I add the time elapsed (in microseconds) to the array item [M,N]. Since this is designed to profile tight loops, I also have \"start of iteration\" call that resets the the \"last checkpoint\" variable. At the end of test, the <code>dumpResults()</code> call produces the list of all pairs of checkpoints that followed each other, together with total time accounted for and unaccounted for.</p>\n" }, { "answer_id": 231614, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 2, "selected": false, "text": "<p>Note, the following is all written specifically for Windows.</p>\n\n<p>I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference. My timer class doesn't dump the elapsed time when the Timer object falls out of scope. Instead, it accumulates the elapsed times in to an collection. I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer's constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min. I also added a Clear() static member function which clears the collection &amp; lets you start over again.</p>\n\n<p><strong>How to use the Timer class (psudocode):</strong></p>\n\n<pre><code>int CInsertBuffer::Read(char* pBuf)\n{\n // TIMER NOTES: Avg Execution Time = ~1 ms\n Timer timer(\"BufferRead\");\n : :\n return -1;\n}\n</code></pre>\n\n<p><strong>Sample output :</strong></p>\n\n<pre><code>Timer Precision = 418.0095 ps\n\n=== Item Trials Ttl Time Avg Time Mean Time StdDev ===\n AddTrade 500 7 ms 14 us 12 us 24 us\n BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s\n BufferWrite 516 511 us 991 ns 482 ns 11 us\n ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s\n ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s\n Insert 515 4.26 s 8 ms 5 ms 27 ms\n recv 101 18.54 s 0.18 s 2603 ns 1.63 s\n</code></pre>\n\n<p><strong>file Timer.inl :</strong></p>\n\n<pre><code>#include &lt;map&gt;\n#include \"x:\\utils\\stlext\\stringext.h\"\n#include &lt;iterator&gt;\n#include &lt;set&gt;\n#include &lt;vector&gt;\n#include &lt;numeric&gt;\n#include \"x:\\utils\\stlext\\algorithmext.h\"\n#include &lt;math.h&gt;\n\n class Timer\n {\n public:\n Timer(const char* name)\n {\n label = std::safe_string(name);\n QueryPerformanceCounter(&amp;startTime);\n }\n\n virtual ~Timer()\n {\n QueryPerformanceCounter(&amp;stopTime);\n __int64 clocks = stopTime.QuadPart-startTime.QuadPart;\n double elapsed = (double)clocks/(double)TimerFreq();\n TimeMap().insert(std::make_pair(label,elapsed));\n };\n\n static std::string Dump(bool ClipboardAlso=true)\n {\n static const std::string loc = \"Timer::Dump\";\n\n if( TimeMap().empty() )\n {\n return \"No trials\\r\\n\";\n }\n\n std::string ret = std::formatstr(\"\\r\\n\\r\\nTimer Precision = %s\\r\\n\\r\\n\", format_elapsed(1.0/(double)TimerFreq()).c_str());\n\n // get a list of keys\n typedef std::set&lt;std::string&gt; keyset;\n keyset keys;\n std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());\n\n size_t maxrows = 0;\n\n typedef std::vector&lt;std::string&gt; strings;\n strings lines;\n\n static const size_t tabWidth = 9;\n\n std::string head = std::formatstr(\"=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===\", tabWidth*2, tabWidth*2, \"Item\", tabWidth, tabWidth, \"Trials\", tabWidth, tabWidth, \"Ttl Time\", tabWidth, tabWidth, \"Avg Time\", tabWidth, tabWidth, \"Mean Time\", tabWidth, tabWidth, \"StdDev\");\n ret += std::formatstr(\"\\r\\n%s\\r\\n\", head.c_str());\n if( ClipboardAlso ) \n lines.push_back(\"Item\\tTrials\\tTtl Time\\tAvg Time\\tMean Time\\tStdDev\\r\\n\");\n // dump the values for each key\n {for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )\n {\n time_type ttl = 0;\n ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));\n size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));\n if( num &gt; maxrows ) \n maxrows = num;\n time_type avg = ttl / num;\n\n // compute mean\n std::vector&lt;time_type&gt; sortedTimes;\n std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));\n std::sort(sortedTimes.begin(), sortedTimes.end());\n size_t mid = (size_t)floor((double)num/2.0);\n double mean = ( num &gt; 1 &amp;&amp; (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];\n // compute variance\n double sum = 0.0;\n if( num &gt; 1 )\n {\n for( std::vector&lt;time_type&gt;::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )\n sum += pow(*timeIt-mean,2.0);\n }\n // compute std dev\n double stddev = num &gt; 1 ? sqrt(sum/((double)num-1.0)) : 0.0;\n\n ret += std::formatstr(\" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\\r\\n\", tabWidth*2, tabWidth*2, key-&gt;c_str(), tabWidth, tabWidth, std::formatstr(\"%d\",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str()); \n if( ClipboardAlso )\n lines.push_back(std::formatstr(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\r\\n\", key-&gt;c_str(), std::formatstr(\"%d\",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str())); \n\n }\n }\n ret += std::formatstr(\"%s\\r\\n\", std::string(head.length(),'=').c_str());\n\n if( ClipboardAlso )\n {\n // dump header row of data block\n lines.push_back(\"\");\n {\n std::string s;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n s.append(\"\\t\");\n s.append(*key);\n }\n s.append(\"\\r\\n\");\n lines.push_back(s);\n }\n\n // blow out the flat map of time values to a seperate vector of times for each key\n typedef std::map&lt;std::string, std::vector&lt;time_type&gt; &gt; nodematrix;\n nodematrix nodes;\n for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )\n nodes[time-&gt;first].push_back(time-&gt;second);\n\n // dump each data point\n for( size_t row = 0; row &lt; maxrows; ++row )\n {\n std::string rowDump;\n for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n {\n if( key != keys.begin() )\n rowDump.append(\"\\t\");\n if( nodes[*key].size() &gt; row )\n rowDump.append(std::formatstr(\"%f\", nodes[*key][row]));\n }\n rowDump.append(\"\\r\\n\");\n lines.push_back(rowDump);\n }\n\n // dump to the clipboard\n std::string dump;\n for( strings::iterator s = lines.begin(); s != lines.end(); ++s )\n {\n dump.append(*s);\n }\n\n OpenClipboard(0);\n EmptyClipboard();\n HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);\n if( hg != 0 )\n {\n char* buf = (char*)GlobalLock(hg);\n if( buf != 0 )\n {\n std::copy(dump.begin(), dump.end(), buf);\n buf[dump.length()] = 0;\n GlobalUnlock(hg);\n SetClipboardData(CF_TEXT, hg);\n }\n }\n CloseClipboard();\n }\n\n return ret;\n }\n\n static void Reset()\n {\n TimeMap().clear();\n }\n\n static std::string format_elapsed(double d) \n {\n if( d &lt; 0.00000001 )\n {\n // show in ps with 4 digits\n return std::formatstr(\"%0.4f ps\", d * 1000000000000.0);\n }\n if( d &lt; 0.00001 )\n {\n // show in ns\n return std::formatstr(\"%0.0f ns\", d * 1000000000.0);\n }\n if( d &lt; 0.001 )\n {\n // show in us\n return std::formatstr(\"%0.0f us\", d * 1000000.0);\n }\n if( d &lt; 0.1 )\n {\n // show in ms\n return std::formatstr(\"%0.0f ms\", d * 1000.0);\n }\n if( d &lt;= 60.0 )\n {\n // show in seconds\n return std::formatstr(\"%0.2f s\", d);\n }\n if( d &lt; 3600.0 )\n {\n // show in min:sec\n return std::formatstr(\"%01.0f:%02.2f\", floor(d/60.0), fmod(d,60.0));\n }\n // show in h:min:sec\n return std::formatstr(\"%01.0f:%02.0f:%02.2f\", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));\n }\n\n private:\n static __int64 TimerFreq()\n {\n static __int64 freq = 0;\n static bool init = false;\n if( !init )\n {\n LARGE_INTEGER li;\n QueryPerformanceFrequency(&amp;li);\n freq = li.QuadPart;\n init = true;\n }\n return freq;\n }\n LARGE_INTEGER startTime, stopTime;\n std::string label;\n\n typedef std::string key_type;\n typedef double time_type;\n typedef std::multimap&lt;key_type, time_type&gt; Times;\n// static Times times;\n static Times&amp; TimeMap()\n {\n static Times times_;\n return times_;\n }\n\n struct extract_key : public std::unary_function&lt;Times::value_type, key_type&gt;\n {\n std::string operator()(Times::value_type const &amp; r) const\n {\n return r.first;\n }\n };\n\n struct extract_val : public std::unary_function&lt;Times::value_type, time_type&gt;\n {\n time_type operator()(Times::value_type const &amp; r) const\n {\n return r.second;\n }\n };\n struct match_key : public std::unary_function&lt;Times::value_type, bool&gt;\n {\n match_key(key_type const &amp; key_) : key(key_) {};\n bool operator()(Times::value_type const &amp; rhs) const\n {\n return key == rhs.first;\n }\n private:\n match_key&amp; operator=(match_key&amp;) { return * this; }\n const key_type key;\n };\n\n struct accum_key : public std::binary_function&lt;time_type, Times::value_type, time_type&gt;\n {\n accum_key(key_type const &amp; key_) : key(key_), n(0) {};\n time_type operator()(time_type const &amp; v, Times::value_type const &amp; rhs) const\n {\n if( key == rhs.first )\n {\n ++n;\n return rhs.second + v;\n }\n return v;\n }\n private:\n accum_key&amp; operator=(accum_key&amp;) { return * this; }\n const Times::key_type key;\n mutable size_t n;\n };\n };\n</code></pre>\n\n<p><strong>file stringext.h (provides formatstr() function):</strong></p>\n\n<pre><code>namespace std\n{\n /* ---\n\n Formatted Print\n\n template&lt;class C&gt;\n int strprintf(basic_string&lt;C&gt;* pString, const C* pFmt, ...);\n\n template&lt;class C&gt;\n int vstrprintf(basic_string&lt;C&gt;* pString, const C* pFmt, va_list args);\n\n Returns :\n\n # characters printed to output\n\n\n Effects :\n\n Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your\n documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(), \n but instead of accepting a variable paramater list it accepts a va_list argument.\n\n Requires :\n\n pString is a pointer to a basic_string&lt;&gt;\n\n --- */\n\n template&lt;class char_type&gt; int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);\n\n template&lt;&gt; inline int vprintf_generic&lt;char&gt;(char* buffer, size_t bufferSize, const char* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template&lt;&gt; inline int vprintf_generic&lt;wchar_t&gt;(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)\n {\n# ifdef SECURE_VSPRINTF\n return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n# else\n return _vsnwprintf(buffer, bufferSize-1, format, argptr);\n# endif\n }\n\n template&lt;class Type, class Traits&gt;\n inline int vstringprintf(basic_string&lt;Type,Traits&gt; &amp; outStr, const Type* format, va_list args)\n {\n // prologue\n static const size_t ChunkSize = 1024;\n size_t curBufSize = 0;\n outStr.erase(); \n\n if( !format )\n {\n return 0;\n }\n\n // keep trying to write the string to an ever-increasing buffer until\n // either we get the string written or we run out of memory\n while( bool cont = true )\n {\n // allocate a local buffer\n curBufSize += ChunkSize;\n std::ref_ptr&lt;Type&gt; localBuffer = new Type[curBufSize];\n if( localBuffer.get() == 0 )\n {\n // we ran out of memory -- nice goin'!\n return -1;\n }\n // format output to local buffer\n int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);\n if( -1 == i )\n {\n // the buffer wasn't big enough -- try again\n continue;\n }\n else if( i &lt; 0 )\n {\n // something wierd happened -- bail\n return i;\n }\n // if we get to this point the string was written completely -- stop looping\n outStr.assign(localBuffer.get(),i);\n return i;\n }\n // unreachable code\n return -1;\n };\n\n // provided for backward-compatibility\n template&lt;class Type, class Traits&gt;\n inline int vstrprintf(basic_string&lt;Type,Traits&gt; * outStr, const Type* format, va_list args)\n {\n return vstringprintf(*outStr, format, args);\n }\n\n template&lt;class Char, class Traits&gt;\n inline int stringprintf(std::basic_string&lt;Char, Traits&gt; &amp; outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(outString, format, args);\n va_end(args);\n return retval;\n }\n\n // old function provided for backward-compatibility\n template&lt;class Char, class Traits&gt;\n inline int strprintf(std::basic_string&lt;Char, Traits&gt; * outString, const Char* format, ...)\n {\n va_list args;\n va_start(args, format);\n int retval = vstringprintf(*outString, format, args);\n va_end(args);\n return retval;\n }\n\n /* ---\n\n Inline Formatted Print\n\n string strprintf(const char* Format, ...);\n\n Returns :\n\n Formatted string\n\n\n Effects :\n\n Writes formatted data to a string. formatstr() works the same as sprintf(); see your\n documentation for sprintf() for details of operation. \n\n --- */\n\n template&lt;class Char&gt;\n inline std::basic_string&lt;Char&gt; formatstr(const Char * format, ...)\n {\n std::string outString;\n\n va_list args;\n va_start(args, format);\n vstringprintf(outString, format, args);\n va_end(args);\n return outString;\n }\n};\n</code></pre>\n\n<p><strong>File algorithmext.h (provides transform_if() function) :</strong></p>\n\n<pre><code>/* ---\n\nTransform\n25.2.3\n\n template&lt;class InputIterator, class OutputIterator, class UnaryOperation, class Predicate&gt;\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)\n\n template&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\n OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)\n\nRequires: \n\n T is of type EqualityComparable (20.1.1) \n op and binary_op have no side effects\n\nEffects :\n\n Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:\n 1: op( *(first1 + (i - result)) \n 2: binary_op( *(first1 + (i - result), *(first2 + (i - result))\n\nReturns :\n\n result + (last1 - first1)\n\nComplexity :\n\n At most last1 - first1 applications of op or binary_op\n\n--- */\n\ntemplate&lt;class InputIterator, class OutputIterator, class UnaryFunction, class Predicate&gt;\nOutputIterator transform_if(InputIterator first, \n InputIterator last, \n OutputIterator result, \n UnaryFunction f, \n Predicate pred)\n{\n for (; first != last; ++first)\n {\n if( pred(*first) )\n *result++ = f(*first);\n }\n return result; \n}\n\ntemplate&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\nOutputIterator transform_if(InputIterator1 first1, \n InputIterator1 last1, \n InputIterator2 first2, \n OutputIterator result, \n BinaryOperation binary_op, \n Predicate pred)\n{\n for (; first1 != last1 ; ++first1, ++first2)\n {\n if( pred(*first1) )\n *result++ = binary_op(*first1,*first2);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 44489926, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 0, "selected": false, "text": "<p>I wrote a simple cross-platform class called <a href=\"http://www.plflib.org/nanotimer.htm\" rel=\"nofollow noreferrer\">nanotimer</a> for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).</p>\n\n<p>Basic usage:</p>\n\n<pre><code>plf::timer t;\ntimer.start();\n\n// stuff\n\ndouble elapsed = t.get_elapsed_ns(); // Get nanoseconds\n</code></pre>\n\n<p>start() also restarts the timer when necessary. \"Pausing\" the timer can be achieved by storing the elapsed time, then restarting the timer when \"unpausing\" and adding to the stored result the next time you check elapsed time.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665/" ]
I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. 1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). 2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now. 3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't. --- I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)). ``` #pragma once #include <tchar.h> #include <windows.h> #include <sstream> #include <boost/noncopyable.hpp> namespace scope_timer { class time_collector : boost::noncopyable { __int64 total; LARGE_INTEGER start; size_t times; const TCHAR* name; double cpu_frequency() { // cache the CPU frequency, which doesn't change. static double ret = 0; // store as double so devision later on is floating point and not truncating if (ret == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); ret = static_cast<double>(freq.QuadPart); } return ret; } bool in_use; public: time_collector(const TCHAR* n) : times(0) , name(n) , total(0) , start(LARGE_INTEGER()) , in_use(false) { } ~time_collector() { std::basic_ostringstream<TCHAR> msg; msg << _T("scope_timer> ") << name << _T(" called: "); double seconds = total / cpu_frequency(); double average = seconds / times; msg << times << _T(" times total time: ") << seconds << _T(" seconds ") << _T(" (avg ") << average <<_T(")\n"); OutputDebugString(msg.str().c_str()); } void add_time(__int64 ticks) { total += ticks; ++times; in_use = false; } bool aquire() { if (in_use) return false; in_use = true; return true; } }; class one_time : boost::noncopyable { LARGE_INTEGER start; time_collector* collector; public: one_time(time_collector& tc) { if (tc.aquire()) { collector = &tc; QueryPerformanceCounter(&start); } else collector = 0; } ~one_time() { if (collector) { LARGE_INTEGER end; QueryPerformanceCounter(&end); collector->add_time(end.QuadPart - start.QuadPart); } } }; } // Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number) #define TIME_THIS_SCOPE(name) \ static scope_timer::time_collector st_time_collector_##name(_T(#name)); \ scope_timer::one_time st_one_time_##name(st_time_collector_##name) ```
61,339
<p>I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?</p>
[ { "answer_id": 61452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Ah, You have to use the UserProfileManager class.\nMore information here: <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx</a></p>\n\n<p>Example use:</p>\n\n<pre><code>public override void ItemAdded(SPItemEventProperties properties)\n{\n // Get list item on which the event occurred.\n SPListItem item = properties.ListItem;\n\n // Set the Author Image field to the user's PictureURL if it exists.\n using (SPWeb web = properties.OpenWeb())\n {\n // Author: {C32DB804-FF2D-4656-A38A-B0394BA5C931}\n SPFieldUserValue authorValue = new SPFieldUserValue(properties.OpenWeb(), item[new Guid(\"{C32DB804-FF2D-4656-A38A-B0394BA5C931}\")].ToString());\n\n UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(web.Site));\n UserProfile profile = profileManager.GetUserProfile(authorValue.LookupId);\n UserProfileValueCollection values = profile[PropertyConstants.PictureUrl];\n\n if (values.Count &gt; 0)\n {\n // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}\n SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString());\n item[new Guid(\"{37A5CA4C-7621-44d7-BF3B-583F742CE52F}\")] = urlValue.Url;\n }\n }\n\n item.Update();\n\n // News Text: {7F55A8F0-4555-46BC-B24C-222240B862AF}\n //\n\n // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}\n // \n\n // Publish Date: {45E84B8B-E161-46C6-AD51-27A42E4992B5}\n //\n}\n</code></pre>\n" }, { "answer_id": 61468, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": true, "text": "<p>Here is a code snippet that should help get the job done for you. You may need to do some additional validation to avoid any exceptions (ensuring the profile actually exists, ensuring the image URL actually exists, etc...):</p>\n\n<pre><code> //get current profile manager\n UserProfileManager objUserProfileManager = new UserProfileManager(PortalContext.Current);\n //get current users profile\n UserProfile profile = objUserProfileManager.GetUserProfile(true);\n //get user image URL\n string imageUrl = (string)profile[PropertyConstants.PictureUrl];\n\n //do something here with imageUrl\n</code></pre>\n" }, { "answer_id": 79922, "author": "Sam Yates", "author_id": 14911, "author_profile": "https://Stackoverflow.com/users/14911", "pm_score": 2, "selected": false, "text": "<p>If you are strictly talking about WSS 3.0 (and not MOSS), then you really don't have global user profiles per se, but a hiddenh User Information List in each site collection. That mean none of the stuff in the Microsoft.Office.Server namespaces is available to you.</p>\n\n<p>However, you can update the User Information List programatically as long as you know the URL to a user's picture. As long as you're running with some kind of elevated privileges, you should be able to <a href=\"http://www.sharepointblogs.com/jimyang/archive/2006/12/05/update-wss-3-0-user-profile-programmatically.aspx\" rel=\"nofollow noreferrer\">manipulate this list</a> just like you can with any other SharePoint list. Keep in mind that this list is only good for the scope of a site collection, so users would have to make this same update all over the place to actually have a photo URL. Plus users don't get into the User Information List until someone assigns some kind of permission to them, so not every user in your domain will be in there.</p>\n\n<p>The clean way to handle this is definitely the User Profile mechanism is MOSS, but if that's an option the question should really be updated to ask about MOSS vs WSS.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?
Here is a code snippet that should help get the job done for you. You may need to do some additional validation to avoid any exceptions (ensuring the profile actually exists, ensuring the image URL actually exists, etc...): ``` //get current profile manager UserProfileManager objUserProfileManager = new UserProfileManager(PortalContext.Current); //get current users profile UserProfile profile = objUserProfileManager.GetUserProfile(true); //get user image URL string imageUrl = (string)profile[PropertyConstants.PictureUrl]; //do something here with imageUrl ```
61,341
<p>I remember back in the day with the old borland DOS compiler you could do something like this:</p> <pre><code>asm { mov ax,ex etc etc... } </code></pre> <p>Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.</p>
[ { "answer_id": 61344, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p>A good start would be reading this article which talk about inline assembly in C/C++:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx</a></p>\n\n<p>Example from the article:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n\nint main() {\n /* Add 10 and 20 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"addl %ebx, %eax;\"\n );\n\n /* Subtract 20 from 10 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"subl %ebx, %eax;\"\n );\n\n /* Multiply 10 and 20 and store result into register %eax */\n __asm__ ( \"movl $10, %eax;\"\n \"movl $20, %ebx;\"\n \"imull %ebx, %eax;\"\n );\n\n return 0 ;\n}\n</code></pre>\n" }, { "answer_id": 61350, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 7, "selected": true, "text": "<p>Using <a href=\"http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html\" rel=\"noreferrer\">GCC</a></p>\n\n<pre><code>__asm__(\"movl %edx, %eax\\n\\t\"\n \"addl $2, %eax\\n\\t\");\n</code></pre>\n\n<p>Using <a href=\"http://msdn.microsoft.com/en-us/library/4ks26t93(VS.71).aspx\" rel=\"noreferrer\">VC++</a></p>\n\n<pre><code>__asm {\n mov eax, edx\n add eax, 2\n}\n</code></pre>\n" }, { "answer_id": 61745, "author": "Martin Del Vecchio", "author_id": 5397, "author_profile": "https://Stackoverflow.com/users/5397", "pm_score": 4, "selected": false, "text": "<p>In GCC, there's more to it than that. In the instruction, you have to tell the compiler what changed, so that its optimizer doesn't screw up. I'm no expert, but sometimes it looks something like this:</p>\n\n<pre><code> asm (\"lock; xaddl %0,%2\" : \"=r\" (result) : \"0\" (1), \"m\" (*atom) : \"memory\");\n</code></pre>\n\n<p>It's a good idea to write some sample code in C, then ask GCC to produce an assembly listing, then modify that code.</p>\n" }, { "answer_id": 63633, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>For Microsoft compilers, <em>inline</em> assembly is supported only for x86. For other targets you have to define the whole function in a separate assembly source file, pass it to an assembler and link the resulting object module.</p>\n\n<p>You're highly unlikely to be able to call into the BIOS under a protected-mode operating system and should use whatever facilities are available on that system. Even if you're in kernel mode it's probably unsafe - the BIOS may not be correctly synchronized with respect to OS state if you do so.</p>\n" }, { "answer_id": 66843327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>use of <code>asm</code> or <code>__asm__</code> function ( in compilers have difference )</p>\n<p>also you can write fortran codes with <code>fortran</code> function</p>\n<pre><code>asm(&quot;syscall&quot;);\nfortran(&quot;Print *,&quot;J&quot;);\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6062/" ]
I remember back in the day with the old borland DOS compiler you could do something like this: ``` asm { mov ax,ex etc etc... } ``` Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.
Using [GCC](http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html) ``` __asm__("movl %edx, %eax\n\t" "addl $2, %eax\n\t"); ``` Using [VC++](http://msdn.microsoft.com/en-us/library/4ks26t93(VS.71).aspx) ``` __asm { mov eax, edx add eax, 2 } ```
61,357
<p>Should I still be using tables anyway?</p> <p>The table code I'd be replacing is:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt; &lt;/tr&gt; ... &lt;/table&gt; </code></pre> <p>From what I've been reading I should have something like</p> <pre><code>&lt;label class="name"&gt;Name&lt;/label&gt;&lt;label class="value"&gt;Value&lt;/value&gt;&lt;br /&gt; ... </code></pre> <p>Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth.</p> <p>EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.</p>
[ { "answer_id": 61360, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p>I think tables are best used for tabular data, which it seems you have there.</p>\n\n<p>If you do not want to use tables, the best thing would be to use definition lists(<code>&lt;dl&gt; and &lt;dt&gt;</code>). Here is how to style them to look like your old <code>&lt;td&gt;</code> layout.\n<a href=\"http://maxdesign.com.au/articles/definition/\" rel=\"nofollow noreferrer\">http://maxdesign.com.au/articles/definition/</a></p>\n" }, { "answer_id": 61362, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 7, "selected": true, "text": "<p>I think that definition lists are pretty close semantically to name/value pairs.</p>\n\n<pre><code>&lt;dl&gt;\n &lt;dt&gt;Name&lt;/dt&gt;\n &lt;dd&gt;Value&lt;/dd&gt;\n&lt;/dl&gt;\n</code></pre>\n\n<p><a href=\"http://www.maxdesign.com.au/presentation/definition\" rel=\"noreferrer\">Definition lists - misused or misunderstood?</a></p>\n" }, { "answer_id": 61364, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": -1, "selected": false, "text": "<p>use the float: property eg:\ncss:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.left {\n float:left;\n padding-right:20px\n}\n</code></pre>\n\n<p>html:</p>\n\n<pre><code>&lt;div class=\"left\"&gt;\n Name&lt;br/&gt;\n AnotherName\n&lt;/div&gt;\n&lt;div&gt;\n Value&lt;br /&gt;\n AnotherValue\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 61379, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 3, "selected": false, "text": "<p>It's perfectly reasonable to use tables for what seems to be tabular data.</p>\n" }, { "answer_id": 61381, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>If I'm writing a form I usually use this:</p>\n\n<pre><code>&lt;form ... class=\"editing\"&gt;\n &lt;div class=\"field\"&gt;\n &lt;label&gt;Label&lt;/label&gt;\n &lt;span class=\"edit\"&gt;&lt;input type=\"text\" value=\"Value\" ... /&gt;&lt;/span&gt;\n &lt;span class=\"view\"&gt;Value&lt;/span&gt;\n &lt;/div&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n\n<p>Then in my css:</p>\n\n<pre><code>.editing .view, .viewing .edit { display: none }\n.editing .edit, .editing .view { display: inline }\n</code></pre>\n\n<p>Then with a little JavaScript I can swap the class of the form from editing to viewing.</p>\n\n<p>I mention this approach since you wanted to display and edit the data with nearly the same layout and this is a way of doing it.</p>\n" }, { "answer_id": 62679, "author": "derek lawless", "author_id": 400464, "author_profile": "https://Stackoverflow.com/users/400464", "pm_score": 2, "selected": false, "text": "<p>Like macbirdie I'd be inclined to mark data like this up as a definition list unless the content of the existing table could be judged to actually <em>be</em> tabular content. </p>\n\n<p>I'd avoid using the label tag in the way you propose. Take a look at explanation of the label tag @ <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label</a> - it's really intended to allow you to focus on its associated control. Also avoid using generic divs and spans as from a semantic point of view they're weak.</p>\n\n<p>If you're display multiple name-value pairs on one screen, but editing only one on an edit screen, I'd use a table on the former screen, and a definition list on the latter.</p>\n" }, { "answer_id": 39487947, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 3, "selected": false, "text": "<p>Horizontal definition lists work pretty well, i.e.</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;dl class=&quot;dl-horizontal&quot;&gt;\n &lt;dt&gt;ID&lt;/dt&gt;\n &lt;dd&gt;25&lt;/dd&gt;\n &lt;dt&gt;Username&lt;/dt&gt;\n &lt;dd&gt;Bob&lt;/dd&gt;\n&lt;/dl&gt;\n</code></pre>\n<p>The <code>dl-horizontal</code> class is provided by the Bootstrap CSS framework.</p>\n<p>From Bootstrap4:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;dl class=&quot;row&quot;&gt;\n &lt;dt class=&quot;col&quot;&gt;ID&lt;/dt&gt;\n &lt;dd class=&quot;col&quot;&gt;25&lt;/dd&gt;\n&lt;/dl&gt;\n&lt;dl class=&quot;row&quot;&gt;\n &lt;dt class=&quot;col&quot;&gt;Username&lt;/dt&gt;\n &lt;dd class=&quot;col&quot;&gt;Bob&lt;/dd&gt;\n&lt;/dl&gt;\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
Should I still be using tables anyway? The table code I'd be replacing is: ``` <table> <tr> <td>Name</td><td>Value</td> </tr> ... </table> ``` From what I've been reading I should have something like ``` <label class="name">Name</label><label class="value">Value</value><br /> ... ``` Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth. EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.
I think that definition lists are pretty close semantically to name/value pairs. ``` <dl> <dt>Name</dt> <dd>Value</dd> </dl> ``` [Definition lists - misused or misunderstood?](http://www.maxdesign.com.au/presentation/definition)